_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
8b353fd011c73aaa3cb371bbcc1ef2b72cdda40bc8bfc370299a84743ce28cd8
jship/monad-logger-aeson
MetadataYesThreadContextYes.hs
# LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # module TestCase.LogDebugNS.MetadataYesThreadContextYes ( testCase ) where import Control.Monad.Logger.Aeson ( (.=), Loc(..), LogLevel(..), LoggedMessage(..), Message(..), logDebugNS, withThreadContext ) import Data.Aeson.QQ.Simple (aesonQQ) import Data.Time (UTCTime(..)) import TestCase (TestCase(..)) import qualified Control.Monad.Logger.Aeson.Internal as Internal import qualified Data.Time as Time testCase :: FilePath -> TestCase testCase logFilePath = TestCase { actionUnderTest = do withThreadContext ["reqId" .= ("74ec1d0b" :: String)] $ do logDebugNS "tests" $ "With metadata" :# [ "a" .= (42 :: Int) , "b" .= ("x" :: String) ] , logFilePath , expectedValue = [aesonQQ| { "time": "2022-05-07T20:03:54.0000000Z", "level": "debug", "location": { "package": "main", "module": "TestCase.LogDebugNS.MetadataYesThreadContextYes", "file": "test-suite/TestCase/LogDebugNS/MetadataYesThreadContextYes.hs", "line": 22, "char": 11 }, "source": "tests", "context": { "reqId": "74ec1d0b" }, "message": { "text": "With metadata", "meta": { "a": 42, "b": "x" } } } |] , expectedPatch = [aesonQQ| [ { "op": "replace", "path": "/time", "value": "2022-05-07T20:03:54.0000000Z" } ] |] , expectedLoggedMessage = LoggedMessage { loggedMessageTimestamp = UTCTime { utctDay = Time.fromGregorian 2022 05 07 , utctDayTime = 72234 } , loggedMessageLevel = LevelDebug , loggedMessageLoc = Just Loc { loc_package = "main" , loc_module = "TestCase.LogDebugNS.MetadataYesThreadContextYes" , loc_filename = "test-suite/TestCase/LogDebugNS/MetadataYesThreadContextYes.hs" , loc_start = (22, 11) , loc_end = (0, 0) } , loggedMessageLogSource = Just "tests" , loggedMessageThreadContext = Internal.keyMapFromList [ "reqId" .= ("74ec1d0b" :: String) ] , loggedMessageText = "With metadata" , loggedMessageMeta = Internal.keyMapFromList [ "a" .= (42 :: Int) , "b" .= ("x" :: String) ] } }
null
https://raw.githubusercontent.com/jship/monad-logger-aeson/b983befb790818628f1c4a5f02a2b96b08dcf6ce/monad-logger-aeson/test-suite/TestCase/LogDebugNS/MetadataYesThreadContextYes.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE NamedFieldPuns # # LANGUAGE QuasiQuotes # module TestCase.LogDebugNS.MetadataYesThreadContextYes ( testCase ) where import Control.Monad.Logger.Aeson ( (.=), Loc(..), LogLevel(..), LoggedMessage(..), Message(..), logDebugNS, withThreadContext ) import Data.Aeson.QQ.Simple (aesonQQ) import Data.Time (UTCTime(..)) import TestCase (TestCase(..)) import qualified Control.Monad.Logger.Aeson.Internal as Internal import qualified Data.Time as Time testCase :: FilePath -> TestCase testCase logFilePath = TestCase { actionUnderTest = do withThreadContext ["reqId" .= ("74ec1d0b" :: String)] $ do logDebugNS "tests" $ "With metadata" :# [ "a" .= (42 :: Int) , "b" .= ("x" :: String) ] , logFilePath , expectedValue = [aesonQQ| { "time": "2022-05-07T20:03:54.0000000Z", "level": "debug", "location": { "package": "main", "module": "TestCase.LogDebugNS.MetadataYesThreadContextYes", "file": "test-suite/TestCase/LogDebugNS/MetadataYesThreadContextYes.hs", "line": 22, "char": 11 }, "source": "tests", "context": { "reqId": "74ec1d0b" }, "message": { "text": "With metadata", "meta": { "a": 42, "b": "x" } } } |] , expectedPatch = [aesonQQ| [ { "op": "replace", "path": "/time", "value": "2022-05-07T20:03:54.0000000Z" } ] |] , expectedLoggedMessage = LoggedMessage { loggedMessageTimestamp = UTCTime { utctDay = Time.fromGregorian 2022 05 07 , utctDayTime = 72234 } , loggedMessageLevel = LevelDebug , loggedMessageLoc = Just Loc { loc_package = "main" , loc_module = "TestCase.LogDebugNS.MetadataYesThreadContextYes" , loc_filename = "test-suite/TestCase/LogDebugNS/MetadataYesThreadContextYes.hs" , loc_start = (22, 11) , loc_end = (0, 0) } , loggedMessageLogSource = Just "tests" , loggedMessageThreadContext = Internal.keyMapFromList [ "reqId" .= ("74ec1d0b" :: String) ] , loggedMessageText = "With metadata" , loggedMessageMeta = Internal.keyMapFromList [ "a" .= (42 :: Int) , "b" .= ("x" :: String) ] } }
47c4bc886de7b3b1abe45ccf90b0d516abf511d377dc0b13102b2ad3763edb3a
GrammaticalFramework/gf-core
CommonCommands.hs
-- | Commands that work in any type of environment, either because they don't use the PGF , or because they are just documented here and implemented -- elsewhere module GF.Command.CommonCommands where import Data.List(sort) import Data.Char (isSpace) import GF.Command.CommandInfo import qualified Data.Map as Map import GF.Infra.SIO import GF.Infra.UseIO(writeUTF8File) import GF.Infra.Option(renameEncoding) import GF.System.Console(changeConsoleEncoding) import GF.System.Process ( isOpt , valStrOpts , prOpt ) import GF.Text.Pretty import GF.Text.Transliterations import GF.Text.Lexing(stringOp,opInEnv) import Data.Char (isSpace) import qualified PGF as H(showCId,showExpr,toATree,toTrie,Trie(..)) extend old new = Map.union (Map.fromList new) old -- Map.union is left-biased commonCommands :: (Monad m,MonadSIO m) => Map.Map String (CommandInfo m) commonCommands = fmap (mapCommandExec liftSIO) $ Map.fromList [ ("!", emptyCommandInfo { synopsis = "system command: escape to system shell", syntax = "! SYSTEMCOMMAND", examples = [ ("! ls *.gf", "list all GF files in the working directory") ] }), ("?", emptyCommandInfo { synopsis = "system pipe: send value from previous command to a system command", syntax = "? SYSTEMCOMMAND", examples = [ ("gt | l | ? wc", "generate, linearize, word-count") ] }), ("dc", emptyCommandInfo { longname = "define_command", syntax = "dc IDENT COMMANDLINE", synopsis = "define a command macro", explanation = unlines [ "Defines IDENT as macro for COMMANDLINE, until IDENT gets redefined.", "A call of the command has the form %IDENT. The command may take an", "argument, which in COMMANDLINE is marked as ?0. Both strings and", "trees can be arguments. Currently at most one argument is possible.", "This command must be a line of its own, and thus cannot be a part", "of a pipe." ] }), ("dt", emptyCommandInfo { longname = "define_tree", syntax = "dt IDENT (TREE | STRING | \"<\" COMMANDLINE)", synopsis = "define a tree or string macro", explanation = unlines [ "Defines IDENT as macro for TREE or STRING, until IDENT gets redefined.", "The defining value can also come from a command, preceded by \"<\".", "If the command gives many values, the first one is selected.", "A use of the macro has the form %IDENT. Currently this use cannot be", "a subtree of another tree. This command must be a line of its own", "and thus cannot be a part of a pipe." ], examples = [ mkEx ("dt ex \"hello world\" -- define ex as string"), mkEx ("dt ex UseN man_N -- define ex as string"), mkEx ("dt ex < p -cat=NP \"the man in the car\" -- define ex as parse result"), mkEx ("l -lang=LangSwe %ex | ps -to_utf8 -- linearize the tree ex") ] }), ("e", emptyCommandInfo { longname = "empty", synopsis = "empty the environment" }), ("eh", emptyCommandInfo { longname = "execute_history", syntax = "eh FILE", synopsis = "read commands from a file and execute them" }), ("ph", emptyCommandInfo { longname = "print_history", synopsis = "print command history", explanation = unlines [ "Prints the commands issued during the GF session.", "The result is readable by the eh command.", "The result can be used as a script when starting GF." ], examples = [ mkEx "ph | wf -file=foo.gfs -- save the history into a file" ] }), ("ps", emptyCommandInfo { longname = "put_string", syntax = "ps OPT? STRING", synopsis = "return a string, possibly processed with a function", explanation = unlines [ "Returns a string obtained from its argument string by applying", "string processing functions in the order given in the command line", "option list. Thus 'ps -f -g s' returns g (f s). Typical string processors", "are lexers and unlexers, but also character encoding conversions are possible.", "The unlexers preserve the division of their input to lines.", "To see transliteration tables, use command ut." ], examples = [ mkEx " l ( EAdd 3 4 ) | ps -code -- linearize code - like output " , mkEx "l (EAdd 3 4) | ps -unlexcode -- linearize code-like output", -- mkEx "ps -lexer=code | p -cat=Exp -- parse code-like input", mkEx "ps -lexcode | p -cat=Exp -- parse code-like input", mkEx "gr -cat=QCl | l | ps -bind -- linearization output from LangFin", mkEx "ps -to_devanagari \"A-p\" -- show Devanagari in UTF8 terminal", mkEx "rf -file=Hin.gf | ps -env=quotes -to_devanagari -- convert translit to UTF8", mkEx "rf -file=Ara.gf | ps -from_utf8 -env=quotes -from_arabic -- convert UTF8 to transliteration", mkEx "ps -to=chinese.trans \"abc\" -- apply transliteration defined in file chinese.trans", mkEx "ps -lexgreek \"a)gavoi` a)'nvrwpoi' tines*\" -- normalize ancient greek accentuation" ], exec = \opts x-> do let (os,fs) = optsAndFlags opts trans <- optTranslit opts case opts of _ | isOpt "lines" opts -> return $ fromStrings $ map (trans . stringOps (envFlag fs) (map prOpt os)) $ toStrings x _ | isOpt "paragraphs" opts -> return $ fromStrings $ map (trans . stringOps (envFlag fs) (map prOpt os)) $ toParagraphs $ toStrings x _ -> return ((fromString . trans . stringOps (envFlag fs) (map prOpt os) . toString) x), options = [ ("lines","apply the operation separately to each input line, returning a list of lines"), ("paragraphs","apply separately to each input paragraph (as separated by empty lines), returning a list of lines") ] ++ stringOpOptions, flags = [ ("env","apply in this environment only"), ("from","backward-apply transliteration defined in this file (format 'unicode translit' per line)"), ("to", "forward-apply transliteration defined in this file") ] }), ("q", emptyCommandInfo { longname = "quit", synopsis = "exit GF interpreter" }), ("r", emptyCommandInfo { longname = "reload", synopsis = "repeat the latest import command" }), ("se", emptyCommandInfo { longname = "set_encoding", synopsis = "set the encoding used in current terminal", syntax = "se ID", examples = [ mkEx "se cp1251 -- set encoding to cp1521", mkEx "se utf8 -- set encoding to utf8 (default)" ], needsTypeCheck = False, exec = \ opts ts -> case words (toString ts) of [c] -> do let cod = renameEncoding c restricted $ changeConsoleEncoding cod return void _ -> return (pipeMessage "se command not parsed") }), ("sp", emptyCommandInfo { longname = "system_pipe", synopsis = "send argument to a system command", syntax = "sp -command=\"SYSTEMCOMMAND\", alt. ? SYSTEMCOMMAND", exec = \opts arg -> do let syst = optComm opts -- ++ " " ++ tmpi let tmpi = " _ tmpi " --- let tmpo = " _ tmpo " restricted $ writeFile tmpi $ toString arg restrictedSystem $ syst + + " < " + + tmpi + + " > " + + tmpo fmap fromString $ restricted $ readFile tmpo , let tmpi = "_tmpi" --- let tmpo = "_tmpo" restricted $ writeFile tmpi $ toString arg restrictedSystem $ syst ++ " <" ++ tmpi ++ " >" ++ tmpo fmap fromString $ restricted $ readFile tmpo, -} fmap (fromStrings . lines) . restricted . readShellProcess syst . unlines . map (dropWhile (=='\n')) $ toStrings $ arg, flags = [ ("command","the system command applied to the argument") ], examples = [ mkEx "gt | l | ? wc -- generate trees, linearize, and count words" ] }), ("tt", emptyCommandInfo { longname = "to_trie", syntax = "to_trie", synopsis = "combine a list of trees into a trie", exec = \ _ -> return . fromString . trie . toExprs }), ("ut", emptyCommandInfo { longname = "unicode_table", synopsis = "show a transliteration table for a unicode character set", exec = \opts _ -> do let t = concatMap prOpt (take 1 opts) let out = maybe "no such transliteration" characterTable $ transliteration t return $ fromString out, options = transliterationPrintNames }), ("wf", emptyCommandInfo { longname = "write_file", synopsis = "send string or tree to a file", exec = \opts arg-> do let file = valStrOpts "file" "_gftmp" opts if isOpt "append" opts then restricted $ appendFile file (toLines arg) else restricted $ writeUTF8File file (toLines arg) return void, options = [ ("append","append to file, instead of overwriting it") ], flags = [("file","the output filename")] }) ] where optComm opts = valStrOpts "command" "" opts optTranslit opts = case (valStrOpts "to" "" opts, valStrOpts "from" "" opts) of ("","") -> return id (file,"") -> do src <- restricted $ readFile file return $ transliterateWithFile file src False (_,file) -> do src <- restricted $ readFile file return $ transliterateWithFile file src True stringOps menv opts s = foldr (menvop . app) s (reverse opts) where app f = maybe id id (stringOp (const False) f) menvop op = maybe op (\ (b,e) -> opInEnv b e op) menv envFlag fs = case valStrOpts "env" "global" fs of "quotes" -> Just ("\"","\"") _ -> Nothing stringOpOptions = sort $ [ ("bind","bind tokens separated by Prelude.BIND, i.e. &+"), ("chars","lexer that makes every non-space character a token"), ("from_cp1251","decode from cp1251 (Cyrillic used in Bulgarian resource)"), ("from_utf8","decode from utf8 (default)"), ("lextext","text-like lexer"), ("lexcode","code-like lexer"), ("lexmixed","mixture of text and code, as in LaTeX (code between $...$, \\(...)\\, \\[...\\])"), ("lexgreek","lexer normalizing ancient Greek accentuation"), ("lexgreek2","lexer normalizing ancient Greek accentuation for text with vowel length annotations"), ("to_cp1251","encode to cp1251 (Cyrillic used in Bulgarian resource)"), ("to_html","wrap in a html file with linebreaks"), ("to_utf8","encode to utf8 (default)"), ("unlextext","text-like unlexer"), ("unlexcode","code-like unlexer"), ("unlexmixed","mixture of text and code (code between $...$, \\(...)\\, \\[...\\])"), ("unchars","unlexer that puts no spaces between tokens"), ("unlexgreek","unlexer de-normalizing ancient Greek accentuation"), ("unwords","unlexer that puts a single space between tokens (default)"), ("words","lexer that assumes tokens separated by spaces (default)") ] ++ concat [ [("from_" ++ p, "from unicode to GF " ++ n ++ " transliteration"), ("to_" ++ p, "from GF " ++ n ++ " transliteration to unicode")] | (p,n) <- transliterationPrintNames] trie = render . pptss . H.toTrie . map H.toATree where pptss [ts] = "*"<+>nest 2 (ppts ts) pptss tss = vcat [i<+>nest 2 (ppts ts)|(i,ts)<-zip [(1::Int)..] tss] ppts = vcat . map ppt ppt t = case t of H.Oth e -> pp (H.showExpr [] e) H.Ap f [[]] -> pp (H.showCId f) H.Ap f tss -> H.showCId f $$ nest 2 (pptss tss) -- ** Converting command input toString = unwords . toStrings toLines = unlines . toStrings toParagraphs = map (unwords . words) . toParas where toParas ls = case break (all isSpace) ls of ([],[]) -> [] ([],_:ll) -> toParas ll (l, []) -> [unwords l] (l, _:ll) -> unwords l : toParas ll
null
https://raw.githubusercontent.com/GrammaticalFramework/gf-core/1b66bf2773b0feda528d3b22fbaf06227a51b864/src/compiler/GF/Command/CommonCommands.hs
haskell
| Commands that work in any type of environment, either because they don't elsewhere Map.union is left-biased mkEx "ps -lexer=code | p -cat=Exp -- parse code-like input", ++ " " ++ tmpi - - ** Converting command input
use the PGF , or because they are just documented here and implemented module GF.Command.CommonCommands where import Data.List(sort) import Data.Char (isSpace) import GF.Command.CommandInfo import qualified Data.Map as Map import GF.Infra.SIO import GF.Infra.UseIO(writeUTF8File) import GF.Infra.Option(renameEncoding) import GF.System.Console(changeConsoleEncoding) import GF.System.Process ( isOpt , valStrOpts , prOpt ) import GF.Text.Pretty import GF.Text.Transliterations import GF.Text.Lexing(stringOp,opInEnv) import Data.Char (isSpace) import qualified PGF as H(showCId,showExpr,toATree,toTrie,Trie(..)) commonCommands :: (Monad m,MonadSIO m) => Map.Map String (CommandInfo m) commonCommands = fmap (mapCommandExec liftSIO) $ Map.fromList [ ("!", emptyCommandInfo { synopsis = "system command: escape to system shell", syntax = "! SYSTEMCOMMAND", examples = [ ("! ls *.gf", "list all GF files in the working directory") ] }), ("?", emptyCommandInfo { synopsis = "system pipe: send value from previous command to a system command", syntax = "? SYSTEMCOMMAND", examples = [ ("gt | l | ? wc", "generate, linearize, word-count") ] }), ("dc", emptyCommandInfo { longname = "define_command", syntax = "dc IDENT COMMANDLINE", synopsis = "define a command macro", explanation = unlines [ "Defines IDENT as macro for COMMANDLINE, until IDENT gets redefined.", "A call of the command has the form %IDENT. The command may take an", "argument, which in COMMANDLINE is marked as ?0. Both strings and", "trees can be arguments. Currently at most one argument is possible.", "This command must be a line of its own, and thus cannot be a part", "of a pipe." ] }), ("dt", emptyCommandInfo { longname = "define_tree", syntax = "dt IDENT (TREE | STRING | \"<\" COMMANDLINE)", synopsis = "define a tree or string macro", explanation = unlines [ "Defines IDENT as macro for TREE or STRING, until IDENT gets redefined.", "The defining value can also come from a command, preceded by \"<\".", "If the command gives many values, the first one is selected.", "A use of the macro has the form %IDENT. Currently this use cannot be", "a subtree of another tree. This command must be a line of its own", "and thus cannot be a part of a pipe." ], examples = [ mkEx ("dt ex \"hello world\" -- define ex as string"), mkEx ("dt ex UseN man_N -- define ex as string"), mkEx ("dt ex < p -cat=NP \"the man in the car\" -- define ex as parse result"), mkEx ("l -lang=LangSwe %ex | ps -to_utf8 -- linearize the tree ex") ] }), ("e", emptyCommandInfo { longname = "empty", synopsis = "empty the environment" }), ("eh", emptyCommandInfo { longname = "execute_history", syntax = "eh FILE", synopsis = "read commands from a file and execute them" }), ("ph", emptyCommandInfo { longname = "print_history", synopsis = "print command history", explanation = unlines [ "Prints the commands issued during the GF session.", "The result is readable by the eh command.", "The result can be used as a script when starting GF." ], examples = [ mkEx "ph | wf -file=foo.gfs -- save the history into a file" ] }), ("ps", emptyCommandInfo { longname = "put_string", syntax = "ps OPT? STRING", synopsis = "return a string, possibly processed with a function", explanation = unlines [ "Returns a string obtained from its argument string by applying", "string processing functions in the order given in the command line", "option list. Thus 'ps -f -g s' returns g (f s). Typical string processors", "are lexers and unlexers, but also character encoding conversions are possible.", "The unlexers preserve the division of their input to lines.", "To see transliteration tables, use command ut." ], examples = [ mkEx " l ( EAdd 3 4 ) | ps -code -- linearize code - like output " , mkEx "l (EAdd 3 4) | ps -unlexcode -- linearize code-like output", mkEx "ps -lexcode | p -cat=Exp -- parse code-like input", mkEx "gr -cat=QCl | l | ps -bind -- linearization output from LangFin", mkEx "ps -to_devanagari \"A-p\" -- show Devanagari in UTF8 terminal", mkEx "rf -file=Hin.gf | ps -env=quotes -to_devanagari -- convert translit to UTF8", mkEx "rf -file=Ara.gf | ps -from_utf8 -env=quotes -from_arabic -- convert UTF8 to transliteration", mkEx "ps -to=chinese.trans \"abc\" -- apply transliteration defined in file chinese.trans", mkEx "ps -lexgreek \"a)gavoi` a)'nvrwpoi' tines*\" -- normalize ancient greek accentuation" ], exec = \opts x-> do let (os,fs) = optsAndFlags opts trans <- optTranslit opts case opts of _ | isOpt "lines" opts -> return $ fromStrings $ map (trans . stringOps (envFlag fs) (map prOpt os)) $ toStrings x _ | isOpt "paragraphs" opts -> return $ fromStrings $ map (trans . stringOps (envFlag fs) (map prOpt os)) $ toParagraphs $ toStrings x _ -> return ((fromString . trans . stringOps (envFlag fs) (map prOpt os) . toString) x), options = [ ("lines","apply the operation separately to each input line, returning a list of lines"), ("paragraphs","apply separately to each input paragraph (as separated by empty lines), returning a list of lines") ] ++ stringOpOptions, flags = [ ("env","apply in this environment only"), ("from","backward-apply transliteration defined in this file (format 'unicode translit' per line)"), ("to", "forward-apply transliteration defined in this file") ] }), ("q", emptyCommandInfo { longname = "quit", synopsis = "exit GF interpreter" }), ("r", emptyCommandInfo { longname = "reload", synopsis = "repeat the latest import command" }), ("se", emptyCommandInfo { longname = "set_encoding", synopsis = "set the encoding used in current terminal", syntax = "se ID", examples = [ mkEx "se cp1251 -- set encoding to cp1521", mkEx "se utf8 -- set encoding to utf8 (default)" ], needsTypeCheck = False, exec = \ opts ts -> case words (toString ts) of [c] -> do let cod = renameEncoding c restricted $ changeConsoleEncoding cod return void _ -> return (pipeMessage "se command not parsed") }), ("sp", emptyCommandInfo { longname = "system_pipe", synopsis = "send argument to a system command", syntax = "sp -command=\"SYSTEMCOMMAND\", alt. ? SYSTEMCOMMAND", exec = \opts arg -> do let tmpo = " _ tmpo " restricted $ writeFile tmpi $ toString arg restrictedSystem $ syst + + " < " + + tmpi + + " > " + + tmpo fmap fromString $ restricted $ readFile tmpo , let tmpo = "_tmpo" restricted $ writeFile tmpi $ toString arg restrictedSystem $ syst ++ " <" ++ tmpi ++ " >" ++ tmpo fmap fromString $ restricted $ readFile tmpo, -} fmap (fromStrings . lines) . restricted . readShellProcess syst . unlines . map (dropWhile (=='\n')) $ toStrings $ arg, flags = [ ("command","the system command applied to the argument") ], examples = [ mkEx "gt | l | ? wc -- generate trees, linearize, and count words" ] }), ("tt", emptyCommandInfo { longname = "to_trie", syntax = "to_trie", synopsis = "combine a list of trees into a trie", exec = \ _ -> return . fromString . trie . toExprs }), ("ut", emptyCommandInfo { longname = "unicode_table", synopsis = "show a transliteration table for a unicode character set", exec = \opts _ -> do let t = concatMap prOpt (take 1 opts) let out = maybe "no such transliteration" characterTable $ transliteration t return $ fromString out, options = transliterationPrintNames }), ("wf", emptyCommandInfo { longname = "write_file", synopsis = "send string or tree to a file", exec = \opts arg-> do let file = valStrOpts "file" "_gftmp" opts if isOpt "append" opts then restricted $ appendFile file (toLines arg) else restricted $ writeUTF8File file (toLines arg) return void, options = [ ("append","append to file, instead of overwriting it") ], flags = [("file","the output filename")] }) ] where optComm opts = valStrOpts "command" "" opts optTranslit opts = case (valStrOpts "to" "" opts, valStrOpts "from" "" opts) of ("","") -> return id (file,"") -> do src <- restricted $ readFile file return $ transliterateWithFile file src False (_,file) -> do src <- restricted $ readFile file return $ transliterateWithFile file src True stringOps menv opts s = foldr (menvop . app) s (reverse opts) where app f = maybe id id (stringOp (const False) f) menvop op = maybe op (\ (b,e) -> opInEnv b e op) menv envFlag fs = case valStrOpts "env" "global" fs of "quotes" -> Just ("\"","\"") _ -> Nothing stringOpOptions = sort $ [ ("bind","bind tokens separated by Prelude.BIND, i.e. &+"), ("chars","lexer that makes every non-space character a token"), ("from_cp1251","decode from cp1251 (Cyrillic used in Bulgarian resource)"), ("from_utf8","decode from utf8 (default)"), ("lextext","text-like lexer"), ("lexcode","code-like lexer"), ("lexmixed","mixture of text and code, as in LaTeX (code between $...$, \\(...)\\, \\[...\\])"), ("lexgreek","lexer normalizing ancient Greek accentuation"), ("lexgreek2","lexer normalizing ancient Greek accentuation for text with vowel length annotations"), ("to_cp1251","encode to cp1251 (Cyrillic used in Bulgarian resource)"), ("to_html","wrap in a html file with linebreaks"), ("to_utf8","encode to utf8 (default)"), ("unlextext","text-like unlexer"), ("unlexcode","code-like unlexer"), ("unlexmixed","mixture of text and code (code between $...$, \\(...)\\, \\[...\\])"), ("unchars","unlexer that puts no spaces between tokens"), ("unlexgreek","unlexer de-normalizing ancient Greek accentuation"), ("unwords","unlexer that puts a single space between tokens (default)"), ("words","lexer that assumes tokens separated by spaces (default)") ] ++ concat [ [("from_" ++ p, "from unicode to GF " ++ n ++ " transliteration"), ("to_" ++ p, "from GF " ++ n ++ " transliteration to unicode")] | (p,n) <- transliterationPrintNames] trie = render . pptss . H.toTrie . map H.toATree where pptss [ts] = "*"<+>nest 2 (ppts ts) pptss tss = vcat [i<+>nest 2 (ppts ts)|(i,ts)<-zip [(1::Int)..] tss] ppts = vcat . map ppt ppt t = case t of H.Oth e -> pp (H.showExpr [] e) H.Ap f [[]] -> pp (H.showCId f) H.Ap f tss -> H.showCId f $$ nest 2 (pptss tss) toString = unwords . toStrings toLines = unlines . toStrings toParagraphs = map (unwords . words) . toParas where toParas ls = case break (all isSpace) ls of ([],[]) -> [] ([],_:ll) -> toParas ll (l, []) -> [unwords l] (l, _:ll) -> unwords l : toParas ll
f572970f2cc43eaf5b1662cf3d9563bd590448635682679c30ddd18e6511c1c6
shayan-najd/NativeMetaprogramming
T9178DataType.hs
module T9178DataType where data T9178_Type
null
https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/warnings/should_compile/T9178DataType.hs
haskell
module T9178DataType where data T9178_Type
07df68400e52d589d5a126a919174335c39af5c0d23af15819f4daa7ead6dafe
j14159/erlang-and-thrift
example_client.erl
-module(example_client). %% need this to get access to the records representing Thrift message %% defined in thrift/example.thrift: -include("example_constants.hrl"). -export([request/4]). request(Host, Port, Id, Msg) -> Req = #message{id = Id, text = Msg}, {ok, Client} = thrift_client_util:new(Host, Port, exampleService_thrift, []), %% "hello" function per our service definition in thrift/example.thrift: {ClientAgain, {ok, Response}} = thrift_client:call(Client, hello, [Req]), thrift_client:close(ClientAgain), Response.
null
https://raw.githubusercontent.com/j14159/erlang-and-thrift/b87a15844559c5fd4eff4d96d15e9c40514fae28/src/example_client.erl
erlang
need this to get access to the records representing Thrift message defined in thrift/example.thrift: "hello" function per our service definition in thrift/example.thrift:
-module(example_client). -include("example_constants.hrl"). -export([request/4]). request(Host, Port, Id, Msg) -> Req = #message{id = Id, text = Msg}, {ok, Client} = thrift_client_util:new(Host, Port, exampleService_thrift, []), {ClientAgain, {ok, Response}} = thrift_client:call(Client, hello, [Req]), thrift_client:close(ClientAgain), Response.
f18cb72840699070b3b104face4c3cff0757107f3036fd8e5222c8c6a5550b36
damn/cdq
ns_without_deps.clj
(ns game.ns-without-deps (:require game.music game.serialization game.monster.monsters game.item.instance-impl game.player.skill.learnable-impl game.components.body-render)) other solution : ( initialize ( require ' the - impl - ns ) ) dort wo . ; doesnt work with compile, so here.
null
https://raw.githubusercontent.com/damn/cdq/5093dbdba91c445e403f53ce96ead05d5ed8262b/src/game/ns_without_deps.clj
clojure
doesnt work with compile, so here.
(ns game.ns-without-deps (:require game.music game.serialization game.monster.monsters game.item.instance-impl game.player.skill.learnable-impl game.components.body-render)) other solution : ( initialize ( require ' the - impl - ns ) ) dort wo .
d14a1a2f3c2f044ea21e75f2cccb42a3b975b830c69e34d65fd52a5db50a713d
fused-effects/fused-effects
Interpret.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # -- | Provides an 'InterpretC' carrier capable of interpreting an arbitrary effect using a passed-in higher order function to interpret that effect. This is suitable for prototyping new effects quickly. module Control.Carrier.Interpret ( -- * Interpret carrier runInterpret , runInterpretState , InterpretC(InterpretC) , Reifies , Interpreter -- * Re-exports , Algebra , Has , run ) where import Control.Algebra import Control.Applicative (Alternative) import Control.Carrier.State.Strict import Control.Monad (MonadPlus) import Control.Monad.Fail as Fail import Control.Monad.Fix import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.IO.Unlift (MonadUnliftIO) import Data.Functor.Const (Const(..)) import Data.Kind (Type) import Unsafe.Coerce (unsafeCoerce) | An @Interpreter@ is a function that interprets effects described by @sig@ into the carrier monad @m@. newtype Interpreter sig m = Interpreter { runInterpreter :: forall ctx n s x . Functor ctx => Handler ctx n (InterpretC s sig m) -> sig n x -> ctx () -> InterpretC s sig m (ctx x) } class Reifies s a | s -> a where reflect :: Const a s data Skolem | @Magic@ captures the GHC implementation detail of how single method type classes are implemented . newtype Magic a r = Magic (Reifies Skolem a => Const r Skolem) -- For more information on this technique, see the @reflection@ library. We use the formulation described in for better inlining. -- Essentially we can view @k@ as internally a function of type @Reifies s a - > Tagged s r@ , which we can again view as just @a - > Tagged s r@ through @unsafeCoerce@. After this coercion , we just apply the function to reify :: a -> (forall s . Reifies s a => Const r s) -> r reify a k = unsafeCoerce (Magic k) a -- | Interpret an effect using a higher-order function. -- Note that due to the higher - rank type , you have to use either ' $ ' or explicit application when applying this interpreter . That is , you will need to write @runInterpret f ( runInterpret g myPrgram)@ or @runInterpret f $ runInterpret g $ myProgram@. If you try and write @runInterpret f . , you will unfortunately get a rather scary type error ! -- @since 1.0.0.0 runInterpret :: (forall ctx n x . Functor ctx => Handler ctx n m -> eff n x -> ctx () -> m (ctx x)) -> (forall s . Reifies s (Interpreter eff m) => InterpretC s eff m a) -> m a runInterpret f m = reify (Interpreter (\ hdl sig -> InterpretC . f (runInterpretC . hdl) sig)) (go m) where go :: InterpretC s eff m x -> Const (m x) s go (InterpretC m) = Const m # INLINE runInterpret # -- | Interpret an effect using a higher-order function with some state variable. -- @since 1.0.0.0 runInterpretState :: (forall ctx n x . Functor ctx => Handler ctx n (StateC s m) -> eff n x -> s -> ctx () -> m (s, ctx x)) -> s -> (forall t . Reifies t (Interpreter eff (StateC s m)) => InterpretC t eff (StateC s m) a) -> m (s, a) runInterpretState handler state m = runState state $ runInterpret (\ hdl sig ctx -> StateC (flip (handler hdl sig) ctx)) m # INLINE runInterpretState # | @since 1.0.0.0 newtype InterpretC s (sig :: (Type -> Type) -> (Type -> Type)) m a = InterpretC { runInterpretC :: m a } deriving (Alternative, Applicative, Functor, Monad, Fail.MonadFail, MonadFix, MonadIO, MonadPlus, MonadUnliftIO) instance MonadTrans (InterpretC s sig) where lift = InterpretC # INLINE lift # instance (Reifies s (Interpreter eff m), Algebra sig m) => Algebra (eff :+: sig) (InterpretC s eff m) where alg hdl = \case L eff -> runInterpreter (getConst (reflect @s)) hdl eff R other -> InterpretC . alg (runInterpretC . hdl) other # INLINE alg #
null
https://raw.githubusercontent.com/fused-effects/fused-effects/eca98eff01d7507b5259002f8414a7594024b919/src/Control/Carrier/Interpret.hs
haskell
# LANGUAGE RankNTypes # | Provides an 'InterpretC' carrier capable of interpreting an arbitrary effect using a passed-in higher order function to interpret that effect. This is suitable for prototyping new effects quickly. * Interpret carrier * Re-exports For more information on this technique, see the @reflection@ library. We use the formulation described in for better inlining. | Interpret an effect using a higher-order function. | Interpret an effect using a higher-order function with some state variable.
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Control.Carrier.Interpret runInterpret , runInterpretState , InterpretC(InterpretC) , Reifies , Interpreter , Algebra , Has , run ) where import Control.Algebra import Control.Applicative (Alternative) import Control.Carrier.State.Strict import Control.Monad (MonadPlus) import Control.Monad.Fail as Fail import Control.Monad.Fix import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.IO.Unlift (MonadUnliftIO) import Data.Functor.Const (Const(..)) import Data.Kind (Type) import Unsafe.Coerce (unsafeCoerce) | An @Interpreter@ is a function that interprets effects described by @sig@ into the carrier monad @m@. newtype Interpreter sig m = Interpreter { runInterpreter :: forall ctx n s x . Functor ctx => Handler ctx n (InterpretC s sig m) -> sig n x -> ctx () -> InterpretC s sig m (ctx x) } class Reifies s a | s -> a where reflect :: Const a s data Skolem | @Magic@ captures the GHC implementation detail of how single method type classes are implemented . newtype Magic a r = Magic (Reifies Skolem a => Const r Skolem) Essentially we can view @k@ as internally a function of type @Reifies s a - > Tagged s r@ , which we can again view as just @a - > Tagged s r@ through @unsafeCoerce@. After this coercion , we just apply the function to reify :: a -> (forall s . Reifies s a => Const r s) -> r reify a k = unsafeCoerce (Magic k) a Note that due to the higher - rank type , you have to use either ' $ ' or explicit application when applying this interpreter . That is , you will need to write @runInterpret f ( runInterpret g myPrgram)@ or @runInterpret f $ runInterpret g $ myProgram@. If you try and write @runInterpret f . , you will unfortunately get a rather scary type error ! @since 1.0.0.0 runInterpret :: (forall ctx n x . Functor ctx => Handler ctx n m -> eff n x -> ctx () -> m (ctx x)) -> (forall s . Reifies s (Interpreter eff m) => InterpretC s eff m a) -> m a runInterpret f m = reify (Interpreter (\ hdl sig -> InterpretC . f (runInterpretC . hdl) sig)) (go m) where go :: InterpretC s eff m x -> Const (m x) s go (InterpretC m) = Const m # INLINE runInterpret # @since 1.0.0.0 runInterpretState :: (forall ctx n x . Functor ctx => Handler ctx n (StateC s m) -> eff n x -> s -> ctx () -> m (s, ctx x)) -> s -> (forall t . Reifies t (Interpreter eff (StateC s m)) => InterpretC t eff (StateC s m) a) -> m (s, a) runInterpretState handler state m = runState state $ runInterpret (\ hdl sig ctx -> StateC (flip (handler hdl sig) ctx)) m # INLINE runInterpretState # | @since 1.0.0.0 newtype InterpretC s (sig :: (Type -> Type) -> (Type -> Type)) m a = InterpretC { runInterpretC :: m a } deriving (Alternative, Applicative, Functor, Monad, Fail.MonadFail, MonadFix, MonadIO, MonadPlus, MonadUnliftIO) instance MonadTrans (InterpretC s sig) where lift = InterpretC # INLINE lift # instance (Reifies s (Interpreter eff m), Algebra sig m) => Algebra (eff :+: sig) (InterpretC s eff m) where alg hdl = \case L eff -> runInterpreter (getConst (reflect @s)) hdl eff R other -> InterpretC . alg (runInterpretC . hdl) other # INLINE alg #
1df288a7d42da238ef94e37d9a35742ca4a7497905410af54d6735b6f2ffff92
gedge-platform/gs-broker
jose_curve25519_libdecaf.erl
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- %% vim: ts=4 sw=4 ft=erlang noet %%%------------------------------------------------------------------- @author < > 2014 - 2016 , %%% @doc %%% %%% @end Created : 01 Mar 2016 by < > %%%------------------------------------------------------------------- -module(jose_curve25519_libdecaf). -behaviour(jose_curve25519). %% jose_curve25519 callbacks -export([eddsa_keypair/0]). -export([eddsa_keypair/1]). -export([eddsa_secret_to_public/1]). -export([ed25519_sign/2]). -export([ed25519_verify/3]). -export([ed25519ph_sign/2]). -export([ed25519ph_verify/3]). -export([x25519_keypair/0]). -export([x25519_keypair/1]). -export([x25519_secret_to_public/1]). -export([x25519_shared_secret/2]). %%==================================================================== %% jose_curve25519 callbacks %%==================================================================== EdDSA eddsa_keypair() -> libdecaf_curve25519:eddsa_keypair(). eddsa_keypair(Seed) -> libdecaf_curve25519:eddsa_keypair(Seed). eddsa_secret_to_public(SecretKey) -> libdecaf_curve25519:eddsa_secret_to_pk(SecretKey). % Ed25519 ed25519_sign(Message, SecretKey) -> libdecaf_curve25519:ed25519_sign(Message, SecretKey). ed25519_verify(Signature, Message, PublicKey) -> libdecaf_curve25519:ed25519_verify(Signature, Message, PublicKey). % Ed25519ph ed25519ph_sign(Message, SecretKey) -> libdecaf_curve25519:ed25519ph_sign(Message, SecretKey). ed25519ph_verify(Signature, Message, PublicKey) -> libdecaf_curve25519:ed25519ph_verify(Signature, Message, PublicKey). % X25519 x25519_keypair() -> libdecaf_curve25519:x25519_keypair(). x25519_keypair(Seed) -> libdecaf_curve25519:x25519_keypair(Seed). x25519_secret_to_public(SecretKey) -> libdecaf_curve25519:x25519(SecretKey). x25519_shared_secret(MySecretKey, YourPublicKey) -> libdecaf_curve25519:x25519(MySecretKey, YourPublicKey).
null
https://raw.githubusercontent.com/gedge-platform/gs-broker/c4c1ad39e563537d46553eae1363317cf75aff26/broker-server/deps/jose/src/jose_curve25519_libdecaf.erl
erlang
vim: ts=4 sw=4 ft=erlang noet ------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- jose_curve25519 callbacks ==================================================================== jose_curve25519 callbacks ==================================================================== Ed25519 Ed25519ph X25519
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- @author < > 2014 - 2016 , Created : 01 Mar 2016 by < > -module(jose_curve25519_libdecaf). -behaviour(jose_curve25519). -export([eddsa_keypair/0]). -export([eddsa_keypair/1]). -export([eddsa_secret_to_public/1]). -export([ed25519_sign/2]). -export([ed25519_verify/3]). -export([ed25519ph_sign/2]). -export([ed25519ph_verify/3]). -export([x25519_keypair/0]). -export([x25519_keypair/1]). -export([x25519_secret_to_public/1]). -export([x25519_shared_secret/2]). EdDSA eddsa_keypair() -> libdecaf_curve25519:eddsa_keypair(). eddsa_keypair(Seed) -> libdecaf_curve25519:eddsa_keypair(Seed). eddsa_secret_to_public(SecretKey) -> libdecaf_curve25519:eddsa_secret_to_pk(SecretKey). ed25519_sign(Message, SecretKey) -> libdecaf_curve25519:ed25519_sign(Message, SecretKey). ed25519_verify(Signature, Message, PublicKey) -> libdecaf_curve25519:ed25519_verify(Signature, Message, PublicKey). ed25519ph_sign(Message, SecretKey) -> libdecaf_curve25519:ed25519ph_sign(Message, SecretKey). ed25519ph_verify(Signature, Message, PublicKey) -> libdecaf_curve25519:ed25519ph_verify(Signature, Message, PublicKey). x25519_keypair() -> libdecaf_curve25519:x25519_keypair(). x25519_keypair(Seed) -> libdecaf_curve25519:x25519_keypair(Seed). x25519_secret_to_public(SecretKey) -> libdecaf_curve25519:x25519(SecretKey). x25519_shared_secret(MySecretKey, YourPublicKey) -> libdecaf_curve25519:x25519(MySecretKey, YourPublicKey).
8f12ad06306dd35d9ca63173a670c0cfc74311573711ea153fb3deb49926624c
input-output-hk/project-icarus-importer
Translate.hs
# LANGUAGE GeneralizedNewtypeDeriving # module UTxO.Translate ( * context for the translation from the DSL to Cardano TranslateT , Translate , runTranslateT , runTranslate , runTranslateNoErrors , withConfig , mapTranslateErrors , catchTranslateErrors , catchSomeTranslateErrors -- * Convenience wrappers , translateFirstSlot , translateNextSlot , translateGenesisHeader -- * Interface to the verifier , verify , verifyBlocksPrefix -- * Convenience re-exports , MonadError(..) , MonadGState(..) ) where import Control.Exception (throw) import Control.Monad.Except import Data.Constraint (Dict (..)) import Universum import Pos.Block.Error import Pos.Block.Types import Pos.Core import Pos.DB.Class (MonadGState (..)) import Pos.Txp.Toil import Pos.Update import Pos.Util.Chrono import Util.Validated import UTxO.Context import UTxO.Verify (Verify) import qualified UTxO.Verify as Verify ------------------------------------------------------------------------------ Testing infrastructure from cardano - sl - core The genesis block comes from defaultTestConf , which in turn uses configuration.yaml . It is specified by a ' GenesisSpec ' . ------------------------------------------------------------------------------ Testing infrastructure from cardano-sl-core The genesis block comes from defaultTestConf, which in turn uses configuration.yaml. It is specified by a 'GenesisSpec'. -------------------------------------------------------------------------------} import Test.Pos.Configuration (withDefConfiguration, withDefUpdateConfiguration) {------------------------------------------------------------------------------- Translation monad The translation provides access to the translation context as well as some dictionaries so that we can lift Cardano operations to the 'Translate' monad. (Eventually we may wish to do this differently.) -------------------------------------------------------------------------------} data TranslateEnv = TranslateEnv { teContext :: TransCtxt , teConfig :: Dict HasConfiguration , teUpdate :: Dict HasUpdateConfiguration } newtype TranslateT e m a = TranslateT { unTranslateT :: ExceptT e (ReaderT TranslateEnv m) a } deriving ( Functor , Applicative , Monad , MonadError e , MonadIO ) instance MonadTrans (TranslateT e) where lift = TranslateT . lift . lift type Translate e = TranslateT e Identity instance Monad m => MonadReader TransCtxt (TranslateT e m) where ask = TranslateT $ asks teContext local f = TranslateT . local f' . unTranslateT where f' env = env { teContext = f (teContext env) } -- | Right now this always returns the genesis policy instance Monad m => MonadGState (TranslateT e m) where gsAdoptedBVData = withConfig $ return genesisBlockVersionData -- | Run translation -- -- NOTE: This uses the default test configuration, and throws any errors as -- pure exceptions. runTranslateT :: Monad m => Exception e => TranslateT e m a -> m a runTranslateT (TranslateT ta) = withDefConfiguration $ withDefUpdateConfiguration $ let env :: TranslateEnv env = TranslateEnv { teContext = initContext initCardanoContext , teConfig = Dict , teUpdate = Dict } in do ma <- runReaderT (runExceptT ta) env case ma of Left e -> throw e Right a -> return a -- | Specialization of 'runTranslateT' runTranslate :: Exception e => Translate e a -> a runTranslate = runIdentity . runTranslateT | Specialised form of ' runTranslate ' when there can be no errors runTranslateNoErrors :: Translate Void a -> a runTranslateNoErrors = runTranslate -- | Lift functions that want the configuration as type class constraints withConfig :: Monad m => ((HasConfiguration, HasUpdateConfiguration) => TranslateT e m a) -> TranslateT e m a withConfig f = do Dict <- TranslateT $ asks teConfig Dict <- TranslateT $ asks teUpdate f -- | Map errors mapTranslateErrors :: Functor m => (e -> e') -> TranslateT e m a -> TranslateT e' m a mapTranslateErrors f (TranslateT ma) = TranslateT $ withExceptT f ma -- | Catch and return errors catchTranslateErrors :: Functor m => TranslateT e m a -> TranslateT e' m (Either e a) catchTranslateErrors (TranslateT (ExceptT (ReaderT ma))) = TranslateT $ ExceptT $ ReaderT $ \env -> fmap Right (ma env) catchSomeTranslateErrors :: Monad m => TranslateT (Either e e') m a -> TranslateT e m (Either e' a) catchSomeTranslateErrors act = do ma <- catchTranslateErrors act case ma of Left (Left e) -> throwError e Left (Right e') -> return $ Left e' Right a -> return $ Right a {------------------------------------------------------------------------------- Convenience wrappers -------------------------------------------------------------------------------} | Slot ID of the first block translateFirstSlot :: Monad m => TranslateT Text m SlotId translateFirstSlot = withConfig $ do SlotId 0 <$> mkLocalSlotIndex 0 -- | Increment slot ID -- -- TODO: Surely a function like this must already exist somewhere? translateNextSlot :: Monad m => SlotId -> TranslateT Text m SlotId translateNextSlot (SlotId epoch lsi) = withConfig $ case addLocalSlotIndex 1 lsi of Just lsi' -> return $ SlotId epoch lsi' Nothing -> SlotId (epoch + 1) <$> mkLocalSlotIndex 0 | Genesis block header translateGenesisHeader :: Monad m => TranslateT e m GenesisBlockHeader translateGenesisHeader = view gbHeader <$> asks (ccBlock0 . tcCardano) {------------------------------------------------------------------------------- Interface to the verifier -------------------------------------------------------------------------------} -- | Run the verifier verify :: Monad m => (HasConfiguration => Verify e a) -> TranslateT e' m (Validated e (a, Utxo)) verify ma = withConfig $ do utxo <- asks (ccUtxo . tcCardano) return $ validatedFromEither (Verify.verify utxo ma) -- | Wrapper around 'UTxO.Verify.verifyBlocksPrefix' verifyBlocksPrefix :: Monad m => OldestFirst NE Block -> TranslateT e' m (Validated VerifyBlocksException (OldestFirst NE Undo, Utxo)) verifyBlocksPrefix blocks = do CardanoContext{..} <- asks tcCardano let tip = ccHash0 currentSlot = Nothing verify $ Verify.verifyBlocksPrefix tip currentSlot TODO : May not be necessary to pass this if we start from genesis (OldestFirst []) -- TODO: LastBlkSlots. Unsure about the required value or its effect blocks
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/test/unit/UTxO/Translate.hs
haskell
* Convenience wrappers * Interface to the verifier * Convenience re-exports ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} ------------------------------------------------------------------------------ Translation monad The translation provides access to the translation context as well as some dictionaries so that we can lift Cardano operations to the 'Translate' monad. (Eventually we may wish to do this differently.) ------------------------------------------------------------------------------ | Right now this always returns the genesis policy | Run translation NOTE: This uses the default test configuration, and throws any errors as pure exceptions. | Specialization of 'runTranslateT' | Lift functions that want the configuration as type class constraints | Map errors | Catch and return errors ------------------------------------------------------------------------------ Convenience wrappers ------------------------------------------------------------------------------ | Increment slot ID TODO: Surely a function like this must already exist somewhere? ------------------------------------------------------------------------------ Interface to the verifier ------------------------------------------------------------------------------ | Run the verifier | Wrapper around 'UTxO.Verify.verifyBlocksPrefix' TODO: LastBlkSlots. Unsure about the required value or its effect
# LANGUAGE GeneralizedNewtypeDeriving # module UTxO.Translate ( * context for the translation from the DSL to Cardano TranslateT , Translate , runTranslateT , runTranslate , runTranslateNoErrors , withConfig , mapTranslateErrors , catchTranslateErrors , catchSomeTranslateErrors , translateFirstSlot , translateNextSlot , translateGenesisHeader , verify , verifyBlocksPrefix , MonadError(..) , MonadGState(..) ) where import Control.Exception (throw) import Control.Monad.Except import Data.Constraint (Dict (..)) import Universum import Pos.Block.Error import Pos.Block.Types import Pos.Core import Pos.DB.Class (MonadGState (..)) import Pos.Txp.Toil import Pos.Update import Pos.Util.Chrono import Util.Validated import UTxO.Context import UTxO.Verify (Verify) import qualified UTxO.Verify as Verify Testing infrastructure from cardano - sl - core The genesis block comes from defaultTestConf , which in turn uses configuration.yaml . It is specified by a ' GenesisSpec ' . Testing infrastructure from cardano-sl-core The genesis block comes from defaultTestConf, which in turn uses configuration.yaml. It is specified by a 'GenesisSpec'. import Test.Pos.Configuration (withDefConfiguration, withDefUpdateConfiguration) data TranslateEnv = TranslateEnv { teContext :: TransCtxt , teConfig :: Dict HasConfiguration , teUpdate :: Dict HasUpdateConfiguration } newtype TranslateT e m a = TranslateT { unTranslateT :: ExceptT e (ReaderT TranslateEnv m) a } deriving ( Functor , Applicative , Monad , MonadError e , MonadIO ) instance MonadTrans (TranslateT e) where lift = TranslateT . lift . lift type Translate e = TranslateT e Identity instance Monad m => MonadReader TransCtxt (TranslateT e m) where ask = TranslateT $ asks teContext local f = TranslateT . local f' . unTranslateT where f' env = env { teContext = f (teContext env) } instance Monad m => MonadGState (TranslateT e m) where gsAdoptedBVData = withConfig $ return genesisBlockVersionData runTranslateT :: Monad m => Exception e => TranslateT e m a -> m a runTranslateT (TranslateT ta) = withDefConfiguration $ withDefUpdateConfiguration $ let env :: TranslateEnv env = TranslateEnv { teContext = initContext initCardanoContext , teConfig = Dict , teUpdate = Dict } in do ma <- runReaderT (runExceptT ta) env case ma of Left e -> throw e Right a -> return a runTranslate :: Exception e => Translate e a -> a runTranslate = runIdentity . runTranslateT | Specialised form of ' runTranslate ' when there can be no errors runTranslateNoErrors :: Translate Void a -> a runTranslateNoErrors = runTranslate withConfig :: Monad m => ((HasConfiguration, HasUpdateConfiguration) => TranslateT e m a) -> TranslateT e m a withConfig f = do Dict <- TranslateT $ asks teConfig Dict <- TranslateT $ asks teUpdate f mapTranslateErrors :: Functor m => (e -> e') -> TranslateT e m a -> TranslateT e' m a mapTranslateErrors f (TranslateT ma) = TranslateT $ withExceptT f ma catchTranslateErrors :: Functor m => TranslateT e m a -> TranslateT e' m (Either e a) catchTranslateErrors (TranslateT (ExceptT (ReaderT ma))) = TranslateT $ ExceptT $ ReaderT $ \env -> fmap Right (ma env) catchSomeTranslateErrors :: Monad m => TranslateT (Either e e') m a -> TranslateT e m (Either e' a) catchSomeTranslateErrors act = do ma <- catchTranslateErrors act case ma of Left (Left e) -> throwError e Left (Right e') -> return $ Left e' Right a -> return $ Right a | Slot ID of the first block translateFirstSlot :: Monad m => TranslateT Text m SlotId translateFirstSlot = withConfig $ do SlotId 0 <$> mkLocalSlotIndex 0 translateNextSlot :: Monad m => SlotId -> TranslateT Text m SlotId translateNextSlot (SlotId epoch lsi) = withConfig $ case addLocalSlotIndex 1 lsi of Just lsi' -> return $ SlotId epoch lsi' Nothing -> SlotId (epoch + 1) <$> mkLocalSlotIndex 0 | Genesis block header translateGenesisHeader :: Monad m => TranslateT e m GenesisBlockHeader translateGenesisHeader = view gbHeader <$> asks (ccBlock0 . tcCardano) verify :: Monad m => (HasConfiguration => Verify e a) -> TranslateT e' m (Validated e (a, Utxo)) verify ma = withConfig $ do utxo <- asks (ccUtxo . tcCardano) return $ validatedFromEither (Verify.verify utxo ma) verifyBlocksPrefix :: Monad m => OldestFirst NE Block -> TranslateT e' m (Validated VerifyBlocksException (OldestFirst NE Undo, Utxo)) verifyBlocksPrefix blocks = do CardanoContext{..} <- asks tcCardano let tip = ccHash0 currentSlot = Nothing verify $ Verify.verifyBlocksPrefix tip currentSlot TODO : May not be necessary to pass this if we start from genesis blocks
4e8f8bd8eefe137038df46ededace51996f180df098463b3d9146a6f0b3b692d
overtone/overtone
audio_in.clj
(ns overtone.sc.cgens.audio-in (:use [overtone.sc defcgen ugens] [overtone.helpers seq])) (defcgen sound-in "read audio from hardware inputs" [bus {:default 0 :doc "the channel (or array of channels) to read in. These start at 0, which will correspond to the first audio input." :modulatable false}] "Reads audio from the input of your computer or soundcard. It is a wrapper UGen based on In, which offsets the index such that 0 will always correspond to the first input regardless of the number of inputs present. N.B. On Intel based Macs, reading the built-in microphone or input may require creating an aggregate device in AudioMIDI Setup." (:ar (cond (integer? bus) (in:ar (+ (num-output-buses:ir) bus) 1) (consecutive-ints? bus) (in:ar (+ (num-output-buses:ir) (first bus)) (count bus)) :else (in:ar (+ (num-output-buses:ir) bus)))))
null
https://raw.githubusercontent.com/overtone/overtone/02f8cdd2817bf810ff390b6f91d3e84d61afcc85/src/overtone/sc/cgens/audio_in.clj
clojure
(ns overtone.sc.cgens.audio-in (:use [overtone.sc defcgen ugens] [overtone.helpers seq])) (defcgen sound-in "read audio from hardware inputs" [bus {:default 0 :doc "the channel (or array of channels) to read in. These start at 0, which will correspond to the first audio input." :modulatable false}] "Reads audio from the input of your computer or soundcard. It is a wrapper UGen based on In, which offsets the index such that 0 will always correspond to the first input regardless of the number of inputs present. N.B. On Intel based Macs, reading the built-in microphone or input may require creating an aggregate device in AudioMIDI Setup." (:ar (cond (integer? bus) (in:ar (+ (num-output-buses:ir) bus) 1) (consecutive-ints? bus) (in:ar (+ (num-output-buses:ir) (first bus)) (count bus)) :else (in:ar (+ (num-output-buses:ir) bus)))))
ef85bbab13f9c00c44e48f31ba5774113b6619130613416de2e5ea4aef4132b9
uwplse/Cassius
layout.rkt
#lang racket (require "../common.rkt" "../smt.rkt" "css-properties.rkt" "browser.rkt") (provide layout-definitions boxref-definitions) (define (get-px-or-% prop wrt b) (define r `(computed-style (box-elt ,b))) (define type (slower (css-type prop))) (define out `(ite (,(sformat "is-~a/px" type) (,(sformat "style.~a" prop) ,r)) (,(sformat "~a.px" type) (,(sformat "style.~a" prop) ,r)) (%of (,(sformat "~a.%" type) (,(sformat "style.~a" prop) ,r)) ,wrt))) (match prop [(or 'min-width 'width 'max-width) `(max (- ,out (ite (is-box-sizing/border-box (style.box-sizing ,r)) (+ (bl ,b) (pl ,b) (pr ,b) (br ,b)) 0.0) (scroll-y ,b)) 0.0)] [(or 'min-height 'height 'max-height) `(max (- ,out (ite (is-box-sizing/border-box (style.box-sizing ,r)) (+ (bt ,b) (pt ,b) (pb ,b) (bb ,b)) 0.0) (scroll-x ,b)) 0.0)] [else out])) (define-constraints (boxref-definitions) (declare-fun vflow (Box) Box) (declare-fun nflow (Box) Box) (declare-fun fflow (Box) Box) (declare-fun lflow (Box) Box) (declare-fun box-collapsed-through (Box) Bool) (declare-fun firstish-box (Box) Bool) (define-fun ez.outside ((ez EZone) (b Box)) Bool (and (ez.valid? ez) (=> (ez.mark? ez) (<= (ez.max ez) (top-border b))))) (define-fun ez.inside ((ez EZone) (b Box)) Bool (and (ez.valid? ez) (=> (ez.mark? ez) (<= (ez.max ez) (bottom-border b))))) (define-fun ez.inside* ((ez EZone) (b Box)) Bool (and (ez.valid? ez) (=> (ez.mark? ez) (<= (ez.max ez) (ite (box-collapsed-through b) (top-outer b) (bottom-border b)))))) (define-fun no-margins ((b Box)) Bool (= (mtp b) (mtn b) (mbp b) (mbn b) 0.0)) (define-fun non-negative-margins ((b Box)) Bool (and (>= (mtp b) (- (mtn b))) (>= (mbp b) (- (mbn b)))))) (define-constraints (layout-definitions) (assert (forall ((b Box)) (= (nflow b) (ite (is-no-box (nbox b)) no-box (ite (box-in-flow (nbox b)) (nbox b) (nflow (nbox b))))))) (assert (forall ((b Box)) (= (vflow b) (ite (is-no-box (vbox b)) no-box (ite (box-in-flow (vbox b)) (vbox b) (vflow (vbox b))))))) (assert (forall ((b Box)) (= (fflow b) (ite (=> (is-box (fbox b)) (box-in-flow (fbox b))) (fbox b) (nflow (fbox b)))))) (assert (forall ((b Box)) (= (lflow b) (ite (=> (is-box (lbox b)) (box-in-flow (lbox b))) (lbox b) (vflow (lbox b)))))) (declare-fun rootbox (Box) Box) (assert (forall ((b Box)) (= (rootbox b) (ite (is-no-box (pbox b)) b (rootbox (pbox b)))))) (assert (forall ((b Box)) (is-box (rootbox b)))) ,@(for/list ([field '(mtn mbn)]) `(assert (forall ((b Box)) (<= (,field b) 0.0)))) ,@(for/list ([field '(bl br bt bb pr pb pt w h mtp mbp stfwidth)]) ; No pl because text-indent `(assert (forall ((b Box)) (>= (,field b) 0.0)))) Three additional pointers to the parent block box and the parent positioned box . (declare-fun ppflow (Box) Box) (assert (forall ((b Box)) (= (ppflow b) (ite (is-no-box (pbox b)) b (ite (box-positioned (pbox b)) (pbox b) (ppflow (pbox b))))))) (declare-fun pbflow (Box) Box) (assert (forall ((b Box)) (= (pbflow b) (ite (is-no-box (pbox b)) no-box (ite (or (is-box/block (type (pbox b))) (is-flow-root (pbox b))) (pbox b) (pbflow (pbox b))))))) (define-const quirks-mode Bool false) (declare-fun contains-content (Box) Bool) (assert (forall ((b Box)) (let ([e (box-elt b)] [v (vflow b)] [l (lflow b)]) (= (contains-content b) (or (> (ml b) 0) (> (bl b) 0) (> (pl b) 0) (> (pr b) 0) (> (br b) 0) (> (mr b) 0) (> (w b) 0) (and (is-elt e) (is-replaced e)) (and (is-box v) (contains-content v)) (and (is-box l) (contains-content l))))))) (assert (forall ((b Box)) (= (box-collapsed-through b) (and (= (box-height b) 0.0) (=> (is-elt (box-elt b)) (not (is-replaced (box-elt b)))) (not (is-flow-root b)) (or (and (is-box/line (type b)) (=> (is-box (lflow b)) (not (contains-content (lflow b))))) (is-no-box (lflow b)) (box-collapsed-through (lflow b))))))) (define-fun min-max-width ((val Real) (b Box)) Real (ite (is-elt (box-elt b)) (max ,(get-px-or-% 'min-width '(w (pflow b)) 'b) (min-if val (not (is-max-width/none (style.max-width (computed-style (box-elt b))))) ,(get-px-or-% 'max-width '(w (pflow b)) 'b))) val)) (define-fun min-max-height ((val Real) (b Box)) Real (max (ite (is-elt (box-elt b)) ,(get-px-or-% 'min-height '(h (pflow b)) 'b) 0.0) (ite (or (is-no-elt (box-elt b)) (is-max-height/none (style.max-height (computed-style (box-elt b))))) val (min val ,(get-px-or-% 'max-height '(h (pflow b)) 'b))))) (define-fun margin-min-px ((m Margin) (b Box)) Real ,(smt-cond [(is-margin/px m) (margin.px m)] [(is-margin/% m) (%of (margin.% m) (w (pflow b)))] [else 0.0])) (define-fun min-w ((b Box)) Real (ite (is-elt (box-elt b)) (ite (is-width/auto (style.width (computed-style (box-elt b)))) (ite (is-replaced (box-elt b)) (- (intrinsic-width (box-elt b)) (bl b) (br b) (pl b) (pr b)) 0.0) ,(get-px-or-% 'width '(w (pflow b)) 'b)) 0.0)) (define-fun min-ml ((b Box)) Real (ite (is-elt (box-elt b)) (margin-min-px (style.margin-left (computed-style (box-elt b))) b) 0.0)) (define-fun min-mr ((b Box)) Real (ite (is-elt (box-elt b)) (margin-min-px (style.margin-right (computed-style (box-elt b))) b) 0.0)) (define-fun top-margin-collapses-with-children ((b Box)) Bool (and (not (is-flow-root b)) (= (pt b) 0.0) (= (bt b) 0.0))) (define-fun bottom-margin-collapses-with-children ((b Box)) Bool (and (not (is-flow-root b)) (= (pb b) 0.0) (= (bb b) 0.0) (=> (is-elt (box-elt b)) (and (is-height/auto (style.height (computed-style (box-elt b)))) (not (is-replaced (box-elt b))))))) (define-fun zero-box-model-except-collapse ((b Box)) Bool (and (= (mt b) (mr b) (mb b) (ml b) 0.0) (= (bt b) (br b) (bb b) (bl b) 0.0) (= (pt b) (pr b) (pb b) (pl b) 0.0))) (define-fun zero-box-model ((b Box)) Bool (and (= (mtp b) (mtn b) (mbp b) (mbn b) (mtp-up b) (mtn-up b) 0.0) (= (mb-clear b) false) (= (mt b) (mr b) (mb b) (ml b) 0.0) (= (bt b) (br b) (bb b) (bl b) 0.0) (= (pt b) (pr b) (pb b) (pl b) 0.0))) (declare-fun ancestor-line (Box) Box) (assert (forall ((b Box)) (= (ancestor-line b) (ite (is-box/line (type b)) b (ite (is-flow-root (pbox b)) no-box (ancestor-line (pbox b))))))) (define-fun vertical-position-for-flow-boxes ((b Box)) Real (let ([p (pflow b)] [v (vflow b)]) ;; These parts don't check (has-clearance) because they're ;; computed "as if" there were no clearance (ite (firstish-box b) (+ (top-content p) (ite (and (top-margin-collapses-with-children p) (not (and (is-elt (box-elt b)) (is-root-elt (box-elt b)))) (not (is-box/root (type b)))) 0.0 (+ (mtp b) (mtn b)))) (+ (ite (box-collapsed-through v) (top-outer v) (bottom-border v)) (+ (max (mbp v) (mtp b)) (min (mbn v) (mtn b))))))) (declare-fun inline-float-next-line (Box) Bool) (define-fun vertical-position-for-flow-roots ((b Box)) Real (let ([p (pflow b)] [v (vflow b)]) (ite (or (is-box/block (type p)) (is-flow-root p)) (ite (is-box v) (+ (ite (box-collapsed-through v) (top-outer v) (bottom-border v)) (mbp v) (mbn v)) (top-content p)) (ite (inline-float-next-line b) (bottom-border (ancestor-line b)) (ite (is-box (vbox (ancestor-line b))) (bottom-border (vbox (ancestor-line b))) (top-content (pbox (ancestor-line b)))))))) (define-fun has-clearance ((b Box)) Bool (and (is-elt (box-elt b)) (or (and (is-clear/left (style.clear (computed-style (box-elt b)))) (< (vertical-position-for-flow-boxes b) (ez.left-max (ez.in b)))) (and (is-clear/right (style.clear (computed-style (box-elt b)))) (< (vertical-position-for-flow-boxes b) (ez.right-max (ez.in b)))) (and (is-clear/both (style.clear (computed-style (box-elt b)))) (< (vertical-position-for-flow-boxes b) (max (ez.left-max (ez.in b)) (ez.right-max (ez.in b)))))))) (assert (forall ((b Box)) (= (firstish-box b) (let ([p (pflow b)] [v (vflow b)]) (or (and (not (is-box v)) (not (has-clearance v))) (and (box-collapsed-through v) (not (has-clearance v)) (firstish-box v))))))) (define-fun change-s831c ((b Box)) Bool (and (top-margin-collapses-with-children b) (is-box (lflow b)) (firstish-box (lflow b)) (box-collapsed-through (lflow b)) (is-elt (box-elt b)) (let ([mh (style.min-height (computed-style (box-elt b)))]) (or (and (is-min-height/px mh) (> (min-height.px mh) 0)) (and (is-min-height/% mh) (> (min-height.% mh) 0)))) (is-height/auto (style.height (computed-style (box-elt b)))))) (define-fun auto-height-for-flow-roots ((b Box)) Real CSS 2.1 § 10.6.7 ,(smt-cond [(is-replaced (box-elt b)) (min-max-height (- (intrinsic-height (box-elt b)) (bt b) (bb b) (pt b) (pb b)) b)] [(is-no-box (fbox b)) (min-max-height 0.0 b)] [(is-no-box (fflow b)) (min-max-height (max (- (ez.max (ez.out (lbox b))) (top-content b)) 0.0) b)] [else ;; If it has block-level children, the height is the distance between the ;; top margin-edge of the topmost block-level child box and the ;; bottom margin-edge of the bottommost block-level child box. (min-max-height (- (max (ez.max (ez.out (lbox b))) (ite (box-collapsed-through (lflow b)) (+ (top-outer (lflow b)) (mbp (lflow b)) (mbn (lflow b))) (bottom-outer (lflow b)))) (top-content b)) b)])) (define-fun auto-height-for-flow-blocks ((b Box)) Real (let ([lb (lflow b)] [e (box-elt b)]) ,(smt-cond CSS 2.1 § 10.6.6 , first bullet [(is-flow-root b) (auto-height-for-flow-roots b)] CSS 2.1 § 10.6.3 , item 4 [(and (is-elt e) (is-replaced e)) (min-max-height (- (intrinsic-height e) (bt b) (bb b) (pt b) (pb b)) b)] [(is-no-box lb) (min-max-height 0.0 b)] CSS 2.1 § 10.6.3 , item 1 [(is-box/line (type lb)) (min-max-height (- (bottom-border lb) (top-content b)) b)] [else ; (is-box/block (type lb)), because blocks only have block or line children (min-max-height (ite (and (box-collapsed-through lb) (firstish-box lb) (top-margin-collapses-with-children b) (not (mb-clear lb))) 0.0 ;; This special case should be refactored CSS 2.1 § 10.6.3 , item 2 (+ (ite (box-collapsed-through lb) (top-outer lb) (bottom-border lb)) (ite (and (bottom-margin-collapses-with-children b) (not (mb-clear lb))) 0.0 (+ (mbp lb) (mbn lb)))) (top-content b))) b)]))) (define-fun margins-collapse ((b Box)) Bool (let ([f (fflow b)] [l (lflow b)] [v (vflow b)]) (and (= (mtp b) (max-if (max-if (ite (> (mt b) 0.0) (mt b) 0.0) (and (top-margin-collapses-with-children b) (is-box f) (not (has-clearance f))) (mtp-up f)) (and (box-collapsed-through b) (not (has-clearance b)) (is-box v)) (mbp v))) (= (mtp-up b) (max-if (ite (box-collapsed-through b) (mbp b) (mtp b)) (and (is-box (nflow b)) (box-collapsed-through b) (not (has-clearance (nflow b)))) (mtp-up (nflow b)))) (= (mtn b) (min-if (min-if (ite (< (mt b) 0.0) (mt b) 0.0) (and (top-margin-collapses-with-children b) (is-box f) (not (has-clearance f))) (mtn-up f)) (and (box-collapsed-through b) (not (has-clearance b)) (is-box v)) (mbn v))) (= (mtn-up b) (min-if (ite (box-collapsed-through b) (mbn b) (mtn b)) (and (is-box (nflow b)) (box-collapsed-through b) (not (has-clearance (nflow b)))) (mtn-up (nflow b)))) (= (mb-clear b) (or (has-clearance b) (and (is-box v) (box-collapsed-through b) (mb-clear v)))) (= (mbp b) (max-if (max-if (ite (> (mb b) 0.0) (mb b) 0.0) (and (bottom-margin-collapses-with-children b) (is-box l) (not (mb-clear l)) (not (change-s831c b))) (mbp l)) (box-collapsed-through b) (mtp b))) (= (mbn b) (min-if (min-if (ite (< (mb b) 0.0) (mb b) 0.0) (and (bottom-margin-collapses-with-children b) (is-box l) (not (mb-clear l)) (not (change-s831c b))) (mbn l)) (box-collapsed-through b) (mtn b)))))) (define-fun margins-dont-collapse ((b Box)) Bool (and (= (mtp-up b) (mtp b) (max (mt b) 0.0)) (= (mb-clear b) false) (= (mtn-up b) (mtn b) (min (mt b) 0.0)) (= (mbp b) (max (mb b) 0.0)) (= (mbn b) (min (mb b) 0.0)))) (declare-fun ancestor-block (Box) Box) (assert (forall ((b Box)) (= (ancestor-block b) (ite (is-box/block (type b)) b (ite (is-flow-root (pbox b)) no-box (ancestor-block (pbox b))))))) (define-fun relative-position-parent ((b Box)) Box (let ([r (computed-style (box-elt b))]) (ite (and (is-elt (box-elt b)) (not (is-float/none (style.float r)))) (ancestor-block (pflow b)) (pflow b)))) (define-fun relatively-positioned ((b Box)) Bool ,(smt-let ([r (computed-style (box-elt b))] [p (relative-position-parent b)]) (=> (is-offset/px (style.left r)) (= (xo b) (+ (offset.px (style.left r)) (xo p)))) (=> (is-offset/% (style.left r)) (= (xo b) (+ (%of (offset.% (style.left r)) (w p)) (xo p)))) (=> (is-offset/px (style.top r)) (= (yo b) (+ (offset.px (style.top r)) (yo p)))) (=> (is-offset/% (style.top r)) (= (yo b) (+ (%of (offset.% (style.top r)) (h p)) (yo p)))) (=> (and (is-offset/auto (style.left r)) (is-offset/px (style.right r))) (= (xo b) (- (xo p) (offset.px (style.right r))))) (=> (and (is-offset/auto (style.left r)) (is-offset/% (style.right r))) (= (xo b) (- (xo p) (%of (offset.% (style.right r)) (w p))))) (=> (and (is-offset/auto (style.top r)) (is-offset/px (style.bottom r))) (= (yo b) (- (yo p) (offset.px (style.bottom r))))) (=> (and (is-offset/auto (style.top r)) (is-offset/% (style.bottom r))) (= (yo b) (- (yo p) (%of (offset.% (style.bottom r)) (h p))))) (=> (and (is-offset/auto (style.left r)) (is-offset/auto (style.right r))) (= (xo b) (xo p))) (=> (and (is-offset/auto (style.top r)) (is-offset/auto (style.bottom r))) (= (yo b) (yo p))))) (define-fun no-relative-offset ((b Box)) Bool ,(smt-let ([r (computed-style (box-elt b))] [p (relative-position-parent b)]) (= (xo b) (xo p)) (= (yo b) (yo p)))) (define-fun resolve-clear ((b Box) (default Real)) Real (max-if (max-if default (and (is-elt (box-elt b)) (or (is-clear/left (style.clear (computed-style (box-elt b)))) (is-clear/both (style.clear (computed-style (box-elt b)))))) (ez.left-max (ez.in b))) (and (is-elt (box-elt b)) (or (is-clear/right (style.clear (computed-style (box-elt b)))) (is-clear/both (style.clear (computed-style (box-elt b)))))) (ez.right-max (ez.in b)))) (define-fun flow-horizontal-layout ((b Box) (available-width Real)) Bool ;; CSS § 10.3.3: Block-level, non-replaced elements in normal flow ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)] ) (= available-width (+ (ml b) (box-width b) (mr b))) (not (w-from-stfwidth b)) (let ([w* (min-max-width (min-w b) b)] [ml* (min-ml b)] [mr* (min-mr b)]) ,(smt-cond [(> (+ ml* (bl b) (pl b) w* (pr b) (br b) mr* (scroll-y b)) available-width) (= (w b) w*) (= (ml b) ml*) (width-set b)] [(or (is-no-elt e) (and (is-width/auto (style.width r)) (not (is-replaced e)))) (ite (and (is-elt e) (not (is-max-width/none (style.max-width r))) (> (- available-width ml* (bl b) (pl b) (pr b) (br b) mr*) ,(get-px-or-% 'max-width '(w p) 'b))) (and (= (w b) ,(get-px-or-% 'max-width '(w p) 'b)) ,(smt-cond [(not (is-margin/auto (style.margin-left r))) (= (ml b) ml*)] [(not (is-margin/auto (style.margin-right r))) (= (mr b) mr*)] [else (= (ml b) (mr b))]) (width-set b)) (and (= (ml b) ml*) (= (mr b) mr*) (width-set b)))] [else (= (w b) w*) (width-set b) ,(smt-cond [(not (is-margin/auto (style.margin-left r))) (= (ml b) ml*)] [(not (is-margin/auto (style.margin-right r))) (= (mr b) mr*)] [else (= (ml b) (mr b))])])))) ;; `lookback-overflow-width` is a black box that is narrower than ;; `(w p)`, used when we don't know the shape of the exclusion zone ;; because `(ez.lookback b)`. (declare-fun lookback-overflow-width (Box) Real) (assert (forall ((b Box)) (<= 0 (lookback-overflow-width b) (w (pbox b))))) (define-fun available-width ((b Box)) Real (- (w (pbox b)) (ml b) (bl b) (pl b) (pr b) (br b) (mr b))) (define-fun usable-stfwidth ((b Box)) Real (let ([l (lbox b)]) (min-max-width (ite (is-box l) (min (max (stfwidth l) (available-width b)) (+ (stfmax l) (float-stfmax l))) (ite (is-replaced (box-elt b)) (- (intrinsic-width (box-elt b)) (bl b) (br b) (pl b) (pr b)) 0.0)) b))) (define-fun compute-stfwidth ((b Box)) Real (let ([l (lbox b)] [v (vbox b)] [r (computed-style (box-elt b))]) (max ,(smt-cond [(is-no-elt (box-elt b)) (+ (bl b) (max (pl b) 0.0) (ite (is-box l) (stfwidth l) 0.0) (pr b) (br b))] [(is-float/left (style.float r)) (- (right-outer b) (left-content (pbox b)))] [(is-float/right (style.float r)) (- (right-content (pbox b)) (left-outer b))] [else (+ (min-ml b) (bl b) (max (pl b) 0.0) (ite (and (not (is-replaced (box-elt b))) (is-width/auto (style.width r))) (ite (is-box l) (stfwidth l) 0.0) (w b)) (pr b) (br b) (min-mr b))]) (ite (is-box v) (stfwidth v) 0.0)))) (define-fun compute-stfmax ((b Box)) Real (let ([l (lbox b)] [v (vbox b)] [r (computed-style (box-elt b))]) ,(smt-cond [(is-no-elt (box-elt b)) (+ (ml b) (bl b) (pl b) (ite (is-box l) (stfmax l) 0.0) (pr b) (br b) (mr b))] [(is-float/left (style.float r)) (- (right-outer b) (left-content (pbox b)))] [(is-float/right (style.float r)) (- (right-content (pbox b)) (left-outer b))] [else (+ (min-ml b) (bl b) (max (pl b) 0.0) (ite (and (not (is-replaced (box-elt b))) (is-width/auto (style.width r))) (ite (is-box l) (stfmax l) 0.0) (w b)) (pr b) (br b) (min-mr b))]))) (define-fun positioned-vertical-layout ((b Box)) Bool CSS 2.1 § 10.6.4 ,(smt-let* ([r (computed-style (box-elt b))] [pp (ite (is-position/fixed (style.position (computed-style (box-elt b)))) (rootbox b) (ppflow b))] [temp-top ,(get-px-or-% 'top '(height-padding pp) 'b)] [temp-bottom ,(get-px-or-% 'bottom '(height-padding pp) 'b)] [temp-height (min-max-height (ite (is-replaced (box-elt b)) (- (intrinsic-height (box-elt b)) (bt b) (bb b) (pt b) (pb b)) ,(get-px-or-% 'height '(height-padding pp) 'b)) b)] [top? (not (is-offset/auto (style.top (computed-style (box-elt b)))))] [bottom? (not (is-offset/auto (style.bottom (computed-style (box-elt b)))))] [height? (or (is-replaced (box-elt b)) (not (is-height/auto (style.height (computed-style (box-elt b))))))]) (=> top? (= (top-outer b) (+ (top-padding pp) temp-top))) (=> height? (= (h b) temp-height)) (=> (and (not top?) (not bottom?)) (= (top-outer b) (vertical-position-for-flow-roots b))) (=> (and (not height?) (not (and top? bottom?))) (= (h b) (auto-height-for-flow-roots b))) (=> (and bottom? (not (and top? height?))) (= (bottom-outer b) (- (bottom-padding pp) temp-bottom))) ;; Margins work identically unless overspecified (=> (not (and top? height? bottom?)) (and (= (mt b) (margin-min-px (style.margin-top r) b)) (= (mb b) (margin-min-px (style.margin-bottom r) b)))) Paragraph before the list , " If none of the three are ' auto ' " (=> (and top? bottom? height?) (and (=> (not (is-margin/auto (style.margin-top r))) (= (mt b) (margin-min-px (style.margin-top r) b))) (=> (not (is-margin/auto (style.margin-bottom r))) (= (mb b) (margin-min-px (style.margin-bottom r) b))) (=> (and (is-margin/auto (style.margin-top r)) (is-margin/auto (style.margin-bottom r))) (= (mt b) (mb b))) (=> (or (is-margin/auto (style.margin-top r)) (is-margin/auto (style.margin-bottom r))) (= (bottom-outer b) (- (bottom-padding pp) temp-bottom))))))) (define-fun positioned-horizontal-layout ((b Box)) Bool ,(smt-let* ([r (computed-style (box-elt b))] [pp (ite (is-position/fixed (style.position (computed-style (box-elt b)))) (rootbox b) (ppflow b))] [p (pflow b)] [temp-left ,(get-px-or-% 'left '(width-padding pp) 'b)] [temp-right ,(get-px-or-% 'right '(width-padding pp) 'b)] [temp-width (min-max-width (ite (is-replaced (box-elt b)) (- (intrinsic-width (box-elt b)) (bl b) (br b) (pl b) (pr b)) ,(get-px-or-% 'width '(width-padding pp) 'b)) b)] [left? (not (is-offset/auto (style.left (computed-style (box-elt b)))))] [right? (not (is-offset/auto (style.right (computed-style (box-elt b)))))] [width? (or (is-replaced (box-elt b)) (not (is-width/auto (style.width (computed-style (box-elt b))))))]) (width-set b) ;; Margins work identically unless overspecified (=> (not (and left? width? right?)) (and (= (ml b) (margin-min-px (style.margin-left r) b)) (= (mr b) (margin-min-px (style.margin-right r) b)))) (=> left? (= (left-outer b) (+ (left-padding pp) temp-left))) (=> width? (and (= (w b) temp-width) (not (w-from-stfwidth b)))) (=> (and (not width?) (not (and left? right?))) (and (= (w b) (usable-stfwidth b)) (w-from-stfwidth b))) (=> (and (not left?) (not right?)) (= (left-outer b) (ite (or (is-box/block (type (pflow b))) (is-flow-root (pflow b))) (left-content p) (ite (is-box (vflow b)) (right-outer (vflow b)) (left-outer (pflow b)))))) (=> (and right? (not (and left? width?))) (= (right-outer b) (- (right-padding pp) temp-right))) (=> (and left? right?) (not (w-from-stfwidth b))) (=> (and left? width? right?) (and (=> (not (is-margin/auto (style.margin-left r))) (= (ml b) (margin-min-px (style.margin-left r) b))) (=> (not (is-margin/auto (style.margin-right r))) (= (mr b) (margin-min-px (style.margin-right r) b))) (=> (and (is-margin/auto (style.margin-left r)) (is-margin/auto (style.margin-right r))) (= (ml b) (mr b))) (=> (or (is-margin/auto (style.margin-left r)) (is-margin/auto (style.margin-right r))) (= (right-outer b) (- (right-padding pp) temp-right))))))) (declare-fun line-height (Box) Real) (assert (forall ((b Box)) (let ([e (box-elt b)]) (= (line-height b) (ite (is-elt e) (let ([lh (style.line-height (computed-style e))] [fs (style.font-size (computed-style e))]) ,(smt-cond [(is-line-height/normal lh) (font.line-height (font-info b))] [(is-line-height/num lh) (%of (* 100.0 (line-height.num lh)) (font-size.px fs))] ( is - line - height / px ( b ) ) (line-height.px lh)])) (ite (is-box (pflow b)) (line-height (pflow b)) 0.0)))))) ;; ez.line is a specialized thing for floats inside lines (declare-fun ez.line (Box) EZone) (declare-fun ez.line-up (Box) EZone) (define-fun float-affects-own-line ((b Box)) Bool ;; PRECONDITION: (is-flow-root b) (let ([l (ancestor-line b)]) (and (is-box l) (or (< (top-outer b) (bottom-outer l)) Special case for zero - height ( empty ) lines (= (top-outer b) (top-outer l) (bottom-outer l)))))) (assert (forall ((b Box)) (= (ez.line-up b) (ite (and (is-flow-root b) (float-affects-own-line b)) (ez.line b) (ite (is-box (lbox b)) (ez.line-up (lbox b)) (ez.line b)))))) (assert (forall ((b Box)) (= (ez.line b) (ite (and (is-flow-root b) (float-affects-own-line b)) (ez.out b) (ite (is-box (vbox b)) (ez.line-up (vbox b)) (ez.in b)))))) These three functions define the three types of layouts ;; supports for block boxes: normal in-flow layout, floating layout, ;; and positioned layout. By and large, these functions refer to the ;; preceding functions. (declare-fun uses-parent-w (Box) Bool) (assert (forall ((b Box)) (let ([e (box-elt b)] [r (computed-style (box-elt b))]) (= (uses-parent-w b) (or (and (=> (is-elt e) (is-width/auto (style.width r))) (is-box (vflow b)) (uses-parent-w (vflow b))) (and (=> (is-elt e) (is-width/auto (style.width r))) (is-box (lflow b)) (uses-parent-w (lflow b))) (and (is-elt e) (is-margin/% (style.margin-left r))) (and (is-elt e) (is-margin/% (style.margin-right r))) (and (is-elt e) (is-border/% (style.border-left-width r))) (and (is-elt e) (is-border/% (style.border-right-width r))) (and (is-elt e) (is-padding/% (style.padding-left r))) (and (is-elt e) (is-padding/% (style.padding-right r))) (and (is-elt e) (is-width/% (style.width r)))))))) (define-fun a-block-flow-box ((b Box)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)] [vb (vflow b)] [fb (fflow b)] [lb (lflow b)]) (ite (is-height/auto (style.height r)) (= (h b) (auto-height-for-flow-blocks b)) (= (h b) (min-max-height ,(get-px-or-% 'height '(h p) 'b) b))) (= (mt b) (ite (is-margin/auto (style.margin-top r)) 0.0 ,(get-px-or-% 'margin-top '(w p) 'b))) (= (mb b) (ite (is-margin/auto (style.margin-bottom r)) 0.0 ,(get-px-or-% 'margin-bottom '(w p) 'b))) (margins-collapse b) (= (stfmax b) (max-if (min-max-width (compute-stfmax b) b) (is-box (vbox b)) (stfmax (vbox b)))) (= (float-stfmax b) (+ (ite (is-flow-root b) 0.0 (min-max-width (ite (is-box (lbox b)) (float-stfmax (lbox b)) 0.0) b)) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (let ([y* (resolve-clear b (vertical-position-for-flow-boxes b))]) (ite (or (is-flow-root b) (and (is-elt e) (is-replaced e))) (and (= (ez.lookback b) (not (ez.test (ez.in b) (y b)))) (ite (not (ez.lookback b)) (= (y b) (ez.level (ez.in b) (+ (bl b) (pl b) (min-w b) (pr b) (br b)) (left-content p) (right-content p) y* float/left)) (>= (y b) y*))) (and (= (ez.lookback b) false) (= (y b) y*)))) (ite (or (is-flow-root b) (and (is-elt e) (is-replaced e))) (flow-horizontal-layout b (ite (not (ez.lookback b)) (- (ez.x (ez.in b) (y b) float/right (left-content p) (right-content p)) (ez.x (ez.in b) (y b) float/left (left-content p) (right-content p))) (lookback-overflow-width b))) (flow-horizontal-layout b (w p))) (=> (not (ez.lookback b)) (= (x b) (+ (ml b) (ite (or (is-flow-root b) (and (is-elt e) (is-replaced e))) (ez.x (ez.in b) (y b) float/left (left-content p) (right-content p)) (left-content p))))))) (define-fun a-block-float-box ((b Box)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)] [vb (vflow b)] [fb (fflow b)] [lb (lflow b)]) (= (mt b) (ite (is-margin/auto (style.margin-top r)) 0.0 ,(get-px-or-% 'margin-top '(w p) 'b))) (= (mr b) (ite (is-margin/auto (style.margin-right r)) 0.0 ,(get-px-or-% 'margin-right '(w p) 'b))) (= (mb b) (ite (is-margin/auto (style.margin-bottom r)) 0.0 ,(get-px-or-% 'margin-bottom '(w p) 'b))) (= (ml b) (ite (is-margin/auto (style.margin-left r)) 0.0 ,(get-px-or-% 'margin-left '(w p) 'b))) (margins-dont-collapse b) (= (w-from-stfwidth b) (is-width/auto (style.width r))) (= (stfmax b) (ite (is-box (vbox b)) (stfmax (vbox b)) 0.0)) (= (float-stfmax b) (+ (min-max-width (max (- (right-outer b) (left-outer b)) 0.0) b) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (width-set b) (ite (is-width/auto (style.width r)) (ite (is-replaced e) (= (w b) (- (intrinsic-width e) (bl b) (br b) (pl b) (pr b))) (or (= (w b) (usable-stfwidth b)) (and (is-box (lbox b)) (uses-parent-w (lbox b))))) ;; todo: what do browsers do when (w-from-stfwidth p) and (is-margin/%)? (= (w b) (min-max-width ,(get-px-or-% 'width '(w (pbflow b)) 'b) b))) (ite (is-height/auto (style.height r)) (ite (is-replaced e) (= (h b) (- (intrinsic-height e) (bt b) (bb b) (pt b) (pb b))) (=> (width-set b) (= (h b) (auto-height-for-flow-roots b)))) (= (h b) (min-max-height ,(get-px-or-% 'height '(h p) 'b) b))) ;; level -> x -> advance -> can-add -> add ,(smt-let* ([ez (ez.in b)] [w (- (right-outer b) (left-outer b))] [h (- (bottom-outer b) (top-outer b))] [y-normal (resolve-clear b (vertical-position-for-flow-roots b))] [y* (ez.level ez w (left-content (pbflow b)) (right-content (pbflow b)) y-normal (style.float r))] [x* (ez.x ez y* (style.float r) (left-content (pbflow b)) (right-content (pbflow b)))] [x (ite (is-float/left (style.float r)) x* (- x* w))]) (= (top-outer b) y*) (= (left-outer b) x) (= (ez.lookback b) false)))) (define-fun a-block-positioned-box ((b Box)) Bool (and (margins-dont-collapse b) (positioned-vertical-layout b) (positioned-horizontal-layout b) (= (stfmax b) (ite (is-box (vbox b)) (stfmax (vbox b)) 0.0)) (= (float-stfmax b) (+ (min-max-width (ite (is-box (lbox b)) (float-stfmax (lbox b)) 0.0) b) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (= (ez.lookback b) false))) (define-fun a-block-box ((b Box)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)]) (= (type b) box/block) (= (bt b) ,(get-px-or-% 'border-top-width '(w p) 'b)) (= (br b) ,(get-px-or-% 'border-right-width '(w p) 'b)) (= (bb b) ,(get-px-or-% 'border-bottom-width '(w p) 'b)) (= (bl b) ,(get-px-or-% 'border-left-width '(w p) 'b)) (= (pt b) ,(get-px-or-% 'padding-top '(w p) 'b)) (= (pr b) ,(get-px-or-% 'padding-right '(w p) 'b)) (= (pb b) ,(get-px-or-% 'padding-bottom '(w p) 'b)) (= (pl b) ,(get-px-or-% 'padding-left '(w p) 'b)) (= (stfwidth b) (min-max-width (compute-stfwidth b) b)) ;;(= (stfmax b) (max-if (compute-stfmax b) (is-box (vbox b)) (stfmax (vbox b)))) (= ( float - stfmax b ) ( ite ( is - box ( vbox b ) ) ( float - stfmax ( vbox b ) ) 0.0 ) ) (ite (is-position/relative (style.position r)) (relatively-positioned b) (no-relative-offset b)) (= (text-indent b) (ite (is-elt e) ,(get-px-or-% 'text-indent '(w b) 'b) 0.0)) ,(smt-cond [(or (is-position/absolute (position b)) (is-position/fixed (position b))) (a-block-positioned-box b)] [(box-in-flow b) (a-block-flow-box b)] [else (a-block-float-box b)]))) (declare-fun inline-block-offset (Box) Real) (define-fun an-inline-box ((b Box)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)] [v (vflow b)] [l (lflow b)] [metrics (font-info b)] [leading (- (line-height b) (height-text b))]) (= (type b) box/inline) (= (bt b) ,(get-px-or-% 'border-top-width '(w p) 'b)) (= (bb b) ,(get-px-or-% 'border-bottom-width '(w p) 'b)) (= (pt b) ,(get-px-or-% 'padding-top '(w p) 'b)) (= (pb b) ,(get-px-or-% 'padding-bottom '(w p) 'b)) (= (mt b) (ite (is-margin/auto (style.margin-top r)) 0.0 ,(get-px-or-% 'margin-top '(w p) 'b))) (= (mb b) (ite (is-margin/auto (style.margin-bottom r)) 0.0 ,(get-px-or-% 'margin-bottom '(w p) 'b))) (ite (first-box? b) (and (= (pl b) ,(get-px-or-% 'padding-left '(w p) 'b)) (= (bl b) ,(get-px-or-% 'border-left-width '(w p) 'b)) (= (ml b) (+ (ite (is-margin/auto (style.margin-left r)) 0.0 ,(get-px-or-% 'margin-left '(w p) 'b)) (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0)))) (and (= (pl b) (bl b) 0.0) (= (ml b) (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0)))) (ite (last-box? b) (and (= (pr b) ,(get-px-or-% 'padding-right '(w p) 'b)) (= (br b) ,(get-px-or-% 'border-right-width '(w p) 'b)) (= (mr b) (ite (is-margin/auto (style.margin-right r)) 0.0 ,(get-px-or-% 'margin-right '(w p) 'b)))) (and (= (pr b) (br b) (mr b) 0.0))) (margins-dont-collapse b) (ite (is-position/relative (style.position r)) (relatively-positioned b) (no-relative-offset b)) (= (stfwidth b) (+ (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0) (min-max-width (compute-stfwidth b) b))) (= (stfmax b) (+ (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0) (ite (is-box (vbox b)) (stfmax (vbox b)) 0.0) (min-max-width (compute-stfmax b) b))) (= (float-stfmax b) (+ (ite (and (not (is-display/inline-block (style.display r))) (is-box (lbox b))) (min-max-width (float-stfmax (lbox b)) b) 0.0) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (= (text-indent b) (ite (is-elt e) ,(get-px-or-% 'text-indent '(w p) 'b) 0.0)) (= (baseline b) (baseline p)) (=> (and (is-elt e) (is-image e)) (= (inline-block-offset b) 0)) (ite (or (and (is-elt e) (is-replaced e)) (is-display/inline-block (style.display r))) (and (<= 0 (inline-block-offset b) (max (height-outer b) (font.descent metrics))) (= (above-baseline b) (max-if (- (height-outer b) (inline-block-offset b)) (is-box v) (above-baseline v))) (= (below-baseline b) (max-if (inline-block-offset b) (is-box v) (below-baseline v))) (= (bottom-outer b) (+ (baseline p) (inline-block-offset b)))) (and (= (top-content b) (- (baseline b) (font.ascent metrics) (font.topoffset metrics))) (= (above-baseline b) (max-if (max-if (+ (font.ascent metrics) (/ leading 2)) (is-box v) (above-baseline v)) (is-box l) (above-baseline l))) (= (below-baseline b) (max-if (max-if (+ (font.descent metrics) (/ leading 2)) (is-box v) (below-baseline v)) (is-box l) (below-baseline l))))) ,(smt-cond [(is-replaced e) (= (h b) (- (intrinsic-height e) (bt b) (bb b) (pt b) (pb b)))] [(is-display/inline-block (style.display r)) (= (h b) (ite (is-height/auto (style.height r)) (auto-height-for-flow-roots b) (min-max-height ,(get-px-or-% 'height '(h p) 'b) b)))] [else (= (h b) (font.selection-height metrics))]) ,(smt-cond [(is-replaced e) (= (w b) (- (intrinsic-width e) (bl b) (br b) (pl b) (pr b)))] [(is-display/inline-block (style.display r)) (ite (is-width/auto (style.width r)) (= (w b) (usable-stfwidth b)) (= (w b) (min-max-width ,(get-px-or-% 'width '(w p) 'b) b)))] [(is-box (fflow b)) (and (= (left-outer (fflow b)) (left-content b)) (= (right-outer (lflow b)) (right-content b)))] [else (= (w b) 0.0)]) (=> (is-box v) (= (left-outer b) (right-outer v))) (= (ez.lookback b) false))) (define-fun a-text-box ((b Box)) Bool ,(smt-let ([p (pflow b)] [v (vflow b)] [metrics (font-info b)] [leading (- (line-height b) (height-text b))]) (= (type b) box/text) ;; Only true if there are no wrapping opportunities in the box (= (stfwidth b) (max (+ (ml b) (w b)) (ite (is-box (vbox b)) (stfwidth (vbox b)) 0.0))) (= (stfmax b) (+ (ite (is-box (vbox b)) (stfmax (vbox b)) 0.0) HAXXX (= (float-stfmax b) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0)) (= (baseline b) (baseline p)) (= (text-indent b) 0.0) (= (h b) (font.selection-height metrics)) (= (above-baseline b) (max-if (ite (> (w b) 0.0) (+ (font.ascent metrics) (/ leading 2)) 0.0) (is-box v) (above-baseline v))) (= (below-baseline b) (max-if (ite (> (w b) 0.0) (+ (font.descent metrics) (/ leading 2)) 0.0) (is-box v) (below-baseline v))) (= (y b) (- (baseline b) (+ (font.ascent metrics) (font.topoffset metrics)))) (no-relative-offset b) (= (mtp b) (mtn b) (mbp b) (mbn b) (mtp-up b) (mtn-up b) 0.0) (= (mb-clear b) false) (= (mt b) (mr b) (mb b) 0.0) (= (bt b) (br b) (bb b) (bl b) 0.0) (= (pt b) (pr b) (pb b) (pl b) 0.0) (= (ml b) (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0)) (=> (is-box v) (= (x b) (right-outer v))) ; Otherwise set by the line box (= (ez.lookback b) false))) (declare-fun ancestor-elt (Box) Element) (assert (forall ((b Box)) (= (ancestor-elt b) (ite (is-elt (box-elt b)) (box-elt b) (ite (is-box (pbox b)) (ancestor-elt (pbox b)) no-elt))))) (define-fun a-line-box ((b Box)) Bool ,(smt-let ([p (pflow b)] [v (vflow b)] [n (nflow b)] [f (fflow b)] [l (lflow b)] [metrics (font-info b)] [leading (- (line-height b) (height-text b))]) (= (type b) box/line) (no-relative-offset b) (zero-box-model b) (= (text-indent b) (text-indent p)) (let ([y-normal (resolve-clear b (ite (is-no-box v) (top-content p) (bottom-border v)))] [ez (ez.line-up (lbox b))]) (and (= (ez.lookback b) (not (ez.test (ez.in b) y-normal))) ;; Key float restriction (ite (not (ez.lookback b)) (and ;; Here we use (stfmax (lbox b)) because that ignores floats on future lines (= (y b) (ez.level ez (stfwidth (lbox b)) (left-content p) (right-content p) y-normal float/left)) (= (left-outer b) (ez.x ez (y b) float/left (left-content p) (right-content p))) (= (right-outer b) (ez.x ez (y b) float/right (left-content p) (right-content p)))) (and (>= (y b) y-normal) (>= (left-outer b) (left-content p)) (<= (right-outer b) (right-content p)))))) (= (stfwidth b) (compute-stfwidth b)) (= (stfmax b) (+ (ite (is-box v) (stfmax v) 0.0) (+ (stfmax (lbox b)) (pl b)))) (= (float-stfmax b) (+ (ite (is-box (lbox b)) (float-stfmax (lbox b)) 0.0) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (=> (is-box l) (= (baseline b) (+ (y b) (ite (contains-content l) (max-if (above-baseline l) (=> quirks-mode (is-display/list-item (style.display (computed-style (box-elt (pflow b)))))) (+ (font.ascent metrics) (* 0.5 leading))) 0.0)))) (=> (is-box l) (= (h b) (ite (contains-content l) (+ (max-if (above-baseline l) (=> quirks-mode (is-display/list-item (style.display (computed-style (box-elt (pflow b)))))) (+ (font.ascent metrics) (* 0.5 leading))) (max-if (below-baseline l) (=> quirks-mode (is-display/list-item (style.display (computed-style (box-elt (pflow b)))))) (+ (font.descent metrics) (* 0.5 leading)))) 0.0))) (=> (is-box f) (let ([wsub (- (right-outer l) (left-outer f))] [textalign (style.text-align (computed-style (ancestor-elt b)))]) ,(smt-cond [(> wsub (w b)) (= (left-outer f) (left-content b))] [(is-text-align/left textalign) (= (left-outer f) (left-content b))] [(is-text-align/justify textalign) (and (= (left-outer f) (left-content b)) (=> (is-box n) (= (right-outer l) (right-content b))))] [(is-text-align/right textalign) (= (right-outer l) (right-content b))] [(is-text-align/center textalign) (= (- (left-outer f) (left-content b)) (- (right-content b) (right-outer l)))] [else false]))))) (define-fun a-view-box ((b Box)) Bool (and (= (type b) box/root) (zero-box-model b) (= (x b) (y b) 0.0) (= (xo b) (yo b) 0.0) (= (box-width b) (browser.w ,(the-browser))) (= (box-height b) (browser.h ,(the-browser))) (= (ez.lookback b) false) (= (text-indent b) 0.0))) (define-fun a-magic-box ((b Box)) Bool (and (or (is-box/block (type b)) (is-box/inline (type b))) (not (ez.lookback b)))) (define-fun an-anon-block-box ((b Box)) Bool ,(smt-let ([p (pflow b)] [v (vflow b)] [l (lflow b)]) (= (type b) box/block) (no-relative-offset b) (zero-box-model-except-collapse b) (margins-collapse b) (flow-horizontal-layout b (w p)) (= (h b) (auto-height-for-flow-blocks b)) (= (text-indent b) (text-indent p)) (= (stfmax b) (max-if (stfmax l) (is-box v) (stfmax v))) (= (stfwidth b) (max-if (stfwidth l) (is-box v) (stfwidth v))) (= (float-stfmax b) (+ (ite (is-box (lbox b)) (float-stfmax (lbox b)) 0.0) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (not (w-from-stfwidth b)) (= (y b) (vertical-position-for-flow-boxes b)) (= (x b) (left-content p)) (= (ez.lookback b) false))) ;; In some cases either the x or y scrollbar can be shown but not both; ;; in this case only the y scrollbar is ever shown ;; Also, we do not model the fact no scrollbars is preferred if both are possible (define-const min-size-for-scrollbars Real 45.0) (assert (forall ((b Box)) (or (= (scroll-x b) (ite (and (> (- (box-width b) (scroll-y b)) min-size-for-scrollbars) (is-box (pbox b)) (is-elt (box-elt b)) (is-elt (pelt (box-elt b))) (is-overflow/scroll (style.overflow-x (computed-style (box-elt b))))) (browser.scrollbar-width ,(the-browser)) 0)) (and (is-no-box (pbox b)) (or (= (scroll-x b) 0) (= (scroll-x b) (browser.scrollbar-width ,(the-browser)) )))))) ; The root box is weird in several ways (assert (forall ((b Box)) (or (= (scroll-y b) (ite (and (> (- (box-height b) (scroll-x b)) min-size-for-scrollbars) (is-box (pbox b)) (is-elt (box-elt b)) (is-elt (pelt (box-elt b))) (is-overflow/scroll (style.overflow-y (computed-style (box-elt b))))) (browser.scrollbar-width ,(the-browser)) 0)) (and (is-no-box (pbox b)) (or (= (scroll-y b) 0) (= (scroll-y b) (browser.scrollbar-width ,(the-browser)))))))))
null
https://raw.githubusercontent.com/uwplse/Cassius/edcb8302c43b7b149280504c00672d8133219b44/src/spec/layout.rkt
racket
No pl because text-indent These parts don't check (has-clearance) because they're computed "as if" there were no clearance If it has block-level children, the height is the distance between the top margin-edge of the topmost block-level child box and the bottom margin-edge of the bottommost block-level child box. (is-box/block (type lb)), because blocks only have block or line children This special case should be refactored CSS § 10.3.3: Block-level, non-replaced elements in normal flow `lookback-overflow-width` is a black box that is narrower than `(w p)`, used when we don't know the shape of the exclusion zone because `(ez.lookback b)`. Margins work identically unless overspecified Margins work identically unless overspecified ez.line is a specialized thing for floats inside lines PRECONDITION: (is-flow-root b) supports for block boxes: normal in-flow layout, floating layout, and positioned layout. By and large, these functions refer to the preceding functions. todo: what do browsers do when (w-from-stfwidth p) and (is-margin/%)? level -> x -> advance -> can-add -> add (= (stfmax b) (max-if (compute-stfmax b) (is-box (vbox b)) (stfmax (vbox b)))) Only true if there are no wrapping opportunities in the box Otherwise set by the line box Key float restriction Here we use (stfmax (lbox b)) because that ignores floats on future lines In some cases either the x or y scrollbar can be shown but not both; in this case only the y scrollbar is ever shown Also, we do not model the fact no scrollbars is preferred if both are possible The root box is weird in several ways
#lang racket (require "../common.rkt" "../smt.rkt" "css-properties.rkt" "browser.rkt") (provide layout-definitions boxref-definitions) (define (get-px-or-% prop wrt b) (define r `(computed-style (box-elt ,b))) (define type (slower (css-type prop))) (define out `(ite (,(sformat "is-~a/px" type) (,(sformat "style.~a" prop) ,r)) (,(sformat "~a.px" type) (,(sformat "style.~a" prop) ,r)) (%of (,(sformat "~a.%" type) (,(sformat "style.~a" prop) ,r)) ,wrt))) (match prop [(or 'min-width 'width 'max-width) `(max (- ,out (ite (is-box-sizing/border-box (style.box-sizing ,r)) (+ (bl ,b) (pl ,b) (pr ,b) (br ,b)) 0.0) (scroll-y ,b)) 0.0)] [(or 'min-height 'height 'max-height) `(max (- ,out (ite (is-box-sizing/border-box (style.box-sizing ,r)) (+ (bt ,b) (pt ,b) (pb ,b) (bb ,b)) 0.0) (scroll-x ,b)) 0.0)] [else out])) (define-constraints (boxref-definitions) (declare-fun vflow (Box) Box) (declare-fun nflow (Box) Box) (declare-fun fflow (Box) Box) (declare-fun lflow (Box) Box) (declare-fun box-collapsed-through (Box) Bool) (declare-fun firstish-box (Box) Bool) (define-fun ez.outside ((ez EZone) (b Box)) Bool (and (ez.valid? ez) (=> (ez.mark? ez) (<= (ez.max ez) (top-border b))))) (define-fun ez.inside ((ez EZone) (b Box)) Bool (and (ez.valid? ez) (=> (ez.mark? ez) (<= (ez.max ez) (bottom-border b))))) (define-fun ez.inside* ((ez EZone) (b Box)) Bool (and (ez.valid? ez) (=> (ez.mark? ez) (<= (ez.max ez) (ite (box-collapsed-through b) (top-outer b) (bottom-border b)))))) (define-fun no-margins ((b Box)) Bool (= (mtp b) (mtn b) (mbp b) (mbn b) 0.0)) (define-fun non-negative-margins ((b Box)) Bool (and (>= (mtp b) (- (mtn b))) (>= (mbp b) (- (mbn b)))))) (define-constraints (layout-definitions) (assert (forall ((b Box)) (= (nflow b) (ite (is-no-box (nbox b)) no-box (ite (box-in-flow (nbox b)) (nbox b) (nflow (nbox b))))))) (assert (forall ((b Box)) (= (vflow b) (ite (is-no-box (vbox b)) no-box (ite (box-in-flow (vbox b)) (vbox b) (vflow (vbox b))))))) (assert (forall ((b Box)) (= (fflow b) (ite (=> (is-box (fbox b)) (box-in-flow (fbox b))) (fbox b) (nflow (fbox b)))))) (assert (forall ((b Box)) (= (lflow b) (ite (=> (is-box (lbox b)) (box-in-flow (lbox b))) (lbox b) (vflow (lbox b)))))) (declare-fun rootbox (Box) Box) (assert (forall ((b Box)) (= (rootbox b) (ite (is-no-box (pbox b)) b (rootbox (pbox b)))))) (assert (forall ((b Box)) (is-box (rootbox b)))) ,@(for/list ([field '(mtn mbn)]) `(assert (forall ((b Box)) (<= (,field b) 0.0)))) `(assert (forall ((b Box)) (>= (,field b) 0.0)))) Three additional pointers to the parent block box and the parent positioned box . (declare-fun ppflow (Box) Box) (assert (forall ((b Box)) (= (ppflow b) (ite (is-no-box (pbox b)) b (ite (box-positioned (pbox b)) (pbox b) (ppflow (pbox b))))))) (declare-fun pbflow (Box) Box) (assert (forall ((b Box)) (= (pbflow b) (ite (is-no-box (pbox b)) no-box (ite (or (is-box/block (type (pbox b))) (is-flow-root (pbox b))) (pbox b) (pbflow (pbox b))))))) (define-const quirks-mode Bool false) (declare-fun contains-content (Box) Bool) (assert (forall ((b Box)) (let ([e (box-elt b)] [v (vflow b)] [l (lflow b)]) (= (contains-content b) (or (> (ml b) 0) (> (bl b) 0) (> (pl b) 0) (> (pr b) 0) (> (br b) 0) (> (mr b) 0) (> (w b) 0) (and (is-elt e) (is-replaced e)) (and (is-box v) (contains-content v)) (and (is-box l) (contains-content l))))))) (assert (forall ((b Box)) (= (box-collapsed-through b) (and (= (box-height b) 0.0) (=> (is-elt (box-elt b)) (not (is-replaced (box-elt b)))) (not (is-flow-root b)) (or (and (is-box/line (type b)) (=> (is-box (lflow b)) (not (contains-content (lflow b))))) (is-no-box (lflow b)) (box-collapsed-through (lflow b))))))) (define-fun min-max-width ((val Real) (b Box)) Real (ite (is-elt (box-elt b)) (max ,(get-px-or-% 'min-width '(w (pflow b)) 'b) (min-if val (not (is-max-width/none (style.max-width (computed-style (box-elt b))))) ,(get-px-or-% 'max-width '(w (pflow b)) 'b))) val)) (define-fun min-max-height ((val Real) (b Box)) Real (max (ite (is-elt (box-elt b)) ,(get-px-or-% 'min-height '(h (pflow b)) 'b) 0.0) (ite (or (is-no-elt (box-elt b)) (is-max-height/none (style.max-height (computed-style (box-elt b))))) val (min val ,(get-px-or-% 'max-height '(h (pflow b)) 'b))))) (define-fun margin-min-px ((m Margin) (b Box)) Real ,(smt-cond [(is-margin/px m) (margin.px m)] [(is-margin/% m) (%of (margin.% m) (w (pflow b)))] [else 0.0])) (define-fun min-w ((b Box)) Real (ite (is-elt (box-elt b)) (ite (is-width/auto (style.width (computed-style (box-elt b)))) (ite (is-replaced (box-elt b)) (- (intrinsic-width (box-elt b)) (bl b) (br b) (pl b) (pr b)) 0.0) ,(get-px-or-% 'width '(w (pflow b)) 'b)) 0.0)) (define-fun min-ml ((b Box)) Real (ite (is-elt (box-elt b)) (margin-min-px (style.margin-left (computed-style (box-elt b))) b) 0.0)) (define-fun min-mr ((b Box)) Real (ite (is-elt (box-elt b)) (margin-min-px (style.margin-right (computed-style (box-elt b))) b) 0.0)) (define-fun top-margin-collapses-with-children ((b Box)) Bool (and (not (is-flow-root b)) (= (pt b) 0.0) (= (bt b) 0.0))) (define-fun bottom-margin-collapses-with-children ((b Box)) Bool (and (not (is-flow-root b)) (= (pb b) 0.0) (= (bb b) 0.0) (=> (is-elt (box-elt b)) (and (is-height/auto (style.height (computed-style (box-elt b)))) (not (is-replaced (box-elt b))))))) (define-fun zero-box-model-except-collapse ((b Box)) Bool (and (= (mt b) (mr b) (mb b) (ml b) 0.0) (= (bt b) (br b) (bb b) (bl b) 0.0) (= (pt b) (pr b) (pb b) (pl b) 0.0))) (define-fun zero-box-model ((b Box)) Bool (and (= (mtp b) (mtn b) (mbp b) (mbn b) (mtp-up b) (mtn-up b) 0.0) (= (mb-clear b) false) (= (mt b) (mr b) (mb b) (ml b) 0.0) (= (bt b) (br b) (bb b) (bl b) 0.0) (= (pt b) (pr b) (pb b) (pl b) 0.0))) (declare-fun ancestor-line (Box) Box) (assert (forall ((b Box)) (= (ancestor-line b) (ite (is-box/line (type b)) b (ite (is-flow-root (pbox b)) no-box (ancestor-line (pbox b))))))) (define-fun vertical-position-for-flow-boxes ((b Box)) Real (let ([p (pflow b)] [v (vflow b)]) (ite (firstish-box b) (+ (top-content p) (ite (and (top-margin-collapses-with-children p) (not (and (is-elt (box-elt b)) (is-root-elt (box-elt b)))) (not (is-box/root (type b)))) 0.0 (+ (mtp b) (mtn b)))) (+ (ite (box-collapsed-through v) (top-outer v) (bottom-border v)) (+ (max (mbp v) (mtp b)) (min (mbn v) (mtn b))))))) (declare-fun inline-float-next-line (Box) Bool) (define-fun vertical-position-for-flow-roots ((b Box)) Real (let ([p (pflow b)] [v (vflow b)]) (ite (or (is-box/block (type p)) (is-flow-root p)) (ite (is-box v) (+ (ite (box-collapsed-through v) (top-outer v) (bottom-border v)) (mbp v) (mbn v)) (top-content p)) (ite (inline-float-next-line b) (bottom-border (ancestor-line b)) (ite (is-box (vbox (ancestor-line b))) (bottom-border (vbox (ancestor-line b))) (top-content (pbox (ancestor-line b)))))))) (define-fun has-clearance ((b Box)) Bool (and (is-elt (box-elt b)) (or (and (is-clear/left (style.clear (computed-style (box-elt b)))) (< (vertical-position-for-flow-boxes b) (ez.left-max (ez.in b)))) (and (is-clear/right (style.clear (computed-style (box-elt b)))) (< (vertical-position-for-flow-boxes b) (ez.right-max (ez.in b)))) (and (is-clear/both (style.clear (computed-style (box-elt b)))) (< (vertical-position-for-flow-boxes b) (max (ez.left-max (ez.in b)) (ez.right-max (ez.in b)))))))) (assert (forall ((b Box)) (= (firstish-box b) (let ([p (pflow b)] [v (vflow b)]) (or (and (not (is-box v)) (not (has-clearance v))) (and (box-collapsed-through v) (not (has-clearance v)) (firstish-box v))))))) (define-fun change-s831c ((b Box)) Bool (and (top-margin-collapses-with-children b) (is-box (lflow b)) (firstish-box (lflow b)) (box-collapsed-through (lflow b)) (is-elt (box-elt b)) (let ([mh (style.min-height (computed-style (box-elt b)))]) (or (and (is-min-height/px mh) (> (min-height.px mh) 0)) (and (is-min-height/% mh) (> (min-height.% mh) 0)))) (is-height/auto (style.height (computed-style (box-elt b)))))) (define-fun auto-height-for-flow-roots ((b Box)) Real CSS 2.1 § 10.6.7 ,(smt-cond [(is-replaced (box-elt b)) (min-max-height (- (intrinsic-height (box-elt b)) (bt b) (bb b) (pt b) (pb b)) b)] [(is-no-box (fbox b)) (min-max-height 0.0 b)] [(is-no-box (fflow b)) (min-max-height (max (- (ez.max (ez.out (lbox b))) (top-content b)) 0.0) b)] [else (min-max-height (- (max (ez.max (ez.out (lbox b))) (ite (box-collapsed-through (lflow b)) (+ (top-outer (lflow b)) (mbp (lflow b)) (mbn (lflow b))) (bottom-outer (lflow b)))) (top-content b)) b)])) (define-fun auto-height-for-flow-blocks ((b Box)) Real (let ([lb (lflow b)] [e (box-elt b)]) ,(smt-cond CSS 2.1 § 10.6.6 , first bullet [(is-flow-root b) (auto-height-for-flow-roots b)] CSS 2.1 § 10.6.3 , item 4 [(and (is-elt e) (is-replaced e)) (min-max-height (- (intrinsic-height e) (bt b) (bb b) (pt b) (pb b)) b)] [(is-no-box lb) (min-max-height 0.0 b)] CSS 2.1 § 10.6.3 , item 1 [(is-box/line (type lb)) (min-max-height (- (bottom-border lb) (top-content b)) b)] (min-max-height (ite (and (box-collapsed-through lb) (firstish-box lb) (top-margin-collapses-with-children b) (not (mb-clear lb))) CSS 2.1 § 10.6.3 , item 2 (+ (ite (box-collapsed-through lb) (top-outer lb) (bottom-border lb)) (ite (and (bottom-margin-collapses-with-children b) (not (mb-clear lb))) 0.0 (+ (mbp lb) (mbn lb)))) (top-content b))) b)]))) (define-fun margins-collapse ((b Box)) Bool (let ([f (fflow b)] [l (lflow b)] [v (vflow b)]) (and (= (mtp b) (max-if (max-if (ite (> (mt b) 0.0) (mt b) 0.0) (and (top-margin-collapses-with-children b) (is-box f) (not (has-clearance f))) (mtp-up f)) (and (box-collapsed-through b) (not (has-clearance b)) (is-box v)) (mbp v))) (= (mtp-up b) (max-if (ite (box-collapsed-through b) (mbp b) (mtp b)) (and (is-box (nflow b)) (box-collapsed-through b) (not (has-clearance (nflow b)))) (mtp-up (nflow b)))) (= (mtn b) (min-if (min-if (ite (< (mt b) 0.0) (mt b) 0.0) (and (top-margin-collapses-with-children b) (is-box f) (not (has-clearance f))) (mtn-up f)) (and (box-collapsed-through b) (not (has-clearance b)) (is-box v)) (mbn v))) (= (mtn-up b) (min-if (ite (box-collapsed-through b) (mbn b) (mtn b)) (and (is-box (nflow b)) (box-collapsed-through b) (not (has-clearance (nflow b)))) (mtn-up (nflow b)))) (= (mb-clear b) (or (has-clearance b) (and (is-box v) (box-collapsed-through b) (mb-clear v)))) (= (mbp b) (max-if (max-if (ite (> (mb b) 0.0) (mb b) 0.0) (and (bottom-margin-collapses-with-children b) (is-box l) (not (mb-clear l)) (not (change-s831c b))) (mbp l)) (box-collapsed-through b) (mtp b))) (= (mbn b) (min-if (min-if (ite (< (mb b) 0.0) (mb b) 0.0) (and (bottom-margin-collapses-with-children b) (is-box l) (not (mb-clear l)) (not (change-s831c b))) (mbn l)) (box-collapsed-through b) (mtn b)))))) (define-fun margins-dont-collapse ((b Box)) Bool (and (= (mtp-up b) (mtp b) (max (mt b) 0.0)) (= (mb-clear b) false) (= (mtn-up b) (mtn b) (min (mt b) 0.0)) (= (mbp b) (max (mb b) 0.0)) (= (mbn b) (min (mb b) 0.0)))) (declare-fun ancestor-block (Box) Box) (assert (forall ((b Box)) (= (ancestor-block b) (ite (is-box/block (type b)) b (ite (is-flow-root (pbox b)) no-box (ancestor-block (pbox b))))))) (define-fun relative-position-parent ((b Box)) Box (let ([r (computed-style (box-elt b))]) (ite (and (is-elt (box-elt b)) (not (is-float/none (style.float r)))) (ancestor-block (pflow b)) (pflow b)))) (define-fun relatively-positioned ((b Box)) Bool ,(smt-let ([r (computed-style (box-elt b))] [p (relative-position-parent b)]) (=> (is-offset/px (style.left r)) (= (xo b) (+ (offset.px (style.left r)) (xo p)))) (=> (is-offset/% (style.left r)) (= (xo b) (+ (%of (offset.% (style.left r)) (w p)) (xo p)))) (=> (is-offset/px (style.top r)) (= (yo b) (+ (offset.px (style.top r)) (yo p)))) (=> (is-offset/% (style.top r)) (= (yo b) (+ (%of (offset.% (style.top r)) (h p)) (yo p)))) (=> (and (is-offset/auto (style.left r)) (is-offset/px (style.right r))) (= (xo b) (- (xo p) (offset.px (style.right r))))) (=> (and (is-offset/auto (style.left r)) (is-offset/% (style.right r))) (= (xo b) (- (xo p) (%of (offset.% (style.right r)) (w p))))) (=> (and (is-offset/auto (style.top r)) (is-offset/px (style.bottom r))) (= (yo b) (- (yo p) (offset.px (style.bottom r))))) (=> (and (is-offset/auto (style.top r)) (is-offset/% (style.bottom r))) (= (yo b) (- (yo p) (%of (offset.% (style.bottom r)) (h p))))) (=> (and (is-offset/auto (style.left r)) (is-offset/auto (style.right r))) (= (xo b) (xo p))) (=> (and (is-offset/auto (style.top r)) (is-offset/auto (style.bottom r))) (= (yo b) (yo p))))) (define-fun no-relative-offset ((b Box)) Bool ,(smt-let ([r (computed-style (box-elt b))] [p (relative-position-parent b)]) (= (xo b) (xo p)) (= (yo b) (yo p)))) (define-fun resolve-clear ((b Box) (default Real)) Real (max-if (max-if default (and (is-elt (box-elt b)) (or (is-clear/left (style.clear (computed-style (box-elt b)))) (is-clear/both (style.clear (computed-style (box-elt b)))))) (ez.left-max (ez.in b))) (and (is-elt (box-elt b)) (or (is-clear/right (style.clear (computed-style (box-elt b)))) (is-clear/both (style.clear (computed-style (box-elt b)))))) (ez.right-max (ez.in b)))) (define-fun flow-horizontal-layout ((b Box) (available-width Real)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)] ) (= available-width (+ (ml b) (box-width b) (mr b))) (not (w-from-stfwidth b)) (let ([w* (min-max-width (min-w b) b)] [ml* (min-ml b)] [mr* (min-mr b)]) ,(smt-cond [(> (+ ml* (bl b) (pl b) w* (pr b) (br b) mr* (scroll-y b)) available-width) (= (w b) w*) (= (ml b) ml*) (width-set b)] [(or (is-no-elt e) (and (is-width/auto (style.width r)) (not (is-replaced e)))) (ite (and (is-elt e) (not (is-max-width/none (style.max-width r))) (> (- available-width ml* (bl b) (pl b) (pr b) (br b) mr*) ,(get-px-or-% 'max-width '(w p) 'b))) (and (= (w b) ,(get-px-or-% 'max-width '(w p) 'b)) ,(smt-cond [(not (is-margin/auto (style.margin-left r))) (= (ml b) ml*)] [(not (is-margin/auto (style.margin-right r))) (= (mr b) mr*)] [else (= (ml b) (mr b))]) (width-set b)) (and (= (ml b) ml*) (= (mr b) mr*) (width-set b)))] [else (= (w b) w*) (width-set b) ,(smt-cond [(not (is-margin/auto (style.margin-left r))) (= (ml b) ml*)] [(not (is-margin/auto (style.margin-right r))) (= (mr b) mr*)] [else (= (ml b) (mr b))])])))) (declare-fun lookback-overflow-width (Box) Real) (assert (forall ((b Box)) (<= 0 (lookback-overflow-width b) (w (pbox b))))) (define-fun available-width ((b Box)) Real (- (w (pbox b)) (ml b) (bl b) (pl b) (pr b) (br b) (mr b))) (define-fun usable-stfwidth ((b Box)) Real (let ([l (lbox b)]) (min-max-width (ite (is-box l) (min (max (stfwidth l) (available-width b)) (+ (stfmax l) (float-stfmax l))) (ite (is-replaced (box-elt b)) (- (intrinsic-width (box-elt b)) (bl b) (br b) (pl b) (pr b)) 0.0)) b))) (define-fun compute-stfwidth ((b Box)) Real (let ([l (lbox b)] [v (vbox b)] [r (computed-style (box-elt b))]) (max ,(smt-cond [(is-no-elt (box-elt b)) (+ (bl b) (max (pl b) 0.0) (ite (is-box l) (stfwidth l) 0.0) (pr b) (br b))] [(is-float/left (style.float r)) (- (right-outer b) (left-content (pbox b)))] [(is-float/right (style.float r)) (- (right-content (pbox b)) (left-outer b))] [else (+ (min-ml b) (bl b) (max (pl b) 0.0) (ite (and (not (is-replaced (box-elt b))) (is-width/auto (style.width r))) (ite (is-box l) (stfwidth l) 0.0) (w b)) (pr b) (br b) (min-mr b))]) (ite (is-box v) (stfwidth v) 0.0)))) (define-fun compute-stfmax ((b Box)) Real (let ([l (lbox b)] [v (vbox b)] [r (computed-style (box-elt b))]) ,(smt-cond [(is-no-elt (box-elt b)) (+ (ml b) (bl b) (pl b) (ite (is-box l) (stfmax l) 0.0) (pr b) (br b) (mr b))] [(is-float/left (style.float r)) (- (right-outer b) (left-content (pbox b)))] [(is-float/right (style.float r)) (- (right-content (pbox b)) (left-outer b))] [else (+ (min-ml b) (bl b) (max (pl b) 0.0) (ite (and (not (is-replaced (box-elt b))) (is-width/auto (style.width r))) (ite (is-box l) (stfmax l) 0.0) (w b)) (pr b) (br b) (min-mr b))]))) (define-fun positioned-vertical-layout ((b Box)) Bool CSS 2.1 § 10.6.4 ,(smt-let* ([r (computed-style (box-elt b))] [pp (ite (is-position/fixed (style.position (computed-style (box-elt b)))) (rootbox b) (ppflow b))] [temp-top ,(get-px-or-% 'top '(height-padding pp) 'b)] [temp-bottom ,(get-px-or-% 'bottom '(height-padding pp) 'b)] [temp-height (min-max-height (ite (is-replaced (box-elt b)) (- (intrinsic-height (box-elt b)) (bt b) (bb b) (pt b) (pb b)) ,(get-px-or-% 'height '(height-padding pp) 'b)) b)] [top? (not (is-offset/auto (style.top (computed-style (box-elt b)))))] [bottom? (not (is-offset/auto (style.bottom (computed-style (box-elt b)))))] [height? (or (is-replaced (box-elt b)) (not (is-height/auto (style.height (computed-style (box-elt b))))))]) (=> top? (= (top-outer b) (+ (top-padding pp) temp-top))) (=> height? (= (h b) temp-height)) (=> (and (not top?) (not bottom?)) (= (top-outer b) (vertical-position-for-flow-roots b))) (=> (and (not height?) (not (and top? bottom?))) (= (h b) (auto-height-for-flow-roots b))) (=> (and bottom? (not (and top? height?))) (= (bottom-outer b) (- (bottom-padding pp) temp-bottom))) (=> (not (and top? height? bottom?)) (and (= (mt b) (margin-min-px (style.margin-top r) b)) (= (mb b) (margin-min-px (style.margin-bottom r) b)))) Paragraph before the list , " If none of the three are ' auto ' " (=> (and top? bottom? height?) (and (=> (not (is-margin/auto (style.margin-top r))) (= (mt b) (margin-min-px (style.margin-top r) b))) (=> (not (is-margin/auto (style.margin-bottom r))) (= (mb b) (margin-min-px (style.margin-bottom r) b))) (=> (and (is-margin/auto (style.margin-top r)) (is-margin/auto (style.margin-bottom r))) (= (mt b) (mb b))) (=> (or (is-margin/auto (style.margin-top r)) (is-margin/auto (style.margin-bottom r))) (= (bottom-outer b) (- (bottom-padding pp) temp-bottom))))))) (define-fun positioned-horizontal-layout ((b Box)) Bool ,(smt-let* ([r (computed-style (box-elt b))] [pp (ite (is-position/fixed (style.position (computed-style (box-elt b)))) (rootbox b) (ppflow b))] [p (pflow b)] [temp-left ,(get-px-or-% 'left '(width-padding pp) 'b)] [temp-right ,(get-px-or-% 'right '(width-padding pp) 'b)] [temp-width (min-max-width (ite (is-replaced (box-elt b)) (- (intrinsic-width (box-elt b)) (bl b) (br b) (pl b) (pr b)) ,(get-px-or-% 'width '(width-padding pp) 'b)) b)] [left? (not (is-offset/auto (style.left (computed-style (box-elt b)))))] [right? (not (is-offset/auto (style.right (computed-style (box-elt b)))))] [width? (or (is-replaced (box-elt b)) (not (is-width/auto (style.width (computed-style (box-elt b))))))]) (width-set b) (=> (not (and left? width? right?)) (and (= (ml b) (margin-min-px (style.margin-left r) b)) (= (mr b) (margin-min-px (style.margin-right r) b)))) (=> left? (= (left-outer b) (+ (left-padding pp) temp-left))) (=> width? (and (= (w b) temp-width) (not (w-from-stfwidth b)))) (=> (and (not width?) (not (and left? right?))) (and (= (w b) (usable-stfwidth b)) (w-from-stfwidth b))) (=> (and (not left?) (not right?)) (= (left-outer b) (ite (or (is-box/block (type (pflow b))) (is-flow-root (pflow b))) (left-content p) (ite (is-box (vflow b)) (right-outer (vflow b)) (left-outer (pflow b)))))) (=> (and right? (not (and left? width?))) (= (right-outer b) (- (right-padding pp) temp-right))) (=> (and left? right?) (not (w-from-stfwidth b))) (=> (and left? width? right?) (and (=> (not (is-margin/auto (style.margin-left r))) (= (ml b) (margin-min-px (style.margin-left r) b))) (=> (not (is-margin/auto (style.margin-right r))) (= (mr b) (margin-min-px (style.margin-right r) b))) (=> (and (is-margin/auto (style.margin-left r)) (is-margin/auto (style.margin-right r))) (= (ml b) (mr b))) (=> (or (is-margin/auto (style.margin-left r)) (is-margin/auto (style.margin-right r))) (= (right-outer b) (- (right-padding pp) temp-right))))))) (declare-fun line-height (Box) Real) (assert (forall ((b Box)) (let ([e (box-elt b)]) (= (line-height b) (ite (is-elt e) (let ([lh (style.line-height (computed-style e))] [fs (style.font-size (computed-style e))]) ,(smt-cond [(is-line-height/normal lh) (font.line-height (font-info b))] [(is-line-height/num lh) (%of (* 100.0 (line-height.num lh)) (font-size.px fs))] ( is - line - height / px ( b ) ) (line-height.px lh)])) (ite (is-box (pflow b)) (line-height (pflow b)) 0.0)))))) (declare-fun ez.line (Box) EZone) (declare-fun ez.line-up (Box) EZone) (define-fun float-affects-own-line ((b Box)) Bool (let ([l (ancestor-line b)]) (and (is-box l) (or (< (top-outer b) (bottom-outer l)) Special case for zero - height ( empty ) lines (= (top-outer b) (top-outer l) (bottom-outer l)))))) (assert (forall ((b Box)) (= (ez.line-up b) (ite (and (is-flow-root b) (float-affects-own-line b)) (ez.line b) (ite (is-box (lbox b)) (ez.line-up (lbox b)) (ez.line b)))))) (assert (forall ((b Box)) (= (ez.line b) (ite (and (is-flow-root b) (float-affects-own-line b)) (ez.out b) (ite (is-box (vbox b)) (ez.line-up (vbox b)) (ez.in b)))))) These three functions define the three types of layouts (declare-fun uses-parent-w (Box) Bool) (assert (forall ((b Box)) (let ([e (box-elt b)] [r (computed-style (box-elt b))]) (= (uses-parent-w b) (or (and (=> (is-elt e) (is-width/auto (style.width r))) (is-box (vflow b)) (uses-parent-w (vflow b))) (and (=> (is-elt e) (is-width/auto (style.width r))) (is-box (lflow b)) (uses-parent-w (lflow b))) (and (is-elt e) (is-margin/% (style.margin-left r))) (and (is-elt e) (is-margin/% (style.margin-right r))) (and (is-elt e) (is-border/% (style.border-left-width r))) (and (is-elt e) (is-border/% (style.border-right-width r))) (and (is-elt e) (is-padding/% (style.padding-left r))) (and (is-elt e) (is-padding/% (style.padding-right r))) (and (is-elt e) (is-width/% (style.width r)))))))) (define-fun a-block-flow-box ((b Box)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)] [vb (vflow b)] [fb (fflow b)] [lb (lflow b)]) (ite (is-height/auto (style.height r)) (= (h b) (auto-height-for-flow-blocks b)) (= (h b) (min-max-height ,(get-px-or-% 'height '(h p) 'b) b))) (= (mt b) (ite (is-margin/auto (style.margin-top r)) 0.0 ,(get-px-or-% 'margin-top '(w p) 'b))) (= (mb b) (ite (is-margin/auto (style.margin-bottom r)) 0.0 ,(get-px-or-% 'margin-bottom '(w p) 'b))) (margins-collapse b) (= (stfmax b) (max-if (min-max-width (compute-stfmax b) b) (is-box (vbox b)) (stfmax (vbox b)))) (= (float-stfmax b) (+ (ite (is-flow-root b) 0.0 (min-max-width (ite (is-box (lbox b)) (float-stfmax (lbox b)) 0.0) b)) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (let ([y* (resolve-clear b (vertical-position-for-flow-boxes b))]) (ite (or (is-flow-root b) (and (is-elt e) (is-replaced e))) (and (= (ez.lookback b) (not (ez.test (ez.in b) (y b)))) (ite (not (ez.lookback b)) (= (y b) (ez.level (ez.in b) (+ (bl b) (pl b) (min-w b) (pr b) (br b)) (left-content p) (right-content p) y* float/left)) (>= (y b) y*))) (and (= (ez.lookback b) false) (= (y b) y*)))) (ite (or (is-flow-root b) (and (is-elt e) (is-replaced e))) (flow-horizontal-layout b (ite (not (ez.lookback b)) (- (ez.x (ez.in b) (y b) float/right (left-content p) (right-content p)) (ez.x (ez.in b) (y b) float/left (left-content p) (right-content p))) (lookback-overflow-width b))) (flow-horizontal-layout b (w p))) (=> (not (ez.lookback b)) (= (x b) (+ (ml b) (ite (or (is-flow-root b) (and (is-elt e) (is-replaced e))) (ez.x (ez.in b) (y b) float/left (left-content p) (right-content p)) (left-content p))))))) (define-fun a-block-float-box ((b Box)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)] [vb (vflow b)] [fb (fflow b)] [lb (lflow b)]) (= (mt b) (ite (is-margin/auto (style.margin-top r)) 0.0 ,(get-px-or-% 'margin-top '(w p) 'b))) (= (mr b) (ite (is-margin/auto (style.margin-right r)) 0.0 ,(get-px-or-% 'margin-right '(w p) 'b))) (= (mb b) (ite (is-margin/auto (style.margin-bottom r)) 0.0 ,(get-px-or-% 'margin-bottom '(w p) 'b))) (= (ml b) (ite (is-margin/auto (style.margin-left r)) 0.0 ,(get-px-or-% 'margin-left '(w p) 'b))) (margins-dont-collapse b) (= (w-from-stfwidth b) (is-width/auto (style.width r))) (= (stfmax b) (ite (is-box (vbox b)) (stfmax (vbox b)) 0.0)) (= (float-stfmax b) (+ (min-max-width (max (- (right-outer b) (left-outer b)) 0.0) b) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (width-set b) (ite (is-width/auto (style.width r)) (ite (is-replaced e) (= (w b) (- (intrinsic-width e) (bl b) (br b) (pl b) (pr b))) (or (= (w b) (usable-stfwidth b)) (and (is-box (lbox b)) (uses-parent-w (lbox b))))) (= (w b) (min-max-width ,(get-px-or-% 'width '(w (pbflow b)) 'b) b))) (ite (is-height/auto (style.height r)) (ite (is-replaced e) (= (h b) (- (intrinsic-height e) (bt b) (bb b) (pt b) (pb b))) (=> (width-set b) (= (h b) (auto-height-for-flow-roots b)))) (= (h b) (min-max-height ,(get-px-or-% 'height '(h p) 'b) b))) ,(smt-let* ([ez (ez.in b)] [w (- (right-outer b) (left-outer b))] [h (- (bottom-outer b) (top-outer b))] [y-normal (resolve-clear b (vertical-position-for-flow-roots b))] [y* (ez.level ez w (left-content (pbflow b)) (right-content (pbflow b)) y-normal (style.float r))] [x* (ez.x ez y* (style.float r) (left-content (pbflow b)) (right-content (pbflow b)))] [x (ite (is-float/left (style.float r)) x* (- x* w))]) (= (top-outer b) y*) (= (left-outer b) x) (= (ez.lookback b) false)))) (define-fun a-block-positioned-box ((b Box)) Bool (and (margins-dont-collapse b) (positioned-vertical-layout b) (positioned-horizontal-layout b) (= (stfmax b) (ite (is-box (vbox b)) (stfmax (vbox b)) 0.0)) (= (float-stfmax b) (+ (min-max-width (ite (is-box (lbox b)) (float-stfmax (lbox b)) 0.0) b) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (= (ez.lookback b) false))) (define-fun a-block-box ((b Box)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)]) (= (type b) box/block) (= (bt b) ,(get-px-or-% 'border-top-width '(w p) 'b)) (= (br b) ,(get-px-or-% 'border-right-width '(w p) 'b)) (= (bb b) ,(get-px-or-% 'border-bottom-width '(w p) 'b)) (= (bl b) ,(get-px-or-% 'border-left-width '(w p) 'b)) (= (pt b) ,(get-px-or-% 'padding-top '(w p) 'b)) (= (pr b) ,(get-px-or-% 'padding-right '(w p) 'b)) (= (pb b) ,(get-px-or-% 'padding-bottom '(w p) 'b)) (= (pl b) ,(get-px-or-% 'padding-left '(w p) 'b)) (= (stfwidth b) (min-max-width (compute-stfwidth b) b)) (= ( float - stfmax b ) ( ite ( is - box ( vbox b ) ) ( float - stfmax ( vbox b ) ) 0.0 ) ) (ite (is-position/relative (style.position r)) (relatively-positioned b) (no-relative-offset b)) (= (text-indent b) (ite (is-elt e) ,(get-px-or-% 'text-indent '(w b) 'b) 0.0)) ,(smt-cond [(or (is-position/absolute (position b)) (is-position/fixed (position b))) (a-block-positioned-box b)] [(box-in-flow b) (a-block-flow-box b)] [else (a-block-float-box b)]))) (declare-fun inline-block-offset (Box) Real) (define-fun an-inline-box ((b Box)) Bool ,(smt-let ([e (box-elt b)] [r (computed-style (box-elt b))] [p (pflow b)] [v (vflow b)] [l (lflow b)] [metrics (font-info b)] [leading (- (line-height b) (height-text b))]) (= (type b) box/inline) (= (bt b) ,(get-px-or-% 'border-top-width '(w p) 'b)) (= (bb b) ,(get-px-or-% 'border-bottom-width '(w p) 'b)) (= (pt b) ,(get-px-or-% 'padding-top '(w p) 'b)) (= (pb b) ,(get-px-or-% 'padding-bottom '(w p) 'b)) (= (mt b) (ite (is-margin/auto (style.margin-top r)) 0.0 ,(get-px-or-% 'margin-top '(w p) 'b))) (= (mb b) (ite (is-margin/auto (style.margin-bottom r)) 0.0 ,(get-px-or-% 'margin-bottom '(w p) 'b))) (ite (first-box? b) (and (= (pl b) ,(get-px-or-% 'padding-left '(w p) 'b)) (= (bl b) ,(get-px-or-% 'border-left-width '(w p) 'b)) (= (ml b) (+ (ite (is-margin/auto (style.margin-left r)) 0.0 ,(get-px-or-% 'margin-left '(w p) 'b)) (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0)))) (and (= (pl b) (bl b) 0.0) (= (ml b) (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0)))) (ite (last-box? b) (and (= (pr b) ,(get-px-or-% 'padding-right '(w p) 'b)) (= (br b) ,(get-px-or-% 'border-right-width '(w p) 'b)) (= (mr b) (ite (is-margin/auto (style.margin-right r)) 0.0 ,(get-px-or-% 'margin-right '(w p) 'b)))) (and (= (pr b) (br b) (mr b) 0.0))) (margins-dont-collapse b) (ite (is-position/relative (style.position r)) (relatively-positioned b) (no-relative-offset b)) (= (stfwidth b) (+ (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0) (min-max-width (compute-stfwidth b) b))) (= (stfmax b) (+ (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0) (ite (is-box (vbox b)) (stfmax (vbox b)) 0.0) (min-max-width (compute-stfmax b) b))) (= (float-stfmax b) (+ (ite (and (not (is-display/inline-block (style.display r))) (is-box (lbox b))) (min-max-width (float-stfmax (lbox b)) b) 0.0) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (= (text-indent b) (ite (is-elt e) ,(get-px-or-% 'text-indent '(w p) 'b) 0.0)) (= (baseline b) (baseline p)) (=> (and (is-elt e) (is-image e)) (= (inline-block-offset b) 0)) (ite (or (and (is-elt e) (is-replaced e)) (is-display/inline-block (style.display r))) (and (<= 0 (inline-block-offset b) (max (height-outer b) (font.descent metrics))) (= (above-baseline b) (max-if (- (height-outer b) (inline-block-offset b)) (is-box v) (above-baseline v))) (= (below-baseline b) (max-if (inline-block-offset b) (is-box v) (below-baseline v))) (= (bottom-outer b) (+ (baseline p) (inline-block-offset b)))) (and (= (top-content b) (- (baseline b) (font.ascent metrics) (font.topoffset metrics))) (= (above-baseline b) (max-if (max-if (+ (font.ascent metrics) (/ leading 2)) (is-box v) (above-baseline v)) (is-box l) (above-baseline l))) (= (below-baseline b) (max-if (max-if (+ (font.descent metrics) (/ leading 2)) (is-box v) (below-baseline v)) (is-box l) (below-baseline l))))) ,(smt-cond [(is-replaced e) (= (h b) (- (intrinsic-height e) (bt b) (bb b) (pt b) (pb b)))] [(is-display/inline-block (style.display r)) (= (h b) (ite (is-height/auto (style.height r)) (auto-height-for-flow-roots b) (min-max-height ,(get-px-or-% 'height '(h p) 'b) b)))] [else (= (h b) (font.selection-height metrics))]) ,(smt-cond [(is-replaced e) (= (w b) (- (intrinsic-width e) (bl b) (br b) (pl b) (pr b)))] [(is-display/inline-block (style.display r)) (ite (is-width/auto (style.width r)) (= (w b) (usable-stfwidth b)) (= (w b) (min-max-width ,(get-px-or-% 'width '(w p) 'b) b)))] [(is-box (fflow b)) (and (= (left-outer (fflow b)) (left-content b)) (= (right-outer (lflow b)) (right-content b)))] [else (= (w b) 0.0)]) (=> (is-box v) (= (left-outer b) (right-outer v))) (= (ez.lookback b) false))) (define-fun a-text-box ((b Box)) Bool ,(smt-let ([p (pflow b)] [v (vflow b)] [metrics (font-info b)] [leading (- (line-height b) (height-text b))]) (= (type b) box/text) (= (stfwidth b) (max (+ (ml b) (w b)) (ite (is-box (vbox b)) (stfwidth (vbox b)) 0.0))) (= (stfmax b) (+ (ite (is-box (vbox b)) (stfmax (vbox b)) 0.0) HAXXX (= (float-stfmax b) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0)) (= (baseline b) (baseline p)) (= (text-indent b) 0.0) (= (h b) (font.selection-height metrics)) (= (above-baseline b) (max-if (ite (> (w b) 0.0) (+ (font.ascent metrics) (/ leading 2)) 0.0) (is-box v) (above-baseline v))) (= (below-baseline b) (max-if (ite (> (w b) 0.0) (+ (font.descent metrics) (/ leading 2)) 0.0) (is-box v) (below-baseline v))) (= (y b) (- (baseline b) (+ (font.ascent metrics) (font.topoffset metrics)))) (no-relative-offset b) (= (mtp b) (mtn b) (mbp b) (mbn b) (mtp-up b) (mtn-up b) 0.0) (= (mb-clear b) false) (= (mt b) (mr b) (mb b) 0.0) (= (bt b) (br b) (bb b) (bl b) 0.0) (= (pt b) (pr b) (pb b) (pl b) 0.0) (= (ml b) (ite (and (is-no-box v) (is-box/line (type p)) (is-no-box (vflow p))) (text-indent p) 0.0)) (= (ez.lookback b) false))) (declare-fun ancestor-elt (Box) Element) (assert (forall ((b Box)) (= (ancestor-elt b) (ite (is-elt (box-elt b)) (box-elt b) (ite (is-box (pbox b)) (ancestor-elt (pbox b)) no-elt))))) (define-fun a-line-box ((b Box)) Bool ,(smt-let ([p (pflow b)] [v (vflow b)] [n (nflow b)] [f (fflow b)] [l (lflow b)] [metrics (font-info b)] [leading (- (line-height b) (height-text b))]) (= (type b) box/line) (no-relative-offset b) (zero-box-model b) (= (text-indent b) (text-indent p)) (let ([y-normal (resolve-clear b (ite (is-no-box v) (top-content p) (bottom-border v)))] [ez (ez.line-up (lbox b))]) (and (ite (not (ez.lookback b)) (and (= (y b) (ez.level ez (stfwidth (lbox b)) (left-content p) (right-content p) y-normal float/left)) (= (left-outer b) (ez.x ez (y b) float/left (left-content p) (right-content p))) (= (right-outer b) (ez.x ez (y b) float/right (left-content p) (right-content p)))) (and (>= (y b) y-normal) (>= (left-outer b) (left-content p)) (<= (right-outer b) (right-content p)))))) (= (stfwidth b) (compute-stfwidth b)) (= (stfmax b) (+ (ite (is-box v) (stfmax v) 0.0) (+ (stfmax (lbox b)) (pl b)))) (= (float-stfmax b) (+ (ite (is-box (lbox b)) (float-stfmax (lbox b)) 0.0) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (=> (is-box l) (= (baseline b) (+ (y b) (ite (contains-content l) (max-if (above-baseline l) (=> quirks-mode (is-display/list-item (style.display (computed-style (box-elt (pflow b)))))) (+ (font.ascent metrics) (* 0.5 leading))) 0.0)))) (=> (is-box l) (= (h b) (ite (contains-content l) (+ (max-if (above-baseline l) (=> quirks-mode (is-display/list-item (style.display (computed-style (box-elt (pflow b)))))) (+ (font.ascent metrics) (* 0.5 leading))) (max-if (below-baseline l) (=> quirks-mode (is-display/list-item (style.display (computed-style (box-elt (pflow b)))))) (+ (font.descent metrics) (* 0.5 leading)))) 0.0))) (=> (is-box f) (let ([wsub (- (right-outer l) (left-outer f))] [textalign (style.text-align (computed-style (ancestor-elt b)))]) ,(smt-cond [(> wsub (w b)) (= (left-outer f) (left-content b))] [(is-text-align/left textalign) (= (left-outer f) (left-content b))] [(is-text-align/justify textalign) (and (= (left-outer f) (left-content b)) (=> (is-box n) (= (right-outer l) (right-content b))))] [(is-text-align/right textalign) (= (right-outer l) (right-content b))] [(is-text-align/center textalign) (= (- (left-outer f) (left-content b)) (- (right-content b) (right-outer l)))] [else false]))))) (define-fun a-view-box ((b Box)) Bool (and (= (type b) box/root) (zero-box-model b) (= (x b) (y b) 0.0) (= (xo b) (yo b) 0.0) (= (box-width b) (browser.w ,(the-browser))) (= (box-height b) (browser.h ,(the-browser))) (= (ez.lookback b) false) (= (text-indent b) 0.0))) (define-fun a-magic-box ((b Box)) Bool (and (or (is-box/block (type b)) (is-box/inline (type b))) (not (ez.lookback b)))) (define-fun an-anon-block-box ((b Box)) Bool ,(smt-let ([p (pflow b)] [v (vflow b)] [l (lflow b)]) (= (type b) box/block) (no-relative-offset b) (zero-box-model-except-collapse b) (margins-collapse b) (flow-horizontal-layout b (w p)) (= (h b) (auto-height-for-flow-blocks b)) (= (text-indent b) (text-indent p)) (= (stfmax b) (max-if (stfmax l) (is-box v) (stfmax v))) (= (stfwidth b) (max-if (stfwidth l) (is-box v) (stfwidth v))) (= (float-stfmax b) (+ (ite (is-box (lbox b)) (float-stfmax (lbox b)) 0.0) (ite (is-box (vbox b)) (float-stfmax (vbox b)) 0.0))) (not (w-from-stfwidth b)) (= (y b) (vertical-position-for-flow-boxes b)) (= (x b) (left-content p)) (= (ez.lookback b) false))) (define-const min-size-for-scrollbars Real 45.0) (assert (forall ((b Box)) (or (= (scroll-x b) (ite (and (> (- (box-width b) (scroll-y b)) min-size-for-scrollbars) (is-box (pbox b)) (is-elt (box-elt b)) (is-elt (pelt (box-elt b))) (is-overflow/scroll (style.overflow-x (computed-style (box-elt b))))) (browser.scrollbar-width ,(the-browser)) 0)) (and (is-no-box (pbox b)) (or (= (scroll-x b) 0) (= (scroll-x b) (browser.scrollbar-width ,(the-browser)) (assert (forall ((b Box)) (or (= (scroll-y b) (ite (and (> (- (box-height b) (scroll-x b)) min-size-for-scrollbars) (is-box (pbox b)) (is-elt (box-elt b)) (is-elt (pelt (box-elt b))) (is-overflow/scroll (style.overflow-y (computed-style (box-elt b))))) (browser.scrollbar-width ,(the-browser)) 0)) (and (is-no-box (pbox b)) (or (= (scroll-y b) 0) (= (scroll-y b) (browser.scrollbar-width ,(the-browser)))))))))
d5cc4da99111244b8462ac5c14b01f7ea4cbeff439b4637ef9376ee4d28e248f
grin-compiler/ghc-wpc-sample-programs
WithDefault.hs
# LANGUAGE KindSignatures # {-# LANGUAGE DataKinds #-} | Potentially uninitialised Booleans -- The initial motivation for this small library is to be able to distinguish -- between a boolean option with a default value and an option which has been set to what happens to be the default value . In one case the default can be -- overriden (e.g. --cubical implies --without-K) while in the other case the -- user has made a mistake which they need to fix. module Agda.Utils.WithDefault where import Agda.Utils.TypeLits -- We don't want to have to remember for each flag whether its default value -- is True or False. So we bake it into the representation: the flag's type -- will mention its default value as a phantom parameter. data WithDefault (b :: Bool) = Default | Value Bool deriving (Eq, Show) -- The main mode of operation of these flags, apart from setting them explicitly, is to toggle them one way or the other if they had n't been already . setDefault :: Bool -> WithDefault b -> WithDefault b setDefault b t = case t of Default -> Value b _ -> t -- Provided that the default value is a known boolean (in practice we only use -- True or False), we can collapse a potentially uninitialised value to a boolean. collapseDefault :: KnownBool b => WithDefault b -> Bool collapseDefault w = case w of Default -> boolVal w Value b -> b
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/Utils/WithDefault.hs
haskell
# LANGUAGE DataKinds # The initial motivation for this small library is to be able to distinguish between a boolean option with a default value and an option which has been overriden (e.g. --cubical implies --without-K) while in the other case the user has made a mistake which they need to fix. We don't want to have to remember for each flag whether its default value is True or False. So we bake it into the representation: the flag's type will mention its default value as a phantom parameter. The main mode of operation of these flags, apart from setting them explicitly, Provided that the default value is a known boolean (in practice we only use True or False), we can collapse a potentially uninitialised value to a boolean.
# LANGUAGE KindSignatures # | Potentially uninitialised Booleans set to what happens to be the default value . In one case the default can be module Agda.Utils.WithDefault where import Agda.Utils.TypeLits data WithDefault (b :: Bool) = Default | Value Bool deriving (Eq, Show) is to toggle them one way or the other if they had n't been already . setDefault :: Bool -> WithDefault b -> WithDefault b setDefault b t = case t of Default -> Value b _ -> t collapseDefault :: KnownBool b => WithDefault b -> Bool collapseDefault w = case w of Default -> boolVal w Value b -> b
38872c11396540f235af66a4c4ecfe8e6d200b32f9f49a8f93603cd7d0a2b7df
charlieg/Sparser
count-lines data.lisp
On 9/18/09 with a "checkpoint" load sparser> (count-lines-in-system) ; Loading /Users / ddm / ws / nlp / Sparser / code / s / init / versions / v3.1 / loaders / master - loader.lisp ;; (format t "~%~A~4,2T~A~10,2T~S" ;; toplevel-forms line-count raw-namestring) 6 6 "tools;basics:loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/tools/basics/loader.lisp 8 8 "sugar;loader" ; Loading ; /Users/ddm/ws/nlp/Sparser/code/s/tools/basics/syntactic-sugar/loader.lisp 3 9 "sugar;then-and-else" 5 50 "sugar;strings" 6 53 "sugar;alists" 3 7 "sugar;predicates" 3 69 "sugar;printing" 2 5 "sugar;sorting" 4 29 "sugar;list hacking" 8 66 "basic tools;time" 9 24 "basic tools;no breaks" 7 8 "basic tools;debug stack" 2 14 "basic tools;SFL Clos" 5 5 "kons;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / tools / cons - resource / loader.lisp 3 6 "kons;heap" 26 71 "kons;alloc" 2 8 "kons;init" 6 26 "kons;kons" 3 3 "objects;traces:ops-loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / traces / ops - loader.lisp 17 56 "traces;trace function" 23 48 "traces;globals" 4 25 "rule objs;rule-links:object2" 3 3 "chart;units-labels:loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / units - labels / loader1.lisp 2 3 "chart;units-labels:units" 3 7 "chart;units-labels:labels" 14 19 "chart;words:loader3" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / words / loader3.lisp 18 153 "word-obj;object3" 4 40 "word-obj;def form" 7 33 "word-obj;catalog1" 3 24 "word-obj;whitespace" 7 77 "word-obj;resolve1" 19 147 "word-obj;polywords3" 3 62 "word-obj;polyword form1" 4 72 "word-obj;punctuation" 7 96 "word-obj;spaces" 3 24 "word-obj;whitespace" 2 23 "word-obj;section markers" 2 28 "word-obj;dummy words" 11 11 "lookup words;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / words / lookup / loader1.lisp 13 59 "lookup words;buffer" 2 15 "lookup words;find" 2 27 "lookup words;canonical" 4 21 "lookup words;properties" 34 247 "lookup words;capitalization" 14 77 "lookup words;morphology" 3 22 "lookup words;switch new1" 3 17 "lookup words;constant1" 14 93 "lookup words;new words4" 2 9 "lookup words;testing" 6 11 "chart;categories1:loader2" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / categories1 / loader2.lisp 2 6 "cat;object2" 6 32 "cat;printers" 17 121 "cat;lookup1" 3 22 "cat;form1" 5 5 "chart;positions:loader3" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / positions / loader3.lisp 14 80 "positions;positions1" 16 121 "positions;array2" 2 9 "positions;generic" 10 172 "positions;display" 5 5 "chart;edges:loader3" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / edges / loader3.lisp 32 296 "edges;object3" 3 33 "edges;printers" 11 46 "edges;multiplication1" 24 183 "edges;resource4" 6 6 "chart;edge-vectors:loader3" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / edge - vectors / loader3.lisp 3 30 "ev;switch" 16 165 "ev;object2" 7 49 "ev;printers2" 8 73 "ev;vectors2" 9 54 "ev;init2" 17 22 "rule objs;cfr:loader4" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / rules / cfr / loader4.lisp 6 25 "cfr;object1" 24 277 "cfr;dotted5" 6 72 "cfr;polywords1" 22 153 "cfr;printers1" 7 30 "cfr;catalog" 10 171 "cfr;lookup5" 6 91 "cfr;duplicates" 10 125 "cfr;multiplier3" 2 45 "cfr;form6" 3 42 "cfr;construct1" 11 225 "cfr;form-rule form" 5 75 "cfr;syntax rules" 2 17 "cfr;define5" 12 153 "cfr;delete4" 5 52 "cfr;knit in3" 2 2 "rule objs;csr:loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / rules / csr / loader.lisp 3 54 "csr;form" 4 37 "rule objs;rule-links:generic1" 6 6 "pattern-objects;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / rules / scan - patterns / loader.lisp 12 66 "pattern-objects;states" 2 26 "pattern-objects;pattern elements" 18 226 "pattern-objects;transitions" 7 35 "pattern-objects;patterns" 5 53 "pattern-objects;forms" 9 13 "chart;brackets:loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / brackets / loader.lisp 5 28 "bracket;object" 9 61 "bracket;assignments1" 12 138 "bracket;printers1" 2 56 "bracket;catalog" 6 101 "bracket;intern1" 5 25 "bracket;rank" 4 57 "bracket;form1" 3 3 "chart;stack:loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / stack / loader.lisp 7 27 "stack;object" 4 32 "stack;operations" 12 16 "objects;forms:loader7" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/forms/loader7.lisp 2 3 "forms;words" 2 4 "forms;polyword4" 2 3 "forms;spaces1" 2 3 "forms;punctuation1" 2 4 "forms;context variables" 5 35 "forms;categories1" 5 23 "forms;cfrs4" 2 15 "forms;csrs1" 2 15 "forms;style" 3 14 "forms;form rules" 2 6 "forms;pair interiors" 5 5 "objects;chart:generics:loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / generics / loader.lisp 7 79 "chart;generics:resolve1" 4 39 "chart;generics:delete" 12 86 "chart;generics:plist" 2 7 "chart;generics:pname" 9 29 "objects;model:loader2" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/model/loader2.lisp 6 45 "objects;model:categories:structure" 3 18 "objects;model:categories:ops structure" 2 11 "objects;model:individuals:structure" 2 9 "objects;model:bindings:structure" 3 17 "objects;model:variables:structure1" 10 98 "objects;model:lattice-points:structure1" 2 14 "objects;model:psi:structure1" 8 8 "objects;model:bindings:loader2" ; Loading ; /Users/ddm/ws/nlp/Sparser/code/s/objects/model/bindings/loader2.lisp 16 221 "bindings;object2" 4 48 "bindings;printers1" 25 323 "bindings;index" 6 65 "bindings;make2" 9 105 "bindings;hooks" 13 86 "bindings;resource" 3 75 "bindings;alloc1" 10 10 "objects;model:individuals:loader2" ; Loading ; /Users/ddm/ws/nlp/Sparser/code/s/objects/model/individuals/loader2.lisp 6 34 "individuals;object" 17 202 "individuals;printers" 9 263 "individuals;decode2" 10 110 "individuals;find1" 9 65 "individuals;index" 9 106 "individuals;delete" 17 104 "individuals;resource1" 29 245 "individuals;make2" 26 284 "individuals;reclaim1" 6 6 "objects;model:variables:loader2" ; Loading ; /Users/ddm/ws/nlp/Sparser/code/s/objects/model/variables/loader2.lisp 4 21 "variables;object2" 7 46 "variables;printers2" 10 54 "variables;index2" 2 17 "variables;form" 3 30 "variables;make2" 13 13 "objects;model:lattice-points:loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / model / lattice - points / loader1.lisp 23 166 "lattice-points;v+v objects2" 9 45 "lattice-points;c+v objects" 7 39 "lattice-points;printers" 24 270 "lattice-points;annotation" 6 21 "lattice-points;make1" 6 58 "lattice-points;find1" 3 59 "lattice-points;find or make at runtime1" 12 108 "lattice-points;initialize1" 4 20 "lattice-points;traverse1" 5 82 "lattice-points;specialize" 1 1 "lattice-points;dependent terms" 24 187 "lattice-points;operations1" 8 8 "objects;model:psi:loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / model / psi / loader1.lisp 13 86 "psi;resource" 5 22 "psi;object1" 4 20 "psi;printing1" 6 72 "psi;make2" 10 148 "psi;find2" 9 102 "psi;find or make2" 3 9 "psi;extend2" 39 177 "psi;traces" 4 4 "objects;model:categories:loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / model / categories / loader1.lisp 9 31 "categories;printing" 13 161 "categories;index instances1" 10 169 "categories;define1" 6 12 "objects;model:tree-families:loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / model / tree - families / loader1.lisp 12 85 "tf;object1" 9 198 "tf;form1" 2 3 "tf;def form" 17 427 "tf;driver2" 9 257 "tf;subrs3" 14 293 "tf;rdata1" 3 3 "objects;export:loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/export/loader.lisp 10 24 "objects;export:common" 1 2 "objects;export:etf" 1 1 "objects;export:mumble-grammar" 2 3 "objects;import:loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/import/loader.lisp 6 6 "init-drivers;loader7" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/inits/loader7.lisp 34 108 "session-inits;globals1" 6 58 "init-drivers;articles2" 3 19 "init-drivers;runs1" 4 4 "action-drivers;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / drivers / actions / loader1.lisp 4 50 "action-drivers;object" 2 38 "action-drivers;hook1" 3 38 "action-drivers;trigger2" 10 20 "required-words;required1" 8 8 "chars;loader3" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / char - level / loader3.lisp 15 52 "chars;state2" 4 79 "chars;setup-string3" 6 48 "chars;setup-file3" 3 10 "chars;setup-switch1" 11 98 "chars;display1" 7 123 "chars;testing1" 6 22 "chars;testing-file" 16 16 "required-words;spaces" 10 12 "tokens;loader3" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / tokenizer / loader3.lisp 9 86 "tokens;alphabet fns" 6 21 "tokens;state2" 5 120 "tokens;punctuation" 3 47 "tokens;caps fsa" 4 82 "tokens;token FSA3" 2 6 "tokens;lookup2" 2 3 "tokens;next token3" 3 13 "tokens;NL buffer" 19 246 "tokens;testing1" 4 4 "run FSAs;loader4" Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / FSA / loader4.lisp 5 22 "run FSAs;dispatches" 10 193 "run FSAs;words2" 7 156 "run FSAs;edges1" 3 3 "init chart;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / init / loader1.lisp 4 39 "init chart;init chart1" 2 22 "init chart;printer1" 9 333 "fsa;polywords4" 6 6 "fill chart;loader4" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / fill - chart / loader4.lisp 11 37 "fill chart;globals" 6 65 "fill chart;add5" 4 62 "fill chart;store5" 8 40 "fill chart;newline" 2 29 "fill chart;testing" 3 3 "scan;loader2" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / scan / loader2.lisp 3 37 "scan;scan1" 2 43 "scan;next-word" 4 4 "assess;loader6" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / assess / loader6.lisp 10 215 "assess;terminal edges2" 3 28 "assess;nonterminals1" 3 13 "assess;switch2" 7 7 "check;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / check / loader1.lisp 24 302 "check;multiply6" 1 1 "check;boundaries" 4 43 "check;one-one3" 2 24 "check;many-one1" 4 54 "check;one-many1" 3 40 "check;many-many1" 2 2 "analyzers;psp:threading:loader2" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / threading / loader2.lisp 7 71 "threading;extension" 1 1 "march;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / march / loader.lisp 22 28 "kinds of edges;loader2" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / edges / loader2.lisp 4 65 "kinds of edges;single-new1" 3 53 "kinds of edges;binary1" 2 62 "kinds of edges;binary-explicit2" 3 133 "kinds of edges;binary-explicit all keys2" 3 64 "kinds of edges;cs2" 3 45 "kinds of edges;initial-new1" 2 26 "kinds of edges;unknown" 2 33 "kinds of edges;polyw1" 2 38 "kinds of edges;long scan1" 4 46 "kinds of edges;looking under" 3 3 "complete;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / complete / loader1.lisp 8 69 "complete;complete HA3" 4 16 "complete;switch complete" 6 6 "annotation;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / annotation / loader.lisp 8 14 "referent;loader3" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / referent / loader3.lisp 4 16 "referent;composite referent" 20 67 "referent;driver2" 6 45 "referent;dispatch2" 14 210 "referent;decode exp1" 4 89 "referent;unary driver3" 5 105 "referent;cases1" 9 172 "referent;new decodings1" 7 270 "referent;new cases3" 2 4 "analyzers;psp:terminate" 7 7 "forest;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / forest / loader1.lisp 17 139 "forest;treetops" 3 100 "forest;sequence" 28 332 "forest;printers" 3 3 "forest;adjacency" 21 130 "forest;extract" 2 53 "forest;layout" 5 5 "traversal-routines;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / traversal / loader.lisp 3 61 "traversal-routines;form" 7 77 "traversal-routines;forest scan" 5 135 "traversal-routines;dispatch" 3 70 "traversal-routines;interiors1" 6 6 "scan-patterns;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / patterns / loader.lisp 6 68 "scan-patterns;take transitions" 1 1 "scan-patterns;start" 36 354 "scan-patterns;driver" 9 79 "scan-patterns;follow-out" 4 38 "scan-patterns;accept" 5 5 "do HA;loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/analyzers/HA/loader.lisp 5 75 "do HA;look" 2 2 "do HA;segment" 20 199 "do HA;place brackets1" 6 124 "do HA;inter-segment boundaries" 5 5 "do CA;loader1" Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / CA / loader1.lisp 6 15 "do CA;actions" 11 71 "do CA;scanners1" 2 44 "do CA;search2" 28 435 "do CA;anaphora3" 3 19 "session-inits;setup3" 41 41 "required-words;punctuation1" 131 413 "tokens;alphabet" 5 5 "required-brackets;required" 28 47 "gr-tests;parsing" 7 9 "source-drivers;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / drivers / sources / loader1.lisp 11 25 "source-drivers;state" 4 17 "source-drivers;core1" 3 5 "source-drivers;string" 4 19 "source-drivers;file1" 3 5 "source-drivers;open file" 10 34 "traces;online hook" 2 2 "articles;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / drivers / articles / loader.lisp 11 79 "articles;style" 6 6 "sink-drivers;loader1" Loading /Users / ddm / ws / nlp / Sparser / code / s / drivers / sinks / loader1.lisp 3 9 "sink-drivers;articles" 5 15 "sink-drivers;records" 7 53 "sink-drivers;core" 46 289 "sink-drivers;export" 7 43 "sink-drivers;return-value" 2 2 "drivers;tokens:loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/tokens/loader.lisp 17 94 "drivers;tokens:next-terminal2" 9 9 "chart-drivers;loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/chart/loader.lisp 5 43 "chart-drivers;select2" 8 53 "chart-drivers;scan-all-terminals" 4 28 "chart-drivers;switch" 9 73 "chart-drivers;headers" 3 92 "chart-drivers;header labels" 5 27 "chart-drivers;hidden markup" 16 78 "chart-drivers;annotate last" 10 10 "chart-drivers;psp:loader5" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / drivers / chart / psp / loader5.lisp 39 130 "psp-drivers;flags" 5 78 "psp-drivers;initiate pattern scan" 28 377 "psp-drivers;scan3" 22 287 "psp-drivers;adjudicators1" 19 385 "psp-drivers;pts5" 12 292 "psp-drivers;march-seg5" 12 163 "psp-drivers;march-forest3" 15 163 "psp-drivers;PPTT8" 6 121 "psp-drivers;trigger5" 6 26 "chart-drivers;traversal1" 3 3 "chart-drivers;all-edges:loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / drivers / chart / all - edges / loader1.lisp 18 250 "all edges;loops" 4 5 "forest-drivers;loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/forest/loader.lisp 7 45 "forest-drivers;actions1" 4 61 "forest-drivers;trap2" 4 49 "drivers;DA:driver1" 23 288 "init-drivers;switches2" 23 23 "objects;traces:cases-loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / objects / traces / cases - loader1.lisp 3 3 "traces;tokenizer" 24 101 "traces;FSA1" 55 232 "traces;cap seq" 96 104 "traces;edges1" 185 855 "traces;psp1" 14 64 "traces;psp-all-edges" 24 100 "traces;scan patterns" 9 23 "traces;completion" 15 55 "traces;conjunction" 3 6 "traces;treetops" 15 48 "traces;CA" 35 134 "traces;DA" 16 46 "traces;HA" 63 271 "traces;DM&P" 8 17 "traces;discourse" 18 53 "traces;sections" 6 12 "traces;section stack" 8 18 "traces;sgml" 8 25 "traces;paragraphs" 2 3 "traces;readout" 7 30 "traces;debugging" 52 217 "traces;psi" 7 12 "file ops;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / interface / files / loader1.lisp 2 17 "file ops;decoding" 3 20 "file ops;file name" 6 15 "file ops;open-close" 4 13 "file ops;read switch1" 3 24 "file ops;read chars1" 8 45 "workbench;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / interface / workbench / loader.lisp 32 92 "workbench;globals" 13 80 "workbench;adjust" 13 141 "workbench;autodef data" 10 152 "workbench;def rule:save1" 6 11 "grammar-interface;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / interface / grammar / loader.lisp 3 37 "grammar-interface;postprocessing" 28 273 "grammar-interface;sort" 5 49 "grammar-interface;printing" 27 246 "grammar-interface;sort individuals" 4 4 "timing;loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/timing/loader.lisp 3 13 "timing;calculation" 12 125 "timing;presentation" 5 20 "timing;cases" 9 43 "measuring;distance between brackets" 7 71 "measuring;line count" 6 6 "citation-code;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / tests / citations / code / loader.lisp 8 32 "citation-code;object" 11 118 "citation-code;test" 4 23 "citation-code;input-output" 6 111 "citation-code;construction" 2 4 "citation-code;batches" 3 166 "loaders;grammar" 4 97 "grammar edge types;digits" 3 97 "grammar edge types;form rules" 2 50 "grammar edge types;CA" 2 39 "grammar edge types;pnf" 2 27 "grammar edge types;pronouns1" 4 7 "fsa;loader - model1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / FSAs / loader --- model1.lisp 11 200 "fsa;abbreviations2" 11 11 "fsa;single quote1" 11 112 "fsa;hyphen" 81 139 "the-categories;categories" 36 52 "brackets;types" 11 248 "brackets;judgements1" 14 30 "words;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / words / loader1.lisp 3 47 "words;fn word routine" 31 31 "words;punctuation bracketing" 4 6 "words;punctuation rules" 10 14 "words;determiners" 18 18 "words;conjunctions" 5 5 "words;interjections" 35 36 "words;pronouns" 4 94 "words;quantifiers1" 36 42 "words;prepositions2" 12 12 "words;WH words" 43 48 "words;aux verbs" 15 15 "words;contractions" 2 5 "words;adjectives" 34 43 "words;adverbs" 2 2 "words;whitespace assignments" 21 21 "tree-families;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / tree - families / loader1.lisp 5 50 "tree-families;single words" 42 628 "tree-families;morphology1" 5 82 "tree-families;postprocessing1" 10 170 "tree-families;NP" 8 76 "tree-families;np adjuncts" 15 132 "tree-families;pre-head np modifiers" 7 68 "tree-families;of" 2 2 "tree-families;dates" 1 9 "tree-families;vp" 5 45 "tree-families;transitive" 3 26 "tree-families;ditransitive" 4 57 "tree-families;indirect obj pattern" 6 117 "tree-families;verbs taking pps" 3 27 "tree-families;copula patterns" 2 25 "tree-families;that comp" 2 16 "tree-families;compounds" 3 18 "tree-families;prepositional phrases" 4 26 "tree-families;adjective phrases" 3 32 "tree-families;adverbs" 16 256 "tree-families;shortcuts" 2 11 "tree-families;interjections" 10 28 "syntax;loader3" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / syntax / loader3.lisp 4 94 "syntax-morph;affix rules" 20 74 "syntax-vg;tense" 13 65 "syntax-vg;have" 26 116 "syntax-vg;be" 57 245 "syntax-vg;modals" 12 34 "syntax-vg;adverbs" 22 65 "syntax-art;articles" 20 271 "syntax-conj;conjunction7" 1 1 "syntax-rel;subject relatives" 8 60 "syntax-poss;possessive" 4 22 "syntax-comp;comparatives" 24 57 "syntax-comp;WH-word-semantics" 21 89 "syntax-comp;questions" 5 13 "adjuncts;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / adjuncts / loader.lisp 9 60 "approx;object" 5 28 "frequency;object" 12 34 "frequency;aux rules" 9 52 "sequence;object" 7 17 "places;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / places / loader1.lisp 19 90 "places;object" 6 35 "places;directions1" 4 34 "places;compass points" 3 7 "places;directional rules" 4 4 "countries;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / places / countries / loader1.lisp 5 46 "countries;object1" 5 29 "countries;relation" 4 4 "countries;rules1" 6 105 "places;city" 5 62 "places;U.S. States" 5 49 "places;other" 4 4 "places;rules2" 4 4 "collections;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / collections / loader1.lisp 4 20 "collections;object1" 11 262 "collections;operations2" 5 55 "collections;obj specific printers" 10 10 "numbers;loader2" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / numbers / loader2.lisp 27 91 "numbers;object1" 12 22 "numbers;categories1" 8 163 "numbers;form2" 25 368 "numbers;fsa digits6" 12 96 "numbers;fsa words" 8 67 "numbers;ordinals3" 4 16 "numbers;percentages1" 7 19 "numbers;rules" 4 14 "numbers;relation" 8 8 "amounts;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / amounts / loader1.lisp 4 15 "amounts;unit of measure1" 3 8 "amounts;quantities" 3 26 "amounts;measurements" 2 10 "amounts;object1" 17 135 "amounts;amount-change verbs" 9 47 "amounts;amount-chg relation" 2 4 "amounts;rules1" 2 2 "kinds;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / kinds / loader.lisp 5 59 "kinds;object" 2 6 "kinds;np rules" 4 4 "money;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / money / loader1.lisp 8 82 "money;objects1" 3 16 "money;printers" 3 7 "money;rules1" 14 14 "core;time:loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / time / loader1.lisp 2 4 "time;object" 2 7 "time;units1" 3 31 "time;weekdays1" 3 33 "time;months1" 3 15 "time;years2" 15 34 "time;time-of-day" 4 30 "time;relative moments" 4 28 "time;dates2" 6 33 "time;amounts" 6 30 "time;phrases1" 8 30 "time;anaphors1" 8 26 "time;age1" 25 145 "time;fiscal2" 5 7 "pronouns;loader2" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / pronouns / loader2.lisp 10 67 "pronouns;object1" 32 33 "pronouns;cases1" 2 10 "ambush;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / sl / ambush / loader.lisp 11 53 "ambush;call-signs" 8 25 "ambush;protocols" 6 20 "ambush;checkpoints" 2 4 "ambush;contact" 1 1 "ambush;perimeter" 1 1 "ambush;munitions" 1 1 "ambush;casualties" 1 1 "ambush;misc" 2 5 "ckpt;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / sl / checkpoint / loader.lisp 69 253 "ckpt;vocabulary" 8281 8351 "ckpt;adjectives" 54 147 "ckpt;rules" 4 8 "ha;loader1" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / HA / loader1.lisp 4 82 "ha;driver" 3 43 "ha;both ends1" 2 28 "ha;determiner1" 2 83 "cat-prefs;category preferences" 44 281 "words;frequency" 30 128 "dossiers;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / dossiers / loader.lisp 0 0 "dossiers;irregular verbs" 2 2 "dossiers;semantics-free verbs" 2 2 "dossiers;new content words" 11 11 "dossiers;comparatives" 3 7 "dossiers;rules comparatives" 2 41 "dossiers;numbers" 2 33 "dossiers;ordinals" 5 5 "dossiers;time units" 8 8 "dossiers;deictic times" 8 8 "dossiers;weekdays" 13 13 "dossiers;months" 62 62 "dossiers;years" 39 39 "dossiers;time of day" 51 51 "dossiers;timezones" 6 6 "dossiers;approximations" 2 4 "dossiers;approximator rules" 9 9 "dossiers;frequency adverbs" 7 7 "dossiers;sequencers" 0 0 "dossiers;kinds" 2 2 "dossiers;location descriptions" 7 7 "dossiers;location kinds" 16 16 "dossiers;directions" 13 13 "dossiers;compass points" 22 22 "dossiers;spatial prepositions" 14 20 "dossiers;countries" 2 2 "dossiers;cities" 7 49 "dossiers;city rules" 52 99 "dossiers;U.S. States" 2 4 "dossiers;U.S. State rules" 2 2 "dossiers;regions" 5 5 "dossiers;units of measure" 2 2 "dossiers;quantities" 6 10 "dossiers;denominations of money" 5 9 "dossiers;currencies" 0 0 "dossiers;semantics-weak verbs" apreq has 3 instances ainrn has 2 instances attributive has 3 instances gradable has 21 instances predicative has 2 instances null-adj has 5 instances greeting has 4 instances acknowledgement has 3 instances call-word has 1 instances pronoun/plural has 5 instances pronoun/inanimate has 3 instances pronoun/female has 3 instances pronoun/male has 4 instances pronoun/first/plural has 5 instances pronoun/first/singular has 5 instances calculated-time has 2 instances relative-time-noun has 1 instances relative-time-adverb has 1 instances year has 61 instances month has 12 instances weekday has 7 instances time-unit has 4 instances currency has 4 instances fractional-denomination/money has 2 instances denomination/money has 3 instances unit-of-measure has 4 instances ordinal has 31 instances illions-distribution has 33 instances multiplier has 7 instances region has 1 instances US-state has 51 instances city has 2 instances country has 13 instances compass-point has 12 instances direction has 15 instances kind-of-location has 6 instances sequencer has 6 instances frequency-of-event has 8 instances approximator has 5 instances quantifier has 20 instances 6 6 "grammar;tests:loader" ; Loading /Users/ddm/ws/nlp/Sparser/code/s/grammar/tests/loader.lisp 18 72 "gr-tests;workspace" 1 1 "gr-tests;rule deletion" 13 28 "gr-tests;edge resource" 8 8 "gr-tests;timing" 1 1 "gr-tests;edge-tests" 3 3 "citations;loader" ; Loading /Users / ddm / ws / nlp / Sparser / code / s / grammar / tests / citations / cases / loader.lisp 18 41 "citations;systematically organized" 9 26 "citations;new ones"Identical rules found: #<PSR311 time-unit -> hyphen time-unit> #<PSR293 time-unit -> hyphen time-unit> ------------------------------------------- 163 Referential categories 74 Syntactic form categories 19 Mixin categories 71 non-terminal categories 100 dotted categories ------------------------------------------- 31 105 "version;workspace:abbreviations" 2 3 "version;workspace:traces" 39 39 "version;workspace:switch settings" 2 9 "version;workspace:basic tests" ----------------------------------------- 601 files 47026 lines of code 14338 toplevel forms ----------------------------------------- nil sparser>
null
https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/documentation/in%20progress/count-lines%20data.lisp
lisp
Loading (format t "~%~A~4,2T~A~10,2T~S" toplevel-forms line-count raw-namestring) Loading /Users/ddm/ws/nlp/Sparser/code/s/tools/basics/loader.lisp Loading /Users/ddm/ws/nlp/Sparser/code/s/tools/basics/syntactic-sugar/loader.lisp Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/forms/loader7.lisp Loading Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/model/loader2.lisp Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/model/bindings/loader2.lisp Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/model/individuals/loader2.lisp Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/model/variables/loader2.lisp Loading Loading Loading Loading Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/export/loader.lisp Loading /Users/ddm/ws/nlp/Sparser/code/s/objects/import/loader.lisp Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/inits/loader7.lisp Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading /Users/ddm/ws/nlp/Sparser/code/s/analyzers/HA/loader.lisp Loading Loading Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/tokens/loader.lisp Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/chart/loader.lisp Loading Loading Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/forest/loader.lisp Loading Loading Loading Loading Loading /Users/ddm/ws/nlp/Sparser/code/s/drivers/timing/loader.lisp Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading Loading /Users/ddm/ws/nlp/Sparser/code/s/grammar/tests/loader.lisp Loading
On 9/18/09 with a "checkpoint" load sparser> (count-lines-in-system) /Users / ddm / ws / nlp / Sparser / code / s / init / versions / v3.1 / loaders / master - loader.lisp 6 6 "tools;basics:loader" 8 8 "sugar;loader" 3 9 "sugar;then-and-else" 5 50 "sugar;strings" 6 53 "sugar;alists" 3 7 "sugar;predicates" 3 69 "sugar;printing" 2 5 "sugar;sorting" 4 29 "sugar;list hacking" 8 66 "basic tools;time" 9 24 "basic tools;no breaks" 7 8 "basic tools;debug stack" 2 14 "basic tools;SFL Clos" 5 5 "kons;loader" /Users / ddm / ws / nlp / Sparser / code / s / tools / cons - resource / loader.lisp 3 6 "kons;heap" 26 71 "kons;alloc" 2 8 "kons;init" 6 26 "kons;kons" 3 3 "objects;traces:ops-loader" /Users / ddm / ws / nlp / Sparser / code / s / objects / traces / ops - loader.lisp 17 56 "traces;trace function" 23 48 "traces;globals" 4 25 "rule objs;rule-links:object2" 3 3 "chart;units-labels:loader1" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / units - labels / loader1.lisp 2 3 "chart;units-labels:units" 3 7 "chart;units-labels:labels" 14 19 "chart;words:loader3" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / words / loader3.lisp 18 153 "word-obj;object3" 4 40 "word-obj;def form" 7 33 "word-obj;catalog1" 3 24 "word-obj;whitespace" 7 77 "word-obj;resolve1" 19 147 "word-obj;polywords3" 3 62 "word-obj;polyword form1" 4 72 "word-obj;punctuation" 7 96 "word-obj;spaces" 3 24 "word-obj;whitespace" 2 23 "word-obj;section markers" 2 28 "word-obj;dummy words" 11 11 "lookup words;loader1" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / words / lookup / loader1.lisp 13 59 "lookup words;buffer" 2 15 "lookup words;find" 2 27 "lookup words;canonical" 4 21 "lookup words;properties" 34 247 "lookup words;capitalization" 14 77 "lookup words;morphology" 3 22 "lookup words;switch new1" 3 17 "lookup words;constant1" 14 93 "lookup words;new words4" 2 9 "lookup words;testing" 6 11 "chart;categories1:loader2" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / categories1 / loader2.lisp 2 6 "cat;object2" 6 32 "cat;printers" 17 121 "cat;lookup1" 3 22 "cat;form1" 5 5 "chart;positions:loader3" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / positions / loader3.lisp 14 80 "positions;positions1" 16 121 "positions;array2" 2 9 "positions;generic" 10 172 "positions;display" 5 5 "chart;edges:loader3" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / edges / loader3.lisp 32 296 "edges;object3" 3 33 "edges;printers" 11 46 "edges;multiplication1" 24 183 "edges;resource4" 6 6 "chart;edge-vectors:loader3" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / edge - vectors / loader3.lisp 3 30 "ev;switch" 16 165 "ev;object2" 7 49 "ev;printers2" 8 73 "ev;vectors2" 9 54 "ev;init2" 17 22 "rule objs;cfr:loader4" /Users / ddm / ws / nlp / Sparser / code / s / objects / rules / cfr / loader4.lisp 6 25 "cfr;object1" 24 277 "cfr;dotted5" 6 72 "cfr;polywords1" 22 153 "cfr;printers1" 7 30 "cfr;catalog" 10 171 "cfr;lookup5" 6 91 "cfr;duplicates" 10 125 "cfr;multiplier3" 2 45 "cfr;form6" 3 42 "cfr;construct1" 11 225 "cfr;form-rule form" 5 75 "cfr;syntax rules" 2 17 "cfr;define5" 12 153 "cfr;delete4" 5 52 "cfr;knit in3" 2 2 "rule objs;csr:loader" /Users / ddm / ws / nlp / Sparser / code / s / objects / rules / csr / loader.lisp 3 54 "csr;form" 4 37 "rule objs;rule-links:generic1" 6 6 "pattern-objects;loader" /Users / ddm / ws / nlp / Sparser / code / s / objects / rules / scan - patterns / loader.lisp 12 66 "pattern-objects;states" 2 26 "pattern-objects;pattern elements" 18 226 "pattern-objects;transitions" 7 35 "pattern-objects;patterns" 5 53 "pattern-objects;forms" 9 13 "chart;brackets:loader" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / brackets / loader.lisp 5 28 "bracket;object" 9 61 "bracket;assignments1" 12 138 "bracket;printers1" 2 56 "bracket;catalog" 6 101 "bracket;intern1" 5 25 "bracket;rank" 4 57 "bracket;form1" 3 3 "chart;stack:loader" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / stack / loader.lisp 7 27 "stack;object" 4 32 "stack;operations" 12 16 "objects;forms:loader7" 2 3 "forms;words" 2 4 "forms;polyword4" 2 3 "forms;spaces1" 2 3 "forms;punctuation1" 2 4 "forms;context variables" 5 35 "forms;categories1" 5 23 "forms;cfrs4" 2 15 "forms;csrs1" 2 15 "forms;style" 3 14 "forms;form rules" 2 6 "forms;pair interiors" 5 5 "objects;chart:generics:loader" /Users / ddm / ws / nlp / Sparser / code / s / objects / chart / generics / loader.lisp 7 79 "chart;generics:resolve1" 4 39 "chart;generics:delete" 12 86 "chart;generics:plist" 2 7 "chart;generics:pname" 9 29 "objects;model:loader2" 6 45 "objects;model:categories:structure" 3 18 "objects;model:categories:ops structure" 2 11 "objects;model:individuals:structure" 2 9 "objects;model:bindings:structure" 3 17 "objects;model:variables:structure1" 10 98 "objects;model:lattice-points:structure1" 2 14 "objects;model:psi:structure1" 8 8 "objects;model:bindings:loader2" 16 221 "bindings;object2" 4 48 "bindings;printers1" 25 323 "bindings;index" 6 65 "bindings;make2" 9 105 "bindings;hooks" 13 86 "bindings;resource" 3 75 "bindings;alloc1" 10 10 "objects;model:individuals:loader2" 6 34 "individuals;object" 17 202 "individuals;printers" 9 263 "individuals;decode2" 10 110 "individuals;find1" 9 65 "individuals;index" 9 106 "individuals;delete" 17 104 "individuals;resource1" 29 245 "individuals;make2" 26 284 "individuals;reclaim1" 6 6 "objects;model:variables:loader2" 4 21 "variables;object2" 7 46 "variables;printers2" 10 54 "variables;index2" 2 17 "variables;form" 3 30 "variables;make2" 13 13 "objects;model:lattice-points:loader1" /Users / ddm / ws / nlp / Sparser / code / s / objects / model / lattice - points / loader1.lisp 23 166 "lattice-points;v+v objects2" 9 45 "lattice-points;c+v objects" 7 39 "lattice-points;printers" 24 270 "lattice-points;annotation" 6 21 "lattice-points;make1" 6 58 "lattice-points;find1" 3 59 "lattice-points;find or make at runtime1" 12 108 "lattice-points;initialize1" 4 20 "lattice-points;traverse1" 5 82 "lattice-points;specialize" 1 1 "lattice-points;dependent terms" 24 187 "lattice-points;operations1" 8 8 "objects;model:psi:loader1" /Users / ddm / ws / nlp / Sparser / code / s / objects / model / psi / loader1.lisp 13 86 "psi;resource" 5 22 "psi;object1" 4 20 "psi;printing1" 6 72 "psi;make2" 10 148 "psi;find2" 9 102 "psi;find or make2" 3 9 "psi;extend2" 39 177 "psi;traces" 4 4 "objects;model:categories:loader1" /Users / ddm / ws / nlp / Sparser / code / s / objects / model / categories / loader1.lisp 9 31 "categories;printing" 13 161 "categories;index instances1" 10 169 "categories;define1" 6 12 "objects;model:tree-families:loader1" /Users / ddm / ws / nlp / Sparser / code / s / objects / model / tree - families / loader1.lisp 12 85 "tf;object1" 9 198 "tf;form1" 2 3 "tf;def form" 17 427 "tf;driver2" 9 257 "tf;subrs3" 14 293 "tf;rdata1" 3 3 "objects;export:loader" 10 24 "objects;export:common" 1 2 "objects;export:etf" 1 1 "objects;export:mumble-grammar" 2 3 "objects;import:loader" 6 6 "init-drivers;loader7" 34 108 "session-inits;globals1" 6 58 "init-drivers;articles2" 3 19 "init-drivers;runs1" 4 4 "action-drivers;loader1" /Users / ddm / ws / nlp / Sparser / code / s / drivers / actions / loader1.lisp 4 50 "action-drivers;object" 2 38 "action-drivers;hook1" 3 38 "action-drivers;trigger2" 10 20 "required-words;required1" 8 8 "chars;loader3" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / char - level / loader3.lisp 15 52 "chars;state2" 4 79 "chars;setup-string3" 6 48 "chars;setup-file3" 3 10 "chars;setup-switch1" 11 98 "chars;display1" 7 123 "chars;testing1" 6 22 "chars;testing-file" 16 16 "required-words;spaces" 10 12 "tokens;loader3" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / tokenizer / loader3.lisp 9 86 "tokens;alphabet fns" 6 21 "tokens;state2" 5 120 "tokens;punctuation" 3 47 "tokens;caps fsa" 4 82 "tokens;token FSA3" 2 6 "tokens;lookup2" 2 3 "tokens;next token3" 3 13 "tokens;NL buffer" 19 246 "tokens;testing1" 4 4 "run FSAs;loader4" Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / FSA / loader4.lisp 5 22 "run FSAs;dispatches" 10 193 "run FSAs;words2" 7 156 "run FSAs;edges1" 3 3 "init chart;loader1" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / init / loader1.lisp 4 39 "init chart;init chart1" 2 22 "init chart;printer1" 9 333 "fsa;polywords4" 6 6 "fill chart;loader4" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / fill - chart / loader4.lisp 11 37 "fill chart;globals" 6 65 "fill chart;add5" 4 62 "fill chart;store5" 8 40 "fill chart;newline" 2 29 "fill chart;testing" 3 3 "scan;loader2" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / scan / loader2.lisp 3 37 "scan;scan1" 2 43 "scan;next-word" 4 4 "assess;loader6" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / assess / loader6.lisp 10 215 "assess;terminal edges2" 3 28 "assess;nonterminals1" 3 13 "assess;switch2" 7 7 "check;loader1" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / check / loader1.lisp 24 302 "check;multiply6" 1 1 "check;boundaries" 4 43 "check;one-one3" 2 24 "check;many-one1" 4 54 "check;one-many1" 3 40 "check;many-many1" 2 2 "analyzers;psp:threading:loader2" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / threading / loader2.lisp 7 71 "threading;extension" 1 1 "march;loader" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / march / loader.lisp 22 28 "kinds of edges;loader2" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / edges / loader2.lisp 4 65 "kinds of edges;single-new1" 3 53 "kinds of edges;binary1" 2 62 "kinds of edges;binary-explicit2" 3 133 "kinds of edges;binary-explicit all keys2" 3 64 "kinds of edges;cs2" 3 45 "kinds of edges;initial-new1" 2 26 "kinds of edges;unknown" 2 33 "kinds of edges;polyw1" 2 38 "kinds of edges;long scan1" 4 46 "kinds of edges;looking under" 3 3 "complete;loader1" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / complete / loader1.lisp 8 69 "complete;complete HA3" 4 16 "complete;switch complete" 6 6 "annotation;loader" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / annotation / loader.lisp 8 14 "referent;loader3" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / referent / loader3.lisp 4 16 "referent;composite referent" 20 67 "referent;driver2" 6 45 "referent;dispatch2" 14 210 "referent;decode exp1" 4 89 "referent;unary driver3" 5 105 "referent;cases1" 9 172 "referent;new decodings1" 7 270 "referent;new cases3" 2 4 "analyzers;psp:terminate" 7 7 "forest;loader1" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / forest / loader1.lisp 17 139 "forest;treetops" 3 100 "forest;sequence" 28 332 "forest;printers" 3 3 "forest;adjacency" 21 130 "forest;extract" 2 53 "forest;layout" 5 5 "traversal-routines;loader" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / traversal / loader.lisp 3 61 "traversal-routines;form" 7 77 "traversal-routines;forest scan" 5 135 "traversal-routines;dispatch" 3 70 "traversal-routines;interiors1" 6 6 "scan-patterns;loader" /Users / ddm / ws / nlp / Sparser / code / s / analyzers / psp / patterns / loader.lisp 6 68 "scan-patterns;take transitions" 1 1 "scan-patterns;start" 36 354 "scan-patterns;driver" 9 79 "scan-patterns;follow-out" 4 38 "scan-patterns;accept" 5 5 "do HA;loader" 5 75 "do HA;look" 2 2 "do HA;segment" 20 199 "do HA;place brackets1" 6 124 "do HA;inter-segment boundaries" 5 5 "do CA;loader1" Loading /Users / ddm / ws / nlp / Sparser / code / s / analyzers / CA / loader1.lisp 6 15 "do CA;actions" 11 71 "do CA;scanners1" 2 44 "do CA;search2" 28 435 "do CA;anaphora3" 3 19 "session-inits;setup3" 41 41 "required-words;punctuation1" 131 413 "tokens;alphabet" 5 5 "required-brackets;required" 28 47 "gr-tests;parsing" 7 9 "source-drivers;loader1" /Users / ddm / ws / nlp / Sparser / code / s / drivers / sources / loader1.lisp 11 25 "source-drivers;state" 4 17 "source-drivers;core1" 3 5 "source-drivers;string" 4 19 "source-drivers;file1" 3 5 "source-drivers;open file" 10 34 "traces;online hook" 2 2 "articles;loader" /Users / ddm / ws / nlp / Sparser / code / s / drivers / articles / loader.lisp 11 79 "articles;style" 6 6 "sink-drivers;loader1" Loading /Users / ddm / ws / nlp / Sparser / code / s / drivers / sinks / loader1.lisp 3 9 "sink-drivers;articles" 5 15 "sink-drivers;records" 7 53 "sink-drivers;core" 46 289 "sink-drivers;export" 7 43 "sink-drivers;return-value" 2 2 "drivers;tokens:loader" 17 94 "drivers;tokens:next-terminal2" 9 9 "chart-drivers;loader" 5 43 "chart-drivers;select2" 8 53 "chart-drivers;scan-all-terminals" 4 28 "chart-drivers;switch" 9 73 "chart-drivers;headers" 3 92 "chart-drivers;header labels" 5 27 "chart-drivers;hidden markup" 16 78 "chart-drivers;annotate last" 10 10 "chart-drivers;psp:loader5" /Users / ddm / ws / nlp / Sparser / code / s / drivers / chart / psp / loader5.lisp 39 130 "psp-drivers;flags" 5 78 "psp-drivers;initiate pattern scan" 28 377 "psp-drivers;scan3" 22 287 "psp-drivers;adjudicators1" 19 385 "psp-drivers;pts5" 12 292 "psp-drivers;march-seg5" 12 163 "psp-drivers;march-forest3" 15 163 "psp-drivers;PPTT8" 6 121 "psp-drivers;trigger5" 6 26 "chart-drivers;traversal1" 3 3 "chart-drivers;all-edges:loader1" /Users / ddm / ws / nlp / Sparser / code / s / drivers / chart / all - edges / loader1.lisp 18 250 "all edges;loops" 4 5 "forest-drivers;loader" 7 45 "forest-drivers;actions1" 4 61 "forest-drivers;trap2" 4 49 "drivers;DA:driver1" 23 288 "init-drivers;switches2" 23 23 "objects;traces:cases-loader1" /Users / ddm / ws / nlp / Sparser / code / s / objects / traces / cases - loader1.lisp 3 3 "traces;tokenizer" 24 101 "traces;FSA1" 55 232 "traces;cap seq" 96 104 "traces;edges1" 185 855 "traces;psp1" 14 64 "traces;psp-all-edges" 24 100 "traces;scan patterns" 9 23 "traces;completion" 15 55 "traces;conjunction" 3 6 "traces;treetops" 15 48 "traces;CA" 35 134 "traces;DA" 16 46 "traces;HA" 63 271 "traces;DM&P" 8 17 "traces;discourse" 18 53 "traces;sections" 6 12 "traces;section stack" 8 18 "traces;sgml" 8 25 "traces;paragraphs" 2 3 "traces;readout" 7 30 "traces;debugging" 52 217 "traces;psi" 7 12 "file ops;loader1" /Users / ddm / ws / nlp / Sparser / code / s / interface / files / loader1.lisp 2 17 "file ops;decoding" 3 20 "file ops;file name" 6 15 "file ops;open-close" 4 13 "file ops;read switch1" 3 24 "file ops;read chars1" 8 45 "workbench;loader" /Users / ddm / ws / nlp / Sparser / code / s / interface / workbench / loader.lisp 32 92 "workbench;globals" 13 80 "workbench;adjust" 13 141 "workbench;autodef data" 10 152 "workbench;def rule:save1" 6 11 "grammar-interface;loader" /Users / ddm / ws / nlp / Sparser / code / s / interface / grammar / loader.lisp 3 37 "grammar-interface;postprocessing" 28 273 "grammar-interface;sort" 5 49 "grammar-interface;printing" 27 246 "grammar-interface;sort individuals" 4 4 "timing;loader" 3 13 "timing;calculation" 12 125 "timing;presentation" 5 20 "timing;cases" 9 43 "measuring;distance between brackets" 7 71 "measuring;line count" 6 6 "citation-code;loader" /Users / ddm / ws / nlp / Sparser / code / s / grammar / tests / citations / code / loader.lisp 8 32 "citation-code;object" 11 118 "citation-code;test" 4 23 "citation-code;input-output" 6 111 "citation-code;construction" 2 4 "citation-code;batches" 3 166 "loaders;grammar" 4 97 "grammar edge types;digits" 3 97 "grammar edge types;form rules" 2 50 "grammar edge types;CA" 2 39 "grammar edge types;pnf" 2 27 "grammar edge types;pronouns1" 4 7 "fsa;loader - model1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / FSAs / loader --- model1.lisp 11 200 "fsa;abbreviations2" 11 11 "fsa;single quote1" 11 112 "fsa;hyphen" 81 139 "the-categories;categories" 36 52 "brackets;types" 11 248 "brackets;judgements1" 14 30 "words;loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / words / loader1.lisp 3 47 "words;fn word routine" 31 31 "words;punctuation bracketing" 4 6 "words;punctuation rules" 10 14 "words;determiners" 18 18 "words;conjunctions" 5 5 "words;interjections" 35 36 "words;pronouns" 4 94 "words;quantifiers1" 36 42 "words;prepositions2" 12 12 "words;WH words" 43 48 "words;aux verbs" 15 15 "words;contractions" 2 5 "words;adjectives" 34 43 "words;adverbs" 2 2 "words;whitespace assignments" 21 21 "tree-families;loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / tree - families / loader1.lisp 5 50 "tree-families;single words" 42 628 "tree-families;morphology1" 5 82 "tree-families;postprocessing1" 10 170 "tree-families;NP" 8 76 "tree-families;np adjuncts" 15 132 "tree-families;pre-head np modifiers" 7 68 "tree-families;of" 2 2 "tree-families;dates" 1 9 "tree-families;vp" 5 45 "tree-families;transitive" 3 26 "tree-families;ditransitive" 4 57 "tree-families;indirect obj pattern" 6 117 "tree-families;verbs taking pps" 3 27 "tree-families;copula patterns" 2 25 "tree-families;that comp" 2 16 "tree-families;compounds" 3 18 "tree-families;prepositional phrases" 4 26 "tree-families;adjective phrases" 3 32 "tree-families;adverbs" 16 256 "tree-families;shortcuts" 2 11 "tree-families;interjections" 10 28 "syntax;loader3" /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / syntax / loader3.lisp 4 94 "syntax-morph;affix rules" 20 74 "syntax-vg;tense" 13 65 "syntax-vg;have" 26 116 "syntax-vg;be" 57 245 "syntax-vg;modals" 12 34 "syntax-vg;adverbs" 22 65 "syntax-art;articles" 20 271 "syntax-conj;conjunction7" 1 1 "syntax-rel;subject relatives" 8 60 "syntax-poss;possessive" 4 22 "syntax-comp;comparatives" 24 57 "syntax-comp;WH-word-semantics" 21 89 "syntax-comp;questions" 5 13 "adjuncts;loader" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / adjuncts / loader.lisp 9 60 "approx;object" 5 28 "frequency;object" 12 34 "frequency;aux rules" 9 52 "sequence;object" 7 17 "places;loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / places / loader1.lisp 19 90 "places;object" 6 35 "places;directions1" 4 34 "places;compass points" 3 7 "places;directional rules" 4 4 "countries;loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / places / countries / loader1.lisp 5 46 "countries;object1" 5 29 "countries;relation" 4 4 "countries;rules1" 6 105 "places;city" 5 62 "places;U.S. States" 5 49 "places;other" 4 4 "places;rules2" 4 4 "collections;loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / collections / loader1.lisp 4 20 "collections;object1" 11 262 "collections;operations2" 5 55 "collections;obj specific printers" 10 10 "numbers;loader2" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / numbers / loader2.lisp 27 91 "numbers;object1" 12 22 "numbers;categories1" 8 163 "numbers;form2" 25 368 "numbers;fsa digits6" 12 96 "numbers;fsa words" 8 67 "numbers;ordinals3" 4 16 "numbers;percentages1" 7 19 "numbers;rules" 4 14 "numbers;relation" 8 8 "amounts;loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / amounts / loader1.lisp 4 15 "amounts;unit of measure1" 3 8 "amounts;quantities" 3 26 "amounts;measurements" 2 10 "amounts;object1" 17 135 "amounts;amount-change verbs" 9 47 "amounts;amount-chg relation" 2 4 "amounts;rules1" 2 2 "kinds;loader" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / kinds / loader.lisp 5 59 "kinds;object" 2 6 "kinds;np rules" 4 4 "money;loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / money / loader1.lisp 8 82 "money;objects1" 3 16 "money;printers" 3 7 "money;rules1" 14 14 "core;time:loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / time / loader1.lisp 2 4 "time;object" 2 7 "time;units1" 3 31 "time;weekdays1" 3 33 "time;months1" 3 15 "time;years2" 15 34 "time;time-of-day" 4 30 "time;relative moments" 4 28 "time;dates2" 6 33 "time;amounts" 6 30 "time;phrases1" 8 30 "time;anaphors1" 8 26 "time;age1" 25 145 "time;fiscal2" 5 7 "pronouns;loader2" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / core / pronouns / loader2.lisp 10 67 "pronouns;object1" 32 33 "pronouns;cases1" 2 10 "ambush;loader" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / sl / ambush / loader.lisp 11 53 "ambush;call-signs" 8 25 "ambush;protocols" 6 20 "ambush;checkpoints" 2 4 "ambush;contact" 1 1 "ambush;perimeter" 1 1 "ambush;munitions" 1 1 "ambush;casualties" 1 1 "ambush;misc" 2 5 "ckpt;loader" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / sl / checkpoint / loader.lisp 69 253 "ckpt;vocabulary" 8281 8351 "ckpt;adjectives" 54 147 "ckpt;rules" 4 8 "ha;loader1" /Users / ddm / ws / nlp / Sparser / code / s / grammar / rules / HA / loader1.lisp 4 82 "ha;driver" 3 43 "ha;both ends1" 2 28 "ha;determiner1" 2 83 "cat-prefs;category preferences" 44 281 "words;frequency" 30 128 "dossiers;loader" /Users / ddm / ws / nlp / Sparser / code / s / grammar / model / dossiers / loader.lisp 0 0 "dossiers;irregular verbs" 2 2 "dossiers;semantics-free verbs" 2 2 "dossiers;new content words" 11 11 "dossiers;comparatives" 3 7 "dossiers;rules comparatives" 2 41 "dossiers;numbers" 2 33 "dossiers;ordinals" 5 5 "dossiers;time units" 8 8 "dossiers;deictic times" 8 8 "dossiers;weekdays" 13 13 "dossiers;months" 62 62 "dossiers;years" 39 39 "dossiers;time of day" 51 51 "dossiers;timezones" 6 6 "dossiers;approximations" 2 4 "dossiers;approximator rules" 9 9 "dossiers;frequency adverbs" 7 7 "dossiers;sequencers" 0 0 "dossiers;kinds" 2 2 "dossiers;location descriptions" 7 7 "dossiers;location kinds" 16 16 "dossiers;directions" 13 13 "dossiers;compass points" 22 22 "dossiers;spatial prepositions" 14 20 "dossiers;countries" 2 2 "dossiers;cities" 7 49 "dossiers;city rules" 52 99 "dossiers;U.S. States" 2 4 "dossiers;U.S. State rules" 2 2 "dossiers;regions" 5 5 "dossiers;units of measure" 2 2 "dossiers;quantities" 6 10 "dossiers;denominations of money" 5 9 "dossiers;currencies" 0 0 "dossiers;semantics-weak verbs" apreq has 3 instances ainrn has 2 instances attributive has 3 instances gradable has 21 instances predicative has 2 instances null-adj has 5 instances greeting has 4 instances acknowledgement has 3 instances call-word has 1 instances pronoun/plural has 5 instances pronoun/inanimate has 3 instances pronoun/female has 3 instances pronoun/male has 4 instances pronoun/first/plural has 5 instances pronoun/first/singular has 5 instances calculated-time has 2 instances relative-time-noun has 1 instances relative-time-adverb has 1 instances year has 61 instances month has 12 instances weekday has 7 instances time-unit has 4 instances currency has 4 instances fractional-denomination/money has 2 instances denomination/money has 3 instances unit-of-measure has 4 instances ordinal has 31 instances illions-distribution has 33 instances multiplier has 7 instances region has 1 instances US-state has 51 instances city has 2 instances country has 13 instances compass-point has 12 instances direction has 15 instances kind-of-location has 6 instances sequencer has 6 instances frequency-of-event has 8 instances approximator has 5 instances quantifier has 20 instances 6 6 "grammar;tests:loader" 18 72 "gr-tests;workspace" 1 1 "gr-tests;rule deletion" 13 28 "gr-tests;edge resource" 8 8 "gr-tests;timing" 1 1 "gr-tests;edge-tests" 3 3 "citations;loader" /Users / ddm / ws / nlp / Sparser / code / s / grammar / tests / citations / cases / loader.lisp 18 41 "citations;systematically organized" 9 26 "citations;new ones"Identical rules found: #<PSR311 time-unit -> hyphen time-unit> #<PSR293 time-unit -> hyphen time-unit> ------------------------------------------- 163 Referential categories 74 Syntactic form categories 19 Mixin categories 71 non-terminal categories 100 dotted categories ------------------------------------------- 31 105 "version;workspace:abbreviations" 2 3 "version;workspace:traces" 39 39 "version;workspace:switch settings" 2 9 "version;workspace:basic tests" ----------------------------------------- 601 files 47026 lines of code 14338 toplevel forms ----------------------------------------- nil sparser>
89e86bcbd582a65911a4e2480369dc91f04959875b6dcd63a0533e9b458ebc2d
statusfailed/cartographer-string-diagrammatic-reasoning
Examples.hs
module Data.Hypergraph.Examples where import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Bimap (Bimap) import qualified Data.Bimap as Bimap import Data.Hypergraph.Type import Data.Hypergraph.Match import Data.Hypergraph.Rewrite ------------------------------- A simple example : two 1x1 generators , matching data SimpleGen = SimpleGen deriving(Eq, Ord, Read, Show) instance Signature SimpleGen where toSize SimpleGen = (1,1) simplePattern :: OpenHypergraph SimpleGen simplePattern = Hypergraph conns sigs 1 where sigs = Map.fromList [(0, SimpleGen)] conns = Bimap.fromList [ (Port Boundary 0, Port (Gen 0) 0) , (Port (Gen 0) 0, Port Boundary 0) ] simpleRhs = identity simpleGraph = Hypergraph conns sigs 2 where sigs = Map.fromList [(0, SimpleGen), (1, SimpleGen)] conns = Bimap.fromList [ (Port Boundary 0, Port (Gen 0) 0) , (Port (Gen 0) 0, Port (Gen 1) 0) , (Port (Gen 1) 0, Port Boundary 0) ] simpleRewrite = let [m1, m2] = match simplePattern simpleGraph in rewrite m1 simpleRhs simpleGraph -- if we apply a rewrite rule forwards then backwards, we should get back the -- same graph (modulo IDs) - meaning the twice-applied rule graph should match in the zero - applied rule graph exactly once . invertRewrite = let (g, m') = simpleRewrite (g', _) = rewrite m' simplePattern g in length (match g' simpleGraph) == 1 ------------------------------- -- The paper's non-convex matching example data NonConvexGen = E1 | E2 | E3 deriving(Eq, Ord, Read, Show) sizeOfNonConvex E1 = (1,2) sizeOfNonConvex E2 = (2,1) sizeOfNonConvex E3 = (1,1) instance Signature NonConvexGen where toSize = sizeOfNonConvex -- ----\/----- -- /\ -- -e1---e2--- nonConvexPattern = Hypergraph conns edges 2 where edges = Map.fromList [(0, E1), (1, E2)] conns = Bimap.fromList $ -- wires from left to right [ (Port Boundary 0, Port (Gen 1) 0) , (Port Boundary 1, Port (Gen 0) 0) , (Port (Gen 0) 0, Port Boundary 0) , (Port (Gen 0) 1, Port (Gen 1) 1) -- gen 1 out , (Port (Gen 1) 0, Port Boundary 1) ] -- e3 -- / \ -- -e1---e2--- nonConvexGraph = Hypergraph conns edges 3 where edges = Map.fromList [(0, E1), (1, E2), (2, E3)] conns = Bimap.fromList $ -- gen 0 in [ (Port Boundary 0, Port (Gen 0) 0) , (Port (Gen 0) 0, Port (Gen 2) 0) , (Port (Gen 0) 1, Port (Gen 1) 1) , (Port (Gen 2) 0, Port (Gen 1) 0) , (Port (Gen 1) 0, Port Boundary 0) ]
null
https://raw.githubusercontent.com/statusfailed/cartographer-string-diagrammatic-reasoning/7559db3f6de17dfa2dc13a6bf29f95c9cebcf7c4/cartographer/src/Data/Hypergraph/Examples.hs
haskell
----------------------------- if we apply a rewrite rule forwards then backwards, we should get back the same graph (modulo IDs) - meaning the twice-applied rule graph should match ----------------------------- The paper's non-convex matching example ----\/----- /\ -e1---e2--- wires from left to right gen 1 out e3 / \ -e1---e2--- gen 0 in
module Data.Hypergraph.Examples where import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Bimap (Bimap) import qualified Data.Bimap as Bimap import Data.Hypergraph.Type import Data.Hypergraph.Match import Data.Hypergraph.Rewrite A simple example : two 1x1 generators , matching data SimpleGen = SimpleGen deriving(Eq, Ord, Read, Show) instance Signature SimpleGen where toSize SimpleGen = (1,1) simplePattern :: OpenHypergraph SimpleGen simplePattern = Hypergraph conns sigs 1 where sigs = Map.fromList [(0, SimpleGen)] conns = Bimap.fromList [ (Port Boundary 0, Port (Gen 0) 0) , (Port (Gen 0) 0, Port Boundary 0) ] simpleRhs = identity simpleGraph = Hypergraph conns sigs 2 where sigs = Map.fromList [(0, SimpleGen), (1, SimpleGen)] conns = Bimap.fromList [ (Port Boundary 0, Port (Gen 0) 0) , (Port (Gen 0) 0, Port (Gen 1) 0) , (Port (Gen 1) 0, Port Boundary 0) ] simpleRewrite = let [m1, m2] = match simplePattern simpleGraph in rewrite m1 simpleRhs simpleGraph in the zero - applied rule graph exactly once . invertRewrite = let (g, m') = simpleRewrite (g', _) = rewrite m' simplePattern g in length (match g' simpleGraph) == 1 data NonConvexGen = E1 | E2 | E3 deriving(Eq, Ord, Read, Show) sizeOfNonConvex E1 = (1,2) sizeOfNonConvex E2 = (2,1) sizeOfNonConvex E3 = (1,1) instance Signature NonConvexGen where toSize = sizeOfNonConvex nonConvexPattern = Hypergraph conns edges 2 where edges = Map.fromList [(0, E1), (1, E2)] conns = Bimap.fromList $ [ (Port Boundary 0, Port (Gen 1) 0) , (Port Boundary 1, Port (Gen 0) 0) , (Port (Gen 0) 0, Port Boundary 0) , (Port (Gen 0) 1, Port (Gen 1) 1) , (Port (Gen 1) 0, Port Boundary 1) ] nonConvexGraph = Hypergraph conns edges 3 where edges = Map.fromList [(0, E1), (1, E2), (2, E3)] conns = Bimap.fromList $ [ (Port Boundary 0, Port (Gen 0) 0) , (Port (Gen 0) 0, Port (Gen 2) 0) , (Port (Gen 0) 1, Port (Gen 1) 1) , (Port (Gen 2) 0, Port (Gen 1) 0) , (Port (Gen 1) 0, Port Boundary 0) ]
11e6517f5c014e385fd79eb366ff57456549c84fe34e684be7f90fef4b7f1735
brendanhay/amazonka
DeleteConnector.hs
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . -- | -- Module : Amazonka.Transfer.DeleteConnector Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- -- Deletes the agreement that\'s specified in the provided @ConnectorId@. module Amazonka.Transfer.DeleteConnector ( -- * Creating a Request DeleteConnector (..), newDeleteConnector, -- * Request Lenses deleteConnector_connectorId, -- * Destructuring the Response DeleteConnectorResponse (..), newDeleteConnectorResponse, ) where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude import qualified Amazonka.Request as Request import qualified Amazonka.Response as Response import Amazonka.Transfer.Types -- | /See:/ 'newDeleteConnector' smart constructor. data DeleteConnector = DeleteConnector' { -- | The unique identifier for the connector. connectorId :: Prelude.Text } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) -- | -- Create a value of 'DeleteConnector' with all optional fields omitted. -- Use < -lens generic - lens > or < optics > to modify other optional fields . -- -- The following record fields are available, with the corresponding lenses provided -- for backwards compatibility: -- -- 'connectorId', 'deleteConnector_connectorId' - The unique identifier for the connector. newDeleteConnector :: -- | 'connectorId' Prelude.Text -> DeleteConnector newDeleteConnector pConnectorId_ = DeleteConnector' {connectorId = pConnectorId_} -- | The unique identifier for the connector. deleteConnector_connectorId :: Lens.Lens' DeleteConnector Prelude.Text deleteConnector_connectorId = Lens.lens (\DeleteConnector' {connectorId} -> connectorId) (\s@DeleteConnector' {} a -> s {connectorId = a} :: DeleteConnector) instance Core.AWSRequest DeleteConnector where type AWSResponse DeleteConnector = DeleteConnectorResponse request overrides = Request.postJSON (overrides defaultService) response = Response.receiveNull DeleteConnectorResponse' instance Prelude.Hashable DeleteConnector where hashWithSalt _salt DeleteConnector' {..} = _salt `Prelude.hashWithSalt` connectorId instance Prelude.NFData DeleteConnector where rnf DeleteConnector' {..} = Prelude.rnf connectorId instance Data.ToHeaders DeleteConnector where toHeaders = Prelude.const ( Prelude.mconcat [ "X-Amz-Target" Data.=# ( "TransferService.DeleteConnector" :: Prelude.ByteString ), "Content-Type" Data.=# ( "application/x-amz-json-1.1" :: Prelude.ByteString ) ] ) instance Data.ToJSON DeleteConnector where toJSON DeleteConnector' {..} = Data.object ( Prelude.catMaybes [Prelude.Just ("ConnectorId" Data..= connectorId)] ) instance Data.ToPath DeleteConnector where toPath = Prelude.const "/" instance Data.ToQuery DeleteConnector where toQuery = Prelude.const Prelude.mempty -- | /See:/ 'newDeleteConnectorResponse' smart constructor. data DeleteConnectorResponse = DeleteConnectorResponse' { } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) -- | -- Create a value of 'DeleteConnectorResponse' with all optional fields omitted. -- Use < -lens generic - lens > or < optics > to modify other optional fields . newDeleteConnectorResponse :: DeleteConnectorResponse newDeleteConnectorResponse = DeleteConnectorResponse' instance Prelude.NFData DeleteConnectorResponse where rnf _ = ()
null
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-transfer/gen/Amazonka/Transfer/DeleteConnector.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Module : Amazonka.Transfer.DeleteConnector Stability : auto-generated Deletes the agreement that\'s specified in the provided @ConnectorId@. * Creating a Request * Request Lenses * Destructuring the Response | /See:/ 'newDeleteConnector' smart constructor. | The unique identifier for the connector. | Create a value of 'DeleteConnector' with all optional fields omitted. The following record fields are available, with the corresponding lenses provided for backwards compatibility: 'connectorId', 'deleteConnector_connectorId' - The unique identifier for the connector. | 'connectorId' | The unique identifier for the connector. | /See:/ 'newDeleteConnectorResponse' smart constructor. | Create a value of 'DeleteConnectorResponse' with all optional fields omitted.
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Amazonka.Transfer.DeleteConnector DeleteConnector (..), newDeleteConnector, deleteConnector_connectorId, DeleteConnectorResponse (..), newDeleteConnectorResponse, ) where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude import qualified Amazonka.Request as Request import qualified Amazonka.Response as Response import Amazonka.Transfer.Types data DeleteConnector = DeleteConnector' connectorId :: Prelude.Text } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) Use < -lens generic - lens > or < optics > to modify other optional fields . newDeleteConnector :: Prelude.Text -> DeleteConnector newDeleteConnector pConnectorId_ = DeleteConnector' {connectorId = pConnectorId_} deleteConnector_connectorId :: Lens.Lens' DeleteConnector Prelude.Text deleteConnector_connectorId = Lens.lens (\DeleteConnector' {connectorId} -> connectorId) (\s@DeleteConnector' {} a -> s {connectorId = a} :: DeleteConnector) instance Core.AWSRequest DeleteConnector where type AWSResponse DeleteConnector = DeleteConnectorResponse request overrides = Request.postJSON (overrides defaultService) response = Response.receiveNull DeleteConnectorResponse' instance Prelude.Hashable DeleteConnector where hashWithSalt _salt DeleteConnector' {..} = _salt `Prelude.hashWithSalt` connectorId instance Prelude.NFData DeleteConnector where rnf DeleteConnector' {..} = Prelude.rnf connectorId instance Data.ToHeaders DeleteConnector where toHeaders = Prelude.const ( Prelude.mconcat [ "X-Amz-Target" Data.=# ( "TransferService.DeleteConnector" :: Prelude.ByteString ), "Content-Type" Data.=# ( "application/x-amz-json-1.1" :: Prelude.ByteString ) ] ) instance Data.ToJSON DeleteConnector where toJSON DeleteConnector' {..} = Data.object ( Prelude.catMaybes [Prelude.Just ("ConnectorId" Data..= connectorId)] ) instance Data.ToPath DeleteConnector where toPath = Prelude.const "/" instance Data.ToQuery DeleteConnector where toQuery = Prelude.const Prelude.mempty data DeleteConnectorResponse = DeleteConnectorResponse' { } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) Use < -lens generic - lens > or < optics > to modify other optional fields . newDeleteConnectorResponse :: DeleteConnectorResponse newDeleteConnectorResponse = DeleteConnectorResponse' instance Prelude.NFData DeleteConnectorResponse where rnf _ = ()
33927b2bc6e2da4b0b24c343b5beaf9f3dcd697eb7dc9689057b15326e97c8ee
markandrus/twilio-haskell
Call.hs
# LANGUAGE MultiParamTypeClasses # {-#LANGUAGE OverloadedStrings #-} # LANGUAGE ViewPatterns # ------------------------------------------------------------------------------- -- | Module : Twilio . Call Copyright : ( C ) 2017- -- License : BSD-style (see the file LICENSE) Maintainer : < > -- Stability : provisional ------------------------------------------------------------------------------- module Twilio.Call ( -- * Resource Call(..) , CallSID , Twilio.Call.get -- * Types , AnsweredBy(..) , CallDirection(..) , CallStatus(..) ) where import Control.Error.Safe import Control.Monad import Control.Monad.Catch import Data.Aeson import Data.Monoid import Data.Text (Text) import Data.Time.Clock import Network.URI import Control.Monad.Twilio import Twilio.Internal.Parser import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types Resource data Call = Call { sid :: !CallSID , parentCallSID :: !(Maybe CallSID) , dateCreated :: !(Maybe UTCTime) -- "date_created" is initially null , dateUpdated :: !(Maybe UTCTime) -- "date_updated" is initially null , accountSID :: !AccountSID , to :: !(Maybe Text) , from :: !Text , phoneNumberSID :: !(Maybe PhoneNumberSID) , status :: !CallStatus , startTime :: !(Maybe UTCTime) -- "start_time" is initially null , endTime :: !(Maybe UTCTime) , duration :: !(Maybe Int) , price :: !(Maybe Double) , priceUnit :: !(Maybe PriceUnit) , direction :: !(Maybe CallDirection) , answeredBy :: !(Maybe AnsweredBy) , forwardedFrom :: !(Maybe Text) , callerName :: !(Maybe Text) , uri :: !URI , apiVersion :: !APIVersion } deriving (Show, Eq) instance FromJSON Call where parseJSON (Object v) = Call <$> v .: "sid" <*> v .: "parent_call_sid" <*> (v .: "date_created" <&> (=<<) parseDateTime) <*> (v .: "date_updated" <&> (=<<) parseDateTime) <*> v .: "account_sid" <*> (v .: "to" <&> filterEmpty) <*> v .: "from" <*> (v .: "phone_number_sid" <&> (=<<) filterEmpty <&> (=<<) parseSID) <*> v .: "status" <*> (v .: "start_time" <&> (=<<) parseDateTime) <*> (v .: "end_time" <&> (=<<) parseDateTime) <*> (v .: "duration" <&> fmap readZ >>= maybeReturn') <*> (v .: "price" <&> fmap readZ >>= maybeReturn') <*> v .: "price_unit" <*> v .: "direction" <*> v .: "answered_by" <*> v .: "forwarded_from" <&> (=<<) filterEmpty <*> v .: "caller_name" <*> (v .: "uri" <&> parseRelativeReference >>= maybeReturn) <*> v .: "api_version" parseJSON _ = mzero instance Get1 CallSID Call where get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest ("/Calls/" <> sid <> ".json") -- | Get a 'Call' by 'CallSID'. get :: MonadThrow m => CallSID -> TwilioT m Call get = Resource.get {- Types -} data AnsweredBy = Human | Machine deriving Eq instance Show AnsweredBy where show Human = "human" show Machine = "machine" instance FromJSON AnsweredBy where parseJSON (String "human") = return Human parseJSON (String "machine") = return Machine parseJSON _ = mzero data CallDirection = Inbound | OutboundAPI | OutboundDial deriving Eq instance Show CallDirection where show Inbound = "inbound" show OutboundAPI = "outbound-api" show OutboundDial = "outbound-dial" instance FromJSON CallDirection where parseJSON (String "inbound") = return Inbound parseJSON (String "outbound-api") = return OutboundAPI parseJSON (String "outbound-dial") = return OutboundDial parseJSON _ = mzero data CallStatus = Queued | Ringing | InProgress | Canceled | Completed | Failed | Busy | NoAnswer deriving (Bounded, Enum, Eq, Ord, Read, Show) instance FromJSON CallStatus where parseJSON (String "queued") = return Queued parseJSON (String "ringing") = return Ringing parseJSON (String "in-progress") = return InProgress parseJSON (String "canceled") = return Canceled parseJSON (String "completed") = return Completed parseJSON (String "failed") = return Failed parseJSON (String "busy") = return Busy parseJSON (String "no-answer") = return NoAnswer parseJSON _ = mzero
null
https://raw.githubusercontent.com/markandrus/twilio-haskell/00704dc86dbf2117b855b1e2dcf8b6c0eff5bfbe/src/Twilio/Call.hs
haskell
#LANGUAGE OverloadedStrings # ----------------------------------------------------------------------------- | License : BSD-style (see the file LICENSE) Stability : provisional ----------------------------------------------------------------------------- * Resource * Types "date_created" is initially null "date_updated" is initially null "start_time" is initially null | Get a 'Call' by 'CallSID'. Types
# LANGUAGE MultiParamTypeClasses # # LANGUAGE ViewPatterns # Module : Twilio . Call Copyright : ( C ) 2017- Maintainer : < > module Twilio.Call Call(..) , CallSID , Twilio.Call.get , AnsweredBy(..) , CallDirection(..) , CallStatus(..) ) where import Control.Error.Safe import Control.Monad import Control.Monad.Catch import Data.Aeson import Data.Monoid import Data.Text (Text) import Data.Time.Clock import Network.URI import Control.Monad.Twilio import Twilio.Internal.Parser import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types Resource data Call = Call { sid :: !CallSID , parentCallSID :: !(Maybe CallSID) , accountSID :: !AccountSID , to :: !(Maybe Text) , from :: !Text , phoneNumberSID :: !(Maybe PhoneNumberSID) , status :: !CallStatus , endTime :: !(Maybe UTCTime) , duration :: !(Maybe Int) , price :: !(Maybe Double) , priceUnit :: !(Maybe PriceUnit) , direction :: !(Maybe CallDirection) , answeredBy :: !(Maybe AnsweredBy) , forwardedFrom :: !(Maybe Text) , callerName :: !(Maybe Text) , uri :: !URI , apiVersion :: !APIVersion } deriving (Show, Eq) instance FromJSON Call where parseJSON (Object v) = Call <$> v .: "sid" <*> v .: "parent_call_sid" <*> (v .: "date_created" <&> (=<<) parseDateTime) <*> (v .: "date_updated" <&> (=<<) parseDateTime) <*> v .: "account_sid" <*> (v .: "to" <&> filterEmpty) <*> v .: "from" <*> (v .: "phone_number_sid" <&> (=<<) filterEmpty <&> (=<<) parseSID) <*> v .: "status" <*> (v .: "start_time" <&> (=<<) parseDateTime) <*> (v .: "end_time" <&> (=<<) parseDateTime) <*> (v .: "duration" <&> fmap readZ >>= maybeReturn') <*> (v .: "price" <&> fmap readZ >>= maybeReturn') <*> v .: "price_unit" <*> v .: "direction" <*> v .: "answered_by" <*> v .: "forwarded_from" <&> (=<<) filterEmpty <*> v .: "caller_name" <*> (v .: "uri" <&> parseRelativeReference >>= maybeReturn) <*> v .: "api_version" parseJSON _ = mzero instance Get1 CallSID Call where get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest ("/Calls/" <> sid <> ".json") get :: MonadThrow m => CallSID -> TwilioT m Call get = Resource.get data AnsweredBy = Human | Machine deriving Eq instance Show AnsweredBy where show Human = "human" show Machine = "machine" instance FromJSON AnsweredBy where parseJSON (String "human") = return Human parseJSON (String "machine") = return Machine parseJSON _ = mzero data CallDirection = Inbound | OutboundAPI | OutboundDial deriving Eq instance Show CallDirection where show Inbound = "inbound" show OutboundAPI = "outbound-api" show OutboundDial = "outbound-dial" instance FromJSON CallDirection where parseJSON (String "inbound") = return Inbound parseJSON (String "outbound-api") = return OutboundAPI parseJSON (String "outbound-dial") = return OutboundDial parseJSON _ = mzero data CallStatus = Queued | Ringing | InProgress | Canceled | Completed | Failed | Busy | NoAnswer deriving (Bounded, Enum, Eq, Ord, Read, Show) instance FromJSON CallStatus where parseJSON (String "queued") = return Queued parseJSON (String "ringing") = return Ringing parseJSON (String "in-progress") = return InProgress parseJSON (String "canceled") = return Canceled parseJSON (String "completed") = return Completed parseJSON (String "failed") = return Failed parseJSON (String "busy") = return Busy parseJSON (String "no-answer") = return NoAnswer parseJSON _ = mzero
46dea8cd0751935f92d166364c2150bcb76d7b761a3d290a4761c8f1a0893a9f
snowleopard/hadrian
Expression.hs
# LANGUAGE MultiParamTypeClasses , TypeFamilies # module Hadrian.Expression ( -- * Expressions Expr, Predicate, Args, -- ** Construction and modification expr, exprIO, arg, remove, -- ** Predicates (?), input, inputs, output, outputs, VerboseCommand (..), verboseCommand, -- ** Evaluation interpret, interpretInContext, -- * Convenient accessors getBuildRoot, getContext, getBuilder, getOutputs, getInputs, getInput, getOutput ) where import Control.Monad.Extra import Control.Monad.Trans import Control.Monad.Trans.Reader import Development.Shake import Development.Shake.Classes import qualified Hadrian.Target as Target import Hadrian.Target (Target, target) import Hadrian.Utilities | ' ' @c b a@ is a computation that produces a value of type ' Action ' @a@ and can read parameters of the current build ' Target ' @c b@. newtype Expr c b a = Expr (ReaderT (Target c b) Action a) deriving (Applicative, Functor, Monad) instance Semigroup a => Semigroup (Expr c b a) where Expr x <> Expr y = Expr $ (<>) <$> x <*> y -- TODO: The 'Semigroup a' constraint will at some point become redundant. instance (Semigroup a, Monoid a) => Monoid (Expr c b a) where mempty = pure mempty mappend = (<>) | Expressions that compute a Boolean value . type Predicate c b = Expr c b Bool -- | Expressions that compute lists of arguments to be passed to builders. type Args c b = Expr c b [String] | Lift actions independent from the current build ' Target ' into the ' ' -- monad. expr :: Action a -> Expr c b a expr = Expr . lift | Lift IO computations independent from the current build ' Target ' into the ' ' monad . exprIO :: IO a -> Expr c b a exprIO = Expr . liftIO -- | Remove given elements from a list expression. remove :: Eq a => [a] -> Expr c b [a] -> Expr c b [a] remove xs e = filter (`notElem` xs) <$> e | Add a single argument to ' ' . arg :: String -> Args c b arg = pure . pure -- | Values that can be converted to a 'Predicate'. class ToPredicate p c b where toPredicate :: p -> Predicate c b infixr 3 ? -- | Apply a predicate to an expression. (?) :: (Monoid a, ToPredicate p c b) => p -> Expr c b a -> Expr c b a p ? e = do bool <- toPredicate p if bool then e else mempty instance ToPredicate Bool c b where toPredicate = pure instance ToPredicate p c b => ToPredicate (Action p) c b where toPredicate = toPredicate . expr instance (c ~ c', b ~ b', ToPredicate p c' b') => ToPredicate (Expr c b p) c' b' where toPredicate p = toPredicate =<< p | Interpret a given expression according to the given ' Target ' . interpret :: Target c b -> Expr c b a -> Action a interpret target (Expr e) = runReaderT e target -- | Interpret a given expression by looking only at the given 'Context'. interpretInContext :: c -> Expr c b a -> Action a interpretInContext c = interpret $ target c (error "contextOnlyTarget: builder not set") (error "contextOnlyTarget: inputs not set" ) (error "contextOnlyTarget: outputs not set") -- | Get the directory of build results. getBuildRoot :: Expr c b FilePath getBuildRoot = expr buildRoot -- | Get the current build 'Context'. getContext :: Expr c b c getContext = Expr $ asks Target.context | Get the ' Builder ' for the current ' Target ' . getBuilder :: Expr c b b getBuilder = Expr $ asks Target.builder | Get the input files of the current ' Target ' . getInputs :: Expr c b [FilePath] getInputs = Expr $ asks Target.inputs | Run ' getInputs ' and check that the result contains one input file only . getInput :: (Show b, Show c) => Expr c b FilePath getInput = Expr $ do target <- ask fromSingleton ("Exactly one input file expected in " ++ show target) <$> asks Target.inputs | Get the files produced by the current ' Target ' . getOutputs :: Expr c b [FilePath] getOutputs = Expr $ asks Target.outputs | Run ' getOutputs ' and check that the result contains one output file only . getOutput :: (Show b, Show c) => Expr c b FilePath getOutput = Expr $ do target <- ask fromSingleton ("Exactly one output file expected in " ++ show target) <$> asks Target.outputs -- | Does any of the input files match a given pattern? input :: FilePattern -> Predicate c b input f = any (f ?==) <$> getInputs -- | Does any of the input files match any of the given patterns? inputs :: [FilePattern] -> Predicate c b inputs = anyM input -- | Does any of the output files match a given pattern? output :: FilePattern -> Predicate c b output f = any (f ?==) <$> getOutputs -- | Does any of the output files match any of the given patterns? outputs :: [FilePattern] -> Predicate c b outputs = anyM output newtype VerboseCommand c b = VerboseCommand { predicate :: Predicate c b } deriving Typeable verboseCommand :: (ShakeValue c, ShakeValue b) => Predicate c b verboseCommand = predicate =<< expr (userSetting . VerboseCommand $ return False)
null
https://raw.githubusercontent.com/snowleopard/hadrian/b9a3f9521b315942e1dabb006688ee7c9902f5fe/src/Hadrian/Expression.hs
haskell
* Expressions ** Construction and modification ** Predicates ** Evaluation * Convenient accessors TODO: The 'Semigroup a' constraint will at some point become redundant. | Expressions that compute lists of arguments to be passed to builders. monad. | Remove given elements from a list expression. | Values that can be converted to a 'Predicate'. | Apply a predicate to an expression. | Interpret a given expression by looking only at the given 'Context'. | Get the directory of build results. | Get the current build 'Context'. | Does any of the input files match a given pattern? | Does any of the input files match any of the given patterns? | Does any of the output files match a given pattern? | Does any of the output files match any of the given patterns?
# LANGUAGE MultiParamTypeClasses , TypeFamilies # module Hadrian.Expression ( Expr, Predicate, Args, expr, exprIO, arg, remove, (?), input, inputs, output, outputs, VerboseCommand (..), verboseCommand, interpret, interpretInContext, getBuildRoot, getContext, getBuilder, getOutputs, getInputs, getInput, getOutput ) where import Control.Monad.Extra import Control.Monad.Trans import Control.Monad.Trans.Reader import Development.Shake import Development.Shake.Classes import qualified Hadrian.Target as Target import Hadrian.Target (Target, target) import Hadrian.Utilities | ' ' @c b a@ is a computation that produces a value of type ' Action ' @a@ and can read parameters of the current build ' Target ' @c b@. newtype Expr c b a = Expr (ReaderT (Target c b) Action a) deriving (Applicative, Functor, Monad) instance Semigroup a => Semigroup (Expr c b a) where Expr x <> Expr y = Expr $ (<>) <$> x <*> y instance (Semigroup a, Monoid a) => Monoid (Expr c b a) where mempty = pure mempty mappend = (<>) | Expressions that compute a Boolean value . type Predicate c b = Expr c b Bool type Args c b = Expr c b [String] | Lift actions independent from the current build ' Target ' into the ' ' expr :: Action a -> Expr c b a expr = Expr . lift | Lift IO computations independent from the current build ' Target ' into the ' ' monad . exprIO :: IO a -> Expr c b a exprIO = Expr . liftIO remove :: Eq a => [a] -> Expr c b [a] -> Expr c b [a] remove xs e = filter (`notElem` xs) <$> e | Add a single argument to ' ' . arg :: String -> Args c b arg = pure . pure class ToPredicate p c b where toPredicate :: p -> Predicate c b infixr 3 ? (?) :: (Monoid a, ToPredicate p c b) => p -> Expr c b a -> Expr c b a p ? e = do bool <- toPredicate p if bool then e else mempty instance ToPredicate Bool c b where toPredicate = pure instance ToPredicate p c b => ToPredicate (Action p) c b where toPredicate = toPredicate . expr instance (c ~ c', b ~ b', ToPredicate p c' b') => ToPredicate (Expr c b p) c' b' where toPredicate p = toPredicate =<< p | Interpret a given expression according to the given ' Target ' . interpret :: Target c b -> Expr c b a -> Action a interpret target (Expr e) = runReaderT e target interpretInContext :: c -> Expr c b a -> Action a interpretInContext c = interpret $ target c (error "contextOnlyTarget: builder not set") (error "contextOnlyTarget: inputs not set" ) (error "contextOnlyTarget: outputs not set") getBuildRoot :: Expr c b FilePath getBuildRoot = expr buildRoot getContext :: Expr c b c getContext = Expr $ asks Target.context | Get the ' Builder ' for the current ' Target ' . getBuilder :: Expr c b b getBuilder = Expr $ asks Target.builder | Get the input files of the current ' Target ' . getInputs :: Expr c b [FilePath] getInputs = Expr $ asks Target.inputs | Run ' getInputs ' and check that the result contains one input file only . getInput :: (Show b, Show c) => Expr c b FilePath getInput = Expr $ do target <- ask fromSingleton ("Exactly one input file expected in " ++ show target) <$> asks Target.inputs | Get the files produced by the current ' Target ' . getOutputs :: Expr c b [FilePath] getOutputs = Expr $ asks Target.outputs | Run ' getOutputs ' and check that the result contains one output file only . getOutput :: (Show b, Show c) => Expr c b FilePath getOutput = Expr $ do target <- ask fromSingleton ("Exactly one output file expected in " ++ show target) <$> asks Target.outputs input :: FilePattern -> Predicate c b input f = any (f ?==) <$> getInputs inputs :: [FilePattern] -> Predicate c b inputs = anyM input output :: FilePattern -> Predicate c b output f = any (f ?==) <$> getOutputs outputs :: [FilePattern] -> Predicate c b outputs = anyM output newtype VerboseCommand c b = VerboseCommand { predicate :: Predicate c b } deriving Typeable verboseCommand :: (ShakeValue c, ShakeValue b) => Predicate c b verboseCommand = predicate =<< expr (userSetting . VerboseCommand $ return False)
34eaa732c8de325ad6c88ed0babf478a6259d011b6ee477731b7a65e0297c218
anoma/juvix
Base.hs
module Juvix.Data.Effect.Files.Base ( module Juvix.Data.Effect.Files.Base, module Juvix.Data.Uid, ) where import Juvix.Data.Uid import Juvix.Prelude.Base import Path data RecursorArgs = RecursorArgs { _recCurDir :: Path Rel Dir, _recDirs :: [Path Rel Dir], _recFiles :: [Path Rel File] } data Recurse r = RecurseNever | RecurseFilter (Path r Dir -> Bool) makeLenses ''RecursorArgs data Files m a where EnsureDir' :: Path Abs Dir -> Files m () DirectoryExists' :: Path Abs Dir -> Files m Bool FileExists' :: Path Abs File -> Files m Bool GetDirAbsPath :: Path Rel Dir -> Files m (Path Abs Dir) ListDirRel :: Path Abs Dir -> Files m ([Path Rel Dir], [Path Rel File]) PathUid :: Path Abs b -> Files m Uid ReadFile' :: Path Abs File -> Files m Text ReadFileBS' :: Path Abs File -> Files m ByteString RemoveDirectoryRecursive' :: Path Abs Dir -> Files m () WriteFile' :: Path Abs File -> Text -> Files m () WriteFileBS :: Path Abs File -> ByteString -> Files m () makeSem ''Files
null
https://raw.githubusercontent.com/anoma/juvix/88ab62235378f669799e3112603277dca00e58c6/src/Juvix/Data/Effect/Files/Base.hs
haskell
module Juvix.Data.Effect.Files.Base ( module Juvix.Data.Effect.Files.Base, module Juvix.Data.Uid, ) where import Juvix.Data.Uid import Juvix.Prelude.Base import Path data RecursorArgs = RecursorArgs { _recCurDir :: Path Rel Dir, _recDirs :: [Path Rel Dir], _recFiles :: [Path Rel File] } data Recurse r = RecurseNever | RecurseFilter (Path r Dir -> Bool) makeLenses ''RecursorArgs data Files m a where EnsureDir' :: Path Abs Dir -> Files m () DirectoryExists' :: Path Abs Dir -> Files m Bool FileExists' :: Path Abs File -> Files m Bool GetDirAbsPath :: Path Rel Dir -> Files m (Path Abs Dir) ListDirRel :: Path Abs Dir -> Files m ([Path Rel Dir], [Path Rel File]) PathUid :: Path Abs b -> Files m Uid ReadFile' :: Path Abs File -> Files m Text ReadFileBS' :: Path Abs File -> Files m ByteString RemoveDirectoryRecursive' :: Path Abs Dir -> Files m () WriteFile' :: Path Abs File -> Text -> Files m () WriteFileBS :: Path Abs File -> ByteString -> Files m () makeSem ''Files
2034ce99d0ea95eed9ebcf87f41f2d58a84c462e988db4e6b7c0713d006443e2
josefs/Gradualizer
record_union_with_any_should_pass.erl
-module(record_union_with_any_should_pass). -export([f/1, g/0]). -record(r, {field}). -spec f(_) -> #r{} | any(). f(R) -> R#r{field = val}. -spec g() -> #r{} | any(). g() -> #r{field = val}.
null
https://raw.githubusercontent.com/josefs/Gradualizer/eb8fc7431275d00ff41f266297e4b3b7de5330b9/test/should_pass/record_union_with_any_should_pass.erl
erlang
-module(record_union_with_any_should_pass). -export([f/1, g/0]). -record(r, {field}). -spec f(_) -> #r{} | any(). f(R) -> R#r{field = val}. -spec g() -> #r{} | any(). g() -> #r{field = val}.
1f4e976744faa9282533bf6a9711841bf3e16feef029bdc36b403cbf2271a9e5
kupl/LearnML
patch.ml
let rec iter ((n : int), (f : 'a -> 'a)) : 'a -> 'a = match n with | 0 -> fun (__s5 : int) -> __s5 | 1 -> f | _ -> fun (__s6 : int) -> iter (n - 1, f) (f __s6)
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/iter/sub5/patch.ml
ocaml
let rec iter ((n : int), (f : 'a -> 'a)) : 'a -> 'a = match n with | 0 -> fun (__s5 : int) -> __s5 | 1 -> f | _ -> fun (__s6 : int) -> iter (n - 1, f) (f __s6)
c274516a05271e27ed970f807641cfee9588d254b8936d6aa8f057e3cda0ffb3
nikita-volkov/rebase
Group.hs
module Rebase.Data.Group ( module Data.Group ) where import Data.Group
null
https://raw.githubusercontent.com/nikita-volkov/rebase/ba6cc42adf0b4a2026055d77e78020527aa5c535/library/Rebase/Data/Group.hs
haskell
module Rebase.Data.Group ( module Data.Group ) where import Data.Group
93fa31760e9600a44a81078f3e1c80829508082c4fdfc33fc1b9edc3095eb016
DanielG/ghc-mod
GhcTestcase.hs
$ ghc -package ghc -package ghc - paths GhcTestcase.hs # LANGUAGE ScopedTypeVariables # module Main where import GHC import GHC.Paths (libdir) import DynFlags import System.Environment main :: IO () main = do args <- getArgs defaultErrorHandler defaultFatalMessager defaultFlushOut $ runGhc (Just libdir) $ doStuff "Main.hs" "Main" args doStuff :: String -> String -> [String] -> Ghc () doStuff targetFile targetModule args = do dflags0 <- getSessionDynFlags let dflags1 = dflags0 { ghcMode = CompManager , ghcLink = LinkInMemory , hscTarget = HscInterpreted , optLevel = 0 } (dflags2, _, _) <- parseDynamicFlags dflags1 (map noLoc args) _ <- setSessionDynFlags dflags2 target <- guessTarget targetFile Nothing setTargets [target { targetAllowObjCode = True }] _ <- load LoadAllTargets setContext [IIModule $ mkModuleName targetModule] return ()
null
https://raw.githubusercontent.com/DanielG/ghc-mod/391e187a5dfef4421aab2508fa6ff7875cc8259d/test/manual/not-interpreted-error/GhcTestcase.hs
haskell
$ ghc -package ghc -package ghc - paths GhcTestcase.hs # LANGUAGE ScopedTypeVariables # module Main where import GHC import GHC.Paths (libdir) import DynFlags import System.Environment main :: IO () main = do args <- getArgs defaultErrorHandler defaultFatalMessager defaultFlushOut $ runGhc (Just libdir) $ doStuff "Main.hs" "Main" args doStuff :: String -> String -> [String] -> Ghc () doStuff targetFile targetModule args = do dflags0 <- getSessionDynFlags let dflags1 = dflags0 { ghcMode = CompManager , ghcLink = LinkInMemory , hscTarget = HscInterpreted , optLevel = 0 } (dflags2, _, _) <- parseDynamicFlags dflags1 (map noLoc args) _ <- setSessionDynFlags dflags2 target <- guessTarget targetFile Nothing setTargets [target { targetAllowObjCode = True }] _ <- load LoadAllTargets setContext [IIModule $ mkModuleName targetModule] return ()
72cf23eeb9dd8414f1f04f66330e9c324bdaef2c29e70c3bbf6063bf6a15fff2
clj-kondo/clj-kondo
namespace.clj
(ns clj-kondo.impl.namespace {:no-doc true} (:refer-clojure :exclude [ns-name]) (:require [clj-kondo.impl.analysis :as analysis] [clj-kondo.impl.analysis.java :as java] [clj-kondo.impl.config :as config] [clj-kondo.impl.findings :as findings] [clj-kondo.impl.utils :as utils :refer [export-ns-sym node->line deep-merge linter-disabled? one-of]] [clj-kondo.impl.var-info :as var-info] [clojure.string :as str]) (:import [java.util StringTokenizer])) (set! *warn-on-reflection* true) (defn lint-duplicate-requires! ([ctx namespaces] (lint-duplicate-requires! ctx #{} namespaces)) ([ctx init namespaces] (reduce (fn [required ns] (if (contains? required ns) (do (findings/reg-finding! ctx (-> (node->line (:filename ctx) ns :duplicate-require (str "duplicate require of " ns)) (assoc :duplicate-ns (export-ns-sym ns)))) required) (conj required ns))) (set init) namespaces) nil)) (defn lint-conflicting-aliases! [ctx namespaces] (let [config (:config ctx) level (-> config :linters :conflicting-alias :level)] (when-not (identical? :off level) (loop [aliases #{} ns-maps (filter :as namespaces)] (let [{:keys [ns as]} (first ns-maps)] (when (contains? aliases as) (findings/reg-finding! ctx (node->line (:filename ctx) as :conflicting-alias (str "Conflicting alias for " ns)))) (when (seq (rest ns-maps)) (recur (conj aliases as) (rest ns-maps)))))))) (defn lint-unsorted-required-namespaces! [ctx namespaces] (let [config (:config ctx) level (-> config :linters :unsorted-required-namespaces :level)] (when-not (identical? :off level) (loop [last-processed-ns nil ns-list namespaces] (when ns-list (let [ns (first ns-list) m (meta ns) raw-ns (:raw-name m) prefix (:prefix m) raw-ns (cond prefix (str prefix "." ns) raw-ns (if (string? raw-ns) (pr-str raw-ns) (str raw-ns)) :else (str ns)) branch (:branch m) raw-ns (str/lower-case raw-ns)] (cond branch (recur last-processed-ns (next ns-list)) (pos? (compare last-processed-ns raw-ns)) (findings/reg-finding! ctx (node->line (:filename ctx) ns :unsorted-required-namespaces (str "Unsorted namespace: " ns))) :else (recur raw-ns (next ns-list))))))))) (defn reg-namespace! "Registers namespace. Deep-merges with already registered namespaces with the same name. Returns updated namespace." [{:keys [:base-lang :lang :namespaces]} ns] (let [{ns-name :name} ns path [base-lang lang ns-name]] (get-in (swap! namespaces update-in path deep-merge ns) path))) (defn reg-var! ([ctx ns-sym var-sym expr] (reg-var! ctx ns-sym var-sym expr nil)) ([{:keys [:base-lang :lang :filename :namespaces :top-level? :top-ns] :as ctx} ns-sym var-sym expr metadata] (let [m (meta expr) expr-row (:row m) expr-col (:col m) expr-end-row (:end-row m) expr-end-col (:end-col m) metadata (assoc metadata :ns ns-sym :name var-sym :name-row (or (:name-row metadata) (:row metadata)) :name-col (or (:name-col metadata) (:col metadata)) :name-end-row (or (:name-end-row metadata) (:end-row metadata)) :name-end-col (or (:name-end-col metadata) (:end-col metadata)) :row expr-row :col expr-col :end-row expr-end-row :end-col expr-end-col :derived-location (:derived-location m)) path [base-lang lang ns-sym] temp? (:temp metadata) config (:config ctx)] (when (and (:analysis ctx) (not temp?)) (analysis/reg-var! ctx filename expr-row expr-col ns-sym var-sym metadata)) (swap! namespaces update-in path (fn [ns] (let [vars (:vars ns) prev-var (get vars var-sym) prev-declared? (:declared prev-var)] ;; declare is idempotent (when (and top-level? (not (:declared metadata)) (not (:in-comment ctx))) (when-not (= 'clojure.core/definterface (:defined-by metadata)) (when-let [redefined-ns (or (when-let [meta-v prev-var] (when-not (or (:temp meta-v) prev-declared?) ns-sym)) (when-let [qv (get (:referred-vars ns) var-sym)] (:ns qv)) (let [core-ns (case lang :clj 'clojure.core :cljs 'cljs.core)] (when (and (not= ns-sym core-ns) (not (contains? (:clojure-excluded ns) var-sym)) (var-info/core-sym? lang var-sym)) core-ns)))] (findings/reg-finding! ctx (node->line filename expr :redefined-var (if (= ns-sym redefined-ns) (str "redefined var #'" redefined-ns "/" var-sym) (str var-sym " already refers to #'" redefined-ns "/" var-sym)))))) (when-not temp? (when (and (not (identical? :off (-> config :linters :missing-docstring :level))) (not (:private metadata)) (not (:doc metadata)) (not (:test metadata)) (not temp?) (not (:imported-var metadata)) (not (when-let [defined-by (or (:linted-as metadata) (:defined-by metadata))] (or (one-of defined-by [clojure.test/deftest clojure.core/deftype clojure.core/defrecord clojure.core/defprotocol clojure.core/definterface]) (when (identical? :cljs lang) (one-of defined-by [cljs.core/deftype cljs.core/defprotocol])))))) (findings/reg-finding! ctx (node->line filename expr :missing-docstring "Missing docstring."))) (when (and (identical? :clj lang) (= '-main var-sym)) ;; TODO: and lang = :clj (when-not (:gen-class ns) (when-not (identical? :off (-> config :linters :main-without-gen-class :level)) (findings/reg-finding! ctx (node->line filename expr :main-without-gen-class "Main function without gen-class."))))))) (update ns :vars assoc var-sym (assoc (merge metadata (select-keys prev-var [:row :col :end-row :end-col])) :top-ns top-ns)))))))) (defn reg-var-usage! [{:keys [:base-lang :lang :namespaces] :as ctx} ns-sym usage] (let [path [base-lang lang ns-sym] usage (assoc usage :config (:config ctx) :unresolved-symbol-disabled? ;; TODO: can we do this via the ctx only? (or (:unresolved-symbol-disabled? usage) (linter-disabled? ctx :unresolved-symbol)))] (swap! namespaces update-in path (fn [ns] (update ns :used-vars (fnil conj []) usage))))) (defn reg-used-namespace! "Registers usage of required namespaced in ns." [{:keys [:base-lang :lang :namespaces]} ns-sym required-ns-sym] (swap! namespaces update-in [base-lang lang ns-sym :used-namespaces] conj required-ns-sym)) (defn reg-proxied-namespaces! [{:keys [:base-lang :lang :namespaces]} ns-sym proxied-ns-syms] (swap! namespaces update-in [base-lang lang ns-sym :proxied-namespaces] into proxied-ns-syms)) (defn reg-alias! [{:keys [:base-lang :lang :namespaces]} ns-sym alias-sym aliased-ns-sym] (swap! namespaces (fn [n] (-> n (assoc-in [base-lang lang ns-sym :qualify-ns alias-sym] aliased-ns-sym) (assoc-in [base-lang lang ns-sym :aliases alias-sym] aliased-ns-sym))))) (defn reg-binding! [ctx ns-sym binding] (when-not (or (:skip-reg-binding? ctx) (:clj-kondo/skip-reg-binding binding)) (when (:analyze-locals? ctx) (analysis/reg-local! ctx (:filename ctx) binding)) (let [binding (if (:mark-bindings-used? ctx) (assoc binding :clj-kondo/mark-used true) binding) {:keys [:base-lang :lang :namespaces]} ctx] (swap! namespaces update-in [base-lang lang ns-sym :bindings] conj binding))) nil) (defn reg-destructuring-default! [{:keys [:base-lang :lang :namespaces :ns]} default binding] (swap! namespaces update-in [base-lang lang (:name ns) :destructuring-defaults] conj (assoc default :binding binding)) nil) (defn reg-used-binding! [{:keys [:base-lang :lang :namespaces :filename] :as ctx} ns-sym binding usage] (when (and usage (:analyze-locals? ctx) (not (:clj-kondo/mark-used binding))) (analysis/reg-local-usage! ctx filename binding usage)) (swap! namespaces update-in [base-lang lang ns-sym :used-bindings] conj binding) nil) (defn reg-required-namespaces! [{:keys [:base-lang :lang :namespaces] :as ctx} ns-sym analyzed-require-clauses] (lint-conflicting-aliases! ctx (:required analyzed-require-clauses)) (lint-unsorted-required-namespaces! ctx (:required analyzed-require-clauses)) (let [path [base-lang lang ns-sym] ns (get-in @namespaces path)] (lint-duplicate-requires! ctx (:required ns) (:required analyzed-require-clauses)) (swap! namespaces update-in path (fn [ns] (merge-with into ns analyzed-require-clauses)))) nil) (defn reg-imports! [{:keys [:base-lang :lang :namespaces] :as ctx} ns-sym imports] (swap! namespaces update-in [base-lang lang ns-sym] (fn [ns] ;; TODO: ;; (lint-duplicate-imports! ctx (:required ns) ...) (update ns :imports merge imports))) (when (java/analyze-class-usages? ctx) (doseq [[k v] imports] (java/reg-class-usage! ctx (str v "." k) (assoc (meta k) :import true))))) (defn class-name? [s] (let [^String s (str s)] (when-let [i (str/last-index-of s \.)] (or (let [should-be-capital-letter-idx (inc i)] (and (> (.length s) should-be-capital-letter-idx) (Character/isUpperCase ^char (.charAt s should-be-capital-letter-idx)))) (when-let [i (str/index-of s "_")] (pos? i)))))) (defn reg-unresolved-symbol! [ctx ns-sym sym {:keys [:base-lang :lang :config :callstack] :as sym-info}] (when-not (or (:unresolved-symbol-disabled? sym-info) (config/unresolved-symbol-excluded config callstack sym) (let [symbol-name (name sym)] (or (and (> (count symbol-name) 1) (str/starts-with? symbol-name ".")) (class-name? symbol-name)))) (swap! (:namespaces ctx) update-in [base-lang lang ns-sym :unresolved-symbols sym] (fnil conj []) sym-info)) nil) (defn reg-unresolved-var! [ctx ns-sym resolved-ns sym {:keys [:base-lang :lang :config] :as sym-info}] (when-not (or ;; this is set because of linting macro bodies ;; before removing this, check script/diff (:unresolved-symbol-disabled? sym-info) (config/unresolved-var-excluded config resolved-ns sym) (let [symbol-name (name sym)] (or (str/starts-with? symbol-name ".") (class-name? symbol-name)))) (swap! (:namespaces ctx) update-in [base-lang lang ns-sym :unresolved-vars [resolved-ns sym]] (fnil conj []) sym-info)) nil) (defn reg-used-referred-var! [{:keys [:base-lang :lang :namespaces] :as _ctx} ns-sym var] (swap! namespaces update-in [base-lang lang ns-sym :used-referred-vars] conj var)) (defn reg-referred-all-var! [{:keys [:base-lang :lang :namespaces] :as _ctx} ns-sym referred-all-ns-sym var-sym] (swap! namespaces update-in [base-lang lang ns-sym :refer-alls referred-all-ns-sym :referred] conj var-sym)) (defn list-namespaces [{:keys [:namespaces]}] (for [[_base-lang m] @namespaces [_lang nss] m [_ns-name ns] nss] ns)) (defn reg-used-import! [{:keys [:base-lang :lang :namespaces] :as ctx} name-sym ns-sym package class-name expr] (swap! namespaces update-in [base-lang lang ns-sym :used-imports] conj class-name) (when (java/analyze-class-usages? ctx) (let [name-meta (meta name-sym) loc (or (meta expr) (meta class-name))] (java/reg-class-usage! ctx (str package "." class-name) (assoc loc :name-row (or (:row name-meta) (:row loc)) :name-col (or (:col name-meta) (:col loc)) :name-end-row (or (:end-row name-meta) (:end-row loc)) :name-end-col (or (:end-col name-meta) (:end-col loc))))))) (defn reg-unresolved-namespace! [{:keys [:base-lang :lang :namespaces :config :callstack :filename] :as _ctx} ns-sym unresolved-ns] (when-not (or (identical? :off (-> config :linters :unresolved-namespace :level)) (config/unresolved-namespace-excluded config unresolved-ns) ;; unresolved namespaces in an excluded unresolved symbols call are not reported (config/unresolved-symbol-excluded config callstack :dummy)) (let [unresolved-ns (vary-meta unresolved-ns ;; since the user namespaces is present in each filesrc/clj_kondo/impl/namespace.clj ;; we must include the filename here see # 73 assoc :filename filename)] (swap! namespaces update-in [base-lang lang ns-sym :unresolved-namespaces unresolved-ns] (fnil conj []) unresolved-ns)))) (defn get-namespace [ctx base-lang lang ns-sym] (get-in @(:namespaces ctx) [base-lang lang ns-sym])) (defn next-token [^StringTokenizer st] (when (.hasMoreTokens st) (.nextToken st))) (defn first-segment "Returns first segment dot-delimited string, only if there is at least one part after the first dot." [name-sym] (let [st (StringTokenizer. (str name-sym) ".")] (when-let [ft (next-token st)] (symbol ft)))) (defn check-shadowed-binding! [ctx name-sym expr] (let [config (:config ctx) level (-> config :linters :shadowed-var :level)] (when-not (identical? :off level) (when-let [{:keys [:ns :name]} (let [ns-name (:name (:ns ctx)) lang (:lang ctx) ns (get-namespace ctx (:base-lang ctx) lang ns-name)] (if-let [v (get (:referred-vars ns) name-sym)] v (if (contains? (:vars ns) name-sym) {:ns (:name ns) :name name-sym} (let [clojure-excluded? (contains? (:clojure-excluded ns) name-sym) core-sym? (when-not clojure-excluded? (var-info/core-sym? lang name-sym)) special-form? (or (special-symbol? name-sym) (contains? var-info/special-forms name-sym))] (when (or core-sym? special-form?) {:ns (case lang :clj 'clojure.core :cljs 'cljs.core) :name name-sym})))))] (when-not (config/shadowed-var-excluded? config name) (let [suggestions (get-in ctx [:config :linters :shadowed-var :suggest]) suggestion (when suggestions (get suggestions name)) message (str "Shadowed var: " ns "/" name) message (if suggestion (str message ". Suggestion: " suggestion) message)] (findings/reg-finding! ctx (node->line (:filename ctx) expr :shadowed-var message)))))))) (defn split-on-dots [name-sym] (vec (.split ^String (str name-sym) "\\."))) (defn normalize-sym-name "Assumes simple symbol. Strips foo.bar.baz into foo if foo is a local or var, as it ignores property access in CLJS. When foo.bar is a known namespace, returns foo.bar/baz." [ctx sym] (let [lang (:lang ctx)] (if (identical? :cljs lang) (let [name-str (str sym)] (if (and (not (str/starts-with? name-str ".")) (not (str/ends-with? name-str ".")) (str/includes? name-str ".")) (let [locals (:bindings ctx) sym-str (str sym) segments (split-on-dots sym-str) prefix-str (segments 0) prefix-sym (symbol prefix-str) the-ns (get-namespace ctx (:base-lang ctx) lang (-> ctx :ns :name))] (if (or (contains? locals prefix-sym) (contains? (:vars the-ns) prefix-sym)) prefix-sym (let [qualify-ns (:qualify-ns the-ns) ns-resolved? (contains? qualify-ns sym)] (if ns-resolved? sym (let [maybe-ns-str (str/join "." (subvec segments 0 (dec (count segments)))) maybe-ns (symbol maybe-ns-str) ns-prefix? (= maybe-ns (get qualify-ns maybe-ns))] (if ns-prefix? ;; return fully qualified symbol (symbol maybe-ns-str (peek segments)) (if-not (= "goog" prefix-str) prefix-sym sym))))))) sym)) sym))) (defn generated? "We assume that a node is generated by clj-kondo when it has no metadata or when it has the key :clj-kondo.impl/generated. For this purpose, we're only checking the whole expression or the first child (in the case of a list node)." [expr] (or (nil? (meta expr)) (:clj-kondo.impl/generated expr))) (defn lint-aliased-namespace "Check if a namespace symbol has an existing `:as` alias." [ctx ns-sym name-sym expr] ;; Reasons to not check the given symbol: ;; * it's already using an existing alias ;; * this lint is disabled ;; * this lint is configured to exclude the given namespace * it 's generated by ;; * current lang is cljs and the "interop" symbol is treated as a var: ;; clojure.lang.Var -> clojure.lang/Var (when-not (or (contains? (:aliases (:ns ctx)) ns-sym) (linter-disabled? ctx :aliased-namespace-symbol) (config/aliased-namespace-symbol-excluded? (:config ctx) ns-sym) (and (= :cljs (:lang ctx)) (not= name-sym (:value expr)))) (let [expr (or (some-> expr :children first) expr)] (when-not (generated? expr) (when-let [ns->aliases (:ns->aliases (:ns ctx))] (when-let [existing (ns->aliases ns-sym)] (findings/reg-finding! ctx (node->line (:filename ctx) expr :aliased-namespace-symbol (format "%s defined for %s: %s" (if (= 1 (count existing)) "An alias is" "Multiple aliases are") ns-sym (if (= 1 (count existing)) (first existing) (str/join ", " (sort existing)))))))))))) (defn lint-as-aliased-usage "Check if a namespace symbol has an existing `:as` alias." [ctx ns-sym name-sym expr] (when expr (let [expr (if (meta name-sym) name-sym expr)] (when-let [ns-sym (get (:aliases (:ns ctx)) ns-sym)] (when (some-> ns-sym meta :alias meta :as-alias) (let [sql (:syntax-quote-level ctx)] (when (or (not sql) (zero? sql)) (findings/reg-finding! ctx (node->line (:filename ctx) expr :aliased-namespace-var-usage (format "Namespace only aliased but wasn't loaded: %s" ns-sym)))))))))) (defn resolve-name [ctx call? ns-name name-sym expr] (let [lang (:lang ctx) ns (get-namespace ctx (:base-lang ctx) lang ns-name) cljs? (identical? :cljs lang)] (if-let [ns* (namespace name-sym)] (let [ns* (if cljs? (str/replace ns* #"\$macros$" "") ns*) ns-sym (symbol ns*)] (or (when-let [ns* (or (get (:qualify-ns ns) ns-sym) ;; referring to the namespace we're in (when (= (:name ns) ns-sym) ns-sym))] (lint-aliased-namespace ctx ns-sym name-sym expr) (lint-as-aliased-usage ctx ns-sym name-sym expr) (let [core? (or (= 'clojure.core ns*) (= 'cljs.core ns*)) [var-name interop] (if cljs? (str/split (name name-sym) #"\." 2) [(name name-sym)]) var-name (symbol var-name) resolved-core? (and core? (var-info/core-sym? lang var-name))] (cond-> {:ns ns* :name var-name :interop? (and cljs? (boolean interop))} (contains? (:aliases ns) ns-sym) (assoc :alias ns-sym) core? (assoc :resolved-core? resolved-core?)))) (when-let [[class-name package] (or (when (identical? :clj lang) (or (when-let [[class fq] (find var-info/default-import->qname ns-sym)] ;; TODO: fix in default-import->qname [class (str/replace fq (str/re-quote-replacement (str "." class)) "")]) (when-let [fq (get var-info/default-fq-imports ns-sym)] (let [fq (str fq) splitted (split-on-dots fq) package (symbol (str/join "." (butlast splitted))) name* (symbol (last splitted))] [name* package])))) (find (:imports ns) ns-sym))] (reg-used-import! ctx name-sym ns-name package class-name expr) (when call? (findings/warn-reflection ctx expr)) {:interop? true :ns (symbol (str package "." class-name)) :name (symbol (name name-sym))}) (if (identical? :clj lang) (if (and (not (one-of ns* ["clojure.core"])) (class-name? ns*)) (do (java/reg-class-usage! ctx ns* (meta expr) (meta name-sym)) (when call? (findings/warn-reflection ctx expr)) {:interop? true}) {:name (symbol (name name-sym)) :unresolved? true :unresolved-ns ns-sym}) (if cljs? ;; see #L781 (when-not (one-of ns* ["js" "goog" "Math" "String"]) {:name (symbol (name name-sym)) :unresolved? true :unresolved-ns ns-sym}) {:name (symbol (name name-sym)) :unresolved? true :unresolved-ns ns-sym})))) (or (when (and call? (special-symbol? name-sym)) {:ns (case lang :clj 'clojure.core :cljs 'cljs.core) :name name-sym :resolved-core? true}) (let [name-sym (if cljs? ;; although we also check for CLJS in normalize-sym, we ;; already know cljs? here (normalize-sym-name ctx name-sym) name-sym)] (if (and cljs? (namespace name-sym)) (recur ctx call? ns-name name-sym expr) (or (when-let [[k v] (find (:referred-vars ns) name-sym)] (reg-used-referred-var! ctx ns-name k) v) (when (contains? (:vars ns) name-sym) {:ns (:name ns) :name name-sym}) (when-let [[name-sym* package] (or (when (identical? :clj lang) (when-let [[class fq] (find var-info/default-import->qname name-sym)] ;; TODO: fix in default-import->qname [class (str/replace fq (str/re-quote-replacement (str "." class)) "")])) ;; (find var-info/default-import->qname name-sym) (when (identical? :clj lang) (when-let [v (get var-info/default-fq-imports name-sym)] (let [splitted (split-on-dots v) package (symbol (str/join "." (butlast splitted))) name* (symbol (last splitted))] [name* package]))) (if cljs? ;; CLJS allows imported classes to be used like this: UtcDateTime.fromTimestamp (let [fs (first-segment name-sym)] (find (:imports ns) fs)) (find (:imports ns) name-sym)))] (reg-used-import! ctx name-sym ns-name package name-sym* expr) (when call? (findings/warn-reflection ctx expr)) {:ns package :interop? true :name name-sym*}) (when cljs? (when-let [ns* (get (:qualify-ns ns) name-sym)] (when (some-> (meta ns*) :raw-name string?) {:ns ns* :name name-sym}))) (let [clojure-excluded? (contains? (:clojure-excluded ns) name-sym)] (if (or ;; check core-sym (when-not clojure-excluded? (var-info/core-sym? lang name-sym)) ;; check special form (and call? (contains? var-info/special-forms name-sym))) {:ns (case lang :clj 'clojure.core :cljs 'cljs.core) :name name-sym :resolved-core? true} (let [referred-all-ns (some (fn [[k {:keys [:excluded]}]] (when-not (contains? excluded name-sym) k)) (:refer-alls ns))] (if (and (not referred-all-ns) (class-name? name-sym)) (do (java/reg-class-usage! ctx (str name-sym) (meta expr)) (when call? (findings/warn-reflection ctx expr)) {:interop? true}) {:ns (or referred-all-ns :clj-kondo/unknown-namespace) :name name-sym :unresolved? true :allow-forward-reference? (:in-comment ctx) :clojure-excluded? clojure-excluded?}))))))))))) ;;;; Scratch (comment )
null
https://raw.githubusercontent.com/clj-kondo/clj-kondo/7c1881753e271fc01185be2489a6504bc6195f96/src/clj_kondo/impl/namespace.clj
clojure
declare is idempotent TODO: and lang = :clj TODO: can we do this via the ctx only? TODO: (lint-duplicate-imports! ctx (:required ns) ...) this is set because of linting macro bodies before removing this, check script/diff unresolved namespaces in an excluded unresolved symbols call are not reported since the user namespaces is present in each filesrc/clj_kondo/impl/namespace.clj we must include the filename here return fully qualified symbol Reasons to not check the given symbol: * it's already using an existing alias * this lint is disabled * this lint is configured to exclude the given namespace * current lang is cljs and the "interop" symbol is treated as a var: clojure.lang.Var -> clojure.lang/Var referring to the namespace we're in TODO: fix in default-import->qname see #L781 although we also check for CLJS in normalize-sym, we already know cljs? here TODO: fix in default-import->qname (find var-info/default-import->qname name-sym) CLJS allows imported classes to be used like this: UtcDateTime.fromTimestamp check core-sym check special form Scratch
(ns clj-kondo.impl.namespace {:no-doc true} (:refer-clojure :exclude [ns-name]) (:require [clj-kondo.impl.analysis :as analysis] [clj-kondo.impl.analysis.java :as java] [clj-kondo.impl.config :as config] [clj-kondo.impl.findings :as findings] [clj-kondo.impl.utils :as utils :refer [export-ns-sym node->line deep-merge linter-disabled? one-of]] [clj-kondo.impl.var-info :as var-info] [clojure.string :as str]) (:import [java.util StringTokenizer])) (set! *warn-on-reflection* true) (defn lint-duplicate-requires! ([ctx namespaces] (lint-duplicate-requires! ctx #{} namespaces)) ([ctx init namespaces] (reduce (fn [required ns] (if (contains? required ns) (do (findings/reg-finding! ctx (-> (node->line (:filename ctx) ns :duplicate-require (str "duplicate require of " ns)) (assoc :duplicate-ns (export-ns-sym ns)))) required) (conj required ns))) (set init) namespaces) nil)) (defn lint-conflicting-aliases! [ctx namespaces] (let [config (:config ctx) level (-> config :linters :conflicting-alias :level)] (when-not (identical? :off level) (loop [aliases #{} ns-maps (filter :as namespaces)] (let [{:keys [ns as]} (first ns-maps)] (when (contains? aliases as) (findings/reg-finding! ctx (node->line (:filename ctx) as :conflicting-alias (str "Conflicting alias for " ns)))) (when (seq (rest ns-maps)) (recur (conj aliases as) (rest ns-maps)))))))) (defn lint-unsorted-required-namespaces! [ctx namespaces] (let [config (:config ctx) level (-> config :linters :unsorted-required-namespaces :level)] (when-not (identical? :off level) (loop [last-processed-ns nil ns-list namespaces] (when ns-list (let [ns (first ns-list) m (meta ns) raw-ns (:raw-name m) prefix (:prefix m) raw-ns (cond prefix (str prefix "." ns) raw-ns (if (string? raw-ns) (pr-str raw-ns) (str raw-ns)) :else (str ns)) branch (:branch m) raw-ns (str/lower-case raw-ns)] (cond branch (recur last-processed-ns (next ns-list)) (pos? (compare last-processed-ns raw-ns)) (findings/reg-finding! ctx (node->line (:filename ctx) ns :unsorted-required-namespaces (str "Unsorted namespace: " ns))) :else (recur raw-ns (next ns-list))))))))) (defn reg-namespace! "Registers namespace. Deep-merges with already registered namespaces with the same name. Returns updated namespace." [{:keys [:base-lang :lang :namespaces]} ns] (let [{ns-name :name} ns path [base-lang lang ns-name]] (get-in (swap! namespaces update-in path deep-merge ns) path))) (defn reg-var! ([ctx ns-sym var-sym expr] (reg-var! ctx ns-sym var-sym expr nil)) ([{:keys [:base-lang :lang :filename :namespaces :top-level? :top-ns] :as ctx} ns-sym var-sym expr metadata] (let [m (meta expr) expr-row (:row m) expr-col (:col m) expr-end-row (:end-row m) expr-end-col (:end-col m) metadata (assoc metadata :ns ns-sym :name var-sym :name-row (or (:name-row metadata) (:row metadata)) :name-col (or (:name-col metadata) (:col metadata)) :name-end-row (or (:name-end-row metadata) (:end-row metadata)) :name-end-col (or (:name-end-col metadata) (:end-col metadata)) :row expr-row :col expr-col :end-row expr-end-row :end-col expr-end-col :derived-location (:derived-location m)) path [base-lang lang ns-sym] temp? (:temp metadata) config (:config ctx)] (when (and (:analysis ctx) (not temp?)) (analysis/reg-var! ctx filename expr-row expr-col ns-sym var-sym metadata)) (swap! namespaces update-in path (fn [ns] (let [vars (:vars ns) prev-var (get vars var-sym) prev-declared? (:declared prev-var)] (when (and top-level? (not (:declared metadata)) (not (:in-comment ctx))) (when-not (= 'clojure.core/definterface (:defined-by metadata)) (when-let [redefined-ns (or (when-let [meta-v prev-var] (when-not (or (:temp meta-v) prev-declared?) ns-sym)) (when-let [qv (get (:referred-vars ns) var-sym)] (:ns qv)) (let [core-ns (case lang :clj 'clojure.core :cljs 'cljs.core)] (when (and (not= ns-sym core-ns) (not (contains? (:clojure-excluded ns) var-sym)) (var-info/core-sym? lang var-sym)) core-ns)))] (findings/reg-finding! ctx (node->line filename expr :redefined-var (if (= ns-sym redefined-ns) (str "redefined var #'" redefined-ns "/" var-sym) (str var-sym " already refers to #'" redefined-ns "/" var-sym)))))) (when-not temp? (when (and (not (identical? :off (-> config :linters :missing-docstring :level))) (not (:private metadata)) (not (:doc metadata)) (not (:test metadata)) (not temp?) (not (:imported-var metadata)) (not (when-let [defined-by (or (:linted-as metadata) (:defined-by metadata))] (or (one-of defined-by [clojure.test/deftest clojure.core/deftype clojure.core/defrecord clojure.core/defprotocol clojure.core/definterface]) (when (identical? :cljs lang) (one-of defined-by [cljs.core/deftype cljs.core/defprotocol])))))) (findings/reg-finding! ctx (node->line filename expr :missing-docstring "Missing docstring."))) (when (and (identical? :clj lang) (= '-main var-sym)) (when-not (:gen-class ns) (when-not (identical? :off (-> config :linters :main-without-gen-class :level)) (findings/reg-finding! ctx (node->line filename expr :main-without-gen-class "Main function without gen-class."))))))) (update ns :vars assoc var-sym (assoc (merge metadata (select-keys prev-var [:row :col :end-row :end-col])) :top-ns top-ns)))))))) (defn reg-var-usage! [{:keys [:base-lang :lang :namespaces] :as ctx} ns-sym usage] (let [path [base-lang lang ns-sym] usage (assoc usage :config (:config ctx) :unresolved-symbol-disabled? (or (:unresolved-symbol-disabled? usage) (linter-disabled? ctx :unresolved-symbol)))] (swap! namespaces update-in path (fn [ns] (update ns :used-vars (fnil conj []) usage))))) (defn reg-used-namespace! "Registers usage of required namespaced in ns." [{:keys [:base-lang :lang :namespaces]} ns-sym required-ns-sym] (swap! namespaces update-in [base-lang lang ns-sym :used-namespaces] conj required-ns-sym)) (defn reg-proxied-namespaces! [{:keys [:base-lang :lang :namespaces]} ns-sym proxied-ns-syms] (swap! namespaces update-in [base-lang lang ns-sym :proxied-namespaces] into proxied-ns-syms)) (defn reg-alias! [{:keys [:base-lang :lang :namespaces]} ns-sym alias-sym aliased-ns-sym] (swap! namespaces (fn [n] (-> n (assoc-in [base-lang lang ns-sym :qualify-ns alias-sym] aliased-ns-sym) (assoc-in [base-lang lang ns-sym :aliases alias-sym] aliased-ns-sym))))) (defn reg-binding! [ctx ns-sym binding] (when-not (or (:skip-reg-binding? ctx) (:clj-kondo/skip-reg-binding binding)) (when (:analyze-locals? ctx) (analysis/reg-local! ctx (:filename ctx) binding)) (let [binding (if (:mark-bindings-used? ctx) (assoc binding :clj-kondo/mark-used true) binding) {:keys [:base-lang :lang :namespaces]} ctx] (swap! namespaces update-in [base-lang lang ns-sym :bindings] conj binding))) nil) (defn reg-destructuring-default! [{:keys [:base-lang :lang :namespaces :ns]} default binding] (swap! namespaces update-in [base-lang lang (:name ns) :destructuring-defaults] conj (assoc default :binding binding)) nil) (defn reg-used-binding! [{:keys [:base-lang :lang :namespaces :filename] :as ctx} ns-sym binding usage] (when (and usage (:analyze-locals? ctx) (not (:clj-kondo/mark-used binding))) (analysis/reg-local-usage! ctx filename binding usage)) (swap! namespaces update-in [base-lang lang ns-sym :used-bindings] conj binding) nil) (defn reg-required-namespaces! [{:keys [:base-lang :lang :namespaces] :as ctx} ns-sym analyzed-require-clauses] (lint-conflicting-aliases! ctx (:required analyzed-require-clauses)) (lint-unsorted-required-namespaces! ctx (:required analyzed-require-clauses)) (let [path [base-lang lang ns-sym] ns (get-in @namespaces path)] (lint-duplicate-requires! ctx (:required ns) (:required analyzed-require-clauses)) (swap! namespaces update-in path (fn [ns] (merge-with into ns analyzed-require-clauses)))) nil) (defn reg-imports! [{:keys [:base-lang :lang :namespaces] :as ctx} ns-sym imports] (swap! namespaces update-in [base-lang lang ns-sym] (fn [ns] (update ns :imports merge imports))) (when (java/analyze-class-usages? ctx) (doseq [[k v] imports] (java/reg-class-usage! ctx (str v "." k) (assoc (meta k) :import true))))) (defn class-name? [s] (let [^String s (str s)] (when-let [i (str/last-index-of s \.)] (or (let [should-be-capital-letter-idx (inc i)] (and (> (.length s) should-be-capital-letter-idx) (Character/isUpperCase ^char (.charAt s should-be-capital-letter-idx)))) (when-let [i (str/index-of s "_")] (pos? i)))))) (defn reg-unresolved-symbol! [ctx ns-sym sym {:keys [:base-lang :lang :config :callstack] :as sym-info}] (when-not (or (:unresolved-symbol-disabled? sym-info) (config/unresolved-symbol-excluded config callstack sym) (let [symbol-name (name sym)] (or (and (> (count symbol-name) 1) (str/starts-with? symbol-name ".")) (class-name? symbol-name)))) (swap! (:namespaces ctx) update-in [base-lang lang ns-sym :unresolved-symbols sym] (fnil conj []) sym-info)) nil) (defn reg-unresolved-var! [ctx ns-sym resolved-ns sym {:keys [:base-lang :lang :config] :as sym-info}] (when-not (or (:unresolved-symbol-disabled? sym-info) (config/unresolved-var-excluded config resolved-ns sym) (let [symbol-name (name sym)] (or (str/starts-with? symbol-name ".") (class-name? symbol-name)))) (swap! (:namespaces ctx) update-in [base-lang lang ns-sym :unresolved-vars [resolved-ns sym]] (fnil conj []) sym-info)) nil) (defn reg-used-referred-var! [{:keys [:base-lang :lang :namespaces] :as _ctx} ns-sym var] (swap! namespaces update-in [base-lang lang ns-sym :used-referred-vars] conj var)) (defn reg-referred-all-var! [{:keys [:base-lang :lang :namespaces] :as _ctx} ns-sym referred-all-ns-sym var-sym] (swap! namespaces update-in [base-lang lang ns-sym :refer-alls referred-all-ns-sym :referred] conj var-sym)) (defn list-namespaces [{:keys [:namespaces]}] (for [[_base-lang m] @namespaces [_lang nss] m [_ns-name ns] nss] ns)) (defn reg-used-import! [{:keys [:base-lang :lang :namespaces] :as ctx} name-sym ns-sym package class-name expr] (swap! namespaces update-in [base-lang lang ns-sym :used-imports] conj class-name) (when (java/analyze-class-usages? ctx) (let [name-meta (meta name-sym) loc (or (meta expr) (meta class-name))] (java/reg-class-usage! ctx (str package "." class-name) (assoc loc :name-row (or (:row name-meta) (:row loc)) :name-col (or (:col name-meta) (:col loc)) :name-end-row (or (:end-row name-meta) (:end-row loc)) :name-end-col (or (:end-col name-meta) (:end-col loc))))))) (defn reg-unresolved-namespace! [{:keys [:base-lang :lang :namespaces :config :callstack :filename] :as _ctx} ns-sym unresolved-ns] (when-not (or (identical? :off (-> config :linters :unresolved-namespace :level)) (config/unresolved-namespace-excluded config unresolved-ns) (config/unresolved-symbol-excluded config callstack :dummy)) (let [unresolved-ns (vary-meta unresolved-ns see # 73 assoc :filename filename)] (swap! namespaces update-in [base-lang lang ns-sym :unresolved-namespaces unresolved-ns] (fnil conj []) unresolved-ns)))) (defn get-namespace [ctx base-lang lang ns-sym] (get-in @(:namespaces ctx) [base-lang lang ns-sym])) (defn next-token [^StringTokenizer st] (when (.hasMoreTokens st) (.nextToken st))) (defn first-segment "Returns first segment dot-delimited string, only if there is at least one part after the first dot." [name-sym] (let [st (StringTokenizer. (str name-sym) ".")] (when-let [ft (next-token st)] (symbol ft)))) (defn check-shadowed-binding! [ctx name-sym expr] (let [config (:config ctx) level (-> config :linters :shadowed-var :level)] (when-not (identical? :off level) (when-let [{:keys [:ns :name]} (let [ns-name (:name (:ns ctx)) lang (:lang ctx) ns (get-namespace ctx (:base-lang ctx) lang ns-name)] (if-let [v (get (:referred-vars ns) name-sym)] v (if (contains? (:vars ns) name-sym) {:ns (:name ns) :name name-sym} (let [clojure-excluded? (contains? (:clojure-excluded ns) name-sym) core-sym? (when-not clojure-excluded? (var-info/core-sym? lang name-sym)) special-form? (or (special-symbol? name-sym) (contains? var-info/special-forms name-sym))] (when (or core-sym? special-form?) {:ns (case lang :clj 'clojure.core :cljs 'cljs.core) :name name-sym})))))] (when-not (config/shadowed-var-excluded? config name) (let [suggestions (get-in ctx [:config :linters :shadowed-var :suggest]) suggestion (when suggestions (get suggestions name)) message (str "Shadowed var: " ns "/" name) message (if suggestion (str message ". Suggestion: " suggestion) message)] (findings/reg-finding! ctx (node->line (:filename ctx) expr :shadowed-var message)))))))) (defn split-on-dots [name-sym] (vec (.split ^String (str name-sym) "\\."))) (defn normalize-sym-name "Assumes simple symbol. Strips foo.bar.baz into foo if foo is a local or var, as it ignores property access in CLJS. When foo.bar is a known namespace, returns foo.bar/baz." [ctx sym] (let [lang (:lang ctx)] (if (identical? :cljs lang) (let [name-str (str sym)] (if (and (not (str/starts-with? name-str ".")) (not (str/ends-with? name-str ".")) (str/includes? name-str ".")) (let [locals (:bindings ctx) sym-str (str sym) segments (split-on-dots sym-str) prefix-str (segments 0) prefix-sym (symbol prefix-str) the-ns (get-namespace ctx (:base-lang ctx) lang (-> ctx :ns :name))] (if (or (contains? locals prefix-sym) (contains? (:vars the-ns) prefix-sym)) prefix-sym (let [qualify-ns (:qualify-ns the-ns) ns-resolved? (contains? qualify-ns sym)] (if ns-resolved? sym (let [maybe-ns-str (str/join "." (subvec segments 0 (dec (count segments)))) maybe-ns (symbol maybe-ns-str) ns-prefix? (= maybe-ns (get qualify-ns maybe-ns))] (if ns-prefix? (symbol maybe-ns-str (peek segments)) (if-not (= "goog" prefix-str) prefix-sym sym))))))) sym)) sym))) (defn generated? "We assume that a node is generated by clj-kondo when it has no metadata or when it has the key :clj-kondo.impl/generated. For this purpose, we're only checking the whole expression or the first child (in the case of a list node)." [expr] (or (nil? (meta expr)) (:clj-kondo.impl/generated expr))) (defn lint-aliased-namespace "Check if a namespace symbol has an existing `:as` alias." [ctx ns-sym name-sym expr] * it 's generated by (when-not (or (contains? (:aliases (:ns ctx)) ns-sym) (linter-disabled? ctx :aliased-namespace-symbol) (config/aliased-namespace-symbol-excluded? (:config ctx) ns-sym) (and (= :cljs (:lang ctx)) (not= name-sym (:value expr)))) (let [expr (or (some-> expr :children first) expr)] (when-not (generated? expr) (when-let [ns->aliases (:ns->aliases (:ns ctx))] (when-let [existing (ns->aliases ns-sym)] (findings/reg-finding! ctx (node->line (:filename ctx) expr :aliased-namespace-symbol (format "%s defined for %s: %s" (if (= 1 (count existing)) "An alias is" "Multiple aliases are") ns-sym (if (= 1 (count existing)) (first existing) (str/join ", " (sort existing)))))))))))) (defn lint-as-aliased-usage "Check if a namespace symbol has an existing `:as` alias." [ctx ns-sym name-sym expr] (when expr (let [expr (if (meta name-sym) name-sym expr)] (when-let [ns-sym (get (:aliases (:ns ctx)) ns-sym)] (when (some-> ns-sym meta :alias meta :as-alias) (let [sql (:syntax-quote-level ctx)] (when (or (not sql) (zero? sql)) (findings/reg-finding! ctx (node->line (:filename ctx) expr :aliased-namespace-var-usage (format "Namespace only aliased but wasn't loaded: %s" ns-sym)))))))))) (defn resolve-name [ctx call? ns-name name-sym expr] (let [lang (:lang ctx) ns (get-namespace ctx (:base-lang ctx) lang ns-name) cljs? (identical? :cljs lang)] (if-let [ns* (namespace name-sym)] (let [ns* (if cljs? (str/replace ns* #"\$macros$" "") ns*) ns-sym (symbol ns*)] (or (when-let [ns* (or (get (:qualify-ns ns) ns-sym) (when (= (:name ns) ns-sym) ns-sym))] (lint-aliased-namespace ctx ns-sym name-sym expr) (lint-as-aliased-usage ctx ns-sym name-sym expr) (let [core? (or (= 'clojure.core ns*) (= 'cljs.core ns*)) [var-name interop] (if cljs? (str/split (name name-sym) #"\." 2) [(name name-sym)]) var-name (symbol var-name) resolved-core? (and core? (var-info/core-sym? lang var-name))] (cond-> {:ns ns* :name var-name :interop? (and cljs? (boolean interop))} (contains? (:aliases ns) ns-sym) (assoc :alias ns-sym) core? (assoc :resolved-core? resolved-core?)))) (when-let [[class-name package] (or (when (identical? :clj lang) (or (when-let [[class fq] (find var-info/default-import->qname ns-sym)] [class (str/replace fq (str/re-quote-replacement (str "." class)) "")]) (when-let [fq (get var-info/default-fq-imports ns-sym)] (let [fq (str fq) splitted (split-on-dots fq) package (symbol (str/join "." (butlast splitted))) name* (symbol (last splitted))] [name* package])))) (find (:imports ns) ns-sym))] (reg-used-import! ctx name-sym ns-name package class-name expr) (when call? (findings/warn-reflection ctx expr)) {:interop? true :ns (symbol (str package "." class-name)) :name (symbol (name name-sym))}) (if (identical? :clj lang) (if (and (not (one-of ns* ["clojure.core"])) (class-name? ns*)) (do (java/reg-class-usage! ctx ns* (meta expr) (meta name-sym)) (when call? (findings/warn-reflection ctx expr)) {:interop? true}) {:name (symbol (name name-sym)) :unresolved? true :unresolved-ns ns-sym}) (if cljs? (when-not (one-of ns* ["js" "goog" "Math" "String"]) {:name (symbol (name name-sym)) :unresolved? true :unresolved-ns ns-sym}) {:name (symbol (name name-sym)) :unresolved? true :unresolved-ns ns-sym})))) (or (when (and call? (special-symbol? name-sym)) {:ns (case lang :clj 'clojure.core :cljs 'cljs.core) :name name-sym :resolved-core? true}) (let [name-sym (if cljs? (normalize-sym-name ctx name-sym) name-sym)] (if (and cljs? (namespace name-sym)) (recur ctx call? ns-name name-sym expr) (or (when-let [[k v] (find (:referred-vars ns) name-sym)] (reg-used-referred-var! ctx ns-name k) v) (when (contains? (:vars ns) name-sym) {:ns (:name ns) :name name-sym}) (when-let [[name-sym* package] (or (when (identical? :clj lang) (when-let [[class fq] (find var-info/default-import->qname name-sym)] [class (str/replace fq (str/re-quote-replacement (str "." class)) "")])) (when (identical? :clj lang) (when-let [v (get var-info/default-fq-imports name-sym)] (let [splitted (split-on-dots v) package (symbol (str/join "." (butlast splitted))) name* (symbol (last splitted))] [name* package]))) (if cljs? (let [fs (first-segment name-sym)] (find (:imports ns) fs)) (find (:imports ns) name-sym)))] (reg-used-import! ctx name-sym ns-name package name-sym* expr) (when call? (findings/warn-reflection ctx expr)) {:ns package :interop? true :name name-sym*}) (when cljs? (when-let [ns* (get (:qualify-ns ns) name-sym)] (when (some-> (meta ns*) :raw-name string?) {:ns ns* :name name-sym}))) (let [clojure-excluded? (contains? (:clojure-excluded ns) name-sym)] (if (or (when-not clojure-excluded? (var-info/core-sym? lang name-sym)) (and call? (contains? var-info/special-forms name-sym))) {:ns (case lang :clj 'clojure.core :cljs 'cljs.core) :name name-sym :resolved-core? true} (let [referred-all-ns (some (fn [[k {:keys [:excluded]}]] (when-not (contains? excluded name-sym) k)) (:refer-alls ns))] (if (and (not referred-all-ns) (class-name? name-sym)) (do (java/reg-class-usage! ctx (str name-sym) (meta expr)) (when call? (findings/warn-reflection ctx expr)) {:interop? true}) {:ns (or referred-all-ns :clj-kondo/unknown-namespace) :name name-sym :unresolved? true :allow-forward-reference? (:in-comment ctx) :clojure-excluded? clojure-excluded?}))))))))))) (comment )
fa9bf155d09dc80761b6b9d5cd32e4fd972aa985e0b6f0c0e983061fdd76453a
brianhempel/maniposynth
queue.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt , Jane Street Europe (* *) Copyright 2002 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. *) (* *) (**************************************************************************) exception Empty type 'a cell = | Nil | Cons of { content: 'a; mutable next: 'a cell } type 'a t = { mutable length: int; mutable first: 'a cell; mutable last: 'a cell } let create () = { length = 0; first = Nil; last = Nil } let clear q = q.length <- 0; q.first <- Nil; q.last <- Nil let add x q = let cell = Cons { content = x; next = Nil } in match q.last with | Nil -> q.length <- 1; q.first <- cell; q.last <- cell | Cons last -> q.length <- q.length + 1; last.next <- cell; q.last <- cell let push = add let peek q = match q.first with | Nil -> raise Empty | Cons { content } -> content let top = peek let take q = match q.first with | Nil -> raise Empty | Cons { content; next = Nil } -> clear q; content | Cons { content; next } -> q.length <- q.length - 1; q.first <- next; content let pop = take let copy = let rec copy q_res prev cell = match cell with | Nil -> q_res.last <- prev; q_res | Cons { content; next } -> let res = Cons { content; next = Nil } in begin match prev with | Nil -> q_res.first <- res | Cons p -> p.next <- res end; copy q_res res next in fun q -> copy { length = q.length; first = Nil; last = Nil } Nil q.first let is_empty q = q.length = 0 let length q = q.length let iter = let rec iter f cell = match cell with | Nil -> () | Cons { content; next } -> f content; iter f next in fun f q -> iter f q.first let fold = let rec fold f accu cell = match cell with | Nil -> accu | Cons { content; next } -> let accu = f accu content in fold f accu next in fun f accu q -> fold f accu q.first let transfer q1 q2 = if q1.length > 0 then match q2.last with | Nil -> q2.length <- q1.length; q2.first <- q1.first; q2.last <- q1.last; clear q1 | Cons last -> q2.length <- q2.length + q1.length; last.next <- q1.first; q2.last <- q1.last; clear q1 * { 6 Iterators } let to_seq q = let rec aux c () = match c with | Nil -> Seq.Nil | Cons { content=x; next; } -> Seq.Cons (x, aux next) in aux q.first let add_seq q i = Seq.iter (fun x -> push x q) i let of_seq g = let q = create() in add_seq q g; q
null
https://raw.githubusercontent.com/brianhempel/maniposynth/8c8e72f2459f1ec05fefcb994253f99620e377f3/ocaml-4.07.1/stdlib/queue.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. ************************************************************************
, projet Cristal , INRIA Rocquencourt , Jane Street Europe Copyright 2002 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the exception Empty type 'a cell = | Nil | Cons of { content: 'a; mutable next: 'a cell } type 'a t = { mutable length: int; mutable first: 'a cell; mutable last: 'a cell } let create () = { length = 0; first = Nil; last = Nil } let clear q = q.length <- 0; q.first <- Nil; q.last <- Nil let add x q = let cell = Cons { content = x; next = Nil } in match q.last with | Nil -> q.length <- 1; q.first <- cell; q.last <- cell | Cons last -> q.length <- q.length + 1; last.next <- cell; q.last <- cell let push = add let peek q = match q.first with | Nil -> raise Empty | Cons { content } -> content let top = peek let take q = match q.first with | Nil -> raise Empty | Cons { content; next = Nil } -> clear q; content | Cons { content; next } -> q.length <- q.length - 1; q.first <- next; content let pop = take let copy = let rec copy q_res prev cell = match cell with | Nil -> q_res.last <- prev; q_res | Cons { content; next } -> let res = Cons { content; next = Nil } in begin match prev with | Nil -> q_res.first <- res | Cons p -> p.next <- res end; copy q_res res next in fun q -> copy { length = q.length; first = Nil; last = Nil } Nil q.first let is_empty q = q.length = 0 let length q = q.length let iter = let rec iter f cell = match cell with | Nil -> () | Cons { content; next } -> f content; iter f next in fun f q -> iter f q.first let fold = let rec fold f accu cell = match cell with | Nil -> accu | Cons { content; next } -> let accu = f accu content in fold f accu next in fun f accu q -> fold f accu q.first let transfer q1 q2 = if q1.length > 0 then match q2.last with | Nil -> q2.length <- q1.length; q2.first <- q1.first; q2.last <- q1.last; clear q1 | Cons last -> q2.length <- q2.length + q1.length; last.next <- q1.first; q2.last <- q1.last; clear q1 * { 6 Iterators } let to_seq q = let rec aux c () = match c with | Nil -> Seq.Nil | Cons { content=x; next; } -> Seq.Cons (x, aux next) in aux q.first let add_seq q i = Seq.iter (fun x -> push x q) i let of_seq g = let q = create() in add_seq q g; q
af3b5b22a4c8cd4dc08448c78ff978efc05639f89c5ab7a5c8e1245e020795c3
gafiatulin/codewars
Collatz.hs
-- Collatz -- / module Collatz where collatz :: Int -> String collatz 1 = "1" collatz n = show n ++ "->" ++ collatz (if odd n then 3 * n + 1 else n `div` 2)
null
https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/6%20kyu/Collatz.hs
haskell
Collatz /
module Collatz where collatz :: Int -> String collatz 1 = "1" collatz n = show n ++ "->" ++ collatz (if odd n then 3 * n + 1 else n `div` 2)
0c56d301233011fcd5d8fe37134132df429a1b48723c418a15cd1d8053cdc7e4
bravit/hid-examples
div.hs
{-# LANGUAGE DeriveAnyClass #-} import Control.Exception (throw, throwIO) import Control.Monad.Catch data MyArithException = DivByZero | OtherArithException deriving (Show, Exception) divPure :: Int -> Int -> Int divPure _ 0 = throw DivByZero divPure a b = a `div` b mult :: Int -> Int -> Int mult 0 _ = 0 mult a b = a * b divIO :: Int -> Int -> IO Int divIO _ 0 = throwIO DivByZero divIO a b = pure (a `div` b) divM :: MonadThrow m => Int -> Int -> m Int divM _ 0 = throwM DivByZero divM a b = pure (a `div` b) testComputation :: MonadThrow m => Int -> Int -> Int -> m Int testComputation a b c = divM a b >>= divM c divTestWithRecovery :: Int -> Int -> Int -> IO Int divTestWithRecovery a b c = try (testComputation a b c) >>= pure . dealWith where dealWith :: Either MyArithException Int -> Int dealWith (Right r) = r dealWith (Left _) = 0 divTestWithRecovery2 :: Int -> Int -> Int -> IO Int divTestWithRecovery2 a b c = tryJust isDivByZero (testComputation a b c) >>= pure . dealWith where isDivByZero :: MyArithException -> Maybe () isDivByZero DivByZero = Just () isDivByZero _ = Nothing dealWith (Right r) = r dealWith (Left _) = 0 divTestIO :: Int -> Int -> Int -> IO Int divTestIO a b c = testComputation a b c `catch` handler where handler :: MyArithException -> IO Int handler e = do putStrLn $ "We've got an exception: " ++ show e ++ "\nUsing default value 0" pure 0 main :: IO () main = do divTestWithRecovery 10 0 2 >>= print divTestWithRecovery2 10 0 2 >>= print divTestIO 10 0 2 >>= print
null
https://raw.githubusercontent.com/bravit/hid-examples/913e116b7ee9c7971bba10fe70ae0b61bfb9391b/ch07/div.hs
haskell
# LANGUAGE DeriveAnyClass #
import Control.Exception (throw, throwIO) import Control.Monad.Catch data MyArithException = DivByZero | OtherArithException deriving (Show, Exception) divPure :: Int -> Int -> Int divPure _ 0 = throw DivByZero divPure a b = a `div` b mult :: Int -> Int -> Int mult 0 _ = 0 mult a b = a * b divIO :: Int -> Int -> IO Int divIO _ 0 = throwIO DivByZero divIO a b = pure (a `div` b) divM :: MonadThrow m => Int -> Int -> m Int divM _ 0 = throwM DivByZero divM a b = pure (a `div` b) testComputation :: MonadThrow m => Int -> Int -> Int -> m Int testComputation a b c = divM a b >>= divM c divTestWithRecovery :: Int -> Int -> Int -> IO Int divTestWithRecovery a b c = try (testComputation a b c) >>= pure . dealWith where dealWith :: Either MyArithException Int -> Int dealWith (Right r) = r dealWith (Left _) = 0 divTestWithRecovery2 :: Int -> Int -> Int -> IO Int divTestWithRecovery2 a b c = tryJust isDivByZero (testComputation a b c) >>= pure . dealWith where isDivByZero :: MyArithException -> Maybe () isDivByZero DivByZero = Just () isDivByZero _ = Nothing dealWith (Right r) = r dealWith (Left _) = 0 divTestIO :: Int -> Int -> Int -> IO Int divTestIO a b c = testComputation a b c `catch` handler where handler :: MyArithException -> IO Int handler e = do putStrLn $ "We've got an exception: " ++ show e ++ "\nUsing default value 0" pure 0 main :: IO () main = do divTestWithRecovery 10 0 2 >>= print divTestWithRecovery2 10 0 2 >>= print divTestIO 10 0 2 >>= print
9de9c8e5080856cca9a6448527e8ef137b43f83196244fcb1d81720ae51bdcb1
tweag/asterius
T12136.hs
# LANGUAGE CPP # #include "MachDeps.h" module Main where import Data.Bits #if WORD_SIZE_IN_BITS != 64 && WORD_SIZE_IN_BITS != 32 # error unsupported WORD_SIZE_IN_BITS config #endif a negative integer the size of negativeBigInteger :: Integer negativeBigInteger = 1 - (1 `shiftL` (64 * 2)) main = do -- rigt shift by GMP_LIMB_BITS print $ negativeBigInteger `shiftR` 64
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/numeric/T12136.hs
haskell
rigt shift by GMP_LIMB_BITS
# LANGUAGE CPP # #include "MachDeps.h" module Main where import Data.Bits #if WORD_SIZE_IN_BITS != 64 && WORD_SIZE_IN_BITS != 32 # error unsupported WORD_SIZE_IN_BITS config #endif a negative integer the size of negativeBigInteger :: Integer negativeBigInteger = 1 - (1 `shiftL` (64 * 2)) main = do print $ negativeBigInteger `shiftR` 64
5748574fe4257a5cab9b2f439e0365e5a27c40fd0381ca57563451962a795d5a
expipiplus1/vulkan
Promoted_From_VK_EXT_tooling_info.hs
{-# language CPP #-} No documentation found for Chapter " Promoted_From_VK_EXT_tooling_info " module Vulkan.Core13.Promoted_From_VK_EXT_tooling_info ( getPhysicalDeviceToolProperties , PhysicalDeviceToolProperties(..) , StructureType(..) , ToolPurposeFlagBits(..) , ToolPurposeFlags ) where import Vulkan.CStruct.Utils (FixedArray) import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Data.ByteString (packCString) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Typeable (Typeable) import Foreign.C.Types (CChar) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.ByteString (ByteString) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.CStruct.Utils (lowerArrayPtr) import Vulkan.CStruct.Utils (pokeFixedLengthNullTerminatedByteString) import Vulkan.NamedType ((:::)) import Vulkan.Dynamic (InstanceCmds(pVkGetPhysicalDeviceToolProperties)) import Vulkan.Core10.APIConstants (MAX_DESCRIPTION_SIZE) import Vulkan.Core10.APIConstants (MAX_EXTENSION_NAME_SIZE) import Vulkan.Core10.Handles (PhysicalDevice) import Vulkan.Core10.Handles (PhysicalDevice(..)) import Vulkan.Core10.Handles (PhysicalDevice(PhysicalDevice)) import Vulkan.Core10.Handles (PhysicalDevice_T) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core13.Enums.ToolPurposeFlagBits (ToolPurposeFlags) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Core10.Enums.StructureType (StructureType(..)) import Vulkan.Core13.Enums.ToolPurposeFlagBits (ToolPurposeFlagBits(..)) import Vulkan.Core13.Enums.ToolPurposeFlagBits (ToolPurposeFlags) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetPhysicalDeviceToolProperties :: FunPtr (Ptr PhysicalDevice_T -> Ptr Word32 -> Ptr PhysicalDeviceToolProperties -> IO Result) -> Ptr PhysicalDevice_T -> Ptr Word32 -> Ptr PhysicalDeviceToolProperties -> IO Result -- | vkGetPhysicalDeviceToolProperties - Reports properties of tools active -- on the specified physical device -- -- = Description -- -- If @pToolProperties@ is @NULL@, then the number of tools currently -- active on @physicalDevice@ is returned in @pToolCount@. Otherwise, -- @pToolCount@ /must/ point to a variable set by the user to the number of -- elements in the @pToolProperties@ array, and on return the variable is -- overwritten with the number of structures actually written to -- @pToolProperties@. If @pToolCount@ is less than the number of currently -- active tools, at most @pToolCount@ structures will be written. -- -- The count and properties of active tools /may/ change in response to -- events outside the scope of the specification. An application /should/ -- assume these properties might change at any given time. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetPhysicalDeviceToolProperties-physicalDevice-parameter# -- @physicalDevice@ /must/ be a valid ' Vulkan . Core10.Handles . PhysicalDevice ' handle -- -- - #VUID-vkGetPhysicalDeviceToolProperties-pToolCount-parameter# @pToolCount@ /must/ be a valid pointer to a @uint32_t@ value -- -- - #VUID-vkGetPhysicalDeviceToolProperties-pToolProperties-parameter# If the value referenced by @pToolCount@ is not @0@ , and -- @pToolProperties@ is not @NULL@, @pToolProperties@ /must/ be a valid -- pointer to an array of @pToolCount@ 'PhysicalDeviceToolProperties' -- structures -- -- == Return Codes -- -- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- - ' Vulkan . Core10.Enums . Result . SUCCESS ' -- - ' Vulkan . Core10.Enums . Result . INCOMPLETE ' -- -- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- - ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY ' -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_EXT_tooling_info VK_EXT_tooling_info>, < , ' Vulkan . Core10.Handles . PhysicalDevice ' , ' PhysicalDeviceToolProperties ' getPhysicalDeviceToolProperties :: forall io . (MonadIO io) => -- | @physicalDevice@ is the handle to the physical device to query for -- active tools. PhysicalDevice -> io (Result, ("toolProperties" ::: Vector PhysicalDeviceToolProperties)) getPhysicalDeviceToolProperties physicalDevice = liftIO . evalContT $ do let vkGetPhysicalDeviceToolPropertiesPtr = pVkGetPhysicalDeviceToolProperties (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) lift $ unless (vkGetPhysicalDeviceToolPropertiesPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetPhysicalDeviceToolProperties is null" Nothing Nothing let vkGetPhysicalDeviceToolProperties' = mkVkGetPhysicalDeviceToolProperties vkGetPhysicalDeviceToolPropertiesPtr let physicalDevice' = physicalDeviceHandle (physicalDevice) pPToolCount <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkGetPhysicalDeviceToolProperties" (vkGetPhysicalDeviceToolProperties' physicalDevice' (pPToolCount) (nullPtr)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pToolCount <- lift $ peek @Word32 pPToolCount pPToolProperties <- ContT $ bracket (callocBytes @PhysicalDeviceToolProperties ((fromIntegral (pToolCount)) * 1048)) free _ <- traverse (\i -> ContT $ pokeZeroCStruct (pPToolProperties `advancePtrBytes` (i * 1048) :: Ptr PhysicalDeviceToolProperties) . ($ ())) [0..(fromIntegral (pToolCount)) - 1] r' <- lift $ traceAroundEvent "vkGetPhysicalDeviceToolProperties" (vkGetPhysicalDeviceToolProperties' physicalDevice' (pPToolCount) ((pPToolProperties))) lift $ when (r' < SUCCESS) (throwIO (VulkanException r')) pToolCount' <- lift $ peek @Word32 pPToolCount pToolProperties' <- lift $ generateM (fromIntegral (pToolCount')) (\i -> peekCStruct @PhysicalDeviceToolProperties (((pPToolProperties) `advancePtrBytes` (1048 * (i)) :: Ptr PhysicalDeviceToolProperties))) pure $ ((r'), pToolProperties') -- | VkPhysicalDeviceToolProperties - Structure providing information about -- an active tool -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_EXT_tooling_info VK_EXT_tooling_info>, < , ' Vulkan . Core10.Enums . StructureType . StructureType ' , ' Vulkan . Core13.Enums . ToolPurposeFlagBits . ToolPurposeFlags ' , -- 'getPhysicalDeviceToolProperties', ' Vulkan . Extensions . VK_EXT_tooling_info.getPhysicalDeviceToolPropertiesEXT ' data PhysicalDeviceToolProperties = PhysicalDeviceToolProperties | @name@ is a null - terminated UTF-8 string containing the name of the -- tool. name :: ByteString | @version@ is a null - terminated UTF-8 string containing the version of -- the tool. version :: ByteString , -- | @purposes@ is a bitmask of ' Vulkan . Core13.Enums . ToolPurposeFlagBits . ToolPurposeFlagBits ' which is -- populated with purposes supported by the tool. purposes :: ToolPurposeFlags | @description@ is a null - terminated UTF-8 string containing a description -- of the tool. description :: ByteString | @layer@ is a null - terminated UTF-8 string containing the name of the -- layer implementing the tool, if the tool is implemented in a layer - -- otherwise it /may/ be an empty string. layer :: ByteString } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceToolProperties) #endif deriving instance Show PhysicalDeviceToolProperties instance ToCStruct PhysicalDeviceToolProperties where withCStruct x f = allocaBytes 1048 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceToolProperties{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 16 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (name) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 272 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (version) poke ((p `plusPtr` 528 :: Ptr ToolPurposeFlags)) (purposes) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 532 :: Ptr (FixedArray MAX_DESCRIPTION_SIZE CChar))) (description) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 788 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (layer) f cStructSize = 1048 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 16 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (mempty) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 272 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (mempty) poke ((p `plusPtr` 528 :: Ptr ToolPurposeFlags)) (zero) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 532 :: Ptr (FixedArray MAX_DESCRIPTION_SIZE CChar))) (mempty) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 788 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (mempty) f instance FromCStruct PhysicalDeviceToolProperties where peekCStruct p = do name <- packCString (lowerArrayPtr ((p `plusPtr` 16 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar)))) version <- packCString (lowerArrayPtr ((p `plusPtr` 272 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar)))) purposes <- peek @ToolPurposeFlags ((p `plusPtr` 528 :: Ptr ToolPurposeFlags)) description <- packCString (lowerArrayPtr ((p `plusPtr` 532 :: Ptr (FixedArray MAX_DESCRIPTION_SIZE CChar)))) layer <- packCString (lowerArrayPtr ((p `plusPtr` 788 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar)))) pure $ PhysicalDeviceToolProperties name version purposes description layer instance Storable PhysicalDeviceToolProperties where sizeOf ~_ = 1048 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceToolProperties where zero = PhysicalDeviceToolProperties mempty mempty zero mempty mempty
null
https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/src/Vulkan/Core13/Promoted_From_VK_EXT_tooling_info.hs
haskell
# language CPP # | vkGetPhysicalDeviceToolProperties - Reports properties of tools active on the specified physical device = Description If @pToolProperties@ is @NULL@, then the number of tools currently active on @physicalDevice@ is returned in @pToolCount@. Otherwise, @pToolCount@ /must/ point to a variable set by the user to the number of elements in the @pToolProperties@ array, and on return the variable is overwritten with the number of structures actually written to @pToolProperties@. If @pToolCount@ is less than the number of currently active tools, at most @pToolCount@ structures will be written. The count and properties of active tools /may/ change in response to events outside the scope of the specification. An application /should/ assume these properties might change at any given time. == Valid Usage (Implicit) - #VUID-vkGetPhysicalDeviceToolProperties-physicalDevice-parameter# @physicalDevice@ /must/ be a valid - #VUID-vkGetPhysicalDeviceToolProperties-pToolCount-parameter# - #VUID-vkGetPhysicalDeviceToolProperties-pToolProperties-parameter# @pToolProperties@ is not @NULL@, @pToolProperties@ /must/ be a valid pointer to an array of @pToolCount@ 'PhysicalDeviceToolProperties' structures == Return Codes [<-extensions/html/vkspec.html#fundamentals-successcodes Success>] [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] = See Also <-extensions/html/vkspec.html#VK_EXT_tooling_info VK_EXT_tooling_info>, | @physicalDevice@ is the handle to the physical device to query for active tools. | VkPhysicalDeviceToolProperties - Structure providing information about an active tool == Valid Usage (Implicit) = See Also <-extensions/html/vkspec.html#VK_EXT_tooling_info VK_EXT_tooling_info>, 'getPhysicalDeviceToolProperties', tool. the tool. | @purposes@ is a bitmask of populated with purposes supported by the tool. of the tool. layer implementing the tool, if the tool is implemented in a layer - otherwise it /may/ be an empty string.
No documentation found for Chapter " Promoted_From_VK_EXT_tooling_info " module Vulkan.Core13.Promoted_From_VK_EXT_tooling_info ( getPhysicalDeviceToolProperties , PhysicalDeviceToolProperties(..) , StructureType(..) , ToolPurposeFlagBits(..) , ToolPurposeFlags ) where import Vulkan.CStruct.Utils (FixedArray) import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Data.ByteString (packCString) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.Typeable (Typeable) import Foreign.C.Types (CChar) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.ByteString (ByteString) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.CStruct.Utils (lowerArrayPtr) import Vulkan.CStruct.Utils (pokeFixedLengthNullTerminatedByteString) import Vulkan.NamedType ((:::)) import Vulkan.Dynamic (InstanceCmds(pVkGetPhysicalDeviceToolProperties)) import Vulkan.Core10.APIConstants (MAX_DESCRIPTION_SIZE) import Vulkan.Core10.APIConstants (MAX_EXTENSION_NAME_SIZE) import Vulkan.Core10.Handles (PhysicalDevice) import Vulkan.Core10.Handles (PhysicalDevice(..)) import Vulkan.Core10.Handles (PhysicalDevice(PhysicalDevice)) import Vulkan.Core10.Handles (PhysicalDevice_T) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core13.Enums.ToolPurposeFlagBits (ToolPurposeFlags) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Core10.Enums.StructureType (StructureType(..)) import Vulkan.Core13.Enums.ToolPurposeFlagBits (ToolPurposeFlagBits(..)) import Vulkan.Core13.Enums.ToolPurposeFlagBits (ToolPurposeFlags) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetPhysicalDeviceToolProperties :: FunPtr (Ptr PhysicalDevice_T -> Ptr Word32 -> Ptr PhysicalDeviceToolProperties -> IO Result) -> Ptr PhysicalDevice_T -> Ptr Word32 -> Ptr PhysicalDeviceToolProperties -> IO Result ' Vulkan . Core10.Handles . PhysicalDevice ' handle @pToolCount@ /must/ be a valid pointer to a @uint32_t@ value If the value referenced by @pToolCount@ is not @0@ , and - ' Vulkan . Core10.Enums . Result . SUCCESS ' - ' Vulkan . Core10.Enums . Result . INCOMPLETE ' - ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY ' < , ' Vulkan . Core10.Handles . PhysicalDevice ' , ' PhysicalDeviceToolProperties ' getPhysicalDeviceToolProperties :: forall io . (MonadIO io) PhysicalDevice -> io (Result, ("toolProperties" ::: Vector PhysicalDeviceToolProperties)) getPhysicalDeviceToolProperties physicalDevice = liftIO . evalContT $ do let vkGetPhysicalDeviceToolPropertiesPtr = pVkGetPhysicalDeviceToolProperties (case physicalDevice of PhysicalDevice{instanceCmds} -> instanceCmds) lift $ unless (vkGetPhysicalDeviceToolPropertiesPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetPhysicalDeviceToolProperties is null" Nothing Nothing let vkGetPhysicalDeviceToolProperties' = mkVkGetPhysicalDeviceToolProperties vkGetPhysicalDeviceToolPropertiesPtr let physicalDevice' = physicalDeviceHandle (physicalDevice) pPToolCount <- ContT $ bracket (callocBytes @Word32 4) free r <- lift $ traceAroundEvent "vkGetPhysicalDeviceToolProperties" (vkGetPhysicalDeviceToolProperties' physicalDevice' (pPToolCount) (nullPtr)) lift $ when (r < SUCCESS) (throwIO (VulkanException r)) pToolCount <- lift $ peek @Word32 pPToolCount pPToolProperties <- ContT $ bracket (callocBytes @PhysicalDeviceToolProperties ((fromIntegral (pToolCount)) * 1048)) free _ <- traverse (\i -> ContT $ pokeZeroCStruct (pPToolProperties `advancePtrBytes` (i * 1048) :: Ptr PhysicalDeviceToolProperties) . ($ ())) [0..(fromIntegral (pToolCount)) - 1] r' <- lift $ traceAroundEvent "vkGetPhysicalDeviceToolProperties" (vkGetPhysicalDeviceToolProperties' physicalDevice' (pPToolCount) ((pPToolProperties))) lift $ when (r' < SUCCESS) (throwIO (VulkanException r')) pToolCount' <- lift $ peek @Word32 pPToolCount pToolProperties' <- lift $ generateM (fromIntegral (pToolCount')) (\i -> peekCStruct @PhysicalDeviceToolProperties (((pPToolProperties) `advancePtrBytes` (1048 * (i)) :: Ptr PhysicalDeviceToolProperties))) pure $ ((r'), pToolProperties') < , ' Vulkan . Core10.Enums . StructureType . StructureType ' , ' Vulkan . Core13.Enums . ToolPurposeFlagBits . ToolPurposeFlags ' , ' Vulkan . Extensions . VK_EXT_tooling_info.getPhysicalDeviceToolPropertiesEXT ' data PhysicalDeviceToolProperties = PhysicalDeviceToolProperties | @name@ is a null - terminated UTF-8 string containing the name of the name :: ByteString | @version@ is a null - terminated UTF-8 string containing the version of version :: ByteString ' Vulkan . Core13.Enums . ToolPurposeFlagBits . ToolPurposeFlagBits ' which is purposes :: ToolPurposeFlags | @description@ is a null - terminated UTF-8 string containing a description description :: ByteString | @layer@ is a null - terminated UTF-8 string containing the name of the layer :: ByteString } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceToolProperties) #endif deriving instance Show PhysicalDeviceToolProperties instance ToCStruct PhysicalDeviceToolProperties where withCStruct x f = allocaBytes 1048 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceToolProperties{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 16 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (name) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 272 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (version) poke ((p `plusPtr` 528 :: Ptr ToolPurposeFlags)) (purposes) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 532 :: Ptr (FixedArray MAX_DESCRIPTION_SIZE CChar))) (description) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 788 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (layer) f cStructSize = 1048 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 16 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (mempty) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 272 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (mempty) poke ((p `plusPtr` 528 :: Ptr ToolPurposeFlags)) (zero) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 532 :: Ptr (FixedArray MAX_DESCRIPTION_SIZE CChar))) (mempty) pokeFixedLengthNullTerminatedByteString ((p `plusPtr` 788 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar))) (mempty) f instance FromCStruct PhysicalDeviceToolProperties where peekCStruct p = do name <- packCString (lowerArrayPtr ((p `plusPtr` 16 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar)))) version <- packCString (lowerArrayPtr ((p `plusPtr` 272 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar)))) purposes <- peek @ToolPurposeFlags ((p `plusPtr` 528 :: Ptr ToolPurposeFlags)) description <- packCString (lowerArrayPtr ((p `plusPtr` 532 :: Ptr (FixedArray MAX_DESCRIPTION_SIZE CChar)))) layer <- packCString (lowerArrayPtr ((p `plusPtr` 788 :: Ptr (FixedArray MAX_EXTENSION_NAME_SIZE CChar)))) pure $ PhysicalDeviceToolProperties name version purposes description layer instance Storable PhysicalDeviceToolProperties where sizeOf ~_ = 1048 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceToolProperties where zero = PhysicalDeviceToolProperties mempty mempty zero mempty mempty
3b9141f2320901fdfd709415f4774753ebd534f69e9cf2e396289238ae70d37f
inconvergent/weir
rel-neigh.lisp
#!/usr/local/bin/sbcl --script ; set your path to sbcl above. i would use env, but it does not appear to work ; with the --script argument. alternately, delete the shebang and the load ; below. and run from repl. let me know if you have a better suggestion for ; making this easily runnable from terminal (load "load") (defun -dot-split (wer e xp plane-point plane-vec g) (weir:ldel-edge! wer e :g g) (destructuring-bind (a b) e (if (> (vec:3dot plane-vec (vec:3sub (weir:3get-vert wer a) plane-point)) 0d0) (progn (weir:add-edge! wer (weir:3add-vert! wer xp) b :g g) (weir:add-edge! wer (weir:3add-vert! wer xp) a :g g)) (progn (weir:add-edge! wer (weir:3add-vert! wer xp) a :g g) (weir:add-edge! wer (weir:3add-vert! wer xp) b :g g))))) (defun plane-intersect (wer &key plane-point plane-vec (a 0d0) (dst 0d0) dot-split g) (let* ((rv (hset:make)) (do-split (if dot-split (lambda (e xp) (-dot-split wer e xp plane-point plane-vec g)) (lambda (e xp) (list (weir:3lsplit-edge! wer e :xy xp)))))) (weir:itr-grp-verts (wer v :g g) (when (> (vec:3dot plane-vec (vec:3sub (weir:3get-vert wer v) plane-point)) 0d0) (hset:add rv v))) (weir:itr-edges (wer e :g g) (multiple-value-bind (x d xp) (vec:3planex plane-vec plane-point (weir:3get-verts wer e)) (when (and x (< 0d0 d 1d0)) (hset:add* rv (funcall do-split e xp))))) (weir:3transform! wer (hset:to-list rv) (lambda (vv) (vec:3ladd* (vec:3lrot* vv plane-vec a :xy plane-point) (vec:3smult plane-vec dst)))))) (defun get-width (d) (* 4d0 (expt (- 1d0 (max 0d0 (min (/ d 1500d0) 1d0))) 2d0))) (defun dst-draw (wer proj psvg) (loop with lr = (line-remove:make :cnt 8 :rs 2d0 :is 1.5d0) for e in (weir:get-edges wer) do (let* ((point-dst (ortho:project* proj (weir:3get-verts wer e))) (dsts (math:lpos point-dst :fx #'second))) (loop for path across (line-remove:path-split lr (list (cpath:cpath (weir-utils:to-vector (math:lpos point-dst)) (loop for d in dsts collect (get-width d)) (ceiling (* 2.2d0 (get-width (apply #'max dsts))))))) do (draw-svg:path psvg path :sw 0.8d0 :so 0.9d0 :stroke "black"))) finally (print (line-remove:stats lr)))) (defun init-cube (n m s) (let* ((dots (weir-utils:to-vector (rnd:3nin-cube m s))) (dt (kdtree:make (weir-utils:to-list dots))) (res (weir-utils:make-adjustable-vector))) (loop for rad in (rnd:nrnd 3 500d0) for mid in (math:nrep 3 (rnd:3on-sphere :rad 300d0)) do (loop for p in (math:nrep n (rnd:3on-sphere :rad rad :xy mid)) if (> (vec:3dst p (aref dots (kdtree:nn dt p ))) 90d0) do (weir-utils:vextend p res))) (weir-utils:to-list res))) (defun main (size fn) (let* ((psvg (draw-svg:make*)) (wer (weir:make :dim 3 :max-verts 200000)) (mid (vec:rep 500d0)) (st (state:make)) (proj (ortho:make :s 0.5d0 :xy mid :cam (rnd:3on-sphere :rad 1000d0) :look vec:*3zero*))) (loop repeat 2 do (plane-intersect wer :plane-point (rnd:3in-cube 500d0) :plane-vec (rnd:3on-sphere) :a (rnd:rnd 0.5d0) :dst 100d0 :dot-split t)) (weir:3add-verts! wer (init-cube 7000 800 500d0)) (weir:3relative-neighborhood! wer 500d0) (loop repeat 2 do (plane-intersect wer :plane-point (rnd:3in-cube 300d0) :plane-vec (rnd:3on-sphere) :a (rnd:rnd 0.3d0) :dst 250d0 :dot-split t)) (dst-draw wer proj psvg) (draw-svg:save psvg fn))) (time (main 1000 (second (weir-utils:cmd-args))))
null
https://raw.githubusercontent.com/inconvergent/weir/3c364e3a0e15526f0d6985f08a57b312b5c35f7d/examples/rel-neigh.lisp
lisp
set your path to sbcl above. i would use env, but it does not appear to work with the --script argument. alternately, delete the shebang and the load below. and run from repl. let me know if you have a better suggestion for making this easily runnable from terminal
#!/usr/local/bin/sbcl --script (load "load") (defun -dot-split (wer e xp plane-point plane-vec g) (weir:ldel-edge! wer e :g g) (destructuring-bind (a b) e (if (> (vec:3dot plane-vec (vec:3sub (weir:3get-vert wer a) plane-point)) 0d0) (progn (weir:add-edge! wer (weir:3add-vert! wer xp) b :g g) (weir:add-edge! wer (weir:3add-vert! wer xp) a :g g)) (progn (weir:add-edge! wer (weir:3add-vert! wer xp) a :g g) (weir:add-edge! wer (weir:3add-vert! wer xp) b :g g))))) (defun plane-intersect (wer &key plane-point plane-vec (a 0d0) (dst 0d0) dot-split g) (let* ((rv (hset:make)) (do-split (if dot-split (lambda (e xp) (-dot-split wer e xp plane-point plane-vec g)) (lambda (e xp) (list (weir:3lsplit-edge! wer e :xy xp)))))) (weir:itr-grp-verts (wer v :g g) (when (> (vec:3dot plane-vec (vec:3sub (weir:3get-vert wer v) plane-point)) 0d0) (hset:add rv v))) (weir:itr-edges (wer e :g g) (multiple-value-bind (x d xp) (vec:3planex plane-vec plane-point (weir:3get-verts wer e)) (when (and x (< 0d0 d 1d0)) (hset:add* rv (funcall do-split e xp))))) (weir:3transform! wer (hset:to-list rv) (lambda (vv) (vec:3ladd* (vec:3lrot* vv plane-vec a :xy plane-point) (vec:3smult plane-vec dst)))))) (defun get-width (d) (* 4d0 (expt (- 1d0 (max 0d0 (min (/ d 1500d0) 1d0))) 2d0))) (defun dst-draw (wer proj psvg) (loop with lr = (line-remove:make :cnt 8 :rs 2d0 :is 1.5d0) for e in (weir:get-edges wer) do (let* ((point-dst (ortho:project* proj (weir:3get-verts wer e))) (dsts (math:lpos point-dst :fx #'second))) (loop for path across (line-remove:path-split lr (list (cpath:cpath (weir-utils:to-vector (math:lpos point-dst)) (loop for d in dsts collect (get-width d)) (ceiling (* 2.2d0 (get-width (apply #'max dsts))))))) do (draw-svg:path psvg path :sw 0.8d0 :so 0.9d0 :stroke "black"))) finally (print (line-remove:stats lr)))) (defun init-cube (n m s) (let* ((dots (weir-utils:to-vector (rnd:3nin-cube m s))) (dt (kdtree:make (weir-utils:to-list dots))) (res (weir-utils:make-adjustable-vector))) (loop for rad in (rnd:nrnd 3 500d0) for mid in (math:nrep 3 (rnd:3on-sphere :rad 300d0)) do (loop for p in (math:nrep n (rnd:3on-sphere :rad rad :xy mid)) if (> (vec:3dst p (aref dots (kdtree:nn dt p ))) 90d0) do (weir-utils:vextend p res))) (weir-utils:to-list res))) (defun main (size fn) (let* ((psvg (draw-svg:make*)) (wer (weir:make :dim 3 :max-verts 200000)) (mid (vec:rep 500d0)) (st (state:make)) (proj (ortho:make :s 0.5d0 :xy mid :cam (rnd:3on-sphere :rad 1000d0) :look vec:*3zero*))) (loop repeat 2 do (plane-intersect wer :plane-point (rnd:3in-cube 500d0) :plane-vec (rnd:3on-sphere) :a (rnd:rnd 0.5d0) :dst 100d0 :dot-split t)) (weir:3add-verts! wer (init-cube 7000 800 500d0)) (weir:3relative-neighborhood! wer 500d0) (loop repeat 2 do (plane-intersect wer :plane-point (rnd:3in-cube 300d0) :plane-vec (rnd:3on-sphere) :a (rnd:rnd 0.3d0) :dst 250d0 :dot-split t)) (dst-draw wer proj psvg) (draw-svg:save psvg fn))) (time (main 1000 (second (weir-utils:cmd-args))))
8b5c23060792caae6034979666b331dafa2ec92a594065e891f7a1f9b540a696
gilith/hol-light
natural-fibonacci.ml
(* ========================================================================= *) (* FIBONACCI NUMBERS *) (* *) (* See *) (* ========================================================================= *) (* ------------------------------------------------------------------------- *) (* Theory requirements. *) (* ------------------------------------------------------------------------- *) import_theories ["base"; "stream"; "probability"];; (* ------------------------------------------------------------------------- *) (* Theory interpretation. *) (* ------------------------------------------------------------------------- *) export_interpretation "opentheory/theories/natural-fibonacci/natural-fibonacci.int";; (* ------------------------------------------------------------------------- *) (* Existence of Fibonacci numbers. *) (* ------------------------------------------------------------------------- *) export_theory "natural-fibonacci-exists";; let fibonacci_induction = prove (`!p : num -> bool. p 0 /\ p 1 /\ (!n. p n /\ p (n + 1) ==> p (n + 2)) ==> !n. p n`, REWRITE_TAC [ONE; TWO; ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN WF_INDUCT_TAC `n : num` THEN MP_TAC (SPEC `n : num` num_CASES) THEN STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN ASM_REWRITE_TAC [] THEN MP_TAC (SPEC `n' : num` num_CASES) THEN STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN ASM_REWRITE_TAC [] THEN UNDISCH_THEN `!n. p n /\ p (SUC n) ==> p (SUC (SUC n))` MATCH_MP_TAC THEN CONJ_TAC THENL [FIRST_X_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC LT_TRANS THEN EXISTS_TAC `SUC n''` THEN CONJ_TAC THEN MATCH_ACCEPT_TAC SUC_LT; FIRST_X_ASSUM MATCH_MP_TAC THEN MATCH_ACCEPT_TAC SUC_LT]);; export_thm fibonacci_induction;; let fibonacci_recursion = prove (`!(h : (num -> A) -> num -> A). (!f g n. (!m. m + 1 = n \/ m + 2 = n ==> (f m = g m)) ==> (h f n = h g n)) ==> ?f. !n. f n = h f n`, SUBGOAL_THEN `!(h : (num -> A) -> num -> A). (!f g n. (!m. (\x y. x + 1 = y \/ x + 2 = y) m n ==> (f m = g m)) ==> (h f n = h g n)) ==> ?f. !n. f n = h f n` (ACCEPT_TAC o REWRITE_RULE []) THEN MATCH_MP_TAC WF_REC THEN MATCH_MP_TAC WF_SUBSET THEN EXISTS_TAC `(<) : num -> num -> bool` THEN CONJ_TAC THENL [REWRITE_TAC [GSYM LE_SUC_LT; ADD1] THEN REPEAT STRIP_TAC THENL [FIRST_X_ASSUM SUBST_VAR_TAC THEN MATCH_ACCEPT_TAC LE_REFL; FIRST_X_ASSUM SUBST_VAR_TAC THEN REWRITE_TAC [LE_ADD_LCANCEL; TWO; SUC_LE]]; ACCEPT_TAC WF_num]);; export_thm fibonacci_recursion;; let fibonacci_exists = prove (`?f. f 0 = 0 /\ f 1 = 1 /\ !n. f (n + 2) = f (n + 1) + f n`, SUBGOAL_THEN `?f. !n. f n = (\f' n'. if n' < 2 then n' else f' (n' - 1) + f' (n' - 2)) f n` MP_TAC THENL [MATCH_MP_TAC fibonacci_recursion THEN GEN_TAC THEN GEN_TAC THEN REWRITE_TAC [] THEN MATCH_MP_TAC fibonacci_induction THEN REPEAT STRIP_TAC THENL [NUM_REDUCE_TAC; NUM_REDUCE_TAC; BOOL_CASES_TAC `n + 2 < 2` THENL [REWRITE_TAC []; REWRITE_TAC [ADD_SUB] THEN SUBGOAL_THEN `(f : num -> num) n = g n` SUBST1_TAC THENL [FIRST_X_ASSUM MATCH_MP_TAC THEN DISJ2_TAC THEN REFL_TAC; REWRITE_TAC [EQ_ADD_RCANCEL] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN DISJ1_TAC THEN MATCH_MP_TAC SUB_ADD THEN REWRITE_TAC [TWO; ONE; LE_SUC; ADD_CLAUSES; LE_0]]]]; REWRITE_TAC [] THEN STRIP_TAC THEN EXISTS_TAC `f : num -> num` THEN REPEAT STRIP_TAC THENL [FIRST_X_ASSUM (fun th -> ONCE_REWRITE_TAC [th]) THEN NUM_REDUCE_TAC; FIRST_X_ASSUM (fun th -> ONCE_REWRITE_TAC [th]) THEN NUM_REDUCE_TAC; FIRST_X_ASSUM (fun th -> CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [th]))) THEN SUBGOAL_THEN `n + 2 < 2 <=> F` SUBST1_TAC THENL [REWRITE_TAC [NOT_LT; LE_ADDR]; REWRITE_TAC [ADD_SUB; EQ_ADD_RCANCEL] THEN REWRITE_TAC [TWO; ADD_CLAUSES] THEN REWRITE_TAC [ADD_SUB; ADD1]]]]);; export_thm fibonacci_exists;; (* ------------------------------------------------------------------------- *) (* Definition of Fibonacci numbers. *) (* ------------------------------------------------------------------------- *) export_theory "natural-fibonacci-def";; let (fibonacci_zero,fibonacci_one,fibonacci_add2) = let def = new_specification ["fibonacci"] fibonacci_exists in let fib1 = CONJUNCT1 def in let def = CONJUNCT2 def in let fib2 = CONJUNCT1 def in let def = CONJUNCT2 def in (fib1,fib2,def);; export_thm fibonacci_zero;; export_thm fibonacci_one;; export_thm fibonacci_add2;; let fibonacci_def = CONJ fibonacci_zero (CONJ fibonacci_one fibonacci_add2);; let fibonaccis_def = new_definition `fibonaccis = stream fibonacci`;; export_thm fibonaccis_def;; let (decode_fib_dest_nil,decode_fib_dest_cons) = let def = new_recursive_definition list_RECURSION `(!f p. decode_fib_dest f p [] = 0) /\ (!f p h t. decode_fib_dest f p (CONS h t) = let s = f + p in let n = decode_fib_dest s f t in if h then s + n else n)` in CONJ_PAIR def;; export_thm decode_fib_dest_nil;; export_thm decode_fib_dest_cons;; let decode_fib_dest_def = CONJ decode_fib_dest_nil decode_fib_dest_cons;; let decode_fib_def = new_definition `!l. decode_fib l = decode_fib_dest 1 0 l`;; export_thm decode_fib_def;; let encode_fib_mk_exists = prove (`?mk. !l n f p. mk l n f p = if p = 0 then l else if f <= n then mk (CONS T l) (n - f) p (f - p) else mk (CONS F l) n p (f - p)`, MP_TAC (ISPECL [`\ ((l : bool list), (n : num), (f : num), (p : num)). ~(p = 0)`; `\ ((l : bool list), (n : num), (f : num), (p : num)). if f <= n then (CONS T l, n - f, p, f - p) else (CONS F l, n, p, f - p)`; `\ ((l : bool list), (n : num), (f : num), (p : num)). l`] WF_REC_TAIL) THEN DISCH_THEN (X_CHOOSE_THEN `mk : bool list # num # num # num -> bool list` STRIP_ASSUME_TAC) THEN EXISTS_TAC `\ (l : bool list) (n : num) (f : num) (p : num). (mk (l,n,f,p) : bool list)` THEN REPEAT GEN_TAC THEN REWRITE_TAC [] THEN FIRST_X_ASSUM (fun th -> CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [th]))) THEN REWRITE_TAC [] THEN BOOL_CASES_TAC `p = 0` THENL [REWRITE_TAC []; REWRITE_TAC [] THEN MATCH_ACCEPT_TAC COND_RAND]);; let encode_fib_mk_def = new_specification ["encode_fib_mk"] encode_fib_mk_exists;; export_thm encode_fib_mk_def;; let encode_fib_find_exists = prove (`!n. ?find. !f p. find f p = let s = f + p in if n < s then encode_fib_mk [] n f p else find s f`, GEN_TAC THEN MP_TAC (ISPECL [`\ ((f : num), (p : num)). ~(n < f + p)`; `\ ((f : num), (p : num)). (f + p, f)`; `\ ((f : num), (p : num)). encode_fib_mk [] n f p`] WF_REC_TAIL) THEN DISCH_THEN (X_CHOOSE_THEN `find : num # num -> bool list` STRIP_ASSUME_TAC) THEN EXISTS_TAC `\ (f : num) (p : num). (find (f,p) : bool list)` THEN REPEAT GEN_TAC THEN REWRITE_TAC [] THEN FIRST_X_ASSUM (fun th -> CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [th]))) THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN BOOL_CASES_TAC `n < f + (p : num)` THENL [REWRITE_TAC []; REWRITE_TAC []]);; let encode_fib_find_def = new_specification ["encode_fib_find"] (REWRITE_RULE [SKOLEM_THM] encode_fib_find_exists);; export_thm encode_fib_find_def;; let encode_fib_def = new_definition `!n. encode_fib n = encode_fib_find n 1 0`;; export_thm encode_fib_def;; let (zeckendorf_nil,zeckendorf_cons) = let def = new_recursive_definition list_RECURSION `(zeckendorf [] <=> T) /\ (!h t. zeckendorf (CONS h t) <=> if NULL t then h else ~(h /\ HD t) /\ zeckendorf t)` in CONJ_PAIR (REWRITE_RULE [] def);; export_thm zeckendorf_nil;; export_thm zeckendorf_cons;; let zeckendorf_def = CONJ zeckendorf_nil zeckendorf_cons;; let random_fib_dest_exists = prove (`?dest. !b (n : num) f p r. dest b n f p r = let (r1,r2) = split_random r in let b' = random_bit r1 in if b' /\ b then n else let s = f + p in dest b' (if b' then s + n else n) s f r2`, MP_TAC (ISPECL [`\ ((b : bool), (n : num), (f : num), (p : num), (r : random)). let (r1,r2) = split_random r in let b' = random_bit r1 in ~(b' /\ b)`; `\ ((b : bool), (n : num), (f : num), (p : num), (r : random)). let (r1,r2) = split_random r in let b' = random_bit r1 in let s = f + p in (b', (if b' then s + n else n), s, f, r2)`; `\ ((b : bool), (n : num), (f : num), (p : num), (r : random)). n`] WF_REC_TAIL) THEN DISCH_THEN (X_CHOOSE_THEN `dest : bool # num # num # num # random -> num` STRIP_ASSUME_TAC) THEN EXISTS_TAC `\ (b : bool) (n : num) (f : num) (p : num) (r : random). ((dest (b,n,f,p,r)) : num)` THEN REPEAT GEN_TAC THEN REWRITE_TAC [] THEN FIRST_X_ASSUM (fun th -> CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [th]))) THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN PAIR_CASES_TAC `split_random r` THEN DISCH_THEN (X_CHOOSE_THEN `r1 : random` (X_CHOOSE_THEN `r2 : random` SUBST1_TAC)) THEN REWRITE_TAC [] THEN BOOL_CASES_TAC `random_bit r1 /\ b` THENL [REWRITE_TAC []; REWRITE_TAC []]);; let random_fib_dest_def = new_specification ["random_fib_dest"] random_fib_dest_exists;; export_thm random_fib_dest_def;; let random_fib_def = new_definition `!r. random_fib r = random_fib_dest F 0 1 0 r - 1`;; export_thm random_fib_def;; let random_fib_list_def = new_definition `!f r. random_fib_list (f : random -> A) r = let (r1,r2) = split_random r in random_vector f (random_fib r1) r2`;; export_thm random_fib_list_def;; (* ------------------------------------------------------------------------- *) (* Properties of Fibonacci numbers. *) (* ------------------------------------------------------------------------- *) export_theory "natural-fibonacci-thm";; export_thm fibonacci_induction;; (* Re-export *) export_thm fibonacci_recursion;; (* Re-export *) let fibonacci_suc_suc = prove (`!k. fibonacci (SUC (SUC k)) = fibonacci (SUC k) + fibonacci k`, GEN_TAC THEN SUBGOAL_THEN `SUC (SUC k) = k + 2` SUBST1_TAC THENL [REWRITE_TAC [TWO; ONE; ADD_CLAUSES]; REWRITE_TAC [fibonacci_def; EQ_ADD_RCANCEL; ADD1]]);; export_thm fibonacci_suc_suc;; let fibonacci_two = prove (`fibonacci 2 = 1`, REWRITE_TAC [TWO; ONE; fibonacci_suc_suc; fibonacci_zero; ADD_CLAUSES] THEN REWRITE_TAC [fibonacci_one; GSYM ONE]);; export_thm fibonacci_two;; let fibonacci_eq_zero = prove (`!k. fibonacci k = 0 <=> k = 0`, MATCH_MP_TAC fibonacci_induction THEN REWRITE_TAC [fibonacci_def] THEN REPEAT STRIP_TAC THEN ASM_REWRITE_TAC [ADD_EQ_0] THEN NUM_REDUCE_TAC);; export_thm fibonacci_eq_zero;; let fibonacci_mono_imp = prove (`!j k. j <= k ==> fibonacci j <= fibonacci k`, MATCH_MP_TAC fibonacci_induction THEN REWRITE_TAC [fibonacci_def; LE_0] THEN STRIP_TAC THENL [GEN_TAC THEN REWRITE_TAC [LT_NZ; ONE; LE_SUC_LT; fibonacci_eq_zero]; ALL_TAC] THEN REPEAT STRIP_TAC THEN SUBGOAL_THEN `j + 2 <= j + k` (MP_TAC o ONCE_REWRITE_RULE [ADD_SYM] o REWRITE_RULE [LE_EXISTS] o REWRITE_RULE [LE_ADD_LCANCEL]) THENL [MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `k : num` THEN ASM_REWRITE_TAC [LE_ADDR]; ALL_TAC] THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [LE_ADD_RCANCEL] THEN STRIP_TAC THEN REWRITE_TAC [fibonacci_def] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `fibonacci (j + 1) + fibonacci d` THEN REWRITE_TAC [LE_ADD_LCANCEL; LE_ADD_RCANCEL] THEN STRIP_TAC THENL [FIRST_X_ASSUM MATCH_MP_TAC THEN FIRST_ASSUM ACCEPT_TAC; FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC [LE_ADD_RCANCEL]]);; export_thm fibonacci_mono_imp;; let fibonacci_strictly_mono_suc = prove (`!j. ~(j = 1) ==> fibonacci j < fibonacci (SUC j)`, REPEAT STRIP_TAC THEN MP_TAC (SPEC `j : num` num_CASES) THEN STRIP_TAC THENL [ASM_REWRITE_TAC [LT_NZ; fibonacci_def; fibonacci_eq_zero; NOT_SUC]; FIRST_X_ASSUM SUBST_VAR_TAC THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [fibonacci_suc_suc; LT_ADD; LT_NZ; fibonacci_eq_zero; ONE; SUC_INJ]]);; export_thm fibonacci_strictly_mono_suc;; let fibonacci_strictly_mono_imp = prove (`!j k. ~(j = 1 /\ k = 2) /\ j < k ==> fibonacci j < fibonacci k`, REPEAT STRIP_TAC THEN POP_ASSUM (MP_TAC o REWRITE_RULE [LT_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [ADD_CLAUSES; TWO; SUC_INJ; DE_MORGAN_THM] THEN STRIP_TAC THENL [MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (SUC j)` THEN CONJ_TAC THENL [MATCH_MP_TAC fibonacci_strictly_mono_suc THEN FIRST_ASSUM ACCEPT_TAC; MATCH_MP_TAC fibonacci_mono_imp THEN REWRITE_TAC [LE_SUC; LE_ADD]]; MATCH_MP_TAC LET_TRANS THEN EXISTS_TAC `fibonacci (j + d)` THEN CONJ_TAC THENL [MATCH_MP_TAC fibonacci_mono_imp THEN MATCH_ACCEPT_TAC LE_ADD; MATCH_MP_TAC fibonacci_strictly_mono_suc THEN FIRST_ASSUM ACCEPT_TAC]]);; export_thm fibonacci_strictly_mono_imp;; let fibonacci_mono_imp' = prove (`!j k. ~(j = 2 /\ k = 1) /\ fibonacci j <= fibonacci k ==> j <= k`, REPEAT STRIP_TAC THEN POP_ASSUM MP_TAC THEN ONCE_REWRITE_TAC [GSYM CONTRAPOS_THM] THEN REWRITE_TAC [NOT_LE] THEN STRIP_TAC THEN MATCH_MP_TAC fibonacci_strictly_mono_imp THEN ASM_REWRITE_TAC [] THEN ONCE_REWRITE_TAC [CONJ_SYM] THEN FIRST_ASSUM ACCEPT_TAC);; export_thm fibonacci_mono_imp';; let fibonacci_strictly_mono_imp' = prove (`!j k. fibonacci j < fibonacci k ==> j < k`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [GSYM CONTRAPOS_THM] THEN REWRITE_TAC [NOT_LT] THEN MATCH_ACCEPT_TAC fibonacci_mono_imp);; export_thm fibonacci_strictly_mono_imp';; let large_fibonacci = prove (`!n. ?k. n <= fibonacci k`, INDUCT_TAC THENL [REWRITE_TAC [LE_0]; POP_ASSUM STRIP_ASSUME_TAC THEN EXISTS_TAC `SUC (SUC k)` THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `SUC (fibonacci k)` THEN CONJ_TAC THENL [ASM_REWRITE_TAC [LE_SUC]; REWRITE_TAC [LE_SUC_LT; fibonacci_suc_suc; LT_ADDR; LT_NZ; fibonacci_eq_zero; NOT_SUC]]]);; export_thm large_fibonacci;; let fibonacci_interval = prove (`!n. ?k. fibonacci k <= n /\ n < fibonacci (k + 1)`, GEN_TAC THEN MP_TAC ((REWRITE_RULE [MINIMAL] o REWRITE_RULE [LE_SUC_LT] o SPEC `SUC n`) large_fibonacci) THEN MP_TAC (SPEC `minimal k. n < fibonacci k` num_CASES) THEN STRIP_TAC THENL [ASM_REWRITE_TAC [fibonacci_zero; LT]; POP_ASSUM SUBST1_TAC THEN REWRITE_TAC [NOT_LT; LT_SUC_LE] THEN STRIP_TAC THEN EXISTS_TAC `n' : num` THEN ASM_REWRITE_TAC [GSYM ADD1] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN MATCH_ACCEPT_TAC LE_REFL]);; export_thm fibonacci_interval;; let fibonacci_vorobev = prove (`!j k. fibonacci (j + k + 1) = fibonacci j * fibonacci k + fibonacci (j + 1) * fibonacci (k + 1)`, INDUCT_TAC THENL [REWRITE_TAC [ADD_CLAUSES; fibonacci_def; MULT_CLAUSES]; ALL_TAC] THEN GEN_TAC THEN REWRITE_TAC [ONE; ADD_CLAUSES] THEN CONV_TAC (RAND_CONV (REWRITE_CONV [fibonacci_suc_suc])) THEN REWRITE_TAC [ADD_ASSOC; RIGHT_ADD_DISTRIB] THEN REWRITE_TAC [GSYM LEFT_ADD_DISTRIB] THEN CONV_TAC (RAND_CONV (ONCE_REWRITE_CONV [ADD_SYM])) THEN CONV_TAC (RAND_CONV (RAND_CONV (ONCE_REWRITE_CONV [ADD_SYM]))) THEN REWRITE_TAC [GSYM fibonacci_suc_suc] THEN ONCE_REWRITE_TAC [GSYM ADD_SUC] THEN REWRITE_TAC [ADD1] THEN CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [GSYM ADD_ASSOC])) THEN FIRST_ASSUM MATCH_ACCEPT_TAC);; export_thm fibonacci_vorobev;; let snth_fibonaccis = prove (`!n. snth fibonaccis n = fibonacci n`, REWRITE_TAC [fibonaccis_def; stream_snth]);; export_thm snth_fibonaccis;; let fibonaccis_sunfold = prove (`fibonaccis = sunfold (\ (p,f). (p, f, p + f)) (0,1)`, MATCH_MP_TAC snth_eq_imp THEN REWRITE_TAC [fibonaccis_def; stream_snth] THEN MATCH_MP_TAC fibonacci_induction THEN CONJ_TAC THENL [REWRITE_TAC [GSYM shd_def; shd_sunfold; fibonacci_zero]; ALL_TAC] THEN CONJ_TAC THENL [REWRITE_TAC [snth_one; stl_sunfold; shd_sunfold; fibonacci_one]; ALL_TAC] THEN X_GEN_TAC `n : num` THEN CONV_TAC (LAND_CONV (LAND_CONV (RAND_CONV (RAND_CONV (REWR_CONV (GSYM ADD_0)))))) THEN REWRITE_TAC [snth_sunfold_add] THEN SPEC_TAC (`funpow (SND o (\(p,f). p,f,p + f)) n (0,1)`, `x : num # num`) THEN REWRITE_TAC [FORALL_PAIR_THM] THEN X_GEN_TAC `p : num` THEN X_GEN_TAC `f : num` THEN REWRITE_TAC [fibonacci_add2] THEN REWRITE_TAC [GSYM shd_def; snth_one; TWO; snth_suc; shd_sunfold; stl_sunfold] THEN STRIP_TAC THEN ASM_REWRITE_TAC [] THEN MATCH_ACCEPT_TAC ADD_SYM);; export_thm fibonaccis_sunfold;; let fibonaccis_vorobev = prove (`!j k. snth fibonaccis (j + k + 1) = snth fibonaccis j * snth fibonaccis k + snth fibonaccis (j + 1) * snth fibonaccis (k + 1)`, REWRITE_TAC [snth_fibonaccis; fibonacci_vorobev]);; export_thm fibonaccis_vorobev;; let decode_fib_nil = prove (`decode_fib [] = 0`, REWRITE_TAC [decode_fib_def; decode_fib_dest_def]);; export_thm decode_fib_nil;; let encode_fib_zero = prove (`encode_fib 0 = []`, REWRITE_TAC [encode_fib_def] THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [LET_DEF; LET_END_DEF; ADD_CLAUSES; LT_NZ; ONE; NOT_SUC] THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN REWRITE_TAC []);; export_thm encode_fib_zero;; let decode_fib_dest_append = prove (`!k l1 l2. decode_fib_dest (fibonacci (k + 1)) (fibonacci k) (APPEND l1 l2) = decode_fib_dest (fibonacci (k + 1)) (fibonacci k) l1 + decode_fib_dest (fibonacci (LENGTH l1 + (k + 1))) (fibonacci (LENGTH l1 + k)) l2`, REPEAT GEN_TAC THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`l1 : bool list`, `l1 : bool list`) THEN LIST_INDUCT_TAC THENL [REWRITE_TAC [APPEND; decode_fib_dest_def; LENGTH; ADD_CLAUSES; fibonacci_def]; ALL_TAC] THEN REPEAT GEN_TAC THEN REWRITE_TAC [APPEND; decode_fib_dest_def; LENGTH; ADD_CLAUSES; GSYM fibonacci_add2] THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN FIRST_X_ASSUM (MP_TAC o SPEC `SUC k`) THEN REWRITE_TAC [ONE; TWO; ADD_CLAUSES] THEN BOOL_CASES_TAC `h : bool` THEN REWRITE_TAC [GSYM ADD_ASSOC; EQ_ADD_LCANCEL]);; let decode_fib_append = prove (`!l1 l2. decode_fib (APPEND l1 l2) = decode_fib l1 + decode_fib_dest (fibonacci (LENGTH l1 + 1)) (fibonacci (LENGTH l1)) l2`, REPEAT GEN_TAC THEN MP_TAC (SPECL [`0`; `l1 : bool list`; `l2 : bool list`] decode_fib_dest_append) THEN REWRITE_TAC [ADD_CLAUSES; fibonacci_def; decode_fib_def]);; let encode_decode_fib_dest_mk = prove (`!n k l. n < fibonacci (k + 2) ==> decode_fib_dest 1 0 (encode_fib_mk l n (fibonacci (k + 1)) (fibonacci k)) = n + decode_fib_dest (fibonacci (k + 1)) (fibonacci k) l`, REPEAT GEN_TAC THEN REWRITE_TAC [fibonacci_add2] THEN SPEC_TAC (`l : bool list`, `l : bool list`) THEN SPEC_TAC (`n : num`, `n : num`) THEN SPEC_TAC (`k : num`, `k : num`) THEN INDUCT_TAC THENL [REPEAT GEN_TAC THEN REWRITE_TAC [fibonacci_def; ADD_CLAUSES] THEN REWRITE_TAC [GSYM LE_SUC_LT; ONE; LE_SUC; LE] THEN DISCH_THEN SUBST_VAR_TAC THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN REWRITE_TAC [ADD_CLAUSES]; ALL_TAC] THEN REPEAT GEN_TAC THEN REWRITE_TAC [GSYM ADD1; fibonacci_suc_suc] THEN REWRITE_TAC [ADD1] THEN STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN SUBGOAL_THEN `fibonacci (k + 1) = 0 <=> F` SUBST1_TAC THENL [REWRITE_TAC [fibonacci_eq_zero; GSYM ADD1; NOT_SUC]; ALL_TAC] THEN REWRITE_TAC [] THEN COND_CASES_TAC THENL [REWRITE_TAC [ADD_SUB2] THEN FIRST_X_ASSUM (MP_TAC o SPECL [`n - (fibonacci (k + 1) + fibonacci k)`; `CONS T l`]) THEN UNDISCH_TAC `n < (fibonacci (k + 1) + fibonacci k) + fibonacci (k + 1)` THEN FIRST_X_ASSUM (MP_TAC o REWRITE_RULE [LE_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN REWRITE_TAC [ADD_SUB2; LT_ADD_LCANCEL] THEN STRIP_TAC THEN ANTS_TAC THENL [MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (k + 1)` THEN ASM_REWRITE_TAC [LE_ADD]; ALL_TAC] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC [decode_fib_dest_def; LET_DEF; LET_END_DEF] THEN REWRITE_TAC [ADD_ASSOC; EQ_ADD_RCANCEL] THEN CONV_TAC (LAND_CONV (REWR_CONV (GSYM ADD_ASSOC))) THEN MATCH_ACCEPT_TAC ADD_SYM; REWRITE_TAC [ADD_SUB2] THEN FIRST_X_ASSUM (MP_TAC o SPECL [`n : num`; `CONS F l`]) THEN ANTS_TAC THENL [ASM_REWRITE_TAC [GSYM NOT_LE]; ALL_TAC] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC [decode_fib_dest_def; LET_DEF; LET_END_DEF]]);; let encode_decode_fib_dest_find = prove (`!n k. decode_fib_dest 1 0 (encode_fib_find n (fibonacci (k + 1)) (fibonacci k)) = n`, REPEAT GEN_TAC THEN SUBGOAL_THEN `?j. n < fibonacci (j + 2) /\ k <= j` MP_TAC THENL [MP_TAC (SPEC `SUC n` large_fibonacci) THEN REWRITE_TAC [LE_SUC_LT] THEN DISCH_THEN (X_CHOOSE_THEN `i : num` STRIP_ASSUME_TAC) THEN EXISTS_TAC `(i : num) + k` THEN REWRITE_TAC [LE_ADDR] THEN MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci i` THEN ASM_REWRITE_TAC [] THEN MATCH_MP_TAC fibonacci_mono_imp THEN REWRITE_TAC [GSYM ADD_ASSOC; LE_ADD]; ALL_TAC] THEN STRIP_TAC THEN POP_ASSUM (MP_TAC o REWRITE_RULE [LE_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN POP_ASSUM MP_TAC THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`d : num`, `d : num`) THEN INDUCT_TAC THENL [REWRITE_TAC [ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [GSYM fibonacci_add2] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF] THEN MP_TAC (SPECL [`n : num`; `k : num`; `[] : bool list`] encode_decode_fib_dest_mk) THEN ASM_REWRITE_TAC [] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC [decode_fib_dest_def; ADD_CLAUSES]; ALL_TAC] THEN REWRITE_TAC [ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [GSYM fibonacci_add2] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF] THEN COND_CASES_TAC THENL [MP_TAC (SPECL [`n : num`; `k : num`; `[] : bool list`] encode_decode_fib_dest_mk) THEN ASM_REWRITE_TAC [] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC [decode_fib_dest_def; ADD_CLAUSES]; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN FIRST_X_ASSUM (MP_TAC o SPEC `SUC k`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC [ADD_CLAUSES]; REWRITE_TAC [TWO; ONE; ADD_CLAUSES]]);; let encode_decode_fib = prove (`!n. decode_fib (encode_fib n) = n`, GEN_TAC THEN REWRITE_TAC [decode_fib_def; encode_fib_def] THEN MP_TAC (SPECL [`n : num`; `0`] encode_decode_fib_dest_find) THEN REWRITE_TAC [ADD_CLAUSES; fibonacci_def]);; export_thm encode_decode_fib;; let null_encode_fib = prove (`!n. NULL (encode_fib n) <=> n = 0`, GEN_TAC THEN REWRITE_TAC [NULL_EQ_NIL] THEN EQ_TAC THENL [STRIP_TAC THEN ONCE_REWRITE_TAC [GSYM encode_decode_fib] THEN ASM_REWRITE_TAC [encode_fib_zero]; DISCH_THEN SUBST1_TAC THEN ACCEPT_TAC encode_fib_zero]);; export_thm null_encode_fib;; let zeckendorf_cons_imp = prove (`!h t. zeckendorf (CONS h t) ==> zeckendorf t`, GEN_TAC THEN LIST_INDUCT_TAC THENL [REWRITE_TAC [zeckendorf_nil]; CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [zeckendorf_def])) THEN REWRITE_TAC [NULL] THEN STRIP_TAC]);; export_thm zeckendorf_cons_imp;; let zeckendorf_decode_fib_dest_lower_bound = prove (`!k h t. zeckendorf (CONS h t) ==> fibonacci ((k + 2) + LENGTH t) <= decode_fib_dest (fibonacci (k + 1)) (fibonacci k) (CONS h t)`, REPEAT GEN_TAC THEN REWRITE_TAC [ONE; TWO; ADD_CLAUSES] THEN SPEC_TAC (`h : bool`, `h : bool`) THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`t : bool list`, `t : bool list`) THEN LIST_INDUCT_TAC THENL [REPEAT GEN_TAC THEN REWRITE_TAC [LENGTH; ADD_CLAUSES; decode_fib_dest_def; zeckendorf_def; NULL; GSYM fibonacci_suc_suc] THEN DISCH_THEN (SUBST_VAR_TAC o EQT_INTRO) THEN REWRITE_TAC [ADD_CLAUSES; LET_DEF; LET_END_DEF; LE_REFL]; ALL_TAC] THEN REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [zeckendorf_def; decode_fib_dest_def; LENGTH] THEN REWRITE_TAC [NULL; HD; GSYM fibonacci_suc_suc; APPEND] THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN STRIP_TAC THEN FIRST_X_ASSUM (MP_TAC o SPECL [`SUC k`; `h : bool`]) THEN ASM_REWRITE_TAC [ADD_CLAUSES] THEN POP_ASSUM (K ALL_TAC) THEN POP_ASSUM (K ALL_TAC) THEN SPEC_TAC (`decode_fib_dest (fibonacci (SUC (SUC k))) (fibonacci (SUC k)) (CONS h t)`, `n : num`) THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `n : num` THEN ASM_REWRITE_TAC [] THEN BOOL_CASES_TAC `h' : bool` THEN REWRITE_TAC [LE_REFL; LE_ADDR]);; let zeckendorf_decode_fib_lower_bound = prove (`!l. ~NULL l /\ zeckendorf l ==> fibonacci (LENGTH l + 1) <= decode_fib l`, LIST_INDUCT_TAC THENL [REWRITE_TAC [NULL]; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN REWRITE_TAC [NULL] THEN STRIP_TAC THEN MP_TAC (SPECL [`0`; `h : bool`; `t : bool list`] zeckendorf_decode_fib_dest_lower_bound) THEN ASM_REWRITE_TAC [decode_fib_def; ADD_CLAUSES; fibonacci_zero; fibonacci_one] THEN REWRITE_TAC [ONE; TWO; THREE; ADD_CLAUSES; LENGTH]);; export_thm zeckendorf_decode_fib_lower_bound;; let zeckendorf_decode_fib_dest_upper_bound = prove (`!k h t l. zeckendorf (CONS h (APPEND t l)) ==> fibonacci (k + (if h then 1 else 2)) + decode_fib_dest (fibonacci (k + 1)) (fibonacci k) (CONS h t) <= fibonacci ((k + 3) + LENGTH t)`, REPEAT GEN_TAC THEN REWRITE_TAC [ONE; TWO; THREE; ADD_CLAUSES] THEN SPEC_TAC (`h : bool`, `h : bool`) THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`t : bool list`, `t : bool list`) THEN LIST_INDUCT_TAC THENL [REPEAT GEN_TAC THEN DISCH_THEN (K ALL_TAC) THEN REWRITE_TAC [LENGTH; ADD_CLAUSES] THEN BOOL_CASES_TAC `h : bool` THENL [REWRITE_TAC [decode_fib_dest_def; GSYM fibonacci_suc_suc] THEN REWRITE_TAC [ADD_CLAUSES; LET_DEF; LET_END_DEF] THEN ONCE_REWRITE_TAC [ADD_SYM] THEN REWRITE_TAC [GSYM fibonacci_suc_suc] THEN MATCH_ACCEPT_TAC LE_REFL; REWRITE_TAC [decode_fib_dest_def; LET_DEF; LET_END_DEF; ADD_CLAUSES] THEN MATCH_MP_TAC fibonacci_mono_imp THEN MATCH_ACCEPT_TAC SUC_LE]; ALL_TAC] THEN REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [zeckendorf_def; decode_fib_dest_def; LENGTH] THEN REWRITE_TAC [NULL; HD; GSYM fibonacci_suc_suc; APPEND] THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN STRIP_TAC THEN FIRST_X_ASSUM (MP_TAC o SPECL [`SUC k`; `h : bool`]) THEN ASM_REWRITE_TAC [] THEN POP_ASSUM (K ALL_TAC) THEN POP_ASSUM MP_TAC THEN BOOL_CASES_TAC `h' : bool` THENL [REWRITE_TAC [ADD_CLAUSES] THEN DISCH_THEN (SUBST_VAR_TAC o EQF_INTRO) THEN REWRITE_TAC [ADD_CLAUSES; ONCE_REWRITE_RULE [ADD_SYM] (GSYM fibonacci_suc_suc); ADD_ASSOC]; ALL_TAC] THEN REWRITE_TAC [ADD_CLAUSES] THEN STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `fibonacci (SUC (k + (if h then SUC 0 else SUC (SUC 0)))) + decode_fib_dest (fibonacci (SUC (SUC k))) (fibonacci (SUC k)) (CONS h t)` THEN CONJ_TAC THENL [REWRITE_TAC [LE_ADD_RCANCEL] THEN MATCH_MP_TAC fibonacci_mono_imp THEN BOOL_CASES_TAC `h : bool` THENL [REWRITE_TAC [ADD_CLAUSES; LE_REFL]; REWRITE_TAC [ADD_CLAUSES; SUC_LE]]; FIRST_ASSUM ACCEPT_TAC]);; let zeckendorf_decode_fib_upper_bound = prove (`!l1 l2. zeckendorf (APPEND l1 l2) ==> decode_fib l1 < fibonacci (LENGTH l1 + 2)`, REPEAT GEN_TAC THEN SPEC_TAC (`l1 : bool list`, `l1 : bool list`) THEN LIST_INDUCT_TAC THENL [DISCH_THEN (K ALL_TAC) THEN REWRITE_TAC [decode_fib_nil; LENGTH; ADD_CLAUSES; fibonacci_def; LT_NZ] THEN REWRITE_TAC [ONE; NOT_SUC]; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN REWRITE_TAC [APPEND] THEN STRIP_TAC THEN MP_TAC (SPECL [`0`; `h : bool`; `t : bool list`; `l2 : bool list`] zeckendorf_decode_fib_dest_upper_bound) THEN ASM_REWRITE_TAC [decode_fib_def; ADD_CLAUSES; fibonacci_zero; fibonacci_one; GSYM fibonacci_add2] THEN SUBGOAL_THEN `fibonacci (if h then 1 else 2) = 1` SUBST1_TAC THENL [BOOL_CASES_TAC `h : bool` THEN REWRITE_TAC [fibonacci_one; fibonacci_two]; REWRITE_TAC [ONE; TWO; THREE; ADD_CLAUSES; LENGTH; LE_SUC_LT]]);; export_thm zeckendorf_decode_fib_upper_bound;; let bool_list_difference_lemma = prove (`!l1 l2. LENGTH l1 = LENGTH l2 /\ ~(l1 = l2) ==> ?k1 k2 h t. l1 = APPEND k1 (CONS h t) /\ l2 = APPEND k2 (CONS (~h) t)`, LIST_INDUCT_TAC THENL [LIST_INDUCT_TAC THENL [REWRITE_TAC []; REWRITE_TAC [LENGTH; NOT_SUC]]; ALL_TAC] THEN LIST_INDUCT_TAC THENL [REWRITE_TAC [LENGTH; NOT_SUC]; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN REWRITE_TAC [LENGTH; SUC_INJ; CONS_11; TAUT `!x y. ~(x /\ y) <=> (y /\ ~x) \/ ~y`] THEN STRIP_TAC THENL [EXISTS_TAC `[] : bool list` THEN EXISTS_TAC `[] : bool list` THEN EXISTS_TAC `h : bool` THEN EXISTS_TAC `t' : bool list` THEN ASM_REWRITE_TAC [APPEND; CONS_11] THEN MATCH_MP_TAC (TAUT `!x y. ~(y <=> x) ==> (x <=> ~y)`) THEN FIRST_ASSUM ACCEPT_TAC; ALL_TAC] THEN FIRST_X_ASSUM (MP_TAC o SPEC `t' : bool list`) THEN ASM_REWRITE_TAC [] THEN STRIP_TAC THEN EXISTS_TAC `CONS (h : bool) k1` THEN EXISTS_TAC `CONS (h' : bool) k2` THEN EXISTS_TAC `h'' : bool` THEN EXISTS_TAC `t'' : bool list` THEN ASM_REWRITE_TAC [APPEND; CONS_11]);; let zeckendorf_decode_fib_dominate = prove (`!l1 l2 t. LENGTH l1 = LENGTH l2 /\ zeckendorf (APPEND l1 (CONS F t)) /\ zeckendorf (APPEND l2 (CONS T t)) ==> decode_fib (APPEND l1 (CONS F t)) < decode_fib (APPEND l2 (CONS T t))`, REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [GSYM APPEND_SING] THEN REWRITE_TAC [APPEND_ASSOC] THEN ONCE_REWRITE_TAC [decode_fib_append] THEN ASM_REWRITE_TAC [LT_ADD_RCANCEL; LENGTH_APPEND; LENGTH] THEN REWRITE_TAC [decode_fib_append; decode_fib_dest_def; GSYM fibonacci_add2] THEN REWRITE_TAC [LET_DEF; LET_END_DEF; ADD_CLAUSES] THEN MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (LENGTH (l1 : bool list) + 2)` THEN STRIP_TAC THENL [MATCH_MP_TAC zeckendorf_decode_fib_upper_bound THEN EXISTS_TAC `CONS F t` THEN FIRST_ASSUM ACCEPT_TAC; ASM_REWRITE_TAC [LE_ADDR]]);; let zeckendorf_decode_fib_length_mono = prove (`!l1 l2. zeckendorf l1 /\ zeckendorf l2 /\ LENGTH l1 < LENGTH l2 ==> decode_fib l1 < decode_fib l2`, REPEAT STRIP_TAC THEN MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (LENGTH (l1 : bool list) + 2)` THEN CONJ_TAC THENL [MATCH_MP_TAC zeckendorf_decode_fib_upper_bound THEN EXISTS_TAC `[] : bool list` THEN ASM_REWRITE_TAC [APPEND_NIL]; ALL_TAC] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `fibonacci (LENGTH (l2 : bool list) + 1)` THEN CONJ_TAC THENL [MATCH_MP_TAC fibonacci_mono_imp THEN ASM_REWRITE_TAC [TWO; ONE; ADD_CLAUSES; LE_SUC_LT; LT_SUC]; ALL_TAC] THEN MATCH_MP_TAC zeckendorf_decode_fib_lower_bound THEN ASM_REWRITE_TAC [NULL_EQ_NIL] THEN STRIP_TAC THEN UNDISCH_TAC `LENGTH (l1 : bool list) < LENGTH (l2 : bool list)` THEN ASM_REWRITE_TAC [LENGTH; LT]);; export_thm zeckendorf_decode_fib_length_mono;; let zeckendorf_decode_fib_inj = prove (`!l1 l2. zeckendorf l1 /\ zeckendorf l2 /\ decode_fib l1 = decode_fib l2 ==> l1 = l2`, REPEAT GEN_TAC THEN REWRITE_TAC [GSYM LE_ANTISYM; GSYM NOT_LT] THEN REPEAT STRIP_TAC THEN SUBGOAL_THEN `LENGTH (l1 : bool list) = LENGTH (l2 : bool list)` MP_TAC THENL [REWRITE_TAC [GSYM LE_ANTISYM] THEN REWRITE_TAC [GSYM NOT_LT] THEN CONJ_TAC THENL [STRIP_TAC THEN UNDISCH_TAC `~(decode_fib l2 < decode_fib l1)` THEN REWRITE_TAC [] THEN MATCH_MP_TAC zeckendorf_decode_fib_length_mono THEN ASM_REWRITE_TAC []; STRIP_TAC THEN UNDISCH_TAC `~(decode_fib l1 < decode_fib l2)` THEN REWRITE_TAC [] THEN MATCH_MP_TAC zeckendorf_decode_fib_length_mono THEN ASM_REWRITE_TAC []]; ALL_TAC] THEN STRIP_TAC THEN MP_TAC (SPECL [`l1 : bool list`; `l2 : bool list`] bool_list_difference_lemma) THEN BOOL_CASES_TAC `l1 = (l2 : bool list)` THEN ASM_REWRITE_TAC [] THEN STRIP_TAC THEN ASM_CASES_TAC `h : bool` THENL [UNDISCH_TAC `~(decode_fib l2 < decode_fib l1)` THEN POP_ASSUM (SUBST_VAR_TAC o EQT_INTRO) THEN POP_ASSUM SUBST_VAR_TAC THEN POP_ASSUM SUBST_VAR_TAC THEN POP_ASSUM MP_TAC THEN POP_ASSUM (K ALL_TAC) THEN REPEAT (POP_ASSUM MP_TAC) THEN REWRITE_TAC [LENGTH_APPEND; LENGTH; EQ_ADD_RCANCEL] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC zeckendorf_decode_fib_dominate THEN ASM_REWRITE_TAC []; UNDISCH_TAC `~(decode_fib l1 < decode_fib l2)` THEN POP_ASSUM (SUBST_VAR_TAC o EQF_INTRO) THEN POP_ASSUM SUBST_VAR_TAC THEN POP_ASSUM SUBST_VAR_TAC THEN POP_ASSUM MP_TAC THEN POP_ASSUM (K ALL_TAC) THEN REPEAT (POP_ASSUM MP_TAC) THEN REWRITE_TAC [LENGTH_APPEND; LENGTH; EQ_ADD_RCANCEL] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC zeckendorf_decode_fib_dominate THEN ASM_REWRITE_TAC []]);; export_thm zeckendorf_decode_fib_inj;; let zeckendorf_encode_fib_mk = prove (`!n k l. ~NULL l /\ ((n < fibonacci (k + 1) /\ zeckendorf l) \/ (n < fibonacci (k + 2) /\ zeckendorf (CONS T l))) ==> zeckendorf (encode_fib_mk l n (fibonacci (k + 1)) (fibonacci k))`, REPEAT GEN_TAC THEN REWRITE_TAC [fibonacci_add2] THEN SPEC_TAC (`l : bool list`, `l : bool list`) THEN SPEC_TAC (`n : num`, `n : num`) THEN SPEC_TAC (`k : num`, `k : num`) THEN INDUCT_TAC THENL [REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN REWRITE_TAC [fibonacci_def] THEN STRIP_TAC THEN MATCH_MP_TAC zeckendorf_cons_imp THEN EXISTS_TAC `T` THEN FIRST_ASSUM ACCEPT_TAC; ALL_TAC] THEN REPEAT GEN_TAC THEN REWRITE_TAC [GSYM ADD1; fibonacci_suc_suc; NOT_SUC] THEN REWRITE_TAC [ADD1] THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN SUBGOAL_THEN `fibonacci (k + 1) = 0 <=> F` SUBST1_TAC THENL [REWRITE_TAC [fibonacci_eq_zero; GSYM ADD1; NOT_SUC]; ALL_TAC] THEN REWRITE_TAC [] THEN REWRITE_TAC [ADD_SUB2] THEN STRIP_TAC THENL [ASM_REWRITE_TAC [GSYM NOT_LT] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC [NULL] THEN DISJ2_TAC THEN ASM_REWRITE_TAC [zeckendorf_def; NULL; HD]; ALL_TAC] THEN COND_CASES_TAC THENL [FIRST_X_ASSUM MATCH_MP_TAC THEN CONJ_TAC THENL [REWRITE_TAC [NULL]; DISJ1_TAC THEN CONJ_TAC THENL [POP_ASSUM (MP_TAC o REWRITE_RULE [LE_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN REWRITE_TAC [ADD_SUB2] THEN POP_ASSUM (K ALL_TAC) THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [LT_ADD_LCANCEL]; FIRST_ASSUM ACCEPT_TAC]]; FIRST_X_ASSUM MATCH_MP_TAC THEN CONJ_TAC THENL [REWRITE_TAC [NULL]; DISJ2_TAC THEN ASM_REWRITE_TAC [GSYM NOT_LE] THEN POP_ASSUM (K ALL_TAC) THEN POP_ASSUM MP_TAC THEN POP_ASSUM (K ALL_TAC) THEN ASM_REWRITE_TAC [zeckendorf_def; NULL; HD] THEN STRIP_TAC]]);; let zeckendorf_encode_fib_find = prove (`!n k. fibonacci (k + 1) <= n ==> zeckendorf (encode_fib_find n (fibonacci (k + 1)) (fibonacci k))`, REPEAT STRIP_TAC THEN SUBGOAL_THEN `?j. fibonacci (j + 1) <= n /\ n < fibonacci (j + 2) /\ k <= j` MP_TAC THENL [MP_TAC (SPEC `n : num` fibonacci_interval) THEN STRIP_TAC THEN SUBGOAL_THEN `k + 1 < SUC k'` (MP_TAC o REWRITE_RULE [LT_SUC_LE; LE_EXISTS]) THENL [REWRITE_TAC [ADD1] THEN MATCH_MP_TAC fibonacci_strictly_mono_imp' THEN MATCH_MP_TAC LET_TRANS THEN EXISTS_TAC `n : num` THEN ASM_REWRITE_TAC []; ALL_TAC] THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN EXISTS_TAC `k + d : num` THEN POP_ASSUM MP_TAC THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [ADD_CLAUSES; ONE; TWO; LE_ADD] THEN REPEAT STRIP_TAC THEN FIRST_ASSUM ACCEPT_TAC; ALL_TAC] THEN STRIP_TAC THEN POP_ASSUM (MP_TAC o REWRITE_RULE [LE_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN POP_ASSUM MP_TAC THEN POP_ASSUM MP_TAC THEN POP_ASSUM (K ALL_TAC) THEN REWRITE_TAC [IMP_IMP] THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`d : num`, `d : num`) THEN INDUCT_TAC THENL [REWRITE_TAC [ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [GSYM fibonacci_add2] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF] THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN ASM_REWRITE_TAC [fibonacci_eq_zero] THEN COND_CASES_TAC THENL [ACCEPT_TAC zeckendorf_nil; ALL_TAC] THEN REPEAT (POP_ASSUM MP_TAC) THEN REWRITE_TAC [fibonacci_def] THEN MP_TAC (SPEC `k : num` num_CASES) THEN STRIP_TAC THENL [ASM_REWRITE_TAC []; ALL_TAC] THEN POP_ASSUM SUBST_VAR_TAC THEN REWRITE_TAC [ONE; TWO; NOT_SUC; ADD_CLAUSES] THEN REWRITE_TAC [LE_EXISTS] THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN REWRITE_TAC [LT_ADD_LCANCEL; ADD_SUB2] THEN REWRITE_TAC [fibonacci_suc_suc; ADD_SUB2] THEN REWRITE_TAC [ADD1] THEN STRIP_TAC THEN MATCH_MP_TAC zeckendorf_encode_fib_mk THEN STRIP_TAC THENL [REWRITE_TAC [NULL]; ALL_TAC] THEN DISJ1_TAC THEN ASM_REWRITE_TAC [zeckendorf_def; NULL; HD]; ALL_TAC] THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [ONE; TWO; ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [GSYM fibonacci_suc_suc] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF] THEN COND_CASES_TAC THENL [SUBGOAL_THEN `F` CONTR_TAC THEN UNDISCH_TAC `fibonacci (SUC (SUC (k + d))) <= n` THEN REWRITE_TAC [NOT_LE] THEN MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (SUC (SUC k))` THEN ASM_REWRITE_TAC [] THEN MATCH_MP_TAC fibonacci_mono_imp THEN REWRITE_TAC [LE_SUC; LE_ADD]; ALL_TAC] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC [ADD_CLAUSES]);; let zeckendorf_encode_fib = prove (`!n. zeckendorf (encode_fib n)`, GEN_TAC THEN REWRITE_TAC [encode_fib_def] THEN MP_TAC (SPEC `n : num` num_CASES) THEN STRIP_TAC THENL [ONCE_REWRITE_TAC [encode_fib_find_def] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF; ONE; LT_SUC_LE; LE_0; ADD_CLAUSES] THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN REWRITE_TAC [zeckendorf_nil]; MP_TAC (SPECL [`n : num`; `0`] zeckendorf_encode_fib_find) THEN REWRITE_TAC [ADD_CLAUSES; fibonacci_def] THEN DISCH_THEN MATCH_MP_TAC THEN ASM_REWRITE_TAC [ONE; LE_SUC; LE_0]]);; export_thm zeckendorf_encode_fib;; let zeckendorf_decode_encode_fib = prove (`!l. zeckendorf l <=> encode_fib (decode_fib l) = l`, GEN_TAC THEN EQ_TAC THENL [STRIP_TAC THEN MATCH_MP_TAC zeckendorf_decode_fib_inj THEN ASM_REWRITE_TAC [zeckendorf_encode_fib; encode_decode_fib]; DISCH_THEN (SUBST1_TAC o SYM) THEN MATCH_ACCEPT_TAC zeckendorf_encode_fib]);; export_thm zeckendorf_decode_encode_fib;; let decode_fib_dest_src = decode_fib_dest_def;; export_thm decode_fib_dest_src;; let decode_fib_src = prove (`decode_fib = decode_fib_dest 1 0`, REWRITE_TAC [FUN_EQ_THM; decode_fib_def]);; export_thm decode_fib_src;; let encode_fib_src = prove (`encode_fib = \n. encode_fib_find n 1 0`, REWRITE_TAC [FUN_EQ_THM; encode_fib_def]);; export_thm encode_fib_src;; let zeckendorf_src = prove (`(zeckendorf [] <=> T) /\ !h t. zeckendorf (CONS h t) <=> if NULL t then h else ~(h /\ HD t) /\ zeckendorf t`, REWRITE_TAC [zeckendorf_def]);; export_thm zeckendorf_src;; (* ------------------------------------------------------------------------- *) HOL Light theorem names . (* ------------------------------------------------------------------------- *) export_theory "natural-fibonacci-hol-light-thm";; export_theory_thm_names "natural-fibonacci" ["natural-fibonacci-def"; "natural-fibonacci-thm"];; (* ------------------------------------------------------------------------- *) (* Haskell source. *) (* ------------------------------------------------------------------------- *) export_theory "natural-fibonacci-haskell-src";; export_thm fibonaccis_sunfold;; (* Haskell *) export_thm decode_fib_dest_src;; (* Haskell *) export_thm decode_fib_src;; (* Haskell *) export_thm encode_fib_mk_def;; (* Haskell *) export_thm encode_fib_find_def;; (* Haskell *) export_thm encode_fib_src;; (* Haskell *) export_thm zeckendorf_src;; (* Haskell *) (* ------------------------------------------------------------------------- *) Haskell tests . (* ------------------------------------------------------------------------- *) export_theory "natural-fibonacci-haskell-test";; export_thm fibonaccis_vorobev;; (* Haskell *) export_thm encode_decode_fib;; (* Haskell *) export_thm zeckendorf_encode_fib;; (* Haskell *)
null
https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/opentheory/theories/natural-fibonacci/natural-fibonacci.ml
ocaml
========================================================================= FIBONACCI NUMBERS See ========================================================================= ------------------------------------------------------------------------- Theory requirements. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Theory interpretation. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Existence of Fibonacci numbers. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Definition of Fibonacci numbers. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Properties of Fibonacci numbers. ------------------------------------------------------------------------- Re-export Re-export ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- Haskell source. ------------------------------------------------------------------------- Haskell Haskell Haskell Haskell Haskell Haskell Haskell ------------------------------------------------------------------------- ------------------------------------------------------------------------- Haskell Haskell Haskell
import_theories ["base"; "stream"; "probability"];; export_interpretation "opentheory/theories/natural-fibonacci/natural-fibonacci.int";; export_theory "natural-fibonacci-exists";; let fibonacci_induction = prove (`!p : num -> bool. p 0 /\ p 1 /\ (!n. p n /\ p (n + 1) ==> p (n + 2)) ==> !n. p n`, REWRITE_TAC [ONE; TWO; ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN WF_INDUCT_TAC `n : num` THEN MP_TAC (SPEC `n : num` num_CASES) THEN STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN ASM_REWRITE_TAC [] THEN MP_TAC (SPEC `n' : num` num_CASES) THEN STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN ASM_REWRITE_TAC [] THEN UNDISCH_THEN `!n. p n /\ p (SUC n) ==> p (SUC (SUC n))` MATCH_MP_TAC THEN CONJ_TAC THENL [FIRST_X_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC LT_TRANS THEN EXISTS_TAC `SUC n''` THEN CONJ_TAC THEN MATCH_ACCEPT_TAC SUC_LT; FIRST_X_ASSUM MATCH_MP_TAC THEN MATCH_ACCEPT_TAC SUC_LT]);; export_thm fibonacci_induction;; let fibonacci_recursion = prove (`!(h : (num -> A) -> num -> A). (!f g n. (!m. m + 1 = n \/ m + 2 = n ==> (f m = g m)) ==> (h f n = h g n)) ==> ?f. !n. f n = h f n`, SUBGOAL_THEN `!(h : (num -> A) -> num -> A). (!f g n. (!m. (\x y. x + 1 = y \/ x + 2 = y) m n ==> (f m = g m)) ==> (h f n = h g n)) ==> ?f. !n. f n = h f n` (ACCEPT_TAC o REWRITE_RULE []) THEN MATCH_MP_TAC WF_REC THEN MATCH_MP_TAC WF_SUBSET THEN EXISTS_TAC `(<) : num -> num -> bool` THEN CONJ_TAC THENL [REWRITE_TAC [GSYM LE_SUC_LT; ADD1] THEN REPEAT STRIP_TAC THENL [FIRST_X_ASSUM SUBST_VAR_TAC THEN MATCH_ACCEPT_TAC LE_REFL; FIRST_X_ASSUM SUBST_VAR_TAC THEN REWRITE_TAC [LE_ADD_LCANCEL; TWO; SUC_LE]]; ACCEPT_TAC WF_num]);; export_thm fibonacci_recursion;; let fibonacci_exists = prove (`?f. f 0 = 0 /\ f 1 = 1 /\ !n. f (n + 2) = f (n + 1) + f n`, SUBGOAL_THEN `?f. !n. f n = (\f' n'. if n' < 2 then n' else f' (n' - 1) + f' (n' - 2)) f n` MP_TAC THENL [MATCH_MP_TAC fibonacci_recursion THEN GEN_TAC THEN GEN_TAC THEN REWRITE_TAC [] THEN MATCH_MP_TAC fibonacci_induction THEN REPEAT STRIP_TAC THENL [NUM_REDUCE_TAC; NUM_REDUCE_TAC; BOOL_CASES_TAC `n + 2 < 2` THENL [REWRITE_TAC []; REWRITE_TAC [ADD_SUB] THEN SUBGOAL_THEN `(f : num -> num) n = g n` SUBST1_TAC THENL [FIRST_X_ASSUM MATCH_MP_TAC THEN DISJ2_TAC THEN REFL_TAC; REWRITE_TAC [EQ_ADD_RCANCEL] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN DISJ1_TAC THEN MATCH_MP_TAC SUB_ADD THEN REWRITE_TAC [TWO; ONE; LE_SUC; ADD_CLAUSES; LE_0]]]]; REWRITE_TAC [] THEN STRIP_TAC THEN EXISTS_TAC `f : num -> num` THEN REPEAT STRIP_TAC THENL [FIRST_X_ASSUM (fun th -> ONCE_REWRITE_TAC [th]) THEN NUM_REDUCE_TAC; FIRST_X_ASSUM (fun th -> ONCE_REWRITE_TAC [th]) THEN NUM_REDUCE_TAC; FIRST_X_ASSUM (fun th -> CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [th]))) THEN SUBGOAL_THEN `n + 2 < 2 <=> F` SUBST1_TAC THENL [REWRITE_TAC [NOT_LT; LE_ADDR]; REWRITE_TAC [ADD_SUB; EQ_ADD_RCANCEL] THEN REWRITE_TAC [TWO; ADD_CLAUSES] THEN REWRITE_TAC [ADD_SUB; ADD1]]]]);; export_thm fibonacci_exists;; export_theory "natural-fibonacci-def";; let (fibonacci_zero,fibonacci_one,fibonacci_add2) = let def = new_specification ["fibonacci"] fibonacci_exists in let fib1 = CONJUNCT1 def in let def = CONJUNCT2 def in let fib2 = CONJUNCT1 def in let def = CONJUNCT2 def in (fib1,fib2,def);; export_thm fibonacci_zero;; export_thm fibonacci_one;; export_thm fibonacci_add2;; let fibonacci_def = CONJ fibonacci_zero (CONJ fibonacci_one fibonacci_add2);; let fibonaccis_def = new_definition `fibonaccis = stream fibonacci`;; export_thm fibonaccis_def;; let (decode_fib_dest_nil,decode_fib_dest_cons) = let def = new_recursive_definition list_RECURSION `(!f p. decode_fib_dest f p [] = 0) /\ (!f p h t. decode_fib_dest f p (CONS h t) = let s = f + p in let n = decode_fib_dest s f t in if h then s + n else n)` in CONJ_PAIR def;; export_thm decode_fib_dest_nil;; export_thm decode_fib_dest_cons;; let decode_fib_dest_def = CONJ decode_fib_dest_nil decode_fib_dest_cons;; let decode_fib_def = new_definition `!l. decode_fib l = decode_fib_dest 1 0 l`;; export_thm decode_fib_def;; let encode_fib_mk_exists = prove (`?mk. !l n f p. mk l n f p = if p = 0 then l else if f <= n then mk (CONS T l) (n - f) p (f - p) else mk (CONS F l) n p (f - p)`, MP_TAC (ISPECL [`\ ((l : bool list), (n : num), (f : num), (p : num)). ~(p = 0)`; `\ ((l : bool list), (n : num), (f : num), (p : num)). if f <= n then (CONS T l, n - f, p, f - p) else (CONS F l, n, p, f - p)`; `\ ((l : bool list), (n : num), (f : num), (p : num)). l`] WF_REC_TAIL) THEN DISCH_THEN (X_CHOOSE_THEN `mk : bool list # num # num # num -> bool list` STRIP_ASSUME_TAC) THEN EXISTS_TAC `\ (l : bool list) (n : num) (f : num) (p : num). (mk (l,n,f,p) : bool list)` THEN REPEAT GEN_TAC THEN REWRITE_TAC [] THEN FIRST_X_ASSUM (fun th -> CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [th]))) THEN REWRITE_TAC [] THEN BOOL_CASES_TAC `p = 0` THENL [REWRITE_TAC []; REWRITE_TAC [] THEN MATCH_ACCEPT_TAC COND_RAND]);; let encode_fib_mk_def = new_specification ["encode_fib_mk"] encode_fib_mk_exists;; export_thm encode_fib_mk_def;; let encode_fib_find_exists = prove (`!n. ?find. !f p. find f p = let s = f + p in if n < s then encode_fib_mk [] n f p else find s f`, GEN_TAC THEN MP_TAC (ISPECL [`\ ((f : num), (p : num)). ~(n < f + p)`; `\ ((f : num), (p : num)). (f + p, f)`; `\ ((f : num), (p : num)). encode_fib_mk [] n f p`] WF_REC_TAIL) THEN DISCH_THEN (X_CHOOSE_THEN `find : num # num -> bool list` STRIP_ASSUME_TAC) THEN EXISTS_TAC `\ (f : num) (p : num). (find (f,p) : bool list)` THEN REPEAT GEN_TAC THEN REWRITE_TAC [] THEN FIRST_X_ASSUM (fun th -> CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [th]))) THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN BOOL_CASES_TAC `n < f + (p : num)` THENL [REWRITE_TAC []; REWRITE_TAC []]);; let encode_fib_find_def = new_specification ["encode_fib_find"] (REWRITE_RULE [SKOLEM_THM] encode_fib_find_exists);; export_thm encode_fib_find_def;; let encode_fib_def = new_definition `!n. encode_fib n = encode_fib_find n 1 0`;; export_thm encode_fib_def;; let (zeckendorf_nil,zeckendorf_cons) = let def = new_recursive_definition list_RECURSION `(zeckendorf [] <=> T) /\ (!h t. zeckendorf (CONS h t) <=> if NULL t then h else ~(h /\ HD t) /\ zeckendorf t)` in CONJ_PAIR (REWRITE_RULE [] def);; export_thm zeckendorf_nil;; export_thm zeckendorf_cons;; let zeckendorf_def = CONJ zeckendorf_nil zeckendorf_cons;; let random_fib_dest_exists = prove (`?dest. !b (n : num) f p r. dest b n f p r = let (r1,r2) = split_random r in let b' = random_bit r1 in if b' /\ b then n else let s = f + p in dest b' (if b' then s + n else n) s f r2`, MP_TAC (ISPECL [`\ ((b : bool), (n : num), (f : num), (p : num), (r : random)). let (r1,r2) = split_random r in let b' = random_bit r1 in ~(b' /\ b)`; `\ ((b : bool), (n : num), (f : num), (p : num), (r : random)). let (r1,r2) = split_random r in let b' = random_bit r1 in let s = f + p in (b', (if b' then s + n else n), s, f, r2)`; `\ ((b : bool), (n : num), (f : num), (p : num), (r : random)). n`] WF_REC_TAIL) THEN DISCH_THEN (X_CHOOSE_THEN `dest : bool # num # num # num # random -> num` STRIP_ASSUME_TAC) THEN EXISTS_TAC `\ (b : bool) (n : num) (f : num) (p : num) (r : random). ((dest (b,n,f,p,r)) : num)` THEN REPEAT GEN_TAC THEN REWRITE_TAC [] THEN FIRST_X_ASSUM (fun th -> CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [th]))) THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN PAIR_CASES_TAC `split_random r` THEN DISCH_THEN (X_CHOOSE_THEN `r1 : random` (X_CHOOSE_THEN `r2 : random` SUBST1_TAC)) THEN REWRITE_TAC [] THEN BOOL_CASES_TAC `random_bit r1 /\ b` THENL [REWRITE_TAC []; REWRITE_TAC []]);; let random_fib_dest_def = new_specification ["random_fib_dest"] random_fib_dest_exists;; export_thm random_fib_dest_def;; let random_fib_def = new_definition `!r. random_fib r = random_fib_dest F 0 1 0 r - 1`;; export_thm random_fib_def;; let random_fib_list_def = new_definition `!f r. random_fib_list (f : random -> A) r = let (r1,r2) = split_random r in random_vector f (random_fib r1) r2`;; export_thm random_fib_list_def;; export_theory "natural-fibonacci-thm";; let fibonacci_suc_suc = prove (`!k. fibonacci (SUC (SUC k)) = fibonacci (SUC k) + fibonacci k`, GEN_TAC THEN SUBGOAL_THEN `SUC (SUC k) = k + 2` SUBST1_TAC THENL [REWRITE_TAC [TWO; ONE; ADD_CLAUSES]; REWRITE_TAC [fibonacci_def; EQ_ADD_RCANCEL; ADD1]]);; export_thm fibonacci_suc_suc;; let fibonacci_two = prove (`fibonacci 2 = 1`, REWRITE_TAC [TWO; ONE; fibonacci_suc_suc; fibonacci_zero; ADD_CLAUSES] THEN REWRITE_TAC [fibonacci_one; GSYM ONE]);; export_thm fibonacci_two;; let fibonacci_eq_zero = prove (`!k. fibonacci k = 0 <=> k = 0`, MATCH_MP_TAC fibonacci_induction THEN REWRITE_TAC [fibonacci_def] THEN REPEAT STRIP_TAC THEN ASM_REWRITE_TAC [ADD_EQ_0] THEN NUM_REDUCE_TAC);; export_thm fibonacci_eq_zero;; let fibonacci_mono_imp = prove (`!j k. j <= k ==> fibonacci j <= fibonacci k`, MATCH_MP_TAC fibonacci_induction THEN REWRITE_TAC [fibonacci_def; LE_0] THEN STRIP_TAC THENL [GEN_TAC THEN REWRITE_TAC [LT_NZ; ONE; LE_SUC_LT; fibonacci_eq_zero]; ALL_TAC] THEN REPEAT STRIP_TAC THEN SUBGOAL_THEN `j + 2 <= j + k` (MP_TAC o ONCE_REWRITE_RULE [ADD_SYM] o REWRITE_RULE [LE_EXISTS] o REWRITE_RULE [LE_ADD_LCANCEL]) THENL [MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `k : num` THEN ASM_REWRITE_TAC [LE_ADDR]; ALL_TAC] THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [LE_ADD_RCANCEL] THEN STRIP_TAC THEN REWRITE_TAC [fibonacci_def] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `fibonacci (j + 1) + fibonacci d` THEN REWRITE_TAC [LE_ADD_LCANCEL; LE_ADD_RCANCEL] THEN STRIP_TAC THENL [FIRST_X_ASSUM MATCH_MP_TAC THEN FIRST_ASSUM ACCEPT_TAC; FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC [LE_ADD_RCANCEL]]);; export_thm fibonacci_mono_imp;; let fibonacci_strictly_mono_suc = prove (`!j. ~(j = 1) ==> fibonacci j < fibonacci (SUC j)`, REPEAT STRIP_TAC THEN MP_TAC (SPEC `j : num` num_CASES) THEN STRIP_TAC THENL [ASM_REWRITE_TAC [LT_NZ; fibonacci_def; fibonacci_eq_zero; NOT_SUC]; FIRST_X_ASSUM SUBST_VAR_TAC THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [fibonacci_suc_suc; LT_ADD; LT_NZ; fibonacci_eq_zero; ONE; SUC_INJ]]);; export_thm fibonacci_strictly_mono_suc;; let fibonacci_strictly_mono_imp = prove (`!j k. ~(j = 1 /\ k = 2) /\ j < k ==> fibonacci j < fibonacci k`, REPEAT STRIP_TAC THEN POP_ASSUM (MP_TAC o REWRITE_RULE [LT_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [ADD_CLAUSES; TWO; SUC_INJ; DE_MORGAN_THM] THEN STRIP_TAC THENL [MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (SUC j)` THEN CONJ_TAC THENL [MATCH_MP_TAC fibonacci_strictly_mono_suc THEN FIRST_ASSUM ACCEPT_TAC; MATCH_MP_TAC fibonacci_mono_imp THEN REWRITE_TAC [LE_SUC; LE_ADD]]; MATCH_MP_TAC LET_TRANS THEN EXISTS_TAC `fibonacci (j + d)` THEN CONJ_TAC THENL [MATCH_MP_TAC fibonacci_mono_imp THEN MATCH_ACCEPT_TAC LE_ADD; MATCH_MP_TAC fibonacci_strictly_mono_suc THEN FIRST_ASSUM ACCEPT_TAC]]);; export_thm fibonacci_strictly_mono_imp;; let fibonacci_mono_imp' = prove (`!j k. ~(j = 2 /\ k = 1) /\ fibonacci j <= fibonacci k ==> j <= k`, REPEAT STRIP_TAC THEN POP_ASSUM MP_TAC THEN ONCE_REWRITE_TAC [GSYM CONTRAPOS_THM] THEN REWRITE_TAC [NOT_LE] THEN STRIP_TAC THEN MATCH_MP_TAC fibonacci_strictly_mono_imp THEN ASM_REWRITE_TAC [] THEN ONCE_REWRITE_TAC [CONJ_SYM] THEN FIRST_ASSUM ACCEPT_TAC);; export_thm fibonacci_mono_imp';; let fibonacci_strictly_mono_imp' = prove (`!j k. fibonacci j < fibonacci k ==> j < k`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [GSYM CONTRAPOS_THM] THEN REWRITE_TAC [NOT_LT] THEN MATCH_ACCEPT_TAC fibonacci_mono_imp);; export_thm fibonacci_strictly_mono_imp';; let large_fibonacci = prove (`!n. ?k. n <= fibonacci k`, INDUCT_TAC THENL [REWRITE_TAC [LE_0]; POP_ASSUM STRIP_ASSUME_TAC THEN EXISTS_TAC `SUC (SUC k)` THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `SUC (fibonacci k)` THEN CONJ_TAC THENL [ASM_REWRITE_TAC [LE_SUC]; REWRITE_TAC [LE_SUC_LT; fibonacci_suc_suc; LT_ADDR; LT_NZ; fibonacci_eq_zero; NOT_SUC]]]);; export_thm large_fibonacci;; let fibonacci_interval = prove (`!n. ?k. fibonacci k <= n /\ n < fibonacci (k + 1)`, GEN_TAC THEN MP_TAC ((REWRITE_RULE [MINIMAL] o REWRITE_RULE [LE_SUC_LT] o SPEC `SUC n`) large_fibonacci) THEN MP_TAC (SPEC `minimal k. n < fibonacci k` num_CASES) THEN STRIP_TAC THENL [ASM_REWRITE_TAC [fibonacci_zero; LT]; POP_ASSUM SUBST1_TAC THEN REWRITE_TAC [NOT_LT; LT_SUC_LE] THEN STRIP_TAC THEN EXISTS_TAC `n' : num` THEN ASM_REWRITE_TAC [GSYM ADD1] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN MATCH_ACCEPT_TAC LE_REFL]);; export_thm fibonacci_interval;; let fibonacci_vorobev = prove (`!j k. fibonacci (j + k + 1) = fibonacci j * fibonacci k + fibonacci (j + 1) * fibonacci (k + 1)`, INDUCT_TAC THENL [REWRITE_TAC [ADD_CLAUSES; fibonacci_def; MULT_CLAUSES]; ALL_TAC] THEN GEN_TAC THEN REWRITE_TAC [ONE; ADD_CLAUSES] THEN CONV_TAC (RAND_CONV (REWRITE_CONV [fibonacci_suc_suc])) THEN REWRITE_TAC [ADD_ASSOC; RIGHT_ADD_DISTRIB] THEN REWRITE_TAC [GSYM LEFT_ADD_DISTRIB] THEN CONV_TAC (RAND_CONV (ONCE_REWRITE_CONV [ADD_SYM])) THEN CONV_TAC (RAND_CONV (RAND_CONV (ONCE_REWRITE_CONV [ADD_SYM]))) THEN REWRITE_TAC [GSYM fibonacci_suc_suc] THEN ONCE_REWRITE_TAC [GSYM ADD_SUC] THEN REWRITE_TAC [ADD1] THEN CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [GSYM ADD_ASSOC])) THEN FIRST_ASSUM MATCH_ACCEPT_TAC);; export_thm fibonacci_vorobev;; let snth_fibonaccis = prove (`!n. snth fibonaccis n = fibonacci n`, REWRITE_TAC [fibonaccis_def; stream_snth]);; export_thm snth_fibonaccis;; let fibonaccis_sunfold = prove (`fibonaccis = sunfold (\ (p,f). (p, f, p + f)) (0,1)`, MATCH_MP_TAC snth_eq_imp THEN REWRITE_TAC [fibonaccis_def; stream_snth] THEN MATCH_MP_TAC fibonacci_induction THEN CONJ_TAC THENL [REWRITE_TAC [GSYM shd_def; shd_sunfold; fibonacci_zero]; ALL_TAC] THEN CONJ_TAC THENL [REWRITE_TAC [snth_one; stl_sunfold; shd_sunfold; fibonacci_one]; ALL_TAC] THEN X_GEN_TAC `n : num` THEN CONV_TAC (LAND_CONV (LAND_CONV (RAND_CONV (RAND_CONV (REWR_CONV (GSYM ADD_0)))))) THEN REWRITE_TAC [snth_sunfold_add] THEN SPEC_TAC (`funpow (SND o (\(p,f). p,f,p + f)) n (0,1)`, `x : num # num`) THEN REWRITE_TAC [FORALL_PAIR_THM] THEN X_GEN_TAC `p : num` THEN X_GEN_TAC `f : num` THEN REWRITE_TAC [fibonacci_add2] THEN REWRITE_TAC [GSYM shd_def; snth_one; TWO; snth_suc; shd_sunfold; stl_sunfold] THEN STRIP_TAC THEN ASM_REWRITE_TAC [] THEN MATCH_ACCEPT_TAC ADD_SYM);; export_thm fibonaccis_sunfold;; let fibonaccis_vorobev = prove (`!j k. snth fibonaccis (j + k + 1) = snth fibonaccis j * snth fibonaccis k + snth fibonaccis (j + 1) * snth fibonaccis (k + 1)`, REWRITE_TAC [snth_fibonaccis; fibonacci_vorobev]);; export_thm fibonaccis_vorobev;; let decode_fib_nil = prove (`decode_fib [] = 0`, REWRITE_TAC [decode_fib_def; decode_fib_dest_def]);; export_thm decode_fib_nil;; let encode_fib_zero = prove (`encode_fib 0 = []`, REWRITE_TAC [encode_fib_def] THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [LET_DEF; LET_END_DEF; ADD_CLAUSES; LT_NZ; ONE; NOT_SUC] THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN REWRITE_TAC []);; export_thm encode_fib_zero;; let decode_fib_dest_append = prove (`!k l1 l2. decode_fib_dest (fibonacci (k + 1)) (fibonacci k) (APPEND l1 l2) = decode_fib_dest (fibonacci (k + 1)) (fibonacci k) l1 + decode_fib_dest (fibonacci (LENGTH l1 + (k + 1))) (fibonacci (LENGTH l1 + k)) l2`, REPEAT GEN_TAC THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`l1 : bool list`, `l1 : bool list`) THEN LIST_INDUCT_TAC THENL [REWRITE_TAC [APPEND; decode_fib_dest_def; LENGTH; ADD_CLAUSES; fibonacci_def]; ALL_TAC] THEN REPEAT GEN_TAC THEN REWRITE_TAC [APPEND; decode_fib_dest_def; LENGTH; ADD_CLAUSES; GSYM fibonacci_add2] THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN FIRST_X_ASSUM (MP_TAC o SPEC `SUC k`) THEN REWRITE_TAC [ONE; TWO; ADD_CLAUSES] THEN BOOL_CASES_TAC `h : bool` THEN REWRITE_TAC [GSYM ADD_ASSOC; EQ_ADD_LCANCEL]);; let decode_fib_append = prove (`!l1 l2. decode_fib (APPEND l1 l2) = decode_fib l1 + decode_fib_dest (fibonacci (LENGTH l1 + 1)) (fibonacci (LENGTH l1)) l2`, REPEAT GEN_TAC THEN MP_TAC (SPECL [`0`; `l1 : bool list`; `l2 : bool list`] decode_fib_dest_append) THEN REWRITE_TAC [ADD_CLAUSES; fibonacci_def; decode_fib_def]);; let encode_decode_fib_dest_mk = prove (`!n k l. n < fibonacci (k + 2) ==> decode_fib_dest 1 0 (encode_fib_mk l n (fibonacci (k + 1)) (fibonacci k)) = n + decode_fib_dest (fibonacci (k + 1)) (fibonacci k) l`, REPEAT GEN_TAC THEN REWRITE_TAC [fibonacci_add2] THEN SPEC_TAC (`l : bool list`, `l : bool list`) THEN SPEC_TAC (`n : num`, `n : num`) THEN SPEC_TAC (`k : num`, `k : num`) THEN INDUCT_TAC THENL [REPEAT GEN_TAC THEN REWRITE_TAC [fibonacci_def; ADD_CLAUSES] THEN REWRITE_TAC [GSYM LE_SUC_LT; ONE; LE_SUC; LE] THEN DISCH_THEN SUBST_VAR_TAC THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN REWRITE_TAC [ADD_CLAUSES]; ALL_TAC] THEN REPEAT GEN_TAC THEN REWRITE_TAC [GSYM ADD1; fibonacci_suc_suc] THEN REWRITE_TAC [ADD1] THEN STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN SUBGOAL_THEN `fibonacci (k + 1) = 0 <=> F` SUBST1_TAC THENL [REWRITE_TAC [fibonacci_eq_zero; GSYM ADD1; NOT_SUC]; ALL_TAC] THEN REWRITE_TAC [] THEN COND_CASES_TAC THENL [REWRITE_TAC [ADD_SUB2] THEN FIRST_X_ASSUM (MP_TAC o SPECL [`n - (fibonacci (k + 1) + fibonacci k)`; `CONS T l`]) THEN UNDISCH_TAC `n < (fibonacci (k + 1) + fibonacci k) + fibonacci (k + 1)` THEN FIRST_X_ASSUM (MP_TAC o REWRITE_RULE [LE_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN REWRITE_TAC [ADD_SUB2; LT_ADD_LCANCEL] THEN STRIP_TAC THEN ANTS_TAC THENL [MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (k + 1)` THEN ASM_REWRITE_TAC [LE_ADD]; ALL_TAC] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC [decode_fib_dest_def; LET_DEF; LET_END_DEF] THEN REWRITE_TAC [ADD_ASSOC; EQ_ADD_RCANCEL] THEN CONV_TAC (LAND_CONV (REWR_CONV (GSYM ADD_ASSOC))) THEN MATCH_ACCEPT_TAC ADD_SYM; REWRITE_TAC [ADD_SUB2] THEN FIRST_X_ASSUM (MP_TAC o SPECL [`n : num`; `CONS F l`]) THEN ANTS_TAC THENL [ASM_REWRITE_TAC [GSYM NOT_LE]; ALL_TAC] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC [decode_fib_dest_def; LET_DEF; LET_END_DEF]]);; let encode_decode_fib_dest_find = prove (`!n k. decode_fib_dest 1 0 (encode_fib_find n (fibonacci (k + 1)) (fibonacci k)) = n`, REPEAT GEN_TAC THEN SUBGOAL_THEN `?j. n < fibonacci (j + 2) /\ k <= j` MP_TAC THENL [MP_TAC (SPEC `SUC n` large_fibonacci) THEN REWRITE_TAC [LE_SUC_LT] THEN DISCH_THEN (X_CHOOSE_THEN `i : num` STRIP_ASSUME_TAC) THEN EXISTS_TAC `(i : num) + k` THEN REWRITE_TAC [LE_ADDR] THEN MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci i` THEN ASM_REWRITE_TAC [] THEN MATCH_MP_TAC fibonacci_mono_imp THEN REWRITE_TAC [GSYM ADD_ASSOC; LE_ADD]; ALL_TAC] THEN STRIP_TAC THEN POP_ASSUM (MP_TAC o REWRITE_RULE [LE_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN POP_ASSUM MP_TAC THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`d : num`, `d : num`) THEN INDUCT_TAC THENL [REWRITE_TAC [ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [GSYM fibonacci_add2] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF] THEN MP_TAC (SPECL [`n : num`; `k : num`; `[] : bool list`] encode_decode_fib_dest_mk) THEN ASM_REWRITE_TAC [] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC [decode_fib_dest_def; ADD_CLAUSES]; ALL_TAC] THEN REWRITE_TAC [ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [GSYM fibonacci_add2] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF] THEN COND_CASES_TAC THENL [MP_TAC (SPECL [`n : num`; `k : num`; `[] : bool list`] encode_decode_fib_dest_mk) THEN ASM_REWRITE_TAC [] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC [decode_fib_dest_def; ADD_CLAUSES]; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN FIRST_X_ASSUM (MP_TAC o SPEC `SUC k`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC [ADD_CLAUSES]; REWRITE_TAC [TWO; ONE; ADD_CLAUSES]]);; let encode_decode_fib = prove (`!n. decode_fib (encode_fib n) = n`, GEN_TAC THEN REWRITE_TAC [decode_fib_def; encode_fib_def] THEN MP_TAC (SPECL [`n : num`; `0`] encode_decode_fib_dest_find) THEN REWRITE_TAC [ADD_CLAUSES; fibonacci_def]);; export_thm encode_decode_fib;; let null_encode_fib = prove (`!n. NULL (encode_fib n) <=> n = 0`, GEN_TAC THEN REWRITE_TAC [NULL_EQ_NIL] THEN EQ_TAC THENL [STRIP_TAC THEN ONCE_REWRITE_TAC [GSYM encode_decode_fib] THEN ASM_REWRITE_TAC [encode_fib_zero]; DISCH_THEN SUBST1_TAC THEN ACCEPT_TAC encode_fib_zero]);; export_thm null_encode_fib;; let zeckendorf_cons_imp = prove (`!h t. zeckendorf (CONS h t) ==> zeckendorf t`, GEN_TAC THEN LIST_INDUCT_TAC THENL [REWRITE_TAC [zeckendorf_nil]; CONV_TAC (LAND_CONV (ONCE_REWRITE_CONV [zeckendorf_def])) THEN REWRITE_TAC [NULL] THEN STRIP_TAC]);; export_thm zeckendorf_cons_imp;; let zeckendorf_decode_fib_dest_lower_bound = prove (`!k h t. zeckendorf (CONS h t) ==> fibonacci ((k + 2) + LENGTH t) <= decode_fib_dest (fibonacci (k + 1)) (fibonacci k) (CONS h t)`, REPEAT GEN_TAC THEN REWRITE_TAC [ONE; TWO; ADD_CLAUSES] THEN SPEC_TAC (`h : bool`, `h : bool`) THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`t : bool list`, `t : bool list`) THEN LIST_INDUCT_TAC THENL [REPEAT GEN_TAC THEN REWRITE_TAC [LENGTH; ADD_CLAUSES; decode_fib_dest_def; zeckendorf_def; NULL; GSYM fibonacci_suc_suc] THEN DISCH_THEN (SUBST_VAR_TAC o EQT_INTRO) THEN REWRITE_TAC [ADD_CLAUSES; LET_DEF; LET_END_DEF; LE_REFL]; ALL_TAC] THEN REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [zeckendorf_def; decode_fib_dest_def; LENGTH] THEN REWRITE_TAC [NULL; HD; GSYM fibonacci_suc_suc; APPEND] THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN STRIP_TAC THEN FIRST_X_ASSUM (MP_TAC o SPECL [`SUC k`; `h : bool`]) THEN ASM_REWRITE_TAC [ADD_CLAUSES] THEN POP_ASSUM (K ALL_TAC) THEN POP_ASSUM (K ALL_TAC) THEN SPEC_TAC (`decode_fib_dest (fibonacci (SUC (SUC k))) (fibonacci (SUC k)) (CONS h t)`, `n : num`) THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `n : num` THEN ASM_REWRITE_TAC [] THEN BOOL_CASES_TAC `h' : bool` THEN REWRITE_TAC [LE_REFL; LE_ADDR]);; let zeckendorf_decode_fib_lower_bound = prove (`!l. ~NULL l /\ zeckendorf l ==> fibonacci (LENGTH l + 1) <= decode_fib l`, LIST_INDUCT_TAC THENL [REWRITE_TAC [NULL]; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN REWRITE_TAC [NULL] THEN STRIP_TAC THEN MP_TAC (SPECL [`0`; `h : bool`; `t : bool list`] zeckendorf_decode_fib_dest_lower_bound) THEN ASM_REWRITE_TAC [decode_fib_def; ADD_CLAUSES; fibonacci_zero; fibonacci_one] THEN REWRITE_TAC [ONE; TWO; THREE; ADD_CLAUSES; LENGTH]);; export_thm zeckendorf_decode_fib_lower_bound;; let zeckendorf_decode_fib_dest_upper_bound = prove (`!k h t l. zeckendorf (CONS h (APPEND t l)) ==> fibonacci (k + (if h then 1 else 2)) + decode_fib_dest (fibonacci (k + 1)) (fibonacci k) (CONS h t) <= fibonacci ((k + 3) + LENGTH t)`, REPEAT GEN_TAC THEN REWRITE_TAC [ONE; TWO; THREE; ADD_CLAUSES] THEN SPEC_TAC (`h : bool`, `h : bool`) THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`t : bool list`, `t : bool list`) THEN LIST_INDUCT_TAC THENL [REPEAT GEN_TAC THEN DISCH_THEN (K ALL_TAC) THEN REWRITE_TAC [LENGTH; ADD_CLAUSES] THEN BOOL_CASES_TAC `h : bool` THENL [REWRITE_TAC [decode_fib_dest_def; GSYM fibonacci_suc_suc] THEN REWRITE_TAC [ADD_CLAUSES; LET_DEF; LET_END_DEF] THEN ONCE_REWRITE_TAC [ADD_SYM] THEN REWRITE_TAC [GSYM fibonacci_suc_suc] THEN MATCH_ACCEPT_TAC LE_REFL; REWRITE_TAC [decode_fib_dest_def; LET_DEF; LET_END_DEF; ADD_CLAUSES] THEN MATCH_MP_TAC fibonacci_mono_imp THEN MATCH_ACCEPT_TAC SUC_LE]; ALL_TAC] THEN REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [zeckendorf_def; decode_fib_dest_def; LENGTH] THEN REWRITE_TAC [NULL; HD; GSYM fibonacci_suc_suc; APPEND] THEN REWRITE_TAC [LET_DEF; LET_END_DEF] THEN STRIP_TAC THEN FIRST_X_ASSUM (MP_TAC o SPECL [`SUC k`; `h : bool`]) THEN ASM_REWRITE_TAC [] THEN POP_ASSUM (K ALL_TAC) THEN POP_ASSUM MP_TAC THEN BOOL_CASES_TAC `h' : bool` THENL [REWRITE_TAC [ADD_CLAUSES] THEN DISCH_THEN (SUBST_VAR_TAC o EQF_INTRO) THEN REWRITE_TAC [ADD_CLAUSES; ONCE_REWRITE_RULE [ADD_SYM] (GSYM fibonacci_suc_suc); ADD_ASSOC]; ALL_TAC] THEN REWRITE_TAC [ADD_CLAUSES] THEN STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `fibonacci (SUC (k + (if h then SUC 0 else SUC (SUC 0)))) + decode_fib_dest (fibonacci (SUC (SUC k))) (fibonacci (SUC k)) (CONS h t)` THEN CONJ_TAC THENL [REWRITE_TAC [LE_ADD_RCANCEL] THEN MATCH_MP_TAC fibonacci_mono_imp THEN BOOL_CASES_TAC `h : bool` THENL [REWRITE_TAC [ADD_CLAUSES; LE_REFL]; REWRITE_TAC [ADD_CLAUSES; SUC_LE]]; FIRST_ASSUM ACCEPT_TAC]);; let zeckendorf_decode_fib_upper_bound = prove (`!l1 l2. zeckendorf (APPEND l1 l2) ==> decode_fib l1 < fibonacci (LENGTH l1 + 2)`, REPEAT GEN_TAC THEN SPEC_TAC (`l1 : bool list`, `l1 : bool list`) THEN LIST_INDUCT_TAC THENL [DISCH_THEN (K ALL_TAC) THEN REWRITE_TAC [decode_fib_nil; LENGTH; ADD_CLAUSES; fibonacci_def; LT_NZ] THEN REWRITE_TAC [ONE; NOT_SUC]; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN REWRITE_TAC [APPEND] THEN STRIP_TAC THEN MP_TAC (SPECL [`0`; `h : bool`; `t : bool list`; `l2 : bool list`] zeckendorf_decode_fib_dest_upper_bound) THEN ASM_REWRITE_TAC [decode_fib_def; ADD_CLAUSES; fibonacci_zero; fibonacci_one; GSYM fibonacci_add2] THEN SUBGOAL_THEN `fibonacci (if h then 1 else 2) = 1` SUBST1_TAC THENL [BOOL_CASES_TAC `h : bool` THEN REWRITE_TAC [fibonacci_one; fibonacci_two]; REWRITE_TAC [ONE; TWO; THREE; ADD_CLAUSES; LENGTH; LE_SUC_LT]]);; export_thm zeckendorf_decode_fib_upper_bound;; let bool_list_difference_lemma = prove (`!l1 l2. LENGTH l1 = LENGTH l2 /\ ~(l1 = l2) ==> ?k1 k2 h t. l1 = APPEND k1 (CONS h t) /\ l2 = APPEND k2 (CONS (~h) t)`, LIST_INDUCT_TAC THENL [LIST_INDUCT_TAC THENL [REWRITE_TAC []; REWRITE_TAC [LENGTH; NOT_SUC]]; ALL_TAC] THEN LIST_INDUCT_TAC THENL [REWRITE_TAC [LENGTH; NOT_SUC]; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN REWRITE_TAC [LENGTH; SUC_INJ; CONS_11; TAUT `!x y. ~(x /\ y) <=> (y /\ ~x) \/ ~y`] THEN STRIP_TAC THENL [EXISTS_TAC `[] : bool list` THEN EXISTS_TAC `[] : bool list` THEN EXISTS_TAC `h : bool` THEN EXISTS_TAC `t' : bool list` THEN ASM_REWRITE_TAC [APPEND; CONS_11] THEN MATCH_MP_TAC (TAUT `!x y. ~(y <=> x) ==> (x <=> ~y)`) THEN FIRST_ASSUM ACCEPT_TAC; ALL_TAC] THEN FIRST_X_ASSUM (MP_TAC o SPEC `t' : bool list`) THEN ASM_REWRITE_TAC [] THEN STRIP_TAC THEN EXISTS_TAC `CONS (h : bool) k1` THEN EXISTS_TAC `CONS (h' : bool) k2` THEN EXISTS_TAC `h'' : bool` THEN EXISTS_TAC `t'' : bool list` THEN ASM_REWRITE_TAC [APPEND; CONS_11]);; let zeckendorf_decode_fib_dominate = prove (`!l1 l2 t. LENGTH l1 = LENGTH l2 /\ zeckendorf (APPEND l1 (CONS F t)) /\ zeckendorf (APPEND l2 (CONS T t)) ==> decode_fib (APPEND l1 (CONS F t)) < decode_fib (APPEND l2 (CONS T t))`, REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [GSYM APPEND_SING] THEN REWRITE_TAC [APPEND_ASSOC] THEN ONCE_REWRITE_TAC [decode_fib_append] THEN ASM_REWRITE_TAC [LT_ADD_RCANCEL; LENGTH_APPEND; LENGTH] THEN REWRITE_TAC [decode_fib_append; decode_fib_dest_def; GSYM fibonacci_add2] THEN REWRITE_TAC [LET_DEF; LET_END_DEF; ADD_CLAUSES] THEN MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (LENGTH (l1 : bool list) + 2)` THEN STRIP_TAC THENL [MATCH_MP_TAC zeckendorf_decode_fib_upper_bound THEN EXISTS_TAC `CONS F t` THEN FIRST_ASSUM ACCEPT_TAC; ASM_REWRITE_TAC [LE_ADDR]]);; let zeckendorf_decode_fib_length_mono = prove (`!l1 l2. zeckendorf l1 /\ zeckendorf l2 /\ LENGTH l1 < LENGTH l2 ==> decode_fib l1 < decode_fib l2`, REPEAT STRIP_TAC THEN MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (LENGTH (l1 : bool list) + 2)` THEN CONJ_TAC THENL [MATCH_MP_TAC zeckendorf_decode_fib_upper_bound THEN EXISTS_TAC `[] : bool list` THEN ASM_REWRITE_TAC [APPEND_NIL]; ALL_TAC] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `fibonacci (LENGTH (l2 : bool list) + 1)` THEN CONJ_TAC THENL [MATCH_MP_TAC fibonacci_mono_imp THEN ASM_REWRITE_TAC [TWO; ONE; ADD_CLAUSES; LE_SUC_LT; LT_SUC]; ALL_TAC] THEN MATCH_MP_TAC zeckendorf_decode_fib_lower_bound THEN ASM_REWRITE_TAC [NULL_EQ_NIL] THEN STRIP_TAC THEN UNDISCH_TAC `LENGTH (l1 : bool list) < LENGTH (l2 : bool list)` THEN ASM_REWRITE_TAC [LENGTH; LT]);; export_thm zeckendorf_decode_fib_length_mono;; let zeckendorf_decode_fib_inj = prove (`!l1 l2. zeckendorf l1 /\ zeckendorf l2 /\ decode_fib l1 = decode_fib l2 ==> l1 = l2`, REPEAT GEN_TAC THEN REWRITE_TAC [GSYM LE_ANTISYM; GSYM NOT_LT] THEN REPEAT STRIP_TAC THEN SUBGOAL_THEN `LENGTH (l1 : bool list) = LENGTH (l2 : bool list)` MP_TAC THENL [REWRITE_TAC [GSYM LE_ANTISYM] THEN REWRITE_TAC [GSYM NOT_LT] THEN CONJ_TAC THENL [STRIP_TAC THEN UNDISCH_TAC `~(decode_fib l2 < decode_fib l1)` THEN REWRITE_TAC [] THEN MATCH_MP_TAC zeckendorf_decode_fib_length_mono THEN ASM_REWRITE_TAC []; STRIP_TAC THEN UNDISCH_TAC `~(decode_fib l1 < decode_fib l2)` THEN REWRITE_TAC [] THEN MATCH_MP_TAC zeckendorf_decode_fib_length_mono THEN ASM_REWRITE_TAC []]; ALL_TAC] THEN STRIP_TAC THEN MP_TAC (SPECL [`l1 : bool list`; `l2 : bool list`] bool_list_difference_lemma) THEN BOOL_CASES_TAC `l1 = (l2 : bool list)` THEN ASM_REWRITE_TAC [] THEN STRIP_TAC THEN ASM_CASES_TAC `h : bool` THENL [UNDISCH_TAC `~(decode_fib l2 < decode_fib l1)` THEN POP_ASSUM (SUBST_VAR_TAC o EQT_INTRO) THEN POP_ASSUM SUBST_VAR_TAC THEN POP_ASSUM SUBST_VAR_TAC THEN POP_ASSUM MP_TAC THEN POP_ASSUM (K ALL_TAC) THEN REPEAT (POP_ASSUM MP_TAC) THEN REWRITE_TAC [LENGTH_APPEND; LENGTH; EQ_ADD_RCANCEL] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC zeckendorf_decode_fib_dominate THEN ASM_REWRITE_TAC []; UNDISCH_TAC `~(decode_fib l1 < decode_fib l2)` THEN POP_ASSUM (SUBST_VAR_TAC o EQF_INTRO) THEN POP_ASSUM SUBST_VAR_TAC THEN POP_ASSUM SUBST_VAR_TAC THEN POP_ASSUM MP_TAC THEN POP_ASSUM (K ALL_TAC) THEN REPEAT (POP_ASSUM MP_TAC) THEN REWRITE_TAC [LENGTH_APPEND; LENGTH; EQ_ADD_RCANCEL] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC zeckendorf_decode_fib_dominate THEN ASM_REWRITE_TAC []]);; export_thm zeckendorf_decode_fib_inj;; let zeckendorf_encode_fib_mk = prove (`!n k l. ~NULL l /\ ((n < fibonacci (k + 1) /\ zeckendorf l) \/ (n < fibonacci (k + 2) /\ zeckendorf (CONS T l))) ==> zeckendorf (encode_fib_mk l n (fibonacci (k + 1)) (fibonacci k))`, REPEAT GEN_TAC THEN REWRITE_TAC [fibonacci_add2] THEN SPEC_TAC (`l : bool list`, `l : bool list`) THEN SPEC_TAC (`n : num`, `n : num`) THEN SPEC_TAC (`k : num`, `k : num`) THEN INDUCT_TAC THENL [REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN REWRITE_TAC [fibonacci_def] THEN STRIP_TAC THEN MATCH_MP_TAC zeckendorf_cons_imp THEN EXISTS_TAC `T` THEN FIRST_ASSUM ACCEPT_TAC; ALL_TAC] THEN REPEAT GEN_TAC THEN REWRITE_TAC [GSYM ADD1; fibonacci_suc_suc; NOT_SUC] THEN REWRITE_TAC [ADD1] THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN SUBGOAL_THEN `fibonacci (k + 1) = 0 <=> F` SUBST1_TAC THENL [REWRITE_TAC [fibonacci_eq_zero; GSYM ADD1; NOT_SUC]; ALL_TAC] THEN REWRITE_TAC [] THEN REWRITE_TAC [ADD_SUB2] THEN STRIP_TAC THENL [ASM_REWRITE_TAC [GSYM NOT_LT] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC [NULL] THEN DISJ2_TAC THEN ASM_REWRITE_TAC [zeckendorf_def; NULL; HD]; ALL_TAC] THEN COND_CASES_TAC THENL [FIRST_X_ASSUM MATCH_MP_TAC THEN CONJ_TAC THENL [REWRITE_TAC [NULL]; DISJ1_TAC THEN CONJ_TAC THENL [POP_ASSUM (MP_TAC o REWRITE_RULE [LE_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN REWRITE_TAC [ADD_SUB2] THEN POP_ASSUM (K ALL_TAC) THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [LT_ADD_LCANCEL]; FIRST_ASSUM ACCEPT_TAC]]; FIRST_X_ASSUM MATCH_MP_TAC THEN CONJ_TAC THENL [REWRITE_TAC [NULL]; DISJ2_TAC THEN ASM_REWRITE_TAC [GSYM NOT_LE] THEN POP_ASSUM (K ALL_TAC) THEN POP_ASSUM MP_TAC THEN POP_ASSUM (K ALL_TAC) THEN ASM_REWRITE_TAC [zeckendorf_def; NULL; HD] THEN STRIP_TAC]]);; let zeckendorf_encode_fib_find = prove (`!n k. fibonacci (k + 1) <= n ==> zeckendorf (encode_fib_find n (fibonacci (k + 1)) (fibonacci k))`, REPEAT STRIP_TAC THEN SUBGOAL_THEN `?j. fibonacci (j + 1) <= n /\ n < fibonacci (j + 2) /\ k <= j` MP_TAC THENL [MP_TAC (SPEC `n : num` fibonacci_interval) THEN STRIP_TAC THEN SUBGOAL_THEN `k + 1 < SUC k'` (MP_TAC o REWRITE_RULE [LT_SUC_LE; LE_EXISTS]) THENL [REWRITE_TAC [ADD1] THEN MATCH_MP_TAC fibonacci_strictly_mono_imp' THEN MATCH_MP_TAC LET_TRANS THEN EXISTS_TAC `n : num` THEN ASM_REWRITE_TAC []; ALL_TAC] THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN EXISTS_TAC `k + d : num` THEN POP_ASSUM MP_TAC THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [ADD_CLAUSES; ONE; TWO; LE_ADD] THEN REPEAT STRIP_TAC THEN FIRST_ASSUM ACCEPT_TAC; ALL_TAC] THEN STRIP_TAC THEN POP_ASSUM (MP_TAC o REWRITE_RULE [LE_EXISTS]) THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN POP_ASSUM MP_TAC THEN POP_ASSUM MP_TAC THEN POP_ASSUM (K ALL_TAC) THEN REWRITE_TAC [IMP_IMP] THEN SPEC_TAC (`k : num`, `k : num`) THEN SPEC_TAC (`d : num`, `d : num`) THEN INDUCT_TAC THENL [REWRITE_TAC [ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [GSYM fibonacci_add2] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF] THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN ASM_REWRITE_TAC [fibonacci_eq_zero] THEN COND_CASES_TAC THENL [ACCEPT_TAC zeckendorf_nil; ALL_TAC] THEN REPEAT (POP_ASSUM MP_TAC) THEN REWRITE_TAC [fibonacci_def] THEN MP_TAC (SPEC `k : num` num_CASES) THEN STRIP_TAC THENL [ASM_REWRITE_TAC []; ALL_TAC] THEN POP_ASSUM SUBST_VAR_TAC THEN REWRITE_TAC [ONE; TWO; NOT_SUC; ADD_CLAUSES] THEN REWRITE_TAC [LE_EXISTS] THEN DISCH_THEN (CHOOSE_THEN SUBST_VAR_TAC) THEN REWRITE_TAC [LT_ADD_LCANCEL; ADD_SUB2] THEN REWRITE_TAC [fibonacci_suc_suc; ADD_SUB2] THEN REWRITE_TAC [ADD1] THEN STRIP_TAC THEN MATCH_MP_TAC zeckendorf_encode_fib_mk THEN STRIP_TAC THENL [REWRITE_TAC [NULL]; ALL_TAC] THEN DISJ1_TAC THEN ASM_REWRITE_TAC [zeckendorf_def; NULL; HD]; ALL_TAC] THEN POP_ASSUM MP_TAC THEN REWRITE_TAC [ONE; TWO; ADD_CLAUSES] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [encode_fib_find_def] THEN REWRITE_TAC [GSYM fibonacci_suc_suc] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF] THEN COND_CASES_TAC THENL [SUBGOAL_THEN `F` CONTR_TAC THEN UNDISCH_TAC `fibonacci (SUC (SUC (k + d))) <= n` THEN REWRITE_TAC [NOT_LE] THEN MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `fibonacci (SUC (SUC k))` THEN ASM_REWRITE_TAC [] THEN MATCH_MP_TAC fibonacci_mono_imp THEN REWRITE_TAC [LE_SUC; LE_ADD]; ALL_TAC] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC [ADD_CLAUSES]);; let zeckendorf_encode_fib = prove (`!n. zeckendorf (encode_fib n)`, GEN_TAC THEN REWRITE_TAC [encode_fib_def] THEN MP_TAC (SPEC `n : num` num_CASES) THEN STRIP_TAC THENL [ONCE_REWRITE_TAC [encode_fib_find_def] THEN ASM_REWRITE_TAC [LET_DEF; LET_END_DEF; ONE; LT_SUC_LE; LE_0; ADD_CLAUSES] THEN ONCE_REWRITE_TAC [encode_fib_mk_def] THEN REWRITE_TAC [zeckendorf_nil]; MP_TAC (SPECL [`n : num`; `0`] zeckendorf_encode_fib_find) THEN REWRITE_TAC [ADD_CLAUSES; fibonacci_def] THEN DISCH_THEN MATCH_MP_TAC THEN ASM_REWRITE_TAC [ONE; LE_SUC; LE_0]]);; export_thm zeckendorf_encode_fib;; let zeckendorf_decode_encode_fib = prove (`!l. zeckendorf l <=> encode_fib (decode_fib l) = l`, GEN_TAC THEN EQ_TAC THENL [STRIP_TAC THEN MATCH_MP_TAC zeckendorf_decode_fib_inj THEN ASM_REWRITE_TAC [zeckendorf_encode_fib; encode_decode_fib]; DISCH_THEN (SUBST1_TAC o SYM) THEN MATCH_ACCEPT_TAC zeckendorf_encode_fib]);; export_thm zeckendorf_decode_encode_fib;; let decode_fib_dest_src = decode_fib_dest_def;; export_thm decode_fib_dest_src;; let decode_fib_src = prove (`decode_fib = decode_fib_dest 1 0`, REWRITE_TAC [FUN_EQ_THM; decode_fib_def]);; export_thm decode_fib_src;; let encode_fib_src = prove (`encode_fib = \n. encode_fib_find n 1 0`, REWRITE_TAC [FUN_EQ_THM; encode_fib_def]);; export_thm encode_fib_src;; let zeckendorf_src = prove (`(zeckendorf [] <=> T) /\ !h t. zeckendorf (CONS h t) <=> if NULL t then h else ~(h /\ HD t) /\ zeckendorf t`, REWRITE_TAC [zeckendorf_def]);; export_thm zeckendorf_src;; HOL Light theorem names . export_theory "natural-fibonacci-hol-light-thm";; export_theory_thm_names "natural-fibonacci" ["natural-fibonacci-def"; "natural-fibonacci-thm"];; export_theory "natural-fibonacci-haskell-src";; Haskell tests . export_theory "natural-fibonacci-haskell-test";;
819ea14307d9daa5be3dd7b27de5a67a043341273abf06f7ddb3071836a916c3
elastic/eui-cljs
eui_panel_styles.cljs
(ns eui.eui-panel-styles (:require ["@elastic/eui/lib/components/panel/panel.style.js" :as eui])) (def euiPanelStyles eui/euiPanelStyles)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/eui_panel_styles.cljs
clojure
(ns eui.eui-panel-styles (:require ["@elastic/eui/lib/components/panel/panel.style.js" :as eui])) (def euiPanelStyles eui/euiPanelStyles)
ed2de471715f60790cef7d6250d4be7d2bf466589b04ba6332dff9689e60063e
facebook/pyre-check
callableTest.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open OUnit2 open IntegrationTest let test_higher_order_callables context = let assert_type_errors = assert_type_errors ~context in assert_type_errors {| import typing def foo(f: typing.Callable[[int], str]) -> str: return f(1) def callme(x: int) -> str: return "" foo(callme) |} []; assert_type_errors {| import typing def foo(f: typing.Callable[..., str]) -> str: return f(1) def callme(x: int) -> str: return "" foo(callme) |} []; assert_type_errors {| import typing T = typing.TypeVar("T") def foo(f: typing.Callable[[int], T]) -> typing.Callable[[str], T]: def takes_str(s: str) -> T: return f(int(s)) return takes_str def callme(x: int) -> str: return "" reveal_type(foo(callme)) |} [ "Revealed type [-1]: Revealed type for `test.foo(test.callme)` is `typing.Callable[[str], \ str]`."; ]; assert_type_errors {| import typing T = typing.TypeVar("T") def foo(f: typing.Callable[..., T]) -> typing.Callable[..., T]: def takes_str(s: str) -> T: return f(int(s)) return takes_str def callme(x: int) -> str: return "" reveal_type(foo(callme)) |} [ "Revealed type [-1]: Revealed type for `test.foo(test.callme)` is `typing.Callable[..., str]`."; ] let test_union_of_callables context = assert_type_errors ~context {| import typing def baz(x: typing.Union[typing.Callable[[int], typing.Any], typing.Callable[..., typing.Any]]) -> None: reveal_type(x) x(1) |} [ "Missing parameter annotation [2]: Parameter `x` must have a type that does not contain `Any`."; "Revealed type [-1]: Revealed type for `x` is `typing.Union[typing.Callable[[int], \ typing.Any], typing.Callable[..., typing.Any]]`."; ] let test_callable_attribute_access context = assert_type_errors ~context {| def foo() -> int: return 0 def bar() -> None: foo.attr |} ["Undefined attribute [16]: Callable `foo` has no attribute `attr`."]; assert_type_errors ~context {| def foo() -> None: anon = lambda x: 0 anon.attr |} ["Undefined attribute [16]: Anonymous callable has no attribute `attr`."]; (* We filter errors related to patching. *) assert_default_type_errors ~context {| from unittest.mock import Mock from unittest import TestCase class C: def foo(self) -> int: ... class Test(TestCase): def test_foo(self) -> None: c = C() c.foo = Mock() c.foo.assert_not_called() |} []; assert_default_type_errors ~context {| from unittest import TestCase def patch(item): ... class C: def foo(self) -> int: ... class Test(TestCase): def test_foo(self) -> None: x = patch("os.path.abspath") x.assert_not_called() x.assert_called_once() |} []; assert_type_errors ~context {| def foo() -> None: pass def bar() -> None: a = foo.__ne__ b = foo.__module__ c = foo.__str__ reveal_type(a) reveal_type(b) reveal_type(c) |} [ "Revealed type [-1]: Revealed type for `a` is \ `BoundMethod[typing.Callable(object.__ne__)[[Named(self, object), Named(o, object)], bool], \ typing.Callable(foo)[[], None]]`."; "Revealed type [-1]: Revealed type for `b` is `str`."; "Revealed type [-1]: Revealed type for `c` is \ `BoundMethod[typing.Callable(object.__str__)[[Named(self, object)], str], \ typing.Callable(foo)[[], None]]`."; ]; assert_type_errors ~context {| def foo() -> None: pass def bar() -> None: foo.nonsense = 1 |} ["Undefined attribute [16]: Callable `foo` has no attribute `nonsense`."]; ` _ _ qualname _ _ ` is supported for all functions , including lambdas , as per PEP 3155 . assert_type_errors ~context {| def foo() -> None: pass def bar() -> str: return foo.__qualname__ |} []; assert_type_errors ~context {| def foo() -> str: f = lambda x: 0 return f.__qualname__ |} []; Pyre unsoundly assumes that all have , even though objects with ` _ _ call _ _ ` * do n't necessarily have one . * don't necessarily have one. *) assert_type_errors ~context {| from typing import Callable class C: def __call__(self) -> int: return 0 def foo(f: Callable[[], int]) -> str: return f.__qualname__ # This fails in the runtime, but type checks. foo(C()) |} []; () let test_position_only_parameters context = let assert_type_errors = assert_type_errors ~context in assert_type_errors {| def foo(a: int, b: int, /) -> None: pass foo(1, 2) |} []; assert_type_errors {| def foo(a: int, b: int, /, c: str) -> None: pass foo(1, 2, c="a") |} []; assert_type_errors {| def foo(a: int, b: int, /, c: str, *, d: int) -> None: pass foo(1, 2, "a", 1) |} ["Too many arguments [19]: Call `foo` expects 3 positional arguments, 4 were provided."]; assert_type_errors {| def foo(a: int, b: int, /, c: str, *, d: int) -> None: pass foo(1, 2, "a", d=1) |} [] let test_bound_method context = let assert_type_errors = assert_type_errors ~context in assert_type_errors {| from typing import Callable def foo(bm: BoundMethod[Callable[[int, str], bool], int]) -> None: c = bm.__call__ reveal_type(c) |} ["Revealed type [-1]: Revealed type for `c` is `typing.Callable[[str], bool]`."]; assert_type_errors {| from typing import Callable # This type is invalid, but we strip the first argument anyway def foo(bm: BoundMethod[Callable[[int, str], bool], str]) -> None: c = bm.__call__ reveal_type(c) |} ["Revealed type [-1]: Revealed type for `c` is `typing.Callable[[str], bool]`."]; assert_type_errors {| from typing import Callable # pyre-ignore[13]: __call__ not initialized class Bar: # pyre-ignore[15]: inconsistent with type.__call__ __call__: BoundMethod[Callable[[Bar, str], bool], Bar] def foo(bar: Bar) -> None: c = bar("A") reveal_type(c) bar(1) |} [ "Revealed type [-1]: Revealed type for `c` is `bool`."; "Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \ `str` but got `int`."; ]; assert_type_errors {| from typing import Callable class Bar: # pyre-ignore[15]: inconsistent with object.__init__ __init__: BoundMethod[Callable[[Bar, str], None], Bar] def foo() -> None: c = Bar("A") reveal_type(c) Bar(1) |} [ "Revealed type [-1]: Revealed type for `c` is `Bar`."; "Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \ `str` but got `int`."; ]; assert_type_errors {| from typing import * def foo(x: int, y:str) -> None: pass def bar(b: bool, s: str) -> None: # pyre-ignore[10]: ensure mismatch errors appear after undefined arguments foo(unknown, b) |} [ "Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected `int` \ but got `unknown`."; "Incompatible parameter type [6]: In call `foo`, for 2nd positional argument, expected `str` \ but got `bool`."; ]; assert_type_errors {| from typing import * from pyre_extensions import Unpack, TypeVarTuple Ts = TypeVarTuple("Ts") def foo(x: Tuple[Unpack[Ts]], y: Tuple[Unpack[Ts]], z: Tuple[Unpack[Ts]]) -> None: pass def bar() -> None: x = (1,2,3) y = (4, 5) z = ("hello") foo(x, y, z) |} [ "Incompatible parameter type [6]: In call `foo`, for 2nd positional argument, expected \ `typing.Tuple[*test.Ts]` but got `Tuple[int, int]`."; "Incompatible parameter type [6]: In call `foo`, for 3rd positional argument, expected \ `typing.Tuple[*test.Ts]` but got `str`."; ]; () let test_reexported_callable context = let assert_type_errors = assert_type_errors ~context in assert_type_errors ~update_environment_with: [ { handle = "reexports_callable.pyi"; source = {| from typing import Callable as Callable |}; }; ] {| from typing import Any, TypeVar from reexports_callable import Callable _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) def identity_for_function(funcobj: _FuncT) -> _FuncT: ... class Foo: @identity_for_function def my_method(self) -> int: ... def main() -> None: f1: Callable[[int], str] reveal_type(f1) reveal_type(Foo.my_method) |} [ "Prohibited any [33]: Type variable `_FuncT` cannot have a bound containing `Any`."; "Revealed type [-1]: Revealed type for `f1` is `typing.Callable[[int], str]`."; "Revealed type [-1]: Revealed type for `test.Foo.my_method` is \ `typing.Callable(Foo.my_method)[[Named(self, Foo)], int]`."; ]; assert_type_errors ~update_environment_with: [ { handle = "reexports_callable.pyi"; source = {| from typing import Callable as Callable, List as List |}; }; ] {| from typing import Any, TypeVar import typing from reexports_callable import Callable, List MyCallable = typing.Callable F = MyCallable[..., Any] G = MyCallable[[int], Any] f1: F f2: G |} [ "Invalid type parameters [24]: Generic type `typing.Callable` expects 2 type parameters."; "Prohibited any [33]: `F` cannot alias to a type containing `Any`."; "Prohibited any [33]: `G` cannot alias to a type containing `Any`."; ]; () let () = "callable" >::: [ "higher_order_callables" >:: test_higher_order_callables; "union_of_callables" >:: test_union_of_callables; "callable_attribute_access" >:: test_callable_attribute_access; "position_only_parameters" >:: test_position_only_parameters; "bound_method" >:: test_bound_method; "reexported_callable" >:: test_reexported_callable; ] |> Test.run
null
https://raw.githubusercontent.com/facebook/pyre-check/518f5ef44d7079c68b273ff8bcbfd4a8bdd985d6/source/analysis/test/integration/callableTest.ml
ocaml
We filter errors related to patching.
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open OUnit2 open IntegrationTest let test_higher_order_callables context = let assert_type_errors = assert_type_errors ~context in assert_type_errors {| import typing def foo(f: typing.Callable[[int], str]) -> str: return f(1) def callme(x: int) -> str: return "" foo(callme) |} []; assert_type_errors {| import typing def foo(f: typing.Callable[..., str]) -> str: return f(1) def callme(x: int) -> str: return "" foo(callme) |} []; assert_type_errors {| import typing T = typing.TypeVar("T") def foo(f: typing.Callable[[int], T]) -> typing.Callable[[str], T]: def takes_str(s: str) -> T: return f(int(s)) return takes_str def callme(x: int) -> str: return "" reveal_type(foo(callme)) |} [ "Revealed type [-1]: Revealed type for `test.foo(test.callme)` is `typing.Callable[[str], \ str]`."; ]; assert_type_errors {| import typing T = typing.TypeVar("T") def foo(f: typing.Callable[..., T]) -> typing.Callable[..., T]: def takes_str(s: str) -> T: return f(int(s)) return takes_str def callme(x: int) -> str: return "" reveal_type(foo(callme)) |} [ "Revealed type [-1]: Revealed type for `test.foo(test.callme)` is `typing.Callable[..., str]`."; ] let test_union_of_callables context = assert_type_errors ~context {| import typing def baz(x: typing.Union[typing.Callable[[int], typing.Any], typing.Callable[..., typing.Any]]) -> None: reveal_type(x) x(1) |} [ "Missing parameter annotation [2]: Parameter `x` must have a type that does not contain `Any`."; "Revealed type [-1]: Revealed type for `x` is `typing.Union[typing.Callable[[int], \ typing.Any], typing.Callable[..., typing.Any]]`."; ] let test_callable_attribute_access context = assert_type_errors ~context {| def foo() -> int: return 0 def bar() -> None: foo.attr |} ["Undefined attribute [16]: Callable `foo` has no attribute `attr`."]; assert_type_errors ~context {| def foo() -> None: anon = lambda x: 0 anon.attr |} ["Undefined attribute [16]: Anonymous callable has no attribute `attr`."]; assert_default_type_errors ~context {| from unittest.mock import Mock from unittest import TestCase class C: def foo(self) -> int: ... class Test(TestCase): def test_foo(self) -> None: c = C() c.foo = Mock() c.foo.assert_not_called() |} []; assert_default_type_errors ~context {| from unittest import TestCase def patch(item): ... class C: def foo(self) -> int: ... class Test(TestCase): def test_foo(self) -> None: x = patch("os.path.abspath") x.assert_not_called() x.assert_called_once() |} []; assert_type_errors ~context {| def foo() -> None: pass def bar() -> None: a = foo.__ne__ b = foo.__module__ c = foo.__str__ reveal_type(a) reveal_type(b) reveal_type(c) |} [ "Revealed type [-1]: Revealed type for `a` is \ `BoundMethod[typing.Callable(object.__ne__)[[Named(self, object), Named(o, object)], bool], \ typing.Callable(foo)[[], None]]`."; "Revealed type [-1]: Revealed type for `b` is `str`."; "Revealed type [-1]: Revealed type for `c` is \ `BoundMethod[typing.Callable(object.__str__)[[Named(self, object)], str], \ typing.Callable(foo)[[], None]]`."; ]; assert_type_errors ~context {| def foo() -> None: pass def bar() -> None: foo.nonsense = 1 |} ["Undefined attribute [16]: Callable `foo` has no attribute `nonsense`."]; ` _ _ qualname _ _ ` is supported for all functions , including lambdas , as per PEP 3155 . assert_type_errors ~context {| def foo() -> None: pass def bar() -> str: return foo.__qualname__ |} []; assert_type_errors ~context {| def foo() -> str: f = lambda x: 0 return f.__qualname__ |} []; Pyre unsoundly assumes that all have , even though objects with ` _ _ call _ _ ` * do n't necessarily have one . * don't necessarily have one. *) assert_type_errors ~context {| from typing import Callable class C: def __call__(self) -> int: return 0 def foo(f: Callable[[], int]) -> str: return f.__qualname__ # This fails in the runtime, but type checks. foo(C()) |} []; () let test_position_only_parameters context = let assert_type_errors = assert_type_errors ~context in assert_type_errors {| def foo(a: int, b: int, /) -> None: pass foo(1, 2) |} []; assert_type_errors {| def foo(a: int, b: int, /, c: str) -> None: pass foo(1, 2, c="a") |} []; assert_type_errors {| def foo(a: int, b: int, /, c: str, *, d: int) -> None: pass foo(1, 2, "a", 1) |} ["Too many arguments [19]: Call `foo` expects 3 positional arguments, 4 were provided."]; assert_type_errors {| def foo(a: int, b: int, /, c: str, *, d: int) -> None: pass foo(1, 2, "a", d=1) |} [] let test_bound_method context = let assert_type_errors = assert_type_errors ~context in assert_type_errors {| from typing import Callable def foo(bm: BoundMethod[Callable[[int, str], bool], int]) -> None: c = bm.__call__ reveal_type(c) |} ["Revealed type [-1]: Revealed type for `c` is `typing.Callable[[str], bool]`."]; assert_type_errors {| from typing import Callable # This type is invalid, but we strip the first argument anyway def foo(bm: BoundMethod[Callable[[int, str], bool], str]) -> None: c = bm.__call__ reveal_type(c) |} ["Revealed type [-1]: Revealed type for `c` is `typing.Callable[[str], bool]`."]; assert_type_errors {| from typing import Callable # pyre-ignore[13]: __call__ not initialized class Bar: # pyre-ignore[15]: inconsistent with type.__call__ __call__: BoundMethod[Callable[[Bar, str], bool], Bar] def foo(bar: Bar) -> None: c = bar("A") reveal_type(c) bar(1) |} [ "Revealed type [-1]: Revealed type for `c` is `bool`."; "Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \ `str` but got `int`."; ]; assert_type_errors {| from typing import Callable class Bar: # pyre-ignore[15]: inconsistent with object.__init__ __init__: BoundMethod[Callable[[Bar, str], None], Bar] def foo() -> None: c = Bar("A") reveal_type(c) Bar(1) |} [ "Revealed type [-1]: Revealed type for `c` is `Bar`."; "Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \ `str` but got `int`."; ]; assert_type_errors {| from typing import * def foo(x: int, y:str) -> None: pass def bar(b: bool, s: str) -> None: # pyre-ignore[10]: ensure mismatch errors appear after undefined arguments foo(unknown, b) |} [ "Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected `int` \ but got `unknown`."; "Incompatible parameter type [6]: In call `foo`, for 2nd positional argument, expected `str` \ but got `bool`."; ]; assert_type_errors {| from typing import * from pyre_extensions import Unpack, TypeVarTuple Ts = TypeVarTuple("Ts") def foo(x: Tuple[Unpack[Ts]], y: Tuple[Unpack[Ts]], z: Tuple[Unpack[Ts]]) -> None: pass def bar() -> None: x = (1,2,3) y = (4, 5) z = ("hello") foo(x, y, z) |} [ "Incompatible parameter type [6]: In call `foo`, for 2nd positional argument, expected \ `typing.Tuple[*test.Ts]` but got `Tuple[int, int]`."; "Incompatible parameter type [6]: In call `foo`, for 3rd positional argument, expected \ `typing.Tuple[*test.Ts]` but got `str`."; ]; () let test_reexported_callable context = let assert_type_errors = assert_type_errors ~context in assert_type_errors ~update_environment_with: [ { handle = "reexports_callable.pyi"; source = {| from typing import Callable as Callable |}; }; ] {| from typing import Any, TypeVar from reexports_callable import Callable _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) def identity_for_function(funcobj: _FuncT) -> _FuncT: ... class Foo: @identity_for_function def my_method(self) -> int: ... def main() -> None: f1: Callable[[int], str] reveal_type(f1) reveal_type(Foo.my_method) |} [ "Prohibited any [33]: Type variable `_FuncT` cannot have a bound containing `Any`."; "Revealed type [-1]: Revealed type for `f1` is `typing.Callable[[int], str]`."; "Revealed type [-1]: Revealed type for `test.Foo.my_method` is \ `typing.Callable(Foo.my_method)[[Named(self, Foo)], int]`."; ]; assert_type_errors ~update_environment_with: [ { handle = "reexports_callable.pyi"; source = {| from typing import Callable as Callable, List as List |}; }; ] {| from typing import Any, TypeVar import typing from reexports_callable import Callable, List MyCallable = typing.Callable F = MyCallable[..., Any] G = MyCallable[[int], Any] f1: F f2: G |} [ "Invalid type parameters [24]: Generic type `typing.Callable` expects 2 type parameters."; "Prohibited any [33]: `F` cannot alias to a type containing `Any`."; "Prohibited any [33]: `G` cannot alias to a type containing `Any`."; ]; () let () = "callable" >::: [ "higher_order_callables" >:: test_higher_order_callables; "union_of_callables" >:: test_union_of_callables; "callable_attribute_access" >:: test_callable_attribute_access; "position_only_parameters" >:: test_position_only_parameters; "bound_method" >:: test_bound_method; "reexported_callable" >:: test_reexported_callable; ] |> Test.run
267b98750414a4c2f5e455f03ac3f0756101a60e74f6314d596cdead07a8f976
ocsigen/js_of_ocaml
ppx_js_rewriter.mli
Js_of_ocaml library * / * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (**/**) val mapper : Ast_mapper.mapper
null
https://raw.githubusercontent.com/ocsigen/js_of_ocaml/58210fabc947c4839b6e71ffbbf353a4ede0dbb7/ppx/ppx_js/lib/ppx_js_rewriter.mli
ocaml
*/*
Js_of_ocaml library * / * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val mapper : Ast_mapper.mapper
efb97bc93279972240da79aed5555e36634005738a609daadec69a2f1d92aba5
Raynes/lein-bin
project.clj
(defproject lein-bin "0.3.4" :description "A leiningen plugin for generating standalone console executables for your project." :url "-bin" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[me.raynes/fs "1.4.0"]] :eval-in-leiningen true)
null
https://raw.githubusercontent.com/Raynes/lein-bin/c0fd6afc39a296ac6f9f5f485592df9867da1a0e/project.clj
clojure
(defproject lein-bin "0.3.4" :description "A leiningen plugin for generating standalone console executables for your project." :url "-bin" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[me.raynes/fs "1.4.0"]] :eval-in-leiningen true)
ada9ccd10522d7e6e1d207dfdb2b3bfe6189ff1c9fd0f02e573128851675c6c6
fresnel/fresnel
Internal.hs
module Fresnel.Prism.Internal ( IsPrism ) where import Control.Arrow (Kleisli) import Data.Profunctor (Choice, Forget, Star) import Fresnel.Iso.Internal import Fresnel.Profunctor.OptionalStar (OptionalStar) import Fresnel.Profunctor.Recall (Recall) class (IsIso p, Choice p) => IsPrism p instance IsPrism (->) instance Monad m => IsPrism (Kleisli m) instance Monoid r => IsPrism (Forget r) instance IsPrism (Recall e) instance Applicative f => IsPrism (Star f) instance Functor f => IsPrism (OptionalStar f)
null
https://raw.githubusercontent.com/fresnel/fresnel/8f0d267779703049568694834c25f619034ca74d/fresnel/src/Fresnel/Prism/Internal.hs
haskell
module Fresnel.Prism.Internal ( IsPrism ) where import Control.Arrow (Kleisli) import Data.Profunctor (Choice, Forget, Star) import Fresnel.Iso.Internal import Fresnel.Profunctor.OptionalStar (OptionalStar) import Fresnel.Profunctor.Recall (Recall) class (IsIso p, Choice p) => IsPrism p instance IsPrism (->) instance Monad m => IsPrism (Kleisli m) instance Monoid r => IsPrism (Forget r) instance IsPrism (Recall e) instance Applicative f => IsPrism (Star f) instance Functor f => IsPrism (OptionalStar f)
d83c09862526a3be6003b5eb7a480387a30a23f0959a0ca2cfcd460b914b64f6
mirage/ocaml-xenstore-server
perms.mli
* Copyright ( C ) Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) open Xenstore type t [@@deriving sexp] (** A role containing a set of privileges *) val superuser: t (** The [superuser] role has all privileges *) val of_domain : int -> t (** The role associated with a specific domain id *) val restrict: t -> int -> t * [ restrict role domid ] returns a new role which contains the subset of [ role ] which applies to domain [ domid ] of [role] which applies to domain [domid] *) val set_target: t -> int -> t * [ set_target role domid ] needs rationalising type permission = | READ (** ability to read the value associated with a node *) | WRITE (** ability to modify the value associated with a node *) * ability to change the ACL associated with a node | DEBUG (** ability to invoke debug operations *) | INTRODUCE (** ability to grant access to other domains *) | ISINTRODUCED (** ability to query whether a domain has been introduced *) | RESUME (** ability to restore access to previously shutdown domains *) | RELEASE (** ability to revoke access from other domains *) * ability to allow one domain to impersonate a specific other | RESTRICT (** ability to imperonate a specific other domain *) | CONFIGURE (** ability to view/edit the daemon configuration *) exception Permission_denied (** Thrown by the [check] function if role does not have a specific permission *) val check: t -> permission -> Protocol.ACL.t -> bool (** [check role permission acl] returns [true] if [role] has [permission] according to the access control list [acl] *) val has: t -> permission -> bool (** [has role permission] returns true if [role] has [permission], false otherwise *)
null
https://raw.githubusercontent.com/mirage/ocaml-xenstore-server/2a8ae397d2f9291107b5d9e9cfc6085fde8c0982/server/perms.mli
ocaml
* A role containing a set of privileges * The [superuser] role has all privileges * The role associated with a specific domain id * ability to read the value associated with a node * ability to modify the value associated with a node * ability to invoke debug operations * ability to grant access to other domains * ability to query whether a domain has been introduced * ability to restore access to previously shutdown domains * ability to revoke access from other domains * ability to imperonate a specific other domain * ability to view/edit the daemon configuration * Thrown by the [check] function if role does not have a specific permission * [check role permission acl] returns [true] if [role] has [permission] according to the access control list [acl] * [has role permission] returns true if [role] has [permission], false otherwise
* Copyright ( C ) Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) open Xenstore type t [@@deriving sexp] val superuser: t val of_domain : int -> t val restrict: t -> int -> t * [ restrict role domid ] returns a new role which contains the subset of [ role ] which applies to domain [ domid ] of [role] which applies to domain [domid] *) val set_target: t -> int -> t * [ set_target role domid ] needs rationalising type permission = * ability to change the ACL associated with a node * ability to allow one domain to impersonate a specific other exception Permission_denied val check: t -> permission -> Protocol.ACL.t -> bool val has: t -> permission -> bool
851c1599f89c4c6db15cda87678eabe9959adb61df1df8a4a249a5b78e0bc27d
ucsd-progsys/dsolve
na_bsearch.ml
let bsearch key vec = let rec look lo hi = let hi_minus = hi - 1 in if lo < hi_minus then let hl = hi + lo in let m = hl / 2 in let x = Junkarray2.get vec m in let diff = key - x in let m_plus = m + 1 in let m_minus = m - 1 in (if diff < 0 then look lo m_minus else if 0 < diff then look m_plus hi else if key = x then m else -1) else -1 in let sv = Junkarray2.length vec in let sv_minus = sv - 1 in look 0 sv_minus let driver = let _ = Random.init 555 in let sz = Random.int 10 in let sz_plus = sz + 2 in let ar = Junkarray2.make sz_plus 0 in bsearch 5 ar
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/tests/POPL2010/na_bsearch.ml
ocaml
let bsearch key vec = let rec look lo hi = let hi_minus = hi - 1 in if lo < hi_minus then let hl = hi + lo in let m = hl / 2 in let x = Junkarray2.get vec m in let diff = key - x in let m_plus = m + 1 in let m_minus = m - 1 in (if diff < 0 then look lo m_minus else if 0 < diff then look m_plus hi else if key = x then m else -1) else -1 in let sv = Junkarray2.length vec in let sv_minus = sv - 1 in look 0 sv_minus let driver = let _ = Random.init 555 in let sz = Random.int 10 in let sz_plus = sz + 2 in let ar = Junkarray2.make sz_plus 0 in bsearch 5 ar
2e1b68fcfd1ae5698c04be960dbd3f9f08f590049573f2ce4b455654706af0f2
kurtharriger/shadow-cljs-reframe-template
dom.cljs
(ns cljsjs.react.dom (:require ["react-dom" :as react-dom])) (js/goog.exportSymbol "ReactDOM" react-dom)
null
https://raw.githubusercontent.com/kurtharriger/shadow-cljs-reframe-template/cfeb1dc2ed89a3e4289aa5dee01f80d2a1e89403/src/cljs/cljsjs/react/dom.cljs
clojure
(ns cljsjs.react.dom (:require ["react-dom" :as react-dom])) (js/goog.exportSymbol "ReactDOM" react-dom)
fc1e8d813100e34943130ccbcd0f0fec00cb7dc2092eb9b836e5fe1389276d16
directrix1/DuplicateBridgeTeamSteele
basiclex.lisp
(in-package "ACL2") (include-book "list-utilities" :dir :teachpacks) ; ds = delimiters to look for (list) ; xs = object to search in (list) ( split - at - delimiter ds xs ) = ( before at+ ) ; where before = longest prefix of xs with no values from ds (list) ; at+ = rest of xs (list) (defun split-at-delimiter (ds xs) (if (or (endp xs) (member-equal (car xs) ds)) (list nil xs) (let* ((cdr-split (split-at-delimiter ds (cdr xs)))) (list (cons (car xs) (car cdr-split)) (cadr cdr-split))))) ; ps = list of signals to pass by (no constraints on signals) ; xs = list of signals (no constraints on signals) ( span ps xs ) = list of two elements 1 longest prefix of xs containing only signals from ps 2 rest of xs (defun span (ps xs) (if (or (endp xs) (not (member-equal (car xs) ps))) (list nil xs) (let* ((cdr-span (span ps (cdr xs)))) (list (cons (car xs) (car cdr-span)) (cadr cdr-span))))) ; ps = prefix to look for (list) ; xs = object to search in (list) ( splitoff - prefix ) = ( ps - matching ps - af - match xs - af - match ) ; where ps-matching = longest ps prefix matching xs prefix (list) ps - af - match = rest of ps ( list ) ; xs-af-match = non-matching suffix of xs (list) Note : ps - af - match = nil means ps is a prefix of xs (defun splitoff-prefix (ps xs) (if (and (consp ps) (consp xs) (equal (car ps) (car xs))) (let* ((3way (splitoff-prefix (cdr ps) (cdr xs))) (ps-matching (car 3way)) (ps-af-match (cadr 3way)) (xs-af-match (caddr 3way))) (list (cons (car ps) ps-matching) ps-af-match xs-af-match)) (list nil ps xs))) ; ps = prefix to look for (list of standard, upper-case characters) ; xs = object to search in (list) ( splitoff - prefix - upr ps xs ) = ( ps - matching ps - af - match xs - af - match ) ; where ps-matching = longest ps prefix matching xs prefix (list) ps - af - match = rest of ps ( list ) ; xs-af-match = non-matching suffix of xs (list) Notes : 1 . search is not sensitive to case of letters in xs 2 . ps - af - match = nil means ps is a prefix of xs ; Implementation issue: combining general and case-insensitive search in one function simplifies maintenance , but complicates ; formulation of software properties and their proofs (defun splitoff-prefix-upr (ps xs) (if (and (consp ps) (consp xs) (equal (car ps) (let* ((x (car xs))) (if (standard-char-p x) (char-upcase x) x)))) (let* ((3way (splitoff-prefix-upr (cdr ps) (cdr xs))) (ps-matching (car 3way)) (ps-af-match (cadr 3way)) (xs-af-match (caddr 3way))) (list (cons (car ps) ps-matching) ps-af-match xs-af-match)) (list nil ps xs))) ; tok-str = characters to look for (string, standard characters) ; chrs = object to search in (defun splitoff-prefix-chr (tok-str xs) (splitoff-prefix-upr (str->chrs(string-upcase tok-str)) xs)) ; tok = object to search for (list) ; xs = object of search (list) ( split - on - token - gen tok xs ) = ( prefix match suffix ) ; where prefix = elems of xs before 1st sublist matching tok ( list ) ; = xs if no match ; match = tok if match (list) ; = nil if no match suffix = elems of xs after 1st sublist matching tok ( list ) ; = nil if no match (defun split-on-token-gen (tok xs) (if (endp xs) (list nil nil nil) (let* ((splitoff-3way (splitoff-prefix tok xs)) (matching? (null (cadr splitoff-3way))) (aftr-tok (caddr splitoff-3way))) (if matching? (list nil tok aftr-tok) (let* ((3way (split-on-token-gen tok (cdr xs))) (bfor-tok (car 3way)) (at-tok (cadr 3way)) (aftr-tok (caddr 3way))) (list (cons (car xs) bfor-tok) at-tok aftr-tok)))))) ; tok = object to search for (list of upper-case standard characters) ; xs = object to search in (list containing no non-standard chars) ; Note: matching is not case-sensitive ; (split-on-token-chr tok xs) = (prefix match suffix) ; where prefix = elems of xs before 1st sublist matching tok ( list ) ; = xs if no match ; match = tok if match (list) ; = nil if no match suffix = elems of xs after 1st sublist matching tok ( list ) ; = nil if no match (defun split-on-token-chr (tok xs) (if (endp xs) (list nil nil nil) (let* ((splitoff-3way (splitoff-prefix-upr tok xs)) (matching? (null (cadr splitoff-3way))) (aftr-tok (caddr splitoff-3way))) (if matching? (list nil tok aftr-tok) (let* ((3way (split-on-token-chr tok (cdr xs))) (bfor-tok (car 3way)) (at-tok (cadr 3way)) (aftr-tok (caddr 3way))) (list (cons (car xs) bfor-tok) at-tok aftr-tok)))))) ; tok = object to search for (string or list) ; xs = object to search in (list, no non-standard chars if tok is string) ; Note: search is not case-sensitive if tok is a string ; Warning! Neither tok nor xs may contain non-standard characters ; if tok is a string ; Implementation issue: combining general and case-insensitive search in one function simplifies maintenance , but complicates ; formulation of software properties and their proofs (defun split-on-token (tok xs) (if (stringp tok) (split-on-token-chr (str->chrs(string-upcase tok)) xs) (split-on-token-gen tok xs)))
null
https://raw.githubusercontent.com/directrix1/DuplicateBridgeTeamSteele/0f0d0312569fb1d26d568e2b87d66ac160ac60c3/timpl/dropbox/basiclex.lisp
lisp
ds = delimiters to look for (list) xs = object to search in (list) where before = longest prefix of xs with no values from ds (list) at+ = rest of xs (list) ps = list of signals to pass by (no constraints on signals) xs = list of signals (no constraints on signals) ps = prefix to look for (list) xs = object to search in (list) where ps-matching = longest ps prefix matching xs prefix (list) xs-af-match = non-matching suffix of xs (list) ps = prefix to look for (list of standard, upper-case characters) xs = object to search in (list) where ps-matching = longest ps prefix matching xs prefix (list) xs-af-match = non-matching suffix of xs (list) Implementation issue: combining general and case-insensitive search formulation of software properties and their proofs tok-str = characters to look for (string, standard characters) chrs = object to search in tok = object to search for (list) xs = object of search (list) where = xs if no match match = tok if match (list) = nil if no match = nil if no match tok = object to search for (list of upper-case standard characters) xs = object to search in (list containing no non-standard chars) Note: matching is not case-sensitive (split-on-token-chr tok xs) = (prefix match suffix) where = xs if no match match = tok if match (list) = nil if no match = nil if no match tok = object to search for (string or list) xs = object to search in (list, no non-standard chars if tok is string) Note: search is not case-sensitive if tok is a string Warning! Neither tok nor xs may contain non-standard characters if tok is a string Implementation issue: combining general and case-insensitive search formulation of software properties and their proofs
(in-package "ACL2") (include-book "list-utilities" :dir :teachpacks) ( split - at - delimiter ds xs ) = ( before at+ ) (defun split-at-delimiter (ds xs) (if (or (endp xs) (member-equal (car xs) ds)) (list nil xs) (let* ((cdr-split (split-at-delimiter ds (cdr xs)))) (list (cons (car xs) (car cdr-split)) (cadr cdr-split))))) ( span ps xs ) = list of two elements 1 longest prefix of xs containing only signals from ps 2 rest of xs (defun span (ps xs) (if (or (endp xs) (not (member-equal (car xs) ps))) (list nil xs) (let* ((cdr-span (span ps (cdr xs)))) (list (cons (car xs) (car cdr-span)) (cadr cdr-span))))) ( splitoff - prefix ) = ( ps - matching ps - af - match xs - af - match ) ps - af - match = rest of ps ( list ) Note : ps - af - match = nil means ps is a prefix of xs (defun splitoff-prefix (ps xs) (if (and (consp ps) (consp xs) (equal (car ps) (car xs))) (let* ((3way (splitoff-prefix (cdr ps) (cdr xs))) (ps-matching (car 3way)) (ps-af-match (cadr 3way)) (xs-af-match (caddr 3way))) (list (cons (car ps) ps-matching) ps-af-match xs-af-match)) (list nil ps xs))) ( splitoff - prefix - upr ps xs ) = ( ps - matching ps - af - match xs - af - match ) ps - af - match = rest of ps ( list ) Notes : 1 . search is not sensitive to case of letters in xs 2 . ps - af - match = nil means ps is a prefix of xs in one function simplifies maintenance , but complicates (defun splitoff-prefix-upr (ps xs) (if (and (consp ps) (consp xs) (equal (car ps) (let* ((x (car xs))) (if (standard-char-p x) (char-upcase x) x)))) (let* ((3way (splitoff-prefix-upr (cdr ps) (cdr xs))) (ps-matching (car 3way)) (ps-af-match (cadr 3way)) (xs-af-match (caddr 3way))) (list (cons (car ps) ps-matching) ps-af-match xs-af-match)) (list nil ps xs))) (defun splitoff-prefix-chr (tok-str xs) (splitoff-prefix-upr (str->chrs(string-upcase tok-str)) xs)) ( split - on - token - gen tok xs ) = ( prefix match suffix ) prefix = elems of xs before 1st sublist matching tok ( list ) suffix = elems of xs after 1st sublist matching tok ( list ) (defun split-on-token-gen (tok xs) (if (endp xs) (list nil nil nil) (let* ((splitoff-3way (splitoff-prefix tok xs)) (matching? (null (cadr splitoff-3way))) (aftr-tok (caddr splitoff-3way))) (if matching? (list nil tok aftr-tok) (let* ((3way (split-on-token-gen tok (cdr xs))) (bfor-tok (car 3way)) (at-tok (cadr 3way)) (aftr-tok (caddr 3way))) (list (cons (car xs) bfor-tok) at-tok aftr-tok)))))) prefix = elems of xs before 1st sublist matching tok ( list ) suffix = elems of xs after 1st sublist matching tok ( list ) (defun split-on-token-chr (tok xs) (if (endp xs) (list nil nil nil) (let* ((splitoff-3way (splitoff-prefix-upr tok xs)) (matching? (null (cadr splitoff-3way))) (aftr-tok (caddr splitoff-3way))) (if matching? (list nil tok aftr-tok) (let* ((3way (split-on-token-chr tok (cdr xs))) (bfor-tok (car 3way)) (at-tok (cadr 3way)) (aftr-tok (caddr 3way))) (list (cons (car xs) bfor-tok) at-tok aftr-tok)))))) in one function simplifies maintenance , but complicates (defun split-on-token (tok xs) (if (stringp tok) (split-on-token-chr (str->chrs(string-upcase tok)) xs) (split-on-token-gen tok xs)))
0162e344d9f672be42e76990e9247e282cf1b268ee43ff20f0d4590b2f2ca163
sol/http-kit
Toolkit.hs
# OPTIONS_GHC -fno - warn - deprecations # module Network.HTTP.Toolkit ( -- * Exceptions -- | -- * All functions that consume input fail with `UnexpectedEndOfInput` if the -- input ends before the function can completely successfully. -- -- * All cases where a function may fail with an exception other than -- @UnexpectedEndOfInput@ are documented thoroughly on a per function level. -- ToolkitError(..) -- * Input handling , InputStream , makeInputStream , inputStreamFromHandle -- * Handling requests , RequestPath , Request(..) , readRequestWithLimit , readRequest , sendRequest -- * Handling responses , Response(..) , readResponseWithLimit , readResponse , sendResponse , simpleResponse -- * Handling message bodies , BodyReader , sendBody , consumeBody -- * Deprecated types and functions , Connection , makeConnection , connectionFromHandle ) where import Network.HTTP.Toolkit.Body import Network.HTTP.Toolkit.InputStream import Network.HTTP.Toolkit.Connection import Network.HTTP.Toolkit.Request import Network.HTTP.Toolkit.Response import Network.HTTP.Toolkit.Error
null
https://raw.githubusercontent.com/sol/http-kit/cc7eb6f1cb3ad6044c822286ad1352e26c112c69/src/Network/HTTP/Toolkit.hs
haskell
* Exceptions | * All functions that consume input fail with `UnexpectedEndOfInput` if the input ends before the function can completely successfully. * All cases where a function may fail with an exception other than @UnexpectedEndOfInput@ are documented thoroughly on a per function level. * Input handling * Handling requests * Handling responses * Handling message bodies * Deprecated types and functions
# OPTIONS_GHC -fno - warn - deprecations # module Network.HTTP.Toolkit ( ToolkitError(..) , InputStream , makeInputStream , inputStreamFromHandle , RequestPath , Request(..) , readRequestWithLimit , readRequest , sendRequest , Response(..) , readResponseWithLimit , readResponse , sendResponse , simpleResponse , BodyReader , sendBody , consumeBody , Connection , makeConnection , connectionFromHandle ) where import Network.HTTP.Toolkit.Body import Network.HTTP.Toolkit.InputStream import Network.HTTP.Toolkit.Connection import Network.HTTP.Toolkit.Request import Network.HTTP.Toolkit.Response import Network.HTTP.Toolkit.Error
b3061b79c5d8053c78f9aed6bf59231bc7b438a29be909e898f693180417f3eb
agajews/soup-lang
Parser.hs
module Soup.Parser ( Parser(..), parserToVal, contToVal, liftEval, catchFail, parserFail, parseType, parseString, parseIf, parseWhile, parseWhile', parseMany, parseMany', parseInterspersed, parseInterspersed', logDebug, ) where import Soup.Debugger import Soup.Eval import Soup.Parse import Soup.Value import Control.Monad.Except import Data.List newtype Parser a = Parser { runParser :: String -> (a -> String -> Eval [Value]) -> Eval [Value] } instance Monad Parser where return x = Parser $ \s c -> c x s p >>= f = Parser $ \s c -> runParser p s $ \x s' -> runParser (f x) s' c instance Applicative Parser where pure = return (<*>) = ap instance Functor Parser where fmap = liftM liftEval :: Eval a -> Parser a liftEval m = Parser $ \s c -> do x <- m c x s parserToVal :: String -> Parser Value -> Value parserToVal name p = PrimFunc ("%" ++ name) $ \args -> do args' <- mapM eval args case args' of [StringVal s, c] -> do l <- runParser p s $ \v s' -> do y <- eval $ FuncCall c [v, StringVal s'] case y of ListVal l' -> return l' _ -> throwError InvalidContinuation return $ ListVal l _ -> throwError $ InvalidArguments' name args' contToVal :: String -> (Value -> String -> Eval [Value]) -> Value contToVal name c = PrimFunc contname $ \args -> do case args of [v, StringVal s] -> do l <- c v s return $ ListVal l _ -> throwError $ InvalidArguments' contname args where contname = "~" ++ name parserFail :: Parser a parserFail = Parser $ \_ _ -> return [] parseType :: Ident -> Parser Value parseType n = Parser $ \s c -> do rs <- eval (Variable n) parse s [(rs, contToVal "" c)] parseString :: String -> Parser () parseString m = Parser $ \s c -> if isPrefixOf m s then c () $ drop (length m) s else return [] parseIf :: (Char -> Bool) -> Parser Char parseIf p = Parser $ \s c -> case s of x:s' -> if p x then c x s' else return [] _ -> return [] parseWhile' :: (Char -> Bool) -> Parser String parseWhile' p = Parser $ \s c -> case span p s of (m, s') -> c m s' parseWhile :: (Char -> Bool) -> Parser String parseWhile p = Parser $ \s c -> case span p s of ([], _) -> return [] (m, s') -> c m s' catchFail :: Parser a -> Parser a -> Parser a catchFail p' p = Parser $ \s c -> do l <- runParser p s c if null l then runParser p' s c else return l parseMany' :: (Show a) => Parser a -> Parser [a] parseMany' p = catchFail (return []) (parseMany p) parseMany :: (Show a) => Parser a -> Parser [a] parseMany p = do x <- p xs <- parseMany' p return (x:xs) parseInterspersed :: (Show a) => Parser a -> Parser b -> Parser [a] parseInterspersed p sep = do x <- p xs <- parseMany' $ sep >> p return (x:xs) parseInterspersed' :: (Show a) => Parser a -> Parser b -> Parser [a] parseInterspersed' p sep = catchFail (return []) (parseInterspersed p sep) logDebug :: String -> Parser () logDebug name = Parser $ \s c -> do logParser name s c () s
null
https://raw.githubusercontent.com/agajews/soup-lang/1c926f5853fe18244e33f0f90830db49f7fb827e/Soup/Parser.hs
haskell
module Soup.Parser ( Parser(..), parserToVal, contToVal, liftEval, catchFail, parserFail, parseType, parseString, parseIf, parseWhile, parseWhile', parseMany, parseMany', parseInterspersed, parseInterspersed', logDebug, ) where import Soup.Debugger import Soup.Eval import Soup.Parse import Soup.Value import Control.Monad.Except import Data.List newtype Parser a = Parser { runParser :: String -> (a -> String -> Eval [Value]) -> Eval [Value] } instance Monad Parser where return x = Parser $ \s c -> c x s p >>= f = Parser $ \s c -> runParser p s $ \x s' -> runParser (f x) s' c instance Applicative Parser where pure = return (<*>) = ap instance Functor Parser where fmap = liftM liftEval :: Eval a -> Parser a liftEval m = Parser $ \s c -> do x <- m c x s parserToVal :: String -> Parser Value -> Value parserToVal name p = PrimFunc ("%" ++ name) $ \args -> do args' <- mapM eval args case args' of [StringVal s, c] -> do l <- runParser p s $ \v s' -> do y <- eval $ FuncCall c [v, StringVal s'] case y of ListVal l' -> return l' _ -> throwError InvalidContinuation return $ ListVal l _ -> throwError $ InvalidArguments' name args' contToVal :: String -> (Value -> String -> Eval [Value]) -> Value contToVal name c = PrimFunc contname $ \args -> do case args of [v, StringVal s] -> do l <- c v s return $ ListVal l _ -> throwError $ InvalidArguments' contname args where contname = "~" ++ name parserFail :: Parser a parserFail = Parser $ \_ _ -> return [] parseType :: Ident -> Parser Value parseType n = Parser $ \s c -> do rs <- eval (Variable n) parse s [(rs, contToVal "" c)] parseString :: String -> Parser () parseString m = Parser $ \s c -> if isPrefixOf m s then c () $ drop (length m) s else return [] parseIf :: (Char -> Bool) -> Parser Char parseIf p = Parser $ \s c -> case s of x:s' -> if p x then c x s' else return [] _ -> return [] parseWhile' :: (Char -> Bool) -> Parser String parseWhile' p = Parser $ \s c -> case span p s of (m, s') -> c m s' parseWhile :: (Char -> Bool) -> Parser String parseWhile p = Parser $ \s c -> case span p s of ([], _) -> return [] (m, s') -> c m s' catchFail :: Parser a -> Parser a -> Parser a catchFail p' p = Parser $ \s c -> do l <- runParser p s c if null l then runParser p' s c else return l parseMany' :: (Show a) => Parser a -> Parser [a] parseMany' p = catchFail (return []) (parseMany p) parseMany :: (Show a) => Parser a -> Parser [a] parseMany p = do x <- p xs <- parseMany' p return (x:xs) parseInterspersed :: (Show a) => Parser a -> Parser b -> Parser [a] parseInterspersed p sep = do x <- p xs <- parseMany' $ sep >> p return (x:xs) parseInterspersed' :: (Show a) => Parser a -> Parser b -> Parser [a] parseInterspersed' p sep = catchFail (return []) (parseInterspersed p sep) logDebug :: String -> Parser () logDebug name = Parser $ \s c -> do logParser name s c () s
eadccb9b305c22068c70cdbc9876daa3d9a67cf281ad7c732e6d41ebf21011bb
FlowForwarding/of_config
of_config_tests.erl
%%------------------------------------------------------------------------------ Copyright 2012 FlowForwarding.org %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%----------------------------------------------------------------------------- @author Erlang Solutions Ltd. < > @author < > 2012 FlowForwarding.org @doc eUnit suite for testing OF - Config protocol . @private -module(of_config_tests). -include("of_config.hrl"). -include_lib("xmerl/include/xmerl.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(XML_PATH(XML), "../test/xml/" ++ XML). %% Tests ----------------------------------------------------------------------- generic_parser_test_() -> {setup, fun setup/0, fun teardown/1, [{"Decode malformed XML data", fun decode_error/0}] }. decode_error() -> {XML, _Rest} = xmerl_scan:file(?XML_PATH("malformed.xml")), Result = of_config:decode(XML), ?assertEqual(error, element(1, Result)). parser_11_test_() -> {setup, fun setup_11/0, fun teardown/1, [ {"Decoding/encoding full-config-1.1.xml with OF-Config 1.1 XSD", fun full_config_11/0}, {"Decoding/encoding example1-edit-config-1.1.xml with OF-Config 1.1 XSD", fun example1_edit_config_11/0}, {"Decoding/encoding example2-edit-config-1.1.xml with OF-Config 1.1 XSD", fun example2_edit_config_11/0}, {"Decoding/encoding example3-edit-config-1.1.xml with OF-Config 1.1 XSD", fun example3_edit_config_11/0}, {"Decoding/encoding get-config-1.1.xml with OF-Config 1.1 XSD", fun get_config_11/0}, {"Decoding/encoding delete-controller-1.1.xml with OF-Config 1.1 XSD", fun delete_controller_11/0}, {"Decoding/encoding replace-controller-1.1.xml with OF-Config 1.1 XSD", fun replace_controller_11/0}, {"Decoding/encoding delete-certificate-1.1.xml with OF-Config 1.1 XSD", fun delete_certificate_11/0}, {"Decoding/encoding set-queue-1.1.xml with OF-Config 1.1 XSD", fun set_queue_11/0}, {"Decoding/encoding set-port-1.1.xml with OF-Config 1.1 XSD", fun set_port_11/0}, {"Encoding of_config_fixtures:get_config_11/0 fixture with OF-Config 1.1 XSD", fun encode_fixture1_11/0} ]}. parser_111_test_() -> {setup, fun setup_111/0, fun teardown/1, [ {"Decoding/encoding full-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun full_config_111/0}, {"Decoding/encoding example1-edit-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun example1_edit_config_111/0}, {"decoding/encoding example2-edit-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun example2_edit_config_111/0}, {"Decoding/encoding example3-edit-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun example3_edit_config_111/0}, {"Decoding/encoding get-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun get_config_111/0}, {"Decoding/encoding delete-controller-1.1.1.xml with OF-Config 1.1.1 XSD", fun delete_controller_111/0}, {"Decoding/encoding replace-controller-1.1.1.xml with OF-Config 1.1.1 XSD", fun replace_controller_111/0}, {"Decoding/encoding delete-certificate-1.1.1.xml with OF-Config 1.1.1 XSD", fun delete_certificate_111/0}, {"Decoding/encoding set-queue-1.1.1.xml with OF-Config 1.1.1 XSD", fun set_queue_111/0}, {"Decoding/encoding set-port-1.1.1.xml with OF-Config 1.1.1 XSD", fun set_port_111/0}, {"Encoding of_config_fixtures:get_config/0 fixture with OF-Config 1.1.1 XSD", fun encode_fixture1_111/0} ]}. %% OF-Config 1.1 --------------------------------------------------------------- full_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("full-config-1.1.xml")), encode(CapableSwitch, XML). example1_edit_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("example1-edit-config-1.1.xml")), encode(CapableSwitch, XML). example2_edit_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("example2-edit-config-1.1.xml")), encode(CapableSwitch, XML). example3_edit_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("example3-edit-config-1.1.xml")), encode(CapableSwitch, XML). get_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("get-config-1.1.xml")), encode(CapableSwitch, XML). delete_controller_11() -> {CapableSwitch, XML} = decode(?XML_PATH("delete-controller-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"delete\""}]). replace_controller_11() -> {CapableSwitch, XML} = decode(?XML_PATH("replace-controller-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}]). delete_certificate_11() -> {CapableSwitch, XML} = decode(?XML_PATH("delete-certificate-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"delete\""}]). set_queue_11() -> {CapableSwitch, XML} = decode(?XML_PATH("set-queue-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}]). set_port_11() -> {CapableSwitch, XML} = decode(?XML_PATH("set-port-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}, {original, "operation=\"delete\""}]). encode_fixture1_11() -> CapableSwitch = of_config_fixtures:get_config_11(), encode(CapableSwitch). %% OF-Config 1.1.1 ------------------------------------------------------------- full_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("full-config-1.1.1.xml")), encode(CapableSwitch, XML). example1_edit_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("example1-edit-config-1.1.1.xml")), encode(CapableSwitch, XML). example2_edit_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("example2-edit-config-1.1.1.xml")), encode(CapableSwitch, XML). example3_edit_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("example3-edit-config-1.1.1.xml")), encode(CapableSwitch, XML). get_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("get-config-1.1.1.xml")), encode(CapableSwitch, XML). delete_controller_111() -> {CapableSwitch, XML} = decode(?XML_PATH("delete-controller-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"delete\""}]). replace_controller_111() -> {CapableSwitch, XML} = decode(?XML_PATH("replace-controller-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}]). delete_certificate_111() -> {CapableSwitch, XML} = decode(?XML_PATH("delete-certificate-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"delete\""}]). set_queue_111() -> {CapableSwitch, XML} = decode(?XML_PATH("set-queue-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}]). set_port_111() -> {CapableSwitch, XML} = decode(?XML_PATH("set-port-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}, {original, "operation=\"delete\""}]). encode_fixture1_111() -> CapableSwitch = of_config_fixtures:get_config_111(), encode(CapableSwitch). %% Helper functions ------------------------------------------------------------ decode(Filename) -> {XML, _Rest} = xmerl_scan:file(Filename), CapableSwitchRecord = of_config:decode(XML), ?assertEqual(true, is_record(CapableSwitchRecord, capable_switch)), {CapableSwitchRecord, XML}. encode(CapableSwitch) -> encode(CapableSwitch, xml, false, [nodiff]). encode(CapableSwitch, XML) -> encode(CapableSwitch, XML, true, [nodiff]). encode(CapableSwitch, XML, Diff) -> encode(CapableSwitch, XML, true, Diff). encode(CapableSwitchRecord1, XML, CompareWithOriginal, Diffs) -> SimpleForm = of_config:encode(CapableSwitchRecord1), DeepList = xmerl:export_simple([SimpleForm], xmerl_xml, [{prolog, ""}]), XMLString = lists:flatten(DeepList), case CompareWithOriginal of true -> Get rid of whitespace characters to compare XML documents OriginalXMLString = lists:flatten(xmerl:export([XML], xmerl_xml, [{prolog, ""}])), OriginalXMLString2 = re:replace(OriginalXMLString, "\\n", "", [{return, list}, global]), OriginalXMLString3 = re:replace(OriginalXMLString2, " ", "", [{return, list}, global]), XMLString2 = re:replace(XMLString, " ", "", [{return, list}, global]), {OriginalFinalXML, ResultFinalXML} = lists:foldl( fun({original, ReplaceString}, {Original, Result}) -> Original2 = re:replace(Original, ReplaceString, "", [{return, list}, global]), {Original2, Result}; ({result, ReplaceString}, {Original, Result}) -> Result2 = re:replace(Result, ReplaceString, "", [{return, list}, global]), {Original, Result2}; (nodiff, {Original, Result}) -> {Original, Result} end, {OriginalXMLString3, XMLString2}, Diffs), ?assertEqual(OriginalFinalXML, ResultFinalXML); false -> ok end, {XML2, _Rest} = xmerl_scan:string(XMLString), CapableSwitchRecord2 = of_config:decode(XML2), ?assertEqual(true, is_record(CapableSwitchRecord2, capable_switch)), ?assertEqual(reset_operations(CapableSwitchRecord1), reset_operations(CapableSwitchRecord2)). reset_operations(Switch) -> reset_resources(reset_controllers(Switch)). reset_controllers(#capable_switch{logical_switches = undefined} = CS) -> CS; reset_controllers(#capable_switch{logical_switches = LS} = CS) -> CS#capable_switch{logical_switches = [reset_controllers(L) || L <- LS]}; reset_controllers(#logical_switch{controllers = undefined} = L) -> L; reset_controllers(#logical_switch{controllers = CS} = L) -> L#logical_switch{controllers = [reset_controllers(C) || C <- CS]}; reset_controllers(#controller{} = C) -> C#controller{operation = undefined}. reset_resources(#capable_switch{resources = undefined} = Switch) -> Switch; reset_resources(#capable_switch{resources = Resources} = Switch) -> Switch#capable_switch{resources = [reset_resources(R) || R <- Resources]}; reset_resources(undefined) -> undefined; reset_resources(#port{configuration = C, features = F} = P) -> C2 = case C of undefiend -> undefiend; #port_configuration{} = PC -> PC#port_configuration{operation = undefined} end, F2 = case F of undefined -> undefined; #port_features{advertised = A} = PF -> A2 = case A of undefined -> undefined; #features{} = Feats -> Feats#features{operation = undefined} end, PF#port_features{advertised = A2} end, P#port{operation = undefined, configuration = C2, features = F2}; reset_resources(#queue{} = Q) -> Q#queue{operation = undefined}; reset_resources(#certificate{} = C) -> C#certificate{operation = undefined}; reset_resources(#flow_table{} = F) -> F. %% Fixtures -------------------------------------------------------------------- setup_11() -> setup(), application:set_env(of_config, schemas, [{'1.1', [{"", "xmldsig-core-schema.xsd"}, {"urn:ietf:params:xml:ns:yang:ietf-inet-types", "ietf-inet-types.xsd"}, {"urn:onf:params:xml:ns:onf:of12:config", "of-config-1.1.xsd"} ]}]), application:set_env(of_config, version, '1.1'). setup_111() -> setup(), application:set_env(of_config, schemas, [{'1.1.1', [{"urn:ietf:params:xml:ns:yang:ietf-inet-types", "ietf-inet-types.xsd"}, {"urn:ietf:params:xml:ns:yang:ietf-yang-types", "ietf-yang-types.xsd"}, {"urn:onf:of111:config:yang", "of-config-1.1.1.xsd"} ]}]), application:set_env(of_config, version, '1.1.1'). setup() -> error_logger:tty(true), HACK : is not preserving the directory structure and copies %% everything to .eunit, so this symlink makes code:priv_dir/1 %% and include_lib work again. file:make_symlink("..", "of_config"), code:add_path("./of_config/ebin"), application:load(of_config), application:start(xmerl), application:start(of_config). teardown(_) -> application:stop(of_config), application:stop(xmerl), file:delete("of_config").
null
https://raw.githubusercontent.com/FlowForwarding/of_config/958a68280808f2454b46d7a63551eb80f6aca353/test/of_config_tests.erl
erlang
------------------------------------------------------------------------------ you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- Tests ----------------------------------------------------------------------- OF-Config 1.1 --------------------------------------------------------------- OF-Config 1.1.1 ------------------------------------------------------------- Helper functions ------------------------------------------------------------ Fixtures -------------------------------------------------------------------- everything to .eunit, so this symlink makes code:priv_dir/1 and include_lib work again.
Copyright 2012 FlowForwarding.org Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author Erlang Solutions Ltd. < > @author < > 2012 FlowForwarding.org @doc eUnit suite for testing OF - Config protocol . @private -module(of_config_tests). -include("of_config.hrl"). -include_lib("xmerl/include/xmerl.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(XML_PATH(XML), "../test/xml/" ++ XML). generic_parser_test_() -> {setup, fun setup/0, fun teardown/1, [{"Decode malformed XML data", fun decode_error/0}] }. decode_error() -> {XML, _Rest} = xmerl_scan:file(?XML_PATH("malformed.xml")), Result = of_config:decode(XML), ?assertEqual(error, element(1, Result)). parser_11_test_() -> {setup, fun setup_11/0, fun teardown/1, [ {"Decoding/encoding full-config-1.1.xml with OF-Config 1.1 XSD", fun full_config_11/0}, {"Decoding/encoding example1-edit-config-1.1.xml with OF-Config 1.1 XSD", fun example1_edit_config_11/0}, {"Decoding/encoding example2-edit-config-1.1.xml with OF-Config 1.1 XSD", fun example2_edit_config_11/0}, {"Decoding/encoding example3-edit-config-1.1.xml with OF-Config 1.1 XSD", fun example3_edit_config_11/0}, {"Decoding/encoding get-config-1.1.xml with OF-Config 1.1 XSD", fun get_config_11/0}, {"Decoding/encoding delete-controller-1.1.xml with OF-Config 1.1 XSD", fun delete_controller_11/0}, {"Decoding/encoding replace-controller-1.1.xml with OF-Config 1.1 XSD", fun replace_controller_11/0}, {"Decoding/encoding delete-certificate-1.1.xml with OF-Config 1.1 XSD", fun delete_certificate_11/0}, {"Decoding/encoding set-queue-1.1.xml with OF-Config 1.1 XSD", fun set_queue_11/0}, {"Decoding/encoding set-port-1.1.xml with OF-Config 1.1 XSD", fun set_port_11/0}, {"Encoding of_config_fixtures:get_config_11/0 fixture with OF-Config 1.1 XSD", fun encode_fixture1_11/0} ]}. parser_111_test_() -> {setup, fun setup_111/0, fun teardown/1, [ {"Decoding/encoding full-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun full_config_111/0}, {"Decoding/encoding example1-edit-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun example1_edit_config_111/0}, {"decoding/encoding example2-edit-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun example2_edit_config_111/0}, {"Decoding/encoding example3-edit-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun example3_edit_config_111/0}, {"Decoding/encoding get-config-1.1.1.xml with OF-Config 1.1.1 XSD", fun get_config_111/0}, {"Decoding/encoding delete-controller-1.1.1.xml with OF-Config 1.1.1 XSD", fun delete_controller_111/0}, {"Decoding/encoding replace-controller-1.1.1.xml with OF-Config 1.1.1 XSD", fun replace_controller_111/0}, {"Decoding/encoding delete-certificate-1.1.1.xml with OF-Config 1.1.1 XSD", fun delete_certificate_111/0}, {"Decoding/encoding set-queue-1.1.1.xml with OF-Config 1.1.1 XSD", fun set_queue_111/0}, {"Decoding/encoding set-port-1.1.1.xml with OF-Config 1.1.1 XSD", fun set_port_111/0}, {"Encoding of_config_fixtures:get_config/0 fixture with OF-Config 1.1.1 XSD", fun encode_fixture1_111/0} ]}. full_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("full-config-1.1.xml")), encode(CapableSwitch, XML). example1_edit_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("example1-edit-config-1.1.xml")), encode(CapableSwitch, XML). example2_edit_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("example2-edit-config-1.1.xml")), encode(CapableSwitch, XML). example3_edit_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("example3-edit-config-1.1.xml")), encode(CapableSwitch, XML). get_config_11() -> {CapableSwitch, XML} = decode(?XML_PATH("get-config-1.1.xml")), encode(CapableSwitch, XML). delete_controller_11() -> {CapableSwitch, XML} = decode(?XML_PATH("delete-controller-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"delete\""}]). replace_controller_11() -> {CapableSwitch, XML} = decode(?XML_PATH("replace-controller-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}]). delete_certificate_11() -> {CapableSwitch, XML} = decode(?XML_PATH("delete-certificate-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"delete\""}]). set_queue_11() -> {CapableSwitch, XML} = decode(?XML_PATH("set-queue-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}]). set_port_11() -> {CapableSwitch, XML} = decode(?XML_PATH("set-port-1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}, {original, "operation=\"delete\""}]). encode_fixture1_11() -> CapableSwitch = of_config_fixtures:get_config_11(), encode(CapableSwitch). full_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("full-config-1.1.1.xml")), encode(CapableSwitch, XML). example1_edit_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("example1-edit-config-1.1.1.xml")), encode(CapableSwitch, XML). example2_edit_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("example2-edit-config-1.1.1.xml")), encode(CapableSwitch, XML). example3_edit_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("example3-edit-config-1.1.1.xml")), encode(CapableSwitch, XML). get_config_111() -> {CapableSwitch, XML} = decode(?XML_PATH("get-config-1.1.1.xml")), encode(CapableSwitch, XML). delete_controller_111() -> {CapableSwitch, XML} = decode(?XML_PATH("delete-controller-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"delete\""}]). replace_controller_111() -> {CapableSwitch, XML} = decode(?XML_PATH("replace-controller-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}]). delete_certificate_111() -> {CapableSwitch, XML} = decode(?XML_PATH("delete-certificate-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"delete\""}]). set_queue_111() -> {CapableSwitch, XML} = decode(?XML_PATH("set-queue-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}]). set_port_111() -> {CapableSwitch, XML} = decode(?XML_PATH("set-port-1.1.1.xml")), encode(CapableSwitch, XML, [{original, "operation=\"replace\""}, {original, "operation=\"delete\""}]). encode_fixture1_111() -> CapableSwitch = of_config_fixtures:get_config_111(), encode(CapableSwitch). decode(Filename) -> {XML, _Rest} = xmerl_scan:file(Filename), CapableSwitchRecord = of_config:decode(XML), ?assertEqual(true, is_record(CapableSwitchRecord, capable_switch)), {CapableSwitchRecord, XML}. encode(CapableSwitch) -> encode(CapableSwitch, xml, false, [nodiff]). encode(CapableSwitch, XML) -> encode(CapableSwitch, XML, true, [nodiff]). encode(CapableSwitch, XML, Diff) -> encode(CapableSwitch, XML, true, Diff). encode(CapableSwitchRecord1, XML, CompareWithOriginal, Diffs) -> SimpleForm = of_config:encode(CapableSwitchRecord1), DeepList = xmerl:export_simple([SimpleForm], xmerl_xml, [{prolog, ""}]), XMLString = lists:flatten(DeepList), case CompareWithOriginal of true -> Get rid of whitespace characters to compare XML documents OriginalXMLString = lists:flatten(xmerl:export([XML], xmerl_xml, [{prolog, ""}])), OriginalXMLString2 = re:replace(OriginalXMLString, "\\n", "", [{return, list}, global]), OriginalXMLString3 = re:replace(OriginalXMLString2, " ", "", [{return, list}, global]), XMLString2 = re:replace(XMLString, " ", "", [{return, list}, global]), {OriginalFinalXML, ResultFinalXML} = lists:foldl( fun({original, ReplaceString}, {Original, Result}) -> Original2 = re:replace(Original, ReplaceString, "", [{return, list}, global]), {Original2, Result}; ({result, ReplaceString}, {Original, Result}) -> Result2 = re:replace(Result, ReplaceString, "", [{return, list}, global]), {Original, Result2}; (nodiff, {Original, Result}) -> {Original, Result} end, {OriginalXMLString3, XMLString2}, Diffs), ?assertEqual(OriginalFinalXML, ResultFinalXML); false -> ok end, {XML2, _Rest} = xmerl_scan:string(XMLString), CapableSwitchRecord2 = of_config:decode(XML2), ?assertEqual(true, is_record(CapableSwitchRecord2, capable_switch)), ?assertEqual(reset_operations(CapableSwitchRecord1), reset_operations(CapableSwitchRecord2)). reset_operations(Switch) -> reset_resources(reset_controllers(Switch)). reset_controllers(#capable_switch{logical_switches = undefined} = CS) -> CS; reset_controllers(#capable_switch{logical_switches = LS} = CS) -> CS#capable_switch{logical_switches = [reset_controllers(L) || L <- LS]}; reset_controllers(#logical_switch{controllers = undefined} = L) -> L; reset_controllers(#logical_switch{controllers = CS} = L) -> L#logical_switch{controllers = [reset_controllers(C) || C <- CS]}; reset_controllers(#controller{} = C) -> C#controller{operation = undefined}. reset_resources(#capable_switch{resources = undefined} = Switch) -> Switch; reset_resources(#capable_switch{resources = Resources} = Switch) -> Switch#capable_switch{resources = [reset_resources(R) || R <- Resources]}; reset_resources(undefined) -> undefined; reset_resources(#port{configuration = C, features = F} = P) -> C2 = case C of undefiend -> undefiend; #port_configuration{} = PC -> PC#port_configuration{operation = undefined} end, F2 = case F of undefined -> undefined; #port_features{advertised = A} = PF -> A2 = case A of undefined -> undefined; #features{} = Feats -> Feats#features{operation = undefined} end, PF#port_features{advertised = A2} end, P#port{operation = undefined, configuration = C2, features = F2}; reset_resources(#queue{} = Q) -> Q#queue{operation = undefined}; reset_resources(#certificate{} = C) -> C#certificate{operation = undefined}; reset_resources(#flow_table{} = F) -> F. setup_11() -> setup(), application:set_env(of_config, schemas, [{'1.1', [{"", "xmldsig-core-schema.xsd"}, {"urn:ietf:params:xml:ns:yang:ietf-inet-types", "ietf-inet-types.xsd"}, {"urn:onf:params:xml:ns:onf:of12:config", "of-config-1.1.xsd"} ]}]), application:set_env(of_config, version, '1.1'). setup_111() -> setup(), application:set_env(of_config, schemas, [{'1.1.1', [{"urn:ietf:params:xml:ns:yang:ietf-inet-types", "ietf-inet-types.xsd"}, {"urn:ietf:params:xml:ns:yang:ietf-yang-types", "ietf-yang-types.xsd"}, {"urn:onf:of111:config:yang", "of-config-1.1.1.xsd"} ]}]), application:set_env(of_config, version, '1.1.1'). setup() -> error_logger:tty(true), HACK : is not preserving the directory structure and copies file:make_symlink("..", "of_config"), code:add_path("./of_config/ebin"), application:load(of_config), application:start(xmerl), application:start(of_config). teardown(_) -> application:stop(of_config), application:stop(xmerl), file:delete("of_config").
5a62d38dee87e98c4b34c9af0088eec8989aea839102030b563d22827220cc31
melange-re/melange
inline_edge_cases.mli
val v : int
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/test/inline_edge_cases.mli
ocaml
val v : int
a2c43daf2b4e8036bd03961c500ad9d16356907205df290f9b0d4be7f1f20ece
mokus0/dependent-sum-template
TH.hs
# LANGUAGE CPP , TemplateHaskell # module Data.GADT.Show.TH ( DeriveGShow(..) , DeriveShowTagIdentity(..) ) where import Control.Applicative import Control.Monad import Data.Dependent.Sum import Data.Dependent.Sum.TH.Internal import Data.Functor.Identity import Data.GADT.Show import Data.Traversable (for) import Data.List import Language.Haskell.TH import Language.Haskell.TH.Extras class DeriveGShow t where deriveGShow :: t -> Q [Dec] instance DeriveGShow Name where deriveGShow typeName = do typeInfo <- reify typeName case typeInfo of TyConI dec -> deriveGShow dec _ -> fail "deriveGShow: the name of a type constructor is required" instance DeriveGShow Dec where deriveGShow = deriveForDec ''GShow (\t -> [t| GShow $t |]) $ \_ -> gshowFunction instance DeriveGShow t => DeriveGShow [t] where deriveGShow [it] = deriveGShow it deriveGShow _ = fail "deriveGShow: [] instance only applies to single-element lists" instance DeriveGShow t => DeriveGShow (Q t) where deriveGShow = (>>= deriveGShow) gshowFunction = funD 'gshowsPrec . map gshowClause gshowClause con = do let conName = nameOfCon con argTypes = argTypesOfCon con nArgs = length argTypes precName = mkName "p" argNames <- replicateM nArgs (newName "x") let precPat = if null argNames then wildP else varP precName clause [precPat, conP conName (map varP argNames)] (normalB (gshowBody (varE precName) conName argNames)) [] showsName name = [| showString $(litE . stringL $ nameBase name) |] gshowBody prec conName [] = showsName conName gshowBody prec conName argNames = [| showParen ($prec > 10) $( composeExprs $ intersperse [| showChar ' ' |] ( showsName conName : [ [| showsPrec 11 $arg |] | argName <- argNames, let arg = varE argName ] )) |] -- A type class purely for overloading purposes class DeriveShowTagIdentity t where deriveShowTagIdentity :: t -> Q [Dec] instance DeriveShowTagIdentity Name where deriveShowTagIdentity typeName = do typeInfo <- reify typeName case typeInfo of TyConI dec -> deriveShowTagIdentity dec _ -> fail "deriveShowTagIdentity: the name of a type constructor is required" instance DeriveShowTagIdentity Dec where deriveShowTagIdentity = deriveForDec ''ShowTag (\t -> [t| ShowTag $t Identity |]) showTaggedFunction instance DeriveShowTagIdentity t => DeriveShowTagIdentity [t] where deriveShowTagIdentity [it] = deriveShowTagIdentity it deriveShowTagIdentity _ = fail "deriveShowTagIdentity: [] instance only applies to single-element lists" instance DeriveShowTagIdentity t => DeriveShowTagIdentity (Q t) where deriveShowTagIdentity = (>>= deriveShowTagIdentity) showTaggedFunction bndrs cons = funD 'showTaggedPrec $ map (showTaggedClause bndrs) cons showTaggedClause bndrs con = do let argTypes = argTypesOfCon con needsGShow argType = any ((`occursInType` argType) . nameOfBinder) (bndrs ++ varsBoundInCon con) argVars <- for argTypes $ \argType -> if needsGShow argType then Just <$> newName "x" else pure Nothing let nonWildPs = [x | Just x <- argVars] doRecur = case nonWildPs of [] -> Nothing [var] -> Just var (_:_) -> error "deriveShowTagIdentity: Can have at most one nested GADT" clause [ conP conName (maybe wildP varP <$> argVars) ] ( normalB $ case doRecur of Nothing -> [| showsPrec |] Just x -> [| showTaggedPrec $(varE x) |] ) [] where conName = nameOfCon con
null
https://raw.githubusercontent.com/mokus0/dependent-sum-template/4b85b8fc6fd016ef03f4ea97e31a2a573d30f2ae/src/Data/GADT/Show/TH.hs
haskell
A type class purely for overloading purposes
# LANGUAGE CPP , TemplateHaskell # module Data.GADT.Show.TH ( DeriveGShow(..) , DeriveShowTagIdentity(..) ) where import Control.Applicative import Control.Monad import Data.Dependent.Sum import Data.Dependent.Sum.TH.Internal import Data.Functor.Identity import Data.GADT.Show import Data.Traversable (for) import Data.List import Language.Haskell.TH import Language.Haskell.TH.Extras class DeriveGShow t where deriveGShow :: t -> Q [Dec] instance DeriveGShow Name where deriveGShow typeName = do typeInfo <- reify typeName case typeInfo of TyConI dec -> deriveGShow dec _ -> fail "deriveGShow: the name of a type constructor is required" instance DeriveGShow Dec where deriveGShow = deriveForDec ''GShow (\t -> [t| GShow $t |]) $ \_ -> gshowFunction instance DeriveGShow t => DeriveGShow [t] where deriveGShow [it] = deriveGShow it deriveGShow _ = fail "deriveGShow: [] instance only applies to single-element lists" instance DeriveGShow t => DeriveGShow (Q t) where deriveGShow = (>>= deriveGShow) gshowFunction = funD 'gshowsPrec . map gshowClause gshowClause con = do let conName = nameOfCon con argTypes = argTypesOfCon con nArgs = length argTypes precName = mkName "p" argNames <- replicateM nArgs (newName "x") let precPat = if null argNames then wildP else varP precName clause [precPat, conP conName (map varP argNames)] (normalB (gshowBody (varE precName) conName argNames)) [] showsName name = [| showString $(litE . stringL $ nameBase name) |] gshowBody prec conName [] = showsName conName gshowBody prec conName argNames = [| showParen ($prec > 10) $( composeExprs $ intersperse [| showChar ' ' |] ( showsName conName : [ [| showsPrec 11 $arg |] | argName <- argNames, let arg = varE argName ] )) |] class DeriveShowTagIdentity t where deriveShowTagIdentity :: t -> Q [Dec] instance DeriveShowTagIdentity Name where deriveShowTagIdentity typeName = do typeInfo <- reify typeName case typeInfo of TyConI dec -> deriveShowTagIdentity dec _ -> fail "deriveShowTagIdentity: the name of a type constructor is required" instance DeriveShowTagIdentity Dec where deriveShowTagIdentity = deriveForDec ''ShowTag (\t -> [t| ShowTag $t Identity |]) showTaggedFunction instance DeriveShowTagIdentity t => DeriveShowTagIdentity [t] where deriveShowTagIdentity [it] = deriveShowTagIdentity it deriveShowTagIdentity _ = fail "deriveShowTagIdentity: [] instance only applies to single-element lists" instance DeriveShowTagIdentity t => DeriveShowTagIdentity (Q t) where deriveShowTagIdentity = (>>= deriveShowTagIdentity) showTaggedFunction bndrs cons = funD 'showTaggedPrec $ map (showTaggedClause bndrs) cons showTaggedClause bndrs con = do let argTypes = argTypesOfCon con needsGShow argType = any ((`occursInType` argType) . nameOfBinder) (bndrs ++ varsBoundInCon con) argVars <- for argTypes $ \argType -> if needsGShow argType then Just <$> newName "x" else pure Nothing let nonWildPs = [x | Just x <- argVars] doRecur = case nonWildPs of [] -> Nothing [var] -> Just var (_:_) -> error "deriveShowTagIdentity: Can have at most one nested GADT" clause [ conP conName (maybe wildP varP <$> argVars) ] ( normalB $ case doRecur of Nothing -> [| showsPrec |] Just x -> [| showTaggedPrec $(varE x) |] ) [] where conName = nameOfCon con
b2e34e40322363062583991014652e0e2827889991f05f5173d442d3c6cda6e0
garrigue/labltk
frx_entry.ml
(***********************************************************************) (* *) MLTk , Tcl / Tk interface of OCaml (* *) , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking (* described in file LICENSE found in the OCaml source tree. *) (* *) (***********************************************************************) open Camltk let version = "$Id$" (* * Tk 4.0 has emacs bindings for entry widgets *) let new_label_entry parent txt action = let f = Frame.create parent [] in let m = Label.create f [Text txt] and e = Entry.create f [Relief Sunken; TextWidth 0] in Camltk.bind e [[], KeyPressDetail "Return"] (BindSet ([], fun _ -> action(Entry.get e))); pack [m][Side Side_Left]; pack [e][Side Side_Right; Fill Fill_X; Expand true]; f,e let new_labelm_entry parent txt memo = let f = Frame.create parent [] in let m = Label.create f [Text txt] and e = Entry.create f [Relief Sunken; TextVariable memo; TextWidth 0] in pack [m][Side Side_Left]; pack [e][Side Side_Right; Fill Fill_X; Expand true]; f,e
null
https://raw.githubusercontent.com/garrigue/labltk/c7f50b4faed57f1ac03cb3c9aedc35b10d36bdb6/frx/frx_entry.ml
ocaml
********************************************************************* described in file LICENSE found in the OCaml source tree. ********************************************************************* * Tk 4.0 has emacs bindings for entry widgets
MLTk , Tcl / Tk interface of OCaml , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking open Camltk let version = "$Id$" let new_label_entry parent txt action = let f = Frame.create parent [] in let m = Label.create f [Text txt] and e = Entry.create f [Relief Sunken; TextWidth 0] in Camltk.bind e [[], KeyPressDetail "Return"] (BindSet ([], fun _ -> action(Entry.get e))); pack [m][Side Side_Left]; pack [e][Side Side_Right; Fill Fill_X; Expand true]; f,e let new_labelm_entry parent txt memo = let f = Frame.create parent [] in let m = Label.create f [Text txt] and e = Entry.create f [Relief Sunken; TextVariable memo; TextWidth 0] in pack [m][Side Side_Left]; pack [e][Side Side_Right; Fill Fill_X; Expand true]; f,e
f6bc09033543c245c9bb24c91cf2bfe3ca1adc6b7c49822dd55bf52407c376ed
clojure-interop/java-jdk
MessageContext.clj
(ns javax.xml.ws.handler.MessageContext "The interface MessageContext abstracts the message context that is processed by a handler in the handle method. The MessageContext interface provides methods to manage a property set. MessageContext properties enable handlers in a handler chain to share processing related state." (:refer-clojure :only [require comment defn ->]) (:import [javax.xml.ws.handler MessageContext])) (defn set-scope "Sets the scope of a property. name - Name of the property associated with the MessageContext - `java.lang.String` scope - Desired scope of the property - `javax.xml.ws.handler.MessageContext$Scope` throws: java.lang.IllegalArgumentException - if an illegal property name is specified" ([^MessageContext this ^java.lang.String name ^javax.xml.ws.handler.MessageContext$Scope scope] (-> this (.setScope name scope)))) (defn get-scope "Gets the scope of a property. name - Name of the property - `java.lang.String` returns: Scope of the property - `javax.xml.ws.handler.MessageContext$Scope` throws: java.lang.IllegalArgumentException - if a non-existant property name is specified" (^javax.xml.ws.handler.MessageContext$Scope [^MessageContext this ^java.lang.String name] (-> this (.getScope name))))
null
https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.xml/src/javax/xml/ws/handler/MessageContext.clj
clojure
(ns javax.xml.ws.handler.MessageContext "The interface MessageContext abstracts the message context that is processed by a handler in the handle method. The MessageContext interface provides methods to manage a property set. MessageContext properties enable handlers in a handler chain to share processing related state." (:refer-clojure :only [require comment defn ->]) (:import [javax.xml.ws.handler MessageContext])) (defn set-scope "Sets the scope of a property. name - Name of the property associated with the MessageContext - `java.lang.String` scope - Desired scope of the property - `javax.xml.ws.handler.MessageContext$Scope` throws: java.lang.IllegalArgumentException - if an illegal property name is specified" ([^MessageContext this ^java.lang.String name ^javax.xml.ws.handler.MessageContext$Scope scope] (-> this (.setScope name scope)))) (defn get-scope "Gets the scope of a property. name - Name of the property - `java.lang.String` returns: Scope of the property - `javax.xml.ws.handler.MessageContext$Scope` throws: java.lang.IllegalArgumentException - if a non-existant property name is specified" (^javax.xml.ws.handler.MessageContext$Scope [^MessageContext this ^java.lang.String name] (-> this (.getScope name))))
0635916d622b61a69af1287552eb90585f8b6e0d487723948a075b7cf68f2994
gregr/dKanren
benchmarks.rkt
#lang racket/base (require (rename-in "lifted-closure-encoding.rkt" (term? term-lifted-closure?) (eval-term eval-term-lifted-closure) (initial-env initial-env-lifted-closure)) (rename-in "closure-encoding.rkt" (term? term-closure-encoded?) (eval-term eval-term-closure-encoded) (initial-env initial-env-closure-encoded)) (rename-in "raw.rkt" (term? term-raw?) (eval-term eval-term-raw) (initial-env initial-env-raw)) racket/list racket/match ) (define problem-iterations 100) (define problem-size 10) ;; Use this size to differentiate immediate and runtime scheme eval, but ;; remember to turn off the slow evaluators! ( define problem - size 10000 ) (define (run/scheme-eval term) (eval term)) (define (run/raw-eval term) (eval-term-raw term initial-env-raw)) (define (run/closure-eval term) (eval-term-closure-encoded term initial-env-closure-encoded)) (define (run/lifted-closure-eval term) (let-values (((st v) ((eval-term-lifted-closure term initial-env-lifted-closure) #t))) v)) (define (run/scheme-eval-eval term) (run/eval-eval run/scheme-eval term)) (define (run/raw-eval-eval term) (run/eval-eval run/raw-eval term)) (define (run/closure-eval-eval term) (run/eval-eval run/closure-eval term)) (define (run/lifted-closure-eval-eval term) (run/eval-eval run/lifted-closure-eval term)) (define (run/eval-eval run/eval term) (run/eval `(let ((closure-tag ',(gensym "#%closure")) (prim-tag ',(gensym "#%primitive")) (empty-env '())) (let ((initial-env `((cons . (val . (,prim-tag . cons))) (car . (val . (,prim-tag . car))) (cdr . (val . (,prim-tag . cdr))) (null? . (val . (,prim-tag . null?))) (pair? . (val . (,prim-tag . pair?))) (symbol? . (val . (,prim-tag . symbol?))) (not . (val . (,prim-tag . not))) (equal? . (val . (,prim-tag . equal?))) (list . (val . (,closure-tag (lambda x x) ,empty-env))) . ,empty-env)) (closure-tag? (lambda (v) (equal? v closure-tag))) (prim-tag? (lambda (v) (equal? v prim-tag)))) (letrec ((applicable-tag? (lambda (v) (or (closure-tag? v) (prim-tag? v)))) (quotable? (lambda (v) (match v ((? symbol?) (not (applicable-tag? v))) (`(,a . ,d) (and (quotable? a) (quotable? d))) (_ #t)))) (not-in-params? (lambda (ps sym) (match ps ('() #t) (`(,a . ,d) (and (not (equal? a sym)) (not-in-params? d sym)))))) (param-list? (lambda (x) (match x ('() #t) (`(,(? symbol? a) . ,d) (and (param-list? d) (not-in-params? d a))) (_ #f)))) (params? (lambda (x) (match x ((? param-list?) #t) (x (symbol? x))))) (in-env? (lambda (env sym) (match env ('() #f) (`((,a . ,_). ,d) (or (equal? a sym) (in-env? d sym)))))) (extend-env* (lambda (params args env) (match `(,params . ,args) (`(() . ()) env) (`((,x . ,dx*) . (,a . ,da*)) (extend-env* dx* da* `((,x . (val . ,a)) . ,env)))))) (lookup (lambda (env sym) (match env (`((,y . ,b) . ,rest) (if (equal? sym y) (match b (`(val . ,v) v) (`(rec . ,lam-expr) `(,closure-tag ,lam-expr ,env))) (lookup rest sym)))))) (term? (lambda (term env) (letrec ((term1? (lambda (v) (term? v env))) (terms? (lambda (ts env) (match ts ('() #t) (`(,t . ,ts) (and (term? t env) (terms? ts env))))))) (match term (#t #t) (#f #t) ((? number?) #t) ((and (? symbol? sym)) (in-env? env sym)) (`(,(? term1?) . ,rands) (terms? rands env)) (`(quote ,datum) (quotable? datum)) (`(if ,c ,t ,f) (and (term1? c) (term1? t) (term1? f))) (`(lambda ,params ,body) (and (params? params) (let ((res (match params ((and (not (? symbol?)) params) (extend-env* params params env)) (sym `((,sym . (val . ,sym)) . ,env))))) (term? body res)))) (`(letrec ((,p-name ,(and `(lambda ,params ,body) lam-expr))) ,letrec-body) (and (params? params) (let ((res `((,p-name . (rec . (lambda ,params ,body))) . ,env))) (and (term? lam-expr res) (term? letrec-body res))))) (_ #f))))) (eval-prim (lambda (prim-id args) (match `(,prim-id . ,args) (`(cons ,a ,d) `(,a . ,d)) (`(car (,(and (not (? applicable-tag?)) a) . ,d)) a) (`(cdr (,(and (not (? applicable-tag?)) a) . ,d)) d) (`(null? ,v) (match v ('() #t) (_ #f))) (`(pair? ,v) (match v (`(,(not (? applicable-tag?)) . ,_) #t) (_ #f))) (`(symbol? ,v) (symbol? v)) (`(number? ,v) (number? v)) (`(not ,v) (match v (#f #t) (_ #f))) (`(equal? ,v1 ,v2) (equal? v1 v2))))) (eval-term-list (lambda (terms env) (match terms ('() '()) (`(,term . ,terms) `(,(eval-term term env) . ,(eval-term-list terms env)))))) (eval-term (lambda (term env) (let ((bound? (lambda (sym) (in-env? env sym))) (term1? (lambda (v) (term? v env)))) (match term (#t #t) (#f #f) ((? number? num) num) (`(,(and 'quote (not (? bound?))) ,(? quotable? datum)) datum) ((? symbol? sym) (lookup env sym)) ((and `(,op . ,_) operation) (match operation (`(,(or (? bound?) (not (? symbol?))) . ,rands) (let ((op (eval-term op env)) (a* (eval-term-list rands env))) (match op (`(,(? prim-tag?) . ,prim-id) (eval-prim prim-id a*)) (`(,(? closure-tag?) (lambda ,x ,body) ,env^) (let ((res (match x ((and (not (? symbol?)) params) (extend-env* params a* env^)) (sym `((,sym . (val . ,a*)) . ,env^))))) (eval-term body res)))))) (`(if ,condition ,alt-true ,alt-false) (if (eval-term condition env) (eval-term alt-true env) (eval-term alt-false env))) (`(lambda ,params ,body) `(,closure-tag (lambda ,params ,body) ,env)) (`(letrec ((,p-name (lambda ,params ,body))) ,letrec-body) (eval-term letrec-body `((,p-name . (rec . (lambda ,params ,body))) . ,env)))))))))) (let ((program ',term)) (eval-term program initial-env))))))) (define ex-append `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (list . ,(make-list problem-iterations `(append ',(range problem-size) '()))))) (define ex-reverse-quadratic `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (letrec ((reverse (lambda (xs) (if (null? xs) '() (append (reverse (cdr xs)) (list (car xs))))))) (list . ,(make-list problem-iterations `(reverse ',(range problem-size))))))) (define (benchmark) (let loop-prog ((programs `((append ,ex-append) (reverse-quadratic ,ex-reverse-quadratic) ))) (when (pair? programs) (let ((program (car programs)) (programs (cdr programs))) (newline) (displayln `(program: ,(car program))) (let loop-eval ((runners `((scheme-eval-static ,(eval `(lambda (,(gensym "unused")) ,(cadr program)))) (scheme-eval-runtime ,run/scheme-eval) (closure-eval ,run/closure-eval) (lifted-closure-eval ,run/lifted-closure-eval) (raw-eval ,run/raw-eval) ;; TODO: this needs to require racket/match ;(scheme-eval-eval ,run/scheme-eval-eval) (closure-eval-eval ,run/closure-eval-eval) (lifted-closure-eval-eval ,run/lifted-closure-eval-eval) (raw-eval-eval ,run/raw-eval-eval) ))) (if (null? runners) (loop-prog programs) (let ((runner (car runners)) (runners (cdr runners))) (collect-garbage 'major) (displayln `(evaluator: ,(car runner))) (time (void ((cadr runner) (cadr program)))) ( time ( ( ( cadr runner ) ( cadr program ) ) ) ) (loop-eval runners)))))))) (benchmark) ; TODO: port these to Chez Scheme ; deterministic evaluation benchmark ideas to measure sources of overhead ; across programs: append, reverse, map, fold, mini interpreter, remove-foo, etc. ; across program implementations: tailcall, w/ fold, etc. ; across runtimes: ; scheme, mk-only, mixed ; across interpreter architectures: ; static (scheme only) ; eval at runtime (scheme only) ; ahead-of-time compiled (dkanren only) ; closure encoding (mk would need to support procedure values) ; de bruin encoding (with and without integer support) ; raw interpretation ; original relational interpreter(s) (mk only)
null
https://raw.githubusercontent.com/gregr/dKanren/2f05275b00dfba5c2f0ca196a514c377b3b60798/dkanren-benchmarks/benchmarks.rkt
racket
Use this size to differentiate immediate and runtime scheme eval, but remember to turn off the slow evaluators! TODO: this needs to require racket/match (scheme-eval-eval ,run/scheme-eval-eval) TODO: port these to Chez Scheme deterministic evaluation benchmark ideas to measure sources of overhead across programs: append, reverse, map, fold, mini interpreter, remove-foo, etc. across program implementations: tailcall, w/ fold, etc. across runtimes: scheme, mk-only, mixed across interpreter architectures: static (scheme only) eval at runtime (scheme only) ahead-of-time compiled (dkanren only) closure encoding (mk would need to support procedure values) de bruin encoding (with and without integer support) raw interpretation original relational interpreter(s) (mk only)
#lang racket/base (require (rename-in "lifted-closure-encoding.rkt" (term? term-lifted-closure?) (eval-term eval-term-lifted-closure) (initial-env initial-env-lifted-closure)) (rename-in "closure-encoding.rkt" (term? term-closure-encoded?) (eval-term eval-term-closure-encoded) (initial-env initial-env-closure-encoded)) (rename-in "raw.rkt" (term? term-raw?) (eval-term eval-term-raw) (initial-env initial-env-raw)) racket/list racket/match ) (define problem-iterations 100) (define problem-size 10) ( define problem - size 10000 ) (define (run/scheme-eval term) (eval term)) (define (run/raw-eval term) (eval-term-raw term initial-env-raw)) (define (run/closure-eval term) (eval-term-closure-encoded term initial-env-closure-encoded)) (define (run/lifted-closure-eval term) (let-values (((st v) ((eval-term-lifted-closure term initial-env-lifted-closure) #t))) v)) (define (run/scheme-eval-eval term) (run/eval-eval run/scheme-eval term)) (define (run/raw-eval-eval term) (run/eval-eval run/raw-eval term)) (define (run/closure-eval-eval term) (run/eval-eval run/closure-eval term)) (define (run/lifted-closure-eval-eval term) (run/eval-eval run/lifted-closure-eval term)) (define (run/eval-eval run/eval term) (run/eval `(let ((closure-tag ',(gensym "#%closure")) (prim-tag ',(gensym "#%primitive")) (empty-env '())) (let ((initial-env `((cons . (val . (,prim-tag . cons))) (car . (val . (,prim-tag . car))) (cdr . (val . (,prim-tag . cdr))) (null? . (val . (,prim-tag . null?))) (pair? . (val . (,prim-tag . pair?))) (symbol? . (val . (,prim-tag . symbol?))) (not . (val . (,prim-tag . not))) (equal? . (val . (,prim-tag . equal?))) (list . (val . (,closure-tag (lambda x x) ,empty-env))) . ,empty-env)) (closure-tag? (lambda (v) (equal? v closure-tag))) (prim-tag? (lambda (v) (equal? v prim-tag)))) (letrec ((applicable-tag? (lambda (v) (or (closure-tag? v) (prim-tag? v)))) (quotable? (lambda (v) (match v ((? symbol?) (not (applicable-tag? v))) (`(,a . ,d) (and (quotable? a) (quotable? d))) (_ #t)))) (not-in-params? (lambda (ps sym) (match ps ('() #t) (`(,a . ,d) (and (not (equal? a sym)) (not-in-params? d sym)))))) (param-list? (lambda (x) (match x ('() #t) (`(,(? symbol? a) . ,d) (and (param-list? d) (not-in-params? d a))) (_ #f)))) (params? (lambda (x) (match x ((? param-list?) #t) (x (symbol? x))))) (in-env? (lambda (env sym) (match env ('() #f) (`((,a . ,_). ,d) (or (equal? a sym) (in-env? d sym)))))) (extend-env* (lambda (params args env) (match `(,params . ,args) (`(() . ()) env) (`((,x . ,dx*) . (,a . ,da*)) (extend-env* dx* da* `((,x . (val . ,a)) . ,env)))))) (lookup (lambda (env sym) (match env (`((,y . ,b) . ,rest) (if (equal? sym y) (match b (`(val . ,v) v) (`(rec . ,lam-expr) `(,closure-tag ,lam-expr ,env))) (lookup rest sym)))))) (term? (lambda (term env) (letrec ((term1? (lambda (v) (term? v env))) (terms? (lambda (ts env) (match ts ('() #t) (`(,t . ,ts) (and (term? t env) (terms? ts env))))))) (match term (#t #t) (#f #t) ((? number?) #t) ((and (? symbol? sym)) (in-env? env sym)) (`(,(? term1?) . ,rands) (terms? rands env)) (`(quote ,datum) (quotable? datum)) (`(if ,c ,t ,f) (and (term1? c) (term1? t) (term1? f))) (`(lambda ,params ,body) (and (params? params) (let ((res (match params ((and (not (? symbol?)) params) (extend-env* params params env)) (sym `((,sym . (val . ,sym)) . ,env))))) (term? body res)))) (`(letrec ((,p-name ,(and `(lambda ,params ,body) lam-expr))) ,letrec-body) (and (params? params) (let ((res `((,p-name . (rec . (lambda ,params ,body))) . ,env))) (and (term? lam-expr res) (term? letrec-body res))))) (_ #f))))) (eval-prim (lambda (prim-id args) (match `(,prim-id . ,args) (`(cons ,a ,d) `(,a . ,d)) (`(car (,(and (not (? applicable-tag?)) a) . ,d)) a) (`(cdr (,(and (not (? applicable-tag?)) a) . ,d)) d) (`(null? ,v) (match v ('() #t) (_ #f))) (`(pair? ,v) (match v (`(,(not (? applicable-tag?)) . ,_) #t) (_ #f))) (`(symbol? ,v) (symbol? v)) (`(number? ,v) (number? v)) (`(not ,v) (match v (#f #t) (_ #f))) (`(equal? ,v1 ,v2) (equal? v1 v2))))) (eval-term-list (lambda (terms env) (match terms ('() '()) (`(,term . ,terms) `(,(eval-term term env) . ,(eval-term-list terms env)))))) (eval-term (lambda (term env) (let ((bound? (lambda (sym) (in-env? env sym))) (term1? (lambda (v) (term? v env)))) (match term (#t #t) (#f #f) ((? number? num) num) (`(,(and 'quote (not (? bound?))) ,(? quotable? datum)) datum) ((? symbol? sym) (lookup env sym)) ((and `(,op . ,_) operation) (match operation (`(,(or (? bound?) (not (? symbol?))) . ,rands) (let ((op (eval-term op env)) (a* (eval-term-list rands env))) (match op (`(,(? prim-tag?) . ,prim-id) (eval-prim prim-id a*)) (`(,(? closure-tag?) (lambda ,x ,body) ,env^) (let ((res (match x ((and (not (? symbol?)) params) (extend-env* params a* env^)) (sym `((,sym . (val . ,a*)) . ,env^))))) (eval-term body res)))))) (`(if ,condition ,alt-true ,alt-false) (if (eval-term condition env) (eval-term alt-true env) (eval-term alt-false env))) (`(lambda ,params ,body) `(,closure-tag (lambda ,params ,body) ,env)) (`(letrec ((,p-name (lambda ,params ,body))) ,letrec-body) (eval-term letrec-body `((,p-name . (rec . (lambda ,params ,body))) . ,env)))))))))) (let ((program ',term)) (eval-term program initial-env))))))) (define ex-append `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (list . ,(make-list problem-iterations `(append ',(range problem-size) '()))))) (define ex-reverse-quadratic `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (letrec ((reverse (lambda (xs) (if (null? xs) '() (append (reverse (cdr xs)) (list (car xs))))))) (list . ,(make-list problem-iterations `(reverse ',(range problem-size))))))) (define (benchmark) (let loop-prog ((programs `((append ,ex-append) (reverse-quadratic ,ex-reverse-quadratic) ))) (when (pair? programs) (let ((program (car programs)) (programs (cdr programs))) (newline) (displayln `(program: ,(car program))) (let loop-eval ((runners `((scheme-eval-static ,(eval `(lambda (,(gensym "unused")) ,(cadr program)))) (scheme-eval-runtime ,run/scheme-eval) (closure-eval ,run/closure-eval) (lifted-closure-eval ,run/lifted-closure-eval) (raw-eval ,run/raw-eval) (closure-eval-eval ,run/closure-eval-eval) (lifted-closure-eval-eval ,run/lifted-closure-eval-eval) (raw-eval-eval ,run/raw-eval-eval) ))) (if (null? runners) (loop-prog programs) (let ((runner (car runners)) (runners (cdr runners))) (collect-garbage 'major) (displayln `(evaluator: ,(car runner))) (time (void ((cadr runner) (cadr program)))) ( time ( ( ( cadr runner ) ( cadr program ) ) ) ) (loop-eval runners)))))))) (benchmark)
36f9066f4b7509f8fb6324689b5b914aa8a68d7c8ffddd23639ed0e4d9bb63b3
xapi-project/xen-api-libs
test_server.ml
open Threadext let finished = ref false let finished_m = Mutex.create () let finished_c = Condition.create () let _ = let port = ref 8080 in let use_fastpath = ref false in Arg.parse [ "-p", Arg.Set_int port, "port to listen on"; "-fast", Arg.Set use_fastpath, "use HTTP fastpath"; ] (fun x -> Printf.fprintf stderr "Ignoring unexpected argument: %s\n" x) "A simple test HTTP server"; let open Http_svr in let server = Server.empty () in if !use_fastpath then Server.enable_fastpath server; Server.add_handler server Http.Get "/stop" (FdIO (fun request s _ -> let r = Http.Response.to_wire_string (Http.Response.make "200" "OK") in Unixext.really_write_string s r; Mutex.execute finished_m (fun () -> finished := true; Condition.signal finished_c ) ) ); Server.add_handler server Http.Post "/echo" (FdIO (fun request s _ -> match request.Http.Request.content_length with | None -> Unixext.really_write_string s (Http.Response.to_wire_string (Http.Response.make "404" "content length missing")) | Some l -> let txt = Unixext.really_read_string s (Int64.to_int l) in let r = Http.Response.to_wire_string (Http.Response.make ~body:txt "200" "OK") in Unixext.really_write_string s r ) ); Server.add_handler server Http.Get "/stats" (FdIO (fun request s _ -> let lines = List.map (fun (m, uri, s) -> Printf.sprintf "%s,%s,%d,%d\n" (Http.string_of_method_t m) uri s.Http_svr.Stats.n_requests s.Http_svr.Stats.n_connections ) (Server.all_stats server) in let txt = String.concat "" lines in let r = Http.Response.to_wire_string (Http.Response.make ~body:txt "200" "OK") in Unixext.really_write_string s r ) ); let ip = "0.0.0.0" in let inet_addr = Unix.inet_addr_of_string ip in let addr = Unix.ADDR_INET(inet_addr, !port) in let socket = Http_svr.bind ~listen_backlog:5 addr "server" in start server socket; Printf.printf "Server started on %s:%d\n" ip !port; Mutex.execute finished_m (fun () -> while not(!finished) do Condition.wait finished_c finished_m done ); Printf.printf "Exiting\n"; stop socket
null
https://raw.githubusercontent.com/xapi-project/xen-api-libs/d603ee2b8456bc2aac99b0a4955f083e22f4f314/http-svr/test_server.ml
ocaml
open Threadext let finished = ref false let finished_m = Mutex.create () let finished_c = Condition.create () let _ = let port = ref 8080 in let use_fastpath = ref false in Arg.parse [ "-p", Arg.Set_int port, "port to listen on"; "-fast", Arg.Set use_fastpath, "use HTTP fastpath"; ] (fun x -> Printf.fprintf stderr "Ignoring unexpected argument: %s\n" x) "A simple test HTTP server"; let open Http_svr in let server = Server.empty () in if !use_fastpath then Server.enable_fastpath server; Server.add_handler server Http.Get "/stop" (FdIO (fun request s _ -> let r = Http.Response.to_wire_string (Http.Response.make "200" "OK") in Unixext.really_write_string s r; Mutex.execute finished_m (fun () -> finished := true; Condition.signal finished_c ) ) ); Server.add_handler server Http.Post "/echo" (FdIO (fun request s _ -> match request.Http.Request.content_length with | None -> Unixext.really_write_string s (Http.Response.to_wire_string (Http.Response.make "404" "content length missing")) | Some l -> let txt = Unixext.really_read_string s (Int64.to_int l) in let r = Http.Response.to_wire_string (Http.Response.make ~body:txt "200" "OK") in Unixext.really_write_string s r ) ); Server.add_handler server Http.Get "/stats" (FdIO (fun request s _ -> let lines = List.map (fun (m, uri, s) -> Printf.sprintf "%s,%s,%d,%d\n" (Http.string_of_method_t m) uri s.Http_svr.Stats.n_requests s.Http_svr.Stats.n_connections ) (Server.all_stats server) in let txt = String.concat "" lines in let r = Http.Response.to_wire_string (Http.Response.make ~body:txt "200" "OK") in Unixext.really_write_string s r ) ); let ip = "0.0.0.0" in let inet_addr = Unix.inet_addr_of_string ip in let addr = Unix.ADDR_INET(inet_addr, !port) in let socket = Http_svr.bind ~listen_backlog:5 addr "server" in start server socket; Printf.printf "Server started on %s:%d\n" ip !port; Mutex.execute finished_m (fun () -> while not(!finished) do Condition.wait finished_c finished_m done ); Printf.printf "Exiting\n"; stop socket
ff86d056a12a0b6cc5fe6fb96f34f851bfcd306be7a12dc2db39d6e2564cf228
DavidAlphaFox/RabbitMQ
websocket_handler_init_shutdown.erl
%% Feel free to use, reuse and abuse the code in this file. -module(websocket_handler_init_shutdown). -behaviour(cowboy_http_handler). -behaviour(cowboy_http_websocket_handler). -export([init/3, handle/2, terminate/2]). -export([websocket_init/3, websocket_handle/3, websocket_info/3, websocket_terminate/3]). init(_Any, _Req, _Opts) -> {upgrade, protocol, cowboy_http_websocket}. handle(_Req, _State) -> exit(badarg). terminate(_Req, _State) -> exit(badarg). websocket_init(_TransportName, Req, _Opts) -> {ok, Req2} = cowboy_http_req:reply(403, Req), {shutdown, Req2}. websocket_handle(_Frame, _Req, _State) -> exit(badarg). websocket_info(_Info, _Req, _State) -> exit(badarg). websocket_terminate(_Reason, _Req, _State) -> exit(badarg).
null
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/plugins-src/cowboy-wrapper/cowboy-git/test/websocket_handler_init_shutdown.erl
erlang
Feel free to use, reuse and abuse the code in this file.
-module(websocket_handler_init_shutdown). -behaviour(cowboy_http_handler). -behaviour(cowboy_http_websocket_handler). -export([init/3, handle/2, terminate/2]). -export([websocket_init/3, websocket_handle/3, websocket_info/3, websocket_terminate/3]). init(_Any, _Req, _Opts) -> {upgrade, protocol, cowboy_http_websocket}. handle(_Req, _State) -> exit(badarg). terminate(_Req, _State) -> exit(badarg). websocket_init(_TransportName, Req, _Opts) -> {ok, Req2} = cowboy_http_req:reply(403, Req), {shutdown, Req2}. websocket_handle(_Frame, _Req, _State) -> exit(badarg). websocket_info(_Info, _Req, _State) -> exit(badarg). websocket_terminate(_Reason, _Req, _State) -> exit(badarg).
c9c798bd733608fbde48cf136a6d8f9639a60d7ff3447be1b62497dcda3dd947
burkaydurdu/mock-ui
core_test.cljs
(ns mock-ui.core-test (:require [cljs.test :refer-macros [deftest testing is]] [mock-ui.core :as core])) (deftest fake-test (testing "fake description" (is (= 1 2))))
null
https://raw.githubusercontent.com/burkaydurdu/mock-ui/eb92657a33100ca10b80827abf7c7acdf7d397bb/test/mock_ui/core_test.cljs
clojure
(ns mock-ui.core-test (:require [cljs.test :refer-macros [deftest testing is]] [mock-ui.core :as core])) (deftest fake-test (testing "fake description" (is (= 1 2))))
9d9a856fb948c9763238308c8e8b6de8500c9eb8ebe2c8fbb079b9f757783a86
music-suite/music-score
Juxtapose.hs
module Music.Time.Juxtapose ( module Music.Time.Split, module Music.Time.Reverse, -- * Align without composition lead, follow, -- * Standard composition after, before, during, (|>), (<|), -- ** More exotic sustain, palindrome, -- * Catenation scat, pcat, -- * Repetition times, ) where import Control.Lens hiding ((<|), (|>)) import Data.AffineSpace import Data.AffineSpace.Point import Data.Semigroup import Data.VectorSpace import Music.Time.Reverse import Music.Time.Split -- | -- @ -- (a `lead` b)^.'offset' = b^.'onset' -- @ -- -- lead :: (HasPosition a, HasPosition b, Transformable a) => a -> b -> a a `lead` b = placeAt 1 (b `_position` 0) a -- | -- @ -- a^.'offset' = (a `follow` b)^.'onset' -- @ -- follow :: (HasPosition a, HasPosition b, Transformable b) => a -> b -> b a `follow` b = placeAt 0 (a `_position` 1) b after :: (Semigroup a, Transformable a, HasPosition a) => a -> a -> a a `after` b = a <> (a `follow` b) before :: (Semigroup a, Transformable a, HasPosition a) => a -> a -> a a `before` b = (a `lead` b) <> b -- | -- A value followed by its reverse (retrograde). -- palindrome :: (Semigroup a, Reversible a, HasPosition a) => a -> a palindrome a = a `after` rev a infixr 6 |> infixr 6 <| -- | -- An infix alias for 'after'. -- (|>) :: (Semigroup a, HasPosition a, Transformable a) => a -> a -> a (|>) = after -- | -- An infix alias for 'before'. -- (<|) :: (Semigroup a, HasPosition a, Transformable a) => a -> a -> a (<|) = before infixr 6 > | infixr 6 | < -- | -- Compose a list of sequential objects, with onset and offset tangent to one another. -- -- For non-positioned types, this is the often same as 'mconcat' -- For positioned types, this is the same as 'afterAnother' -- scat :: (Semigroup a, Monoid a, HasPosition a, Transformable a) => [a] -> a scat = Prelude.foldr (|>) mempty -- | -- Compose a list of parallel objects, so that their local origins align. -- -- This not possible for non-positioned types, as they have no notion of an origin. -- For positioned types this is the same as 'mconcat'. -- pcat :: (Semigroup a, Monoid a) => [a] -> a pcat = Prelude.foldr (<>) mempty -- | -- Move a value so that its era is equal to the era of another value. -- during :: (HasPosition a, HasPosition b, Transformable a, Transformable b) => a -> b -> a y `during` x = set era (view era x) y -- | Like ' < > ' , but scaling the second agument to the duration of the first . -- sustain :: (Semigroup a, HasPosition a, Transformable a) => a -> a -> a x `sustain` y = x <> y `during` x -- | -- Repeat exact amount of times. -- -- @ -- 'Int' -> 'Score' a -> 'Score' a -- @ -- times :: (Semigroup a, Monoid a, HasPosition a, Transformable a) => Int -> a -> a times n = scat . replicate n
null
https://raw.githubusercontent.com/music-suite/music-score/aa7182d8ded25c03a56b83941fc625123a7931f8/src/Music/Time/Juxtapose.hs
haskell
* Align without composition * Standard composition ** More exotic * Catenation * Repetition | @ (a `lead` b)^.'offset' = b^.'onset' @ | @ a^.'offset' = (a `follow` b)^.'onset' @ | A value followed by its reverse (retrograde). | An infix alias for 'after'. | An infix alias for 'before'. | Compose a list of sequential objects, with onset and offset tangent to one another. For non-positioned types, this is the often same as 'mconcat' For positioned types, this is the same as 'afterAnother' | Compose a list of parallel objects, so that their local origins align. This not possible for non-positioned types, as they have no notion of an origin. For positioned types this is the same as 'mconcat'. | Move a value so that its era is equal to the era of another value. | | Repeat exact amount of times. @ 'Int' -> 'Score' a -> 'Score' a @
module Music.Time.Juxtapose ( module Music.Time.Split, module Music.Time.Reverse, lead, follow, after, before, during, (|>), (<|), sustain, palindrome, scat, pcat, times, ) where import Control.Lens hiding ((<|), (|>)) import Data.AffineSpace import Data.AffineSpace.Point import Data.Semigroup import Data.VectorSpace import Music.Time.Reverse import Music.Time.Split lead :: (HasPosition a, HasPosition b, Transformable a) => a -> b -> a a `lead` b = placeAt 1 (b `_position` 0) a follow :: (HasPosition a, HasPosition b, Transformable b) => a -> b -> b a `follow` b = placeAt 0 (a `_position` 1) b after :: (Semigroup a, Transformable a, HasPosition a) => a -> a -> a a `after` b = a <> (a `follow` b) before :: (Semigroup a, Transformable a, HasPosition a) => a -> a -> a a `before` b = (a `lead` b) <> b palindrome :: (Semigroup a, Reversible a, HasPosition a) => a -> a palindrome a = a `after` rev a infixr 6 |> infixr 6 <| (|>) :: (Semigroup a, HasPosition a, Transformable a) => a -> a -> a (|>) = after (<|) :: (Semigroup a, HasPosition a, Transformable a) => a -> a -> a (<|) = before infixr 6 > | infixr 6 | < scat :: (Semigroup a, Monoid a, HasPosition a, Transformable a) => [a] -> a scat = Prelude.foldr (|>) mempty pcat :: (Semigroup a, Monoid a) => [a] -> a pcat = Prelude.foldr (<>) mempty during :: (HasPosition a, HasPosition b, Transformable a, Transformable b) => a -> b -> a y `during` x = set era (view era x) y Like ' < > ' , but scaling the second agument to the duration of the first . sustain :: (Semigroup a, HasPosition a, Transformable a) => a -> a -> a x `sustain` y = x <> y `during` x times :: (Semigroup a, Monoid a, HasPosition a, Transformable a) => Int -> a -> a times n = scat . replicate n
248b9a1c593c0ed91f9d40151906381cf94e281a22e3ff35414f97ad976262fd
rossberg/1ml
main.ml
* ( c ) 2014 * (c) 2014 Andreas Rossberg *) let name = "1ML" let version = "0.2" let interactive_flag = ref false let trace_flag = ref false let ast_flag = ref false let result_flag = ref false let no_run_flag = ref false let run_f_flag = ref false let trace_phase name = if !trace_flag then print_endline ("-- " ^ name) let load file = let f = open_in file in let size = in_channel_length f in let source = really_input_string f size in close_in f; source let parse name source = let lexbuf = Lexing.from_string source in lexbuf.Lexing.lex_curr_p <- {lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = name}; try Parser.prog Lexer.token lexbuf with Source.Error (region, s) -> let region' = if region <> Source.nowhere_region then region else {Source.left = Lexer.convert_pos lexbuf.Lexing.lex_start_p; Source.right = Lexer.convert_pos lexbuf.Lexing.lex_curr_p} in raise (Source.Error (region', s)) let env = ref Env.empty let state = ref Lambda.Env.empty let f_state = ref [] let print_sig s = match s with | Types.ExT(aks, Types.StrT(tr)) -> List.iter (fun (a, k) -> Format.open_box 0; Format.print_string ("? " ^ a ^ " : "); Types.print_kind k; Format.print_break 1 0; Format.close_box () ) aks; Types.print_row tr; print_endline "" | _ -> Types.print_extyp s; print_endline "" let process file source = try trace_phase "Parsing..."; let prog = parse file source in if !ast_flag then begin print_endline (Syntax.string_of_exp prog) end; trace_phase "Elaborating..."; let sign, _, fprog = Elab.elab !env prog in if !Elab.verify_flag then begin trace_phase "Checking..."; Fomega.check_exp (Erase.erase_env !env) fprog (Erase.erase_extyp sign) "Prog" end; let Types.ExT(aks, typ) = sign in let typrow = match typ with Types.StrT(row) -> row | _ -> [] in if !no_run_flag then print_sig sign else begin if !run_f_flag then begin trace_phase "Running..."; let closed_prog = List.fold_right (fun (x, t, e1) e2 -> Fomega.LetE(e1, x, e2)) !f_state fprog in let result = Fomega.norm_exp closed_prog in trace_phase "Result:"; if !result_flag then begin print_string (Fomega.string_of_exp result); print_string " : "; print_endline (Types.string_of_norm_extyp sign) end else begin print_sig sign end; let rec unpack = function | Fomega.PackE(_, v, _) -> unpack v | Fomega.TupE(vr) -> vr | _ -> assert false in let f_state' = List.map2 (fun (x, t) (x', v) -> assert (x = x'); x, Erase.erase_typ t, v ) typrow (unpack result) in f_state := !f_state @ f_state' end else begin trace_phase "Compiling..."; let lambda = Compile.compile (Erase.erase_env !env) fprog in trace_phase "Running..."; let value = Lambda.eval !state lambda in trace_phase "Result:"; if !result_flag then begin print_string (Lambda.string_of_value value); print_string " : "; print_endline (Types.string_of_norm_extyp sign) end else begin print_sig sign end; let ls = match sign with | Types.ExT(_, Types.StrT(tr)) -> List.sort compare (List.map fst tr) | _ -> assert false in let vs = match value with | Lambda.TupV(vs) -> vs | _ -> assert false in state := List.fold_right2 Lambda.Env.add ls vs !state end end; env := Env.add_row typrow (Env.add_typs aks !env) with Source.Error (at, s) -> trace_phase "Error:"; prerr_endline (Source.string_of_region at ^ ": " ^ s); if not !interactive_flag then exit 1 let process_file file = trace_phase ("Loading (" ^ file ^ ")..."); let source = load file in process file source let rec process_stdin () = print_string (name ^ "> "); flush_all (); match try Some (input_line stdin) with End_of_file -> None with | None -> print_endline ""; trace_phase "Bye." | Some source -> process "stdin" source; process_stdin () let greet () = print_endline ("Version " ^ version) let usage = "Usage: " ^ name ^ " [option] [file ...]" let argspec = Arg.align [ "-", Arg.Set interactive_flag, " run interactively (default if no files given)"; "-c", Arg.Set Elab.verify_flag, " check target program"; "-d", Arg.Set no_run_flag, " dry, do not run program"; "-f", Arg.Set run_f_flag, " run program as System F reduction"; "-p", Arg.Set ast_flag, " show parse tree"; "-r", Arg.Set result_flag, " show resulting term"; "-t", Arg.Set trace_flag, " trace compiler phases"; "-v", Arg.Unit greet, " show version"; "-tb", Arg.Set Trace.bind_flag, " trace bindings"; "-te", Arg.Set Trace.elab_flag, " trace elaboration"; "-ts", Arg.Set Trace.sub_flag, " trace subtyping"; "-td", Arg.Set Trace.debug_flag, " debug output"; "-vt", Arg.Unit Types.verbosest_on, " verbose types"; "-ut", Arg.Set Types.undecidable_flag, " allow undecidable subtyping" ] let () = Printexc.record_backtrace true; try let files = ref [] in Arg.parse argspec (fun file -> files := !files @ [file]) usage; if !files = [] then interactive_flag := true; List.iter process_file !files; if !interactive_flag then process_stdin () with exn -> flush stdout; prerr_endline (Sys.argv.(0) ^ ": uncaught exception " ^ Printexc.to_string exn); Printexc.print_backtrace stderr; exit 2
null
https://raw.githubusercontent.com/rossberg/1ml/028859a6a687d874981f440bdc5be5f8daa4a777/main.ml
ocaml
* ( c ) 2014 * (c) 2014 Andreas Rossberg *) let name = "1ML" let version = "0.2" let interactive_flag = ref false let trace_flag = ref false let ast_flag = ref false let result_flag = ref false let no_run_flag = ref false let run_f_flag = ref false let trace_phase name = if !trace_flag then print_endline ("-- " ^ name) let load file = let f = open_in file in let size = in_channel_length f in let source = really_input_string f size in close_in f; source let parse name source = let lexbuf = Lexing.from_string source in lexbuf.Lexing.lex_curr_p <- {lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = name}; try Parser.prog Lexer.token lexbuf with Source.Error (region, s) -> let region' = if region <> Source.nowhere_region then region else {Source.left = Lexer.convert_pos lexbuf.Lexing.lex_start_p; Source.right = Lexer.convert_pos lexbuf.Lexing.lex_curr_p} in raise (Source.Error (region', s)) let env = ref Env.empty let state = ref Lambda.Env.empty let f_state = ref [] let print_sig s = match s with | Types.ExT(aks, Types.StrT(tr)) -> List.iter (fun (a, k) -> Format.open_box 0; Format.print_string ("? " ^ a ^ " : "); Types.print_kind k; Format.print_break 1 0; Format.close_box () ) aks; Types.print_row tr; print_endline "" | _ -> Types.print_extyp s; print_endline "" let process file source = try trace_phase "Parsing..."; let prog = parse file source in if !ast_flag then begin print_endline (Syntax.string_of_exp prog) end; trace_phase "Elaborating..."; let sign, _, fprog = Elab.elab !env prog in if !Elab.verify_flag then begin trace_phase "Checking..."; Fomega.check_exp (Erase.erase_env !env) fprog (Erase.erase_extyp sign) "Prog" end; let Types.ExT(aks, typ) = sign in let typrow = match typ with Types.StrT(row) -> row | _ -> [] in if !no_run_flag then print_sig sign else begin if !run_f_flag then begin trace_phase "Running..."; let closed_prog = List.fold_right (fun (x, t, e1) e2 -> Fomega.LetE(e1, x, e2)) !f_state fprog in let result = Fomega.norm_exp closed_prog in trace_phase "Result:"; if !result_flag then begin print_string (Fomega.string_of_exp result); print_string " : "; print_endline (Types.string_of_norm_extyp sign) end else begin print_sig sign end; let rec unpack = function | Fomega.PackE(_, v, _) -> unpack v | Fomega.TupE(vr) -> vr | _ -> assert false in let f_state' = List.map2 (fun (x, t) (x', v) -> assert (x = x'); x, Erase.erase_typ t, v ) typrow (unpack result) in f_state := !f_state @ f_state' end else begin trace_phase "Compiling..."; let lambda = Compile.compile (Erase.erase_env !env) fprog in trace_phase "Running..."; let value = Lambda.eval !state lambda in trace_phase "Result:"; if !result_flag then begin print_string (Lambda.string_of_value value); print_string " : "; print_endline (Types.string_of_norm_extyp sign) end else begin print_sig sign end; let ls = match sign with | Types.ExT(_, Types.StrT(tr)) -> List.sort compare (List.map fst tr) | _ -> assert false in let vs = match value with | Lambda.TupV(vs) -> vs | _ -> assert false in state := List.fold_right2 Lambda.Env.add ls vs !state end end; env := Env.add_row typrow (Env.add_typs aks !env) with Source.Error (at, s) -> trace_phase "Error:"; prerr_endline (Source.string_of_region at ^ ": " ^ s); if not !interactive_flag then exit 1 let process_file file = trace_phase ("Loading (" ^ file ^ ")..."); let source = load file in process file source let rec process_stdin () = print_string (name ^ "> "); flush_all (); match try Some (input_line stdin) with End_of_file -> None with | None -> print_endline ""; trace_phase "Bye." | Some source -> process "stdin" source; process_stdin () let greet () = print_endline ("Version " ^ version) let usage = "Usage: " ^ name ^ " [option] [file ...]" let argspec = Arg.align [ "-", Arg.Set interactive_flag, " run interactively (default if no files given)"; "-c", Arg.Set Elab.verify_flag, " check target program"; "-d", Arg.Set no_run_flag, " dry, do not run program"; "-f", Arg.Set run_f_flag, " run program as System F reduction"; "-p", Arg.Set ast_flag, " show parse tree"; "-r", Arg.Set result_flag, " show resulting term"; "-t", Arg.Set trace_flag, " trace compiler phases"; "-v", Arg.Unit greet, " show version"; "-tb", Arg.Set Trace.bind_flag, " trace bindings"; "-te", Arg.Set Trace.elab_flag, " trace elaboration"; "-ts", Arg.Set Trace.sub_flag, " trace subtyping"; "-td", Arg.Set Trace.debug_flag, " debug output"; "-vt", Arg.Unit Types.verbosest_on, " verbose types"; "-ut", Arg.Set Types.undecidable_flag, " allow undecidable subtyping" ] let () = Printexc.record_backtrace true; try let files = ref [] in Arg.parse argspec (fun file -> files := !files @ [file]) usage; if !files = [] then interactive_flag := true; List.iter process_file !files; if !interactive_flag then process_stdin () with exn -> flush stdout; prerr_endline (Sys.argv.(0) ^ ": uncaught exception " ^ Printexc.to_string exn); Printexc.print_backtrace stderr; exit 2
8529769ae4a5f523dec198a32dd3a67cdcfa193bd608c51ae2a58dbc8ff75280
uw-unsat/serval-sosp19
x32-alu32-k.rkt
#lang racket (require "../x32.rkt") (require serval/lib/unittest) (define tests (test-suite+ "x32-alu32-k tests" (jit-test-case '(BPF_ALU BPF_MOV BPF_K)) (jit-test-case '(BPF_ALU BPF_ADD BPF_K)) (jit-test-case '(BPF_ALU BPF_SUB BPF_K)) (jit-test-case '(BPF_ALU BPF_AND BPF_K)) (jit-test-case '(BPF_ALU BPF_OR BPF_K)) (jit-test-case '(BPF_ALU BPF_XOR BPF_K)) (jit-test-case '(BPF_ALU BPF_MUL BPF_K)) (jit-test-case '(BPF_ALU BPF_LSH BPF_K)) (jit-test-case '(BPF_ALU BPF_RSH BPF_K)) (jit-test-case '(BPF_ALU BPF_ARSH BPF_K)) )) (module+ test (time (run-tests tests)))
null
https://raw.githubusercontent.com/uw-unsat/serval-sosp19/175c42660fad84b44e4c9f6f723fd3c9450d65d4/bpf/jit/test/x32-alu32-k.rkt
racket
#lang racket (require "../x32.rkt") (require serval/lib/unittest) (define tests (test-suite+ "x32-alu32-k tests" (jit-test-case '(BPF_ALU BPF_MOV BPF_K)) (jit-test-case '(BPF_ALU BPF_ADD BPF_K)) (jit-test-case '(BPF_ALU BPF_SUB BPF_K)) (jit-test-case '(BPF_ALU BPF_AND BPF_K)) (jit-test-case '(BPF_ALU BPF_OR BPF_K)) (jit-test-case '(BPF_ALU BPF_XOR BPF_K)) (jit-test-case '(BPF_ALU BPF_MUL BPF_K)) (jit-test-case '(BPF_ALU BPF_LSH BPF_K)) (jit-test-case '(BPF_ALU BPF_RSH BPF_K)) (jit-test-case '(BPF_ALU BPF_ARSH BPF_K)) )) (module+ test (time (run-tests tests)))
cc67f7bf63ce13dbd9cfaec40682d3d52a65d99e51a2c57973285aadb02b257b
pa-ba/compdata
Eval.hs
# LANGUAGE GADTs , TemplateHaskell , MultiParamTypeClasses , FlexibleInstances , FlexibleContexts , UndecidableInstances , TypeOperators , ScopedTypeVariables , TypeSynonymInstances # GADTs, TemplateHaskell, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, UndecidableInstances, TypeOperators, ScopedTypeVariables, TypeSynonymInstances#-} module Multi.Functions.Comp.Eval where import Multi.DataTypes.Comp import Multi.Functions.Comp.Desugar import Data.Comp.Multi import Data.Comp.Multi.HEquality -- evaluation class Eval e v where evalAlg :: Alg e (Term v) eval :: (HFunctor e, Eval e v) => Term e :-> (Term v) eval = cata evalAlg instance (Eval f v, Eval g v) => Eval (f :++: g) v where evalAlg (HInl v) = evalAlg v evalAlg (HInr v) = evalAlg v instance (Value :<<: v) => Eval Value v where evalAlg = inject getInt :: (Value :<<: v) => Term v Int -> Int getInt t = case project t of Just (VInt x) -> x Nothing -> undefined getBool :: (Value :<<: v) => Term v Bool -> Bool getBool t = case project t of Just (VBool x) -> x Nothing -> undefined getPair :: (Value :<<: v) => Term v (s,t) -> ((Term v s), (Term v t)) getPair t = case project t of Just (VPair x y) -> (x, y) Nothing -> undefined instance (Value :<<: v, HEqF v) => Eval Op v where evalAlg (Plus x y) = iVInt $ getInt x + getInt y evalAlg (Mult x y) = iVInt $ getInt x * getInt y evalAlg (If b x y) = if getBool b then x else y evalAlg (Eq x y) = iVBool $ x == y evalAlg (Lt x y) = iVBool $ getInt x < getInt y evalAlg (And x y) = iVBool $ getBool x && getBool y evalAlg (Not x) = iVBool $ not $ getBool x evalAlg (ProjLeft x) = fst $ getPair x evalAlg (ProjRight x) = snd $ getPair x instance (Value :<<: v) => Eval Sugar v where evalAlg (Neg x) = iVInt $ negate $ getInt x evalAlg (Minus x y) = iVInt $ getInt x - getInt y evalAlg (Gt x y) = iVBool $ getInt x > getInt y evalAlg (Or x y) = iVBool $ getBool x || getBool y evalAlg (Impl x y) = iVBool $ not (getBool x) || getBool y desugarEval :: SugarExpr :-> ValueExpr desugarEval = eval . (desugar :: SugarExpr :-> Expr) evalSugar :: SugarExpr :-> ValueExpr evalSugar = eval desugarEvalAlg :: Alg SugarSig ValueExpr desugarEvalAlg = evalAlg `compAlg` (desugarAlg :: Hom SugarSig ExprSig) desugarEval' :: SugarExpr :-> ValueExpr desugarEval' e = cata desugarEvalAlg e
null
https://raw.githubusercontent.com/pa-ba/compdata/5783d0e11129097e045cabba61643114b154e3f2/benchmark/Multi/Functions/Comp/Eval.hs
haskell
evaluation
# LANGUAGE GADTs , TemplateHaskell , MultiParamTypeClasses , FlexibleInstances , FlexibleContexts , UndecidableInstances , TypeOperators , ScopedTypeVariables , TypeSynonymInstances # GADTs, TemplateHaskell, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, UndecidableInstances, TypeOperators, ScopedTypeVariables, TypeSynonymInstances#-} module Multi.Functions.Comp.Eval where import Multi.DataTypes.Comp import Multi.Functions.Comp.Desugar import Data.Comp.Multi import Data.Comp.Multi.HEquality class Eval e v where evalAlg :: Alg e (Term v) eval :: (HFunctor e, Eval e v) => Term e :-> (Term v) eval = cata evalAlg instance (Eval f v, Eval g v) => Eval (f :++: g) v where evalAlg (HInl v) = evalAlg v evalAlg (HInr v) = evalAlg v instance (Value :<<: v) => Eval Value v where evalAlg = inject getInt :: (Value :<<: v) => Term v Int -> Int getInt t = case project t of Just (VInt x) -> x Nothing -> undefined getBool :: (Value :<<: v) => Term v Bool -> Bool getBool t = case project t of Just (VBool x) -> x Nothing -> undefined getPair :: (Value :<<: v) => Term v (s,t) -> ((Term v s), (Term v t)) getPair t = case project t of Just (VPair x y) -> (x, y) Nothing -> undefined instance (Value :<<: v, HEqF v) => Eval Op v where evalAlg (Plus x y) = iVInt $ getInt x + getInt y evalAlg (Mult x y) = iVInt $ getInt x * getInt y evalAlg (If b x y) = if getBool b then x else y evalAlg (Eq x y) = iVBool $ x == y evalAlg (Lt x y) = iVBool $ getInt x < getInt y evalAlg (And x y) = iVBool $ getBool x && getBool y evalAlg (Not x) = iVBool $ not $ getBool x evalAlg (ProjLeft x) = fst $ getPair x evalAlg (ProjRight x) = snd $ getPair x instance (Value :<<: v) => Eval Sugar v where evalAlg (Neg x) = iVInt $ negate $ getInt x evalAlg (Minus x y) = iVInt $ getInt x - getInt y evalAlg (Gt x y) = iVBool $ getInt x > getInt y evalAlg (Or x y) = iVBool $ getBool x || getBool y evalAlg (Impl x y) = iVBool $ not (getBool x) || getBool y desugarEval :: SugarExpr :-> ValueExpr desugarEval = eval . (desugar :: SugarExpr :-> Expr) evalSugar :: SugarExpr :-> ValueExpr evalSugar = eval desugarEvalAlg :: Alg SugarSig ValueExpr desugarEvalAlg = evalAlg `compAlg` (desugarAlg :: Hom SugarSig ExprSig) desugarEval' :: SugarExpr :-> ValueExpr desugarEval' e = cata desugarEvalAlg e
f69a233714eef90a8c06c8a047222512496b0e25e9c5d10ded1182722d835309
3b/3bgl-misc
package.lisp
(defpackage #:3bgl-splines (:use :cl) (:export #:interpolate-quadratic #:evaluate-quadratic #:evaluate-quadratic-normal #:evaluate-quadratic-tangent #:subdivide-quadratic))
null
https://raw.githubusercontent.com/3b/3bgl-misc/e3bf2781d603feb6b44e5c4ec20f06225648ffd9/spline/package.lisp
lisp
(defpackage #:3bgl-splines (:use :cl) (:export #:interpolate-quadratic #:evaluate-quadratic #:evaluate-quadratic-normal #:evaluate-quadratic-tangent #:subdivide-quadratic))
a3cdf5df1adeebfd0a9f88b14e48085f514d4c272345f8b10fa498143766038a
lambdamikel/DLMAPS
result-inspector2.lisp
-*- Mode : Lisp ; Syntax : Ansi - Common - Lisp ; Package : SPATIAL - SUBSTRATE ; Base : 10 -*- (in-package spatial-substrate) (defconstant +x-no-of-thumbnails+ 6) (defconstant +y-no-of-thumbnails+ 6) (defconstant +spacing+ 10) (defconstant +offset-radius+ 100) (defconstant +light-blue+ (make-rgb-color 0.5 0.5 1)) (defconstant +inspector-text-style+ (make-text-style :sans-serif :bold :large)) (defconstant +inspector-interactor-text-style+ (make-text-style :sans-serif :bold :normal)) ;;; ;;; Achtung: die Spatial Atoms (s. spatial-substrate;compiler5.lisp) ;;; können NUR compiliert werden! -> *runtime-evaluation* = NIL ts::*compile - queries - p * = T , dass die erzeugten werden ; bei NIL werden ( aber letztlich wurde die Query " compiliert " ) ;;; (defparameter *searching-active* nil) (defparameter *buttons* nil) (defparameter *draw-thumbnails* t) (defparameter *inspector-solid-areas* t) (defparameter *experimental* nil) (defparameter *exclude-permutations* nil) (defparameter *inspector-display-binding-names-mode* t) ;;; ;;; ;;; (defvar *result-inspector-frame* nil) (defvar *inspector-process*) ;;; ;;; ;;; (defvar +button-abort+) (defvar +button-draw-thumbnails+) (defvar +button-solid-areas+) (defvar +button-experimental+) (defvar +button-permutations+) (defvar +button-show-bindings+) (defvar +button-next+) (defvar +button-previous+) (defvar +button-delete-all-pages+) (defvar +button-delete-page+) (defvar +button-delete-selected+) (defvar +button-delete-unselected+) (defvar +button-unselect-all+) ;;; ;;; ;;; (defmacro with-result-inspector ((name) &body body) `(let ((,name *result-inspector-frame*)) ,@body)) (defmacro with-query-result-output (&body body) `(let ((*display-binding-names-mode* *inspector-display-binding-names-mode*) (*solid-areas* *inspector-solid-areas*) (*display-nodes-mode* nil) (*sensitive-objects-mode* nil) (*highlight-bindings* t)) ,@body)) (defmacro with-overview-output (&body body) `(let ((*display-map-text-mode* nil) (*display-nodes-mode* nil) (*sensitive-objects-mode* nil) (*highlight-bindings* t) (*solid-areas* *inspector-solid-areas*) (*display-binding-names-mode* *inspector-display-binding-names-mode*)) ,@body)) ;;; ;;; ;;; (defun result-inspector-running-p () *result-inspector-frame*) (define-command-table query-table :menu (("Answer Query" :command (com-inspector-answer-query)))) (define-application-frame inspector () ((pages :accessor pages :initform nil) (selected-page :accessor selected-page :initform nil) (active-page :accessor active-page :initform nil) (selected-query-result :accessor selected-query-result :initform nil) (map-on-display-p :accessor map-on-display-p :initform nil) (all-matches :accessor all-matches :initform nil) (last-percent :initform nil) (last-time :initform nil)) (:command-table (inspector :inherit-from (query-table) :menu (("Query" :menu query-table)))) (:menu-bar nil) (:panes (query-results :application :label "Query Results" :initial-cursor-visibility :inactive :display-after-commands nil :textcusor nil :scroll-bars nil :display-function #'draw-query-results) (infos :application :label "Infos" :text-style +inspector-text-style+ :scroll-bars :both :textcursor nil :initial-cursor-visibility :inactive :end-of-line-action :allow :end-of-page-action :follow) (progress-bar :application :label nil :borders nil :scroll-bars nil :textcursor nil :initial-cursor-visibility :inactive) (command :interactor :text-style +inspector-interactor-text-style+ :scroll-bars :vertical) (button-abort (setf +button-abort+ (make-pane 'push-button :label "Abort Search" :activate-callback 'abort-search))) (button-draw-thumbnails (setf +button-draw-thumbnails+ (make-pane 'toggle-button :value *draw-thumbnails* :default *draw-thumbnails* :label "DT" :value-changed-callback 'button-draw-thumbnails))) (button-show-bindings (setf +button-show-bindings+ (make-pane 'toggle-button :value *inspector-display-binding-names-mode* :label "SB" :default *inspector-display-binding-names-mode* :value-changed-callback 'button-show-bindings))) (button-solid-areas (setf +button-solid-areas+ (make-pane 'toggle-button :value *inspector-solid-areas* :label "SA" :default *inspector-solid-areas* :value-changed-callback 'button-solid-areas))) (button-experimental (setf +button-experimental+ (make-pane 'toggle-button :value *experimental* :default *experimental* :label "ES" :value-changed-callback 'button-experimental))) (button-permutations (setf +button-permutations+ (make-pane 'toggle-button :value *exclude-permutations* :default *exclude-permutations* :label "EP" :value-changed-callback 'button-permutations))) (button-previous (setf +button-previous+ (make-pane 'push-button :label "<< Previous Page <<" :activate-callback 'previous-page))) (button-next (setf +button-next+ (make-pane 'push-button :label ">> Next Page >>" :activate-callback 'next-page))) (button-delete-all-pages (setf +button-delete-all-pages+ (make-pane 'push-button :label "Delete All Pages" :activate-callback 'delete-all-pages))) (button-delete-page (setf +button-delete-page+ (make-pane 'push-button :label "Delete Page" :activate-callback 'delete-page))) (button-delete-selected (setf +button-delete-selected+ (make-pane 'push-button :label "Delete Selected" :activate-callback 'delete-selected))) (button-delete-unselected (setf +button-delete-unselected+ (make-pane 'push-button :label "Delete Unselected" :activate-callback 'delete-unselected))) (button-unselect-all (setf +button-unselect-all+ (make-pane 'push-button :label "Unselect All" :activate-callback 'unselect-all))) (page-nr :application :label nil :borders nil :scroll-bars nil :textcursor nil :initial-cursor-visibility :inactive :display-function #'show-page-nr)) (:layouts (:default #+(and :lispworks :win32) (horizontally () (1/2 (outl (vertically () (1/26 progress-bar) (1/26 (horizontally () (1 button-abort) +fill+)) (1/26 (horizontally () (1/2 button-previous) (1/2 button-next) +fill+)) (1/26 page-nr) (19/26 query-results) (1/26 (horizontally () (1/2 button-delete-page) (1/2 button-delete-all-pages) +fill+)) (1/26 (horizontally () (1/3 button-unselect-all) (1/3 button-delete-selected) (1/3 button-delete-unselected) +fill+)) (1/26 (horizontally () (1/5 button-draw-thumbnails) (1/5 button-solid-areas) (1/5 button-show-bindings) (1/5 button-experimental) (1/5 button-permutations) +fill+))))) (1/2 (vertically () (1/2 (outl infos)) (1/2 (outl (labelling (:label "Query Processor") command)))))) #-(and :lispworks :win32) (horizontally () (1/2 (outl (vertically () (1/26 progress-bar) (1/26 button-abort) (1/26 (horizontally () (1/2 button-previous) (1/2 button-next))) (1/26 page-nr) (19/26 query-results) (1/26 (horizontally () (1/2 button-delete-page) (1/2 button-delete-all-pages))) (1/26 (horizontally () (1/3 button-unselect-all) (1/3 button-delete-selected) (1/3 button-delete-unselected))) (1/26 (horizontally () (1/5 button-draw-thumbnails) (1/5 button-solid-areas) (1/5 button-show-bindings) (1/5 button-experimental) (1/5 button-permutations)))))) (1/2 (vertically () (1/2 (outl infos)) (1/2 (outl (labelling (:label "Query Processor") command))))))))) (defun result-inspector (&key (force t) left top width height &allow-other-keys) (let ((port (find-port))) (when (or force (null *map-viewer-frame*)) (unless left (multiple-value-bind (screen-width screen-height) (bounding-rectangle-size (sheet-region (find-graft :port port))) (setf left 0 top 0 width screen-width height screen-height))) (setf *result-inspector-frame* (make-application-frame 'inspector :left left :top top :width (- width 40) :height (- height 100) :pretty-name "Inspector")) (setf *inspector-process* (mp:process-run-function "Result Inspector" nil #'(lambda () (run-frame-top-level *result-inspector-frame*)))) *result-inspector-frame*))) (defmethod frame-standard-output ((frame inspector)) (get-frame-pane frame 'infos)) (defmethod frame-error-output ((frame inspector)) (get-frame-pane frame 'infos)) (defmethod frame-query-io ((frame inspector)) (get-frame-pane frame 'command)) ;;; ;;; ;;; (defun show-search-progress (percent &key force-p) (with-result-inspector (frame) (let* ((stream (get-frame-pane frame 'progress-bar)) (time (get-universal-time))) (with-slots (last-percent last-time) frame (when (or (not last-percent) (and (not (= last-percent percent)) (or force-p (> (- time last-time) 1)))) (multiple-value-bind (width height) (bounding-rectangle-size (bounding-rectangle stream)) (with-output-recording-options (stream :draw t :record nil) (when last-percent (draw-rectangle* stream 0 0 (* (/ last-percent 100) width) height :ink +background-ink+)) (setf last-percent percent) (draw-rectangle* stream 0 0 (* (/ percent 100) width) height :ink +red+) (setf last-time time)))))))) (defmethod run-frame-top-level :before ((frame inspector) &key) (lock-buttons) (deactivate-gadget +button-abort+)) ;;; ;;; ;;; (defclass query-result () ((bindings :accessor bindings :initarg :bindings) (selected :accessor selected :initform nil) (map-radius :accessor map-radius :initarg :map-radius) (map-xcenter :accessor map-xcenter :initarg :map-xcenter) (map-ycenter :accessor map-ycenter :initarg :map-ycenter))) (defclass query-page () ((objects :accessor objects :initarg :objects :initform nil))) ;;; ;;; ;;; (defmethod full ((obj query-page)) (= (length (objects obj)) (* +x-no-of-thumbnails+ +y-no-of-thumbnails+))) (defun make-new-page () (with-result-inspector (frame) (let ((obj (make-instance 'query-page))) (pushend obj (pages frame)) (setf (active-page frame) obj) (setf (selected-page frame) obj) (update-buttons) obj))) (defun get-position (obj) (with-result-inspector (frame) (when (and obj (selected-page frame)) (let ((pos (position obj (objects (selected-page frame))))) (when pos (multiple-value-bind (w h) (thumbnail-size frame) (let ((y (floor pos +x-no-of-thumbnails+)) (x (mod pos +x-no-of-thumbnails+))) (values (+ (* w x) +spacing+) (+ (* h y) +spacing+) (- (* w (1+ x)) +spacing+) (- (* h (1+ y)) +spacing+))))))))) (defmethod thumbnail-size ((frame inspector)) (multiple-value-bind (width height) (window-inside-size (get-frame-pane frame 'query-results)) (values (/ (- width 1) +x-no-of-thumbnails+) (/ (- height 1) +y-no-of-thumbnails+)))) ;;; ;;; ;;; (defclass foobar () ()) (defmethod draw-result ((result query-result) stream w h &key (fast-p t) text-p full-view) (set-current-map-position-and-radius (map-xcenter result) (map-ycenter result) (+ (map-radius result) 50)) (select-query-result result) (labels ((draw-it () (when *draw-thumbnails* (with-query-result-output (let ((*display-map-text-mode* text-p)) (draw-current-map-to-foreign-stream stream :fast-p fast-p :overview t :width w :height h)))))) (let ((bgink +background-ink+) (fgink +black+)) (if (not full-view) (progn (when (selected result) (setf bgink +red+) (setf fgink +black+)) (with-output-as-presentation (stream result 'query-result :single-box t :allow-sensitive-inferiors nil) (draw-rectangle* stream -7 -7 (+ 7 w) (+ 7 h) :ink bgink) (draw-rectangle* stream 0 0 w h :ink fgink :filled nil)) (with-drawing-options (stream :clipping-region (make-bounding-rectangle 0 0 (1+ w) (1+ h))) (with-output-as-presentation (stream result 'foobar :single-box nil :allow-sensitive-inferiors nil) (draw-it)))) (draw-it))))) (defmethod draw-overview ((frame inspector) stream) (with-slots (overview-pattern current-map-range overview-transformation) frame (multiple-value-bind (width height) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))) (when (get-current-map) (with-overview-output (full-map-range) (recalculate-transformation stream :width width :height height) (with-map-viewer-frame (map-viewer) (draw-rectangle* stream 0 0 width height :ink +white+) (draw-current-map map-viewer stream :overview t :fast-p t :clear-p nil))))))) (defmethod draw-thumbnail ((result query-result)) (with-result-inspector (frame) (let ((stream (get-frame-pane frame 'query-results))) (when (map-on-display-p frame) (window-clear stream)) (setf (map-on-display-p frame) nil) (multiple-value-bind (xf yf xt yt) (get-position result) (when (and xf yf xt yt) (with-translation (stream xf yf) (draw-result result stream (- xt xf) (- yt yf)))))))) ;;; ;;; ;;; (define-presentation-method highlight-presentation ((obj query-result) record stream state) (declare (ignore state)) (let* ((obj (presentation-object record))) (multiple-value-bind (xf yf xt yt) (get-position obj) get - position liefern (draw-rectangle* stream xf yf xt yt :filled nil :ink +flipping-ink+ :line-thickness 10))))) #| (define-presentation-method presentation-refined-position-test ((obj query-result) record stream state) (break) |# (defun get-page-nr () (with-result-inspector (frame) (if (selected-page frame) (1+ (position (selected-page frame) (pages frame))) 0))) ;;; ;;; ;;; (defun abort-search (&optional button) (declare (ignore button)) (thematic-substrate::abort-all-queries)) (defun previous-page (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (let ((pos (position (selected-page frame) (pages frame)))) (unless (zerop pos) (setf (selected-page frame) (nth (1- pos) (pages frame))) (update-buttons)))))) (defun next-page (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (let ((rest (rest (member (selected-page frame) (pages frame))))) (when rest (setf (selected-page frame) (first rest)) (update-buttons))))) (defun delete-all-pages (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (setf (pages frame) nil (active-page frame) nil (selected-page frame) nil) (update-buttons))) (defun delete-page (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (setf (pages frame) (delete (selected-page frame) (pages frame))) (setf (selected-page frame) (first (pages frame))) (update-buttons)))) (defun delete-selected (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (dolist (obj (remove-if-not #'selected (objects (selected-page frame)))) (setf (objects (selected-page frame)) (delete obj (objects (selected-page frame))))) (if (objects (selected-page frame)) (update-buttons) (delete-page +button-delete-page+))))) (defun delete-unselected (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (dolist (obj (remove-if #'selected (objects (selected-page frame)))) (setf (objects (selected-page frame)) (delete obj (objects (selected-page frame))))) (if (objects (selected-page frame)) (update-buttons) (delete-page +button-delete-page+))))) (defun unselect-all (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (dolist (obj (objects (selected-page frame))) (setf (selected obj) nil)) (update-buttons)))) (defun button-draw-thumbnails (button value) (declare (ignore button)) (setf *draw-thumbnails* value) (with-result-inspector (frame) (redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t))) (defun button-show-bindings (button value) (declare (ignore button)) (setf *inspector-display-binding-names-mode* value) (with-result-inspector (frame) (redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t))) (defun button-solid-areas (button value) (declare (ignore button)) (setf *inspector-solid-areas* value) (with-result-inspector (frame) (redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t))) (defun button-permutations (button value) (declare (ignore button)) (setf *exclude-permutations* value)) (defun button-experimental (button value) (declare (ignore button)) (setf *experimental* value)) ;;; ;;; ;;; (defun lock-buttons () (dolist (button (list +button-previous+ +button-next+ +button-delete-all-pages+ +button-delete-page+ +button-delete-selected+ +button-delete-unselected+ +button-unselect-all+)) (deactivate-gadget button)) (activate-gadget +button-abort+) (show-search-progress 100) (setf *searching-active* t)) (defun unlock-buttons () (setf *searching-active* nil) (deactivate-gadget +button-abort+) (update-buttons) (show-search-progress 0 :force-p t)) (defun update-buttons () (with-result-inspector (frame) (unless *searching-active* (cond ((pages frame) (let ((nr (get-page-nr))) (if (= 1 nr) (deactivate-gadget +button-previous+) (activate-gadget +button-previous+)) (if (= nr (length (pages frame))) (deactivate-gadget +button-next+) (activate-gadget +button-next+)) (activate-gadget +button-delete-selected+) (activate-gadget +button-delete-unselected+) (activate-gadget +button-delete-page+) (activate-gadget +button-delete-all-pages+) (activate-gadget +button-unselect-all+))) (t (deactivate-gadget +button-previous+) (deactivate-gadget +button-next+) (deactivate-gadget +button-delete-all-pages+) (deactivate-gadget +button-delete-page+) (deactivate-gadget +button-delete-selected+) (deactivate-gadget +button-delete-unselected+) (deactivate-gadget +button-unselect-all+)))) (window-clear (get-frame-pane frame 'query-results)) (redisplay-frame-pane frame (get-frame-pane frame 'page-nr) :force-p t) (draw-query-results frame (get-frame-pane frame 'query-results)))) (defmethod show-page-nr ((frame inspector) stream) (format stream " Page No. ~A of ~A Pages." (get-page-nr) (length (pages frame)))) ;;; ;;; ;;; (defun make-query-result (vars binding) (with-result-inspector (inspector-frame) (let ((binding (mapcar #'(lambda (var object) (list var (etypecase object (symbol (get-associated-substrate-node (get-current-map) object)) (map-object object)))) vars binding))) (when (or (not (active-page inspector-frame)) (full (active-page inspector-frame))) (make-new-page)) (let* ((agg (make-aggregate (mapcar #'second binding) :hierarchicly-p nil)) (xcenter (x (pcenter agg))) (ycenter (y (pcenter agg))) (radius (max (+ +offset-radius+ (/ (- (x (pmax agg)) (x (pmin agg))) 2)) (+ +offset-radius+ (/ (- (y (pmax agg)) (y (pmin agg))) 2)))) (res-object (make-instance 'query-result :bindings binding :map-radius radius :map-xcenter xcenter :map-ycenter ycenter))) (pushend res-object (objects (active-page inspector-frame))) (delete-object agg) (when (eq (selected-page inspector-frame) (active-page inspector-frame)) (draw-thumbnail res-object)))))) ;;; ;;; ;;; (defun draw-selected-query-result () (with-result-inspector (frame) (let ((result (selected-query-result frame)) (stream (get-frame-pane frame 'infos))) (window-clear stream) (multiple-value-bind (w h) (window-inside-size stream) (when result (let ((*draw-thumbnails* t) (*display-map-text-mode* t)) (draw-result result stream (- w 2) (- h 2) :fast-p nil :text-p t :full-view t))))))) (defmethod draw-query-results ((frame inspector) stream) (declare (ignore stream)) (if (map-on-display-p frame) (com-inspector-show-map) (when (selected-page frame) (dolist (result (objects (selected-page frame))) (let ((*display-map-text-mode* nil)) (draw-thumbnail result)))))) ;;; ;;; ;;; (define-gesture-name :select-query-result :pointer-button (:left :shift)) (define-gesture-name :inspect-query-result :pointer-button :left) ;;; ;;; ;;; (define-inspector-command (com-inspector-query :name "Query") () (com-inspector-answer-query)) (define-inspector-command (com-inspector-answer-query :name "Answer Query") () (let ((query (accept 'form :prompt "Enter Query"))) (terpri *standard-input*) (let ((vois (accept '((sequence symbol) :separator #\Space) :prompt "Enter Variables"))) (inspector-answer-query query vois)))) (define-inspector-command (com-inspector-load-sqd-map :name "Load SQD Map") () (let ((file (file-selector "Load SQD Map" "maps:" "sqd"))) (when file (window-clear *standard-output*) (format *standard-output* "Attempting to load SQD map ~A!" file) (install-as-current-mapviewer-map (load-and-install-map file))))) (define-inspector-command (com-inspector-load-map :name "Load Map") () (let ((file (file-selector "Load Map" "maps:" "map"))) (when file (install-as-current-mapviewer-map (load-map file))))) (define-inspector-command (com-inspector-map :name "Map") () (com-inspector-show-map)) (define-inspector-command (com-inspector-show-map :name "Show Map") () (with-result-inspector (frame) (let ((stream (get-frame-pane frame 'query-results))) (setf (map-on-display-p frame) t) (unhighlight-all) (when (and *last-query* (is-map-query-p *last-query*)) (dolist (binding (result-bindings *last-query*)) (mapcar #'(lambda (var object) (let ((object (if (symbolp object) (get-associated-substrate-node (substrate *last-query*) object) object))) (when object (setf (geometry::bound-to object) var)))) (answer-pattern *last-query*) binding))) (window-clear stream) (draw-overview frame stream)))) (define-inspector-command (com-inspector-thumbnails :name "Thumbnails") () (com-inspector-show-thumbnails)) (define-inspector-command (com-inspector-show-thumbnails :name "Show Thumbnails") () (with-result-inspector (frame) (let ((stream (get-frame-pane frame 'query-results))) (setf (map-on-display-p frame) nil) (window-clear stream) (draw-query-results frame stream)))) (define-inspector-command (com-reload-ontology :name "Reload Ontology") () (load-geo-ontology)) (define-inspector-command (com-reload-queries :name "Reload Queries") () (load "q-queries.lisp")) (define-inspector-command (com-inspector-ontology :name "Ontology") () (com-inspector-show-ontology)) #+:midelora (define-inspector-command (com-inspector-show-ontology :name "Show Ontology") () (if (is-midelora-map-p *cur-map*) (dag::visualize-dag (taxonomy (find-tbox 'prover::oejendorf :error-p t))) (let ((taxonomy (racer-dag::get-racer-taxonomy 'racer-user::oejendorf))) (dag:visualize-dag taxonomy)))) #-:midelora (define-inspector-command (com-inspector-show-ontology :name "Show Ontology") () (let ((taxonomy (racer-dag::get-racer-taxonomy 'racer-user::oejendorf))) (dag:visualize-dag taxonomy))) (define-inspector-command (com-inspector-delete-page :name "Delete Page") () (delete-page)) (define-inspector-command (com-inspector-delete-all-pages :name "Delete All Pages") () (delete-all-pages)) (define-inspector-command (com-inspector-next-page :name "Next Page") () (next-page)) (define-inspector-command (com-inspector-prev-page :name "Previous Page") () (previous-page)) (define-inspector-command (com-inspector-show-query :name "Show Query") () (window-clear *standard-output*) (when *last-query* (terpri *standard-output*) (format t "Query: ") (write (unparse-query *last-query*) :pretty t :escape nil :readably nil) (format t "~%~% Variables: ") (write (answer-pattern *last-query*) :pretty t :escape nil :readably nil))) (define-inspector-command (com-inspector-show-code :name "Show Code") () (window-clear *standard-output*) (when *last-query* (dolist (query (cons *last-query* (thematic-substrate::all-subqueries *last-query*))) (pprint (source query) *standard-output*)))) (define-inspector-command (com-inspector-answer :name "Answer") () (com-inspector-show-answer)) (define-inspector-command (com-inspector-show-answer :name "Show Answer") () (let ((stream *standard-output*) ) (when *last-query* (run #'(lambda () (window-clear stream) (format stream "Last query returned ~A tuples: ~%" (length (result-bindings *last-query*))) (pprint (mapcar #'(lambda (binding) (mapcar #'(lambda (var object) (list var (if (symbolp object) object (name object)))) (answer-pattern *last-query*) binding)) (result-bindings *last-query*) ) stream)))))) (define-inspector-command (com-inspector-clear :name "Clear") () (window-clear *standard-output*) (window-clear *query-io*) (unhighlight-all) (setf *last-query* nil) (setf (map-on-display-p *application-frame*) nil) (delete-all-pages) (update-buttons)) (define-inspector-command (com-inspector-show-repository :name "Show Repository") () (show-qbox (get-current-map))) (define-inspector-command (com-inspector-clear-repository :name "Clear Repository") () (thematic-substrate::clear-repository (get-current-map))) #| (define-inspector-command (com-inspector-kill :name "Kill") () (kill) (unlock-buttons)) |# (define-inspector-command (com-inspector-restart-map-viewer :name "Restart Map Viewer") () (map-viewer)) (define-inspector-command (com-inspector-quit :name "Quit") () (with-result-inspector (frame) (let ((yes-or-no (notify-user frame "Quit selected! Are you sure?" :style :question))) (when yes-or-no (setf *result-inspector-frame* nil) (frame-exit frame))))) ;;; ;;; ;;; (define-inspector-command (com-inspector-inspect-query-result) ((object 'query-result)) (select-query-result object) (draw-selected-query-result)) (defmethod select-query-result ((object query-result)) (with-result-inspector (frame) (setf (selected-query-result frame) object) (unhighlight-all) (dolist (tuple (bindings object)) (let ((object (second tuple)) (var (first tuple))) (setf (geometry::bound-to (if (symbolp object) (get-associated-substrate-node (substrate *last-query*) object) object)) var))))) (define-presentation-to-command-translator inspect-query-result (query-result com-inspector-inspect-query-result inspector :tester (() (not *searching-active*)) :echo t :maintain-history nil :gesture :inspect-query-result) (object) (list object)) ;;; ;;; ;;; (define-inspector-command (com-inspector-select-query-result) ((object 'query-result)) (setf (selected object) (not (selected object))) (com-inspector-inspect-query-result object) (draw-thumbnail object)) (define-presentation-to-command-translator select-query-result (query-result com-inspector-select-query-result inspector :echo nil :tester (() (not *searching-active*)) :maintain-history nil :gesture :select-query-result) (object) (list object)) ;;; ;;; ;;; (defmacro with-dlmaps-standard-settings (&body body) `(if *exclude-permutations* (with-nrql-settings (:abox-mirroring nil :query-optimization t :two-phase-query-processing-mode nil :told-information-querying nil :tuple-computation-mode :set-at-a-time :exclude-permutations t :query-repository nil :report-inconsistent-queries nil :report-tautological-queries nil :query-realization nil :check-abox-consistency nil :rewrite-to-dnf t) (racer:with-unique-name-assumption (let ((ts::*runtime-evaluation-p* nil) (ts::*compile-queries-p* nil)) ,@body))) (with-nrql-settings (:abox-mirroring nil :query-optimization t :two-phase-query-processing-mode nil :told-information-querying nil :tuple-computation-mode :set-at-a-time :exclude-permutations nil :query-repository nil :report-inconsistent-queries nil :report-tautological-queries nil :query-realization nil :check-abox-consistency nil :rewrite-to-dnf t) (racer:with-unique-name-assumption (let ((ts::*runtime-evaluation-p* nil) (ts::*compile-queries-p* nil)) ,@body))))) (defmacro with-dlmaps-experimental-settings (&body body) `(if *exclude-permutations* (with-nrql-settings (:query-optimization t :two-phase-query-processing-mode nil :tuple-computation-mode :set-at-a-time :exclude-permutations t :query-repository t :report-inconsistent-queries t :query-realization nil) (racer:with-unique-name-assumption (let ((ts::*runtime-evaluation-p* nil) (ts::*compile-queries-p* nil)) ,@body))) (with-nrql-settings (:query-optimization t :two-phase-query-processing-mode t :tuple-computation-mode :set-at-a-time :exclude-permutations nil :query-repository t :report-inconsistent-queries t :query-realization nil) (racer:with-unique-name-assumption (let ((ts::*runtime-evaluation-p* nil) (ts::*compile-queries-p* nil)) ,@body))))) ;;; ;;; ;;; (defun inspector-answer-query (query vois &optional doc) (present-query query vois) (terpri *standard-input*) (terpri *standard-input*) (in-substrate* (get-current-map)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (delete-all-pages) (let ((*standard-output* (frame-standard-output frame)) (*package* ;(racer-package *cur-substrate*) (find-package :racer-user))) (window-clear *standard-output*) (terpri *standard-output*) (when doc (format t "Natürlichsprachlich:~%") (format t doc) (terpri *standard-output*) (terpri *standard-output*)) (format t "Query: ") (write query :pretty t :escape nil :readably nil) (format t "~%~% Variables: ") (write vois :pretty t :escape nil :readably nil) (terpri *standard-output*) (terpri *standard-output*) (pprint aus irgendwelchen ( locking ? ) blockiert die , wenn kein ;;; Prozess gestartet wird! (run #'(lambda () (if *experimental* (with-dlmaps-experimental-settings (answer-query query vois)) (with-dlmaps-standard-settings (answer-query query vois))))))))) (defun present-query (q v) (let ((stream *standard-input* ) (*print-pretty* t)) (format stream "Command: Answer Query~%") (format stream "Enter Query: ") (present q 'form :stream stream) (terpri stream) (format stream "Enter Variables: ") (present v '(sequence symbol) :separator #\Space :stream stream))) ;;; ;;; Demo-Queries ;;; (define-inspector-command (com-inspector-q1 :name "Q1") () (q1)) (define-inspector-command (com-inspector-q2 :name "Q2") () (q2)) (define-inspector-command (com-inspector-q3 :name "Q3") () (q3)) (define-inspector-command (com-inspector-q4 :name "Q4") () (q4)) (define-inspector-command (com-inspector-q5 :name "Q5") () (q5)) (define-inspector-command (com-inspector-q6 :name "Q6") () (q6)) (define-inspector-command (com-inspector-q7 :name "Q7") () (q7)) (define-inspector-command (com-inspector-q8 :name "Q8") () (q8)) (define-inspector-command (com-inspector-q9 :name "Q9") () (q9)) (define-inspector-command (com-inspector-q10 :name "Q10") () (q10)) (define-inspector-command (com-inspector-q11 :name "Q11") () (q11)) (define-inspector-command (com-inspector-q12 :name "Q12") () (q12)) (define-inspector-command (com-inspector-q13 :name "Q13") () (q13)) (define-inspector-command (com-inspector-q14 :name "Q14") () (q14)) (define-inspector-command (com-inspector-q15 :name "Q15") () (q15)) (define-inspector-command (com-inspector-q16 :name "Q16") () (q16)) (define-inspector-command (com-inspector-q17 :name "Q17") () (q17)) (define-inspector-command (com-inspector-q18 :name "Q18") () (q18)) (define-inspector-command (com-inspector-q19 :name "Q19") () (q19)) (define-inspector-command (com-inspector-q20 :name "Q20") () (q20))
null
https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/map-viewer/result-inspector2.lisp
lisp
Syntax : Ansi - Common - Lisp ; Package : SPATIAL - SUBSTRATE ; Base : 10 -*- Achtung: die Spatial Atoms (s. spatial-substrate;compiler5.lisp) können NUR compiliert werden! -> *runtime-evaluation* = NIL bei NIL werden (define-presentation-method presentation-refined-position-test ((obj query-result) record stream state) (break) (define-inspector-command (com-inspector-kill :name "Kill") () (kill) (unlock-buttons)) (racer-package *cur-substrate*) Prozess gestartet wird! Demo-Queries
(in-package spatial-substrate) (defconstant +x-no-of-thumbnails+ 6) (defconstant +y-no-of-thumbnails+ 6) (defconstant +spacing+ 10) (defconstant +offset-radius+ 100) (defconstant +light-blue+ (make-rgb-color 0.5 0.5 1)) (defconstant +inspector-text-style+ (make-text-style :sans-serif :bold :large)) (defconstant +inspector-interactor-text-style+ (make-text-style :sans-serif :bold :normal)) ts::*compile - queries - p * = T , dass die erzeugten ( aber letztlich wurde die Query " compiliert " ) (defparameter *searching-active* nil) (defparameter *buttons* nil) (defparameter *draw-thumbnails* t) (defparameter *inspector-solid-areas* t) (defparameter *experimental* nil) (defparameter *exclude-permutations* nil) (defparameter *inspector-display-binding-names-mode* t) (defvar *result-inspector-frame* nil) (defvar *inspector-process*) (defvar +button-abort+) (defvar +button-draw-thumbnails+) (defvar +button-solid-areas+) (defvar +button-experimental+) (defvar +button-permutations+) (defvar +button-show-bindings+) (defvar +button-next+) (defvar +button-previous+) (defvar +button-delete-all-pages+) (defvar +button-delete-page+) (defvar +button-delete-selected+) (defvar +button-delete-unselected+) (defvar +button-unselect-all+) (defmacro with-result-inspector ((name) &body body) `(let ((,name *result-inspector-frame*)) ,@body)) (defmacro with-query-result-output (&body body) `(let ((*display-binding-names-mode* *inspector-display-binding-names-mode*) (*solid-areas* *inspector-solid-areas*) (*display-nodes-mode* nil) (*sensitive-objects-mode* nil) (*highlight-bindings* t)) ,@body)) (defmacro with-overview-output (&body body) `(let ((*display-map-text-mode* nil) (*display-nodes-mode* nil) (*sensitive-objects-mode* nil) (*highlight-bindings* t) (*solid-areas* *inspector-solid-areas*) (*display-binding-names-mode* *inspector-display-binding-names-mode*)) ,@body)) (defun result-inspector-running-p () *result-inspector-frame*) (define-command-table query-table :menu (("Answer Query" :command (com-inspector-answer-query)))) (define-application-frame inspector () ((pages :accessor pages :initform nil) (selected-page :accessor selected-page :initform nil) (active-page :accessor active-page :initform nil) (selected-query-result :accessor selected-query-result :initform nil) (map-on-display-p :accessor map-on-display-p :initform nil) (all-matches :accessor all-matches :initform nil) (last-percent :initform nil) (last-time :initform nil)) (:command-table (inspector :inherit-from (query-table) :menu (("Query" :menu query-table)))) (:menu-bar nil) (:panes (query-results :application :label "Query Results" :initial-cursor-visibility :inactive :display-after-commands nil :textcusor nil :scroll-bars nil :display-function #'draw-query-results) (infos :application :label "Infos" :text-style +inspector-text-style+ :scroll-bars :both :textcursor nil :initial-cursor-visibility :inactive :end-of-line-action :allow :end-of-page-action :follow) (progress-bar :application :label nil :borders nil :scroll-bars nil :textcursor nil :initial-cursor-visibility :inactive) (command :interactor :text-style +inspector-interactor-text-style+ :scroll-bars :vertical) (button-abort (setf +button-abort+ (make-pane 'push-button :label "Abort Search" :activate-callback 'abort-search))) (button-draw-thumbnails (setf +button-draw-thumbnails+ (make-pane 'toggle-button :value *draw-thumbnails* :default *draw-thumbnails* :label "DT" :value-changed-callback 'button-draw-thumbnails))) (button-show-bindings (setf +button-show-bindings+ (make-pane 'toggle-button :value *inspector-display-binding-names-mode* :label "SB" :default *inspector-display-binding-names-mode* :value-changed-callback 'button-show-bindings))) (button-solid-areas (setf +button-solid-areas+ (make-pane 'toggle-button :value *inspector-solid-areas* :label "SA" :default *inspector-solid-areas* :value-changed-callback 'button-solid-areas))) (button-experimental (setf +button-experimental+ (make-pane 'toggle-button :value *experimental* :default *experimental* :label "ES" :value-changed-callback 'button-experimental))) (button-permutations (setf +button-permutations+ (make-pane 'toggle-button :value *exclude-permutations* :default *exclude-permutations* :label "EP" :value-changed-callback 'button-permutations))) (button-previous (setf +button-previous+ (make-pane 'push-button :label "<< Previous Page <<" :activate-callback 'previous-page))) (button-next (setf +button-next+ (make-pane 'push-button :label ">> Next Page >>" :activate-callback 'next-page))) (button-delete-all-pages (setf +button-delete-all-pages+ (make-pane 'push-button :label "Delete All Pages" :activate-callback 'delete-all-pages))) (button-delete-page (setf +button-delete-page+ (make-pane 'push-button :label "Delete Page" :activate-callback 'delete-page))) (button-delete-selected (setf +button-delete-selected+ (make-pane 'push-button :label "Delete Selected" :activate-callback 'delete-selected))) (button-delete-unselected (setf +button-delete-unselected+ (make-pane 'push-button :label "Delete Unselected" :activate-callback 'delete-unselected))) (button-unselect-all (setf +button-unselect-all+ (make-pane 'push-button :label "Unselect All" :activate-callback 'unselect-all))) (page-nr :application :label nil :borders nil :scroll-bars nil :textcursor nil :initial-cursor-visibility :inactive :display-function #'show-page-nr)) (:layouts (:default #+(and :lispworks :win32) (horizontally () (1/2 (outl (vertically () (1/26 progress-bar) (1/26 (horizontally () (1 button-abort) +fill+)) (1/26 (horizontally () (1/2 button-previous) (1/2 button-next) +fill+)) (1/26 page-nr) (19/26 query-results) (1/26 (horizontally () (1/2 button-delete-page) (1/2 button-delete-all-pages) +fill+)) (1/26 (horizontally () (1/3 button-unselect-all) (1/3 button-delete-selected) (1/3 button-delete-unselected) +fill+)) (1/26 (horizontally () (1/5 button-draw-thumbnails) (1/5 button-solid-areas) (1/5 button-show-bindings) (1/5 button-experimental) (1/5 button-permutations) +fill+))))) (1/2 (vertically () (1/2 (outl infos)) (1/2 (outl (labelling (:label "Query Processor") command)))))) #-(and :lispworks :win32) (horizontally () (1/2 (outl (vertically () (1/26 progress-bar) (1/26 button-abort) (1/26 (horizontally () (1/2 button-previous) (1/2 button-next))) (1/26 page-nr) (19/26 query-results) (1/26 (horizontally () (1/2 button-delete-page) (1/2 button-delete-all-pages))) (1/26 (horizontally () (1/3 button-unselect-all) (1/3 button-delete-selected) (1/3 button-delete-unselected))) (1/26 (horizontally () (1/5 button-draw-thumbnails) (1/5 button-solid-areas) (1/5 button-show-bindings) (1/5 button-experimental) (1/5 button-permutations)))))) (1/2 (vertically () (1/2 (outl infos)) (1/2 (outl (labelling (:label "Query Processor") command))))))))) (defun result-inspector (&key (force t) left top width height &allow-other-keys) (let ((port (find-port))) (when (or force (null *map-viewer-frame*)) (unless left (multiple-value-bind (screen-width screen-height) (bounding-rectangle-size (sheet-region (find-graft :port port))) (setf left 0 top 0 width screen-width height screen-height))) (setf *result-inspector-frame* (make-application-frame 'inspector :left left :top top :width (- width 40) :height (- height 100) :pretty-name "Inspector")) (setf *inspector-process* (mp:process-run-function "Result Inspector" nil #'(lambda () (run-frame-top-level *result-inspector-frame*)))) *result-inspector-frame*))) (defmethod frame-standard-output ((frame inspector)) (get-frame-pane frame 'infos)) (defmethod frame-error-output ((frame inspector)) (get-frame-pane frame 'infos)) (defmethod frame-query-io ((frame inspector)) (get-frame-pane frame 'command)) (defun show-search-progress (percent &key force-p) (with-result-inspector (frame) (let* ((stream (get-frame-pane frame 'progress-bar)) (time (get-universal-time))) (with-slots (last-percent last-time) frame (when (or (not last-percent) (and (not (= last-percent percent)) (or force-p (> (- time last-time) 1)))) (multiple-value-bind (width height) (bounding-rectangle-size (bounding-rectangle stream)) (with-output-recording-options (stream :draw t :record nil) (when last-percent (draw-rectangle* stream 0 0 (* (/ last-percent 100) width) height :ink +background-ink+)) (setf last-percent percent) (draw-rectangle* stream 0 0 (* (/ percent 100) width) height :ink +red+) (setf last-time time)))))))) (defmethod run-frame-top-level :before ((frame inspector) &key) (lock-buttons) (deactivate-gadget +button-abort+)) (defclass query-result () ((bindings :accessor bindings :initarg :bindings) (selected :accessor selected :initform nil) (map-radius :accessor map-radius :initarg :map-radius) (map-xcenter :accessor map-xcenter :initarg :map-xcenter) (map-ycenter :accessor map-ycenter :initarg :map-ycenter))) (defclass query-page () ((objects :accessor objects :initarg :objects :initform nil))) (defmethod full ((obj query-page)) (= (length (objects obj)) (* +x-no-of-thumbnails+ +y-no-of-thumbnails+))) (defun make-new-page () (with-result-inspector (frame) (let ((obj (make-instance 'query-page))) (pushend obj (pages frame)) (setf (active-page frame) obj) (setf (selected-page frame) obj) (update-buttons) obj))) (defun get-position (obj) (with-result-inspector (frame) (when (and obj (selected-page frame)) (let ((pos (position obj (objects (selected-page frame))))) (when pos (multiple-value-bind (w h) (thumbnail-size frame) (let ((y (floor pos +x-no-of-thumbnails+)) (x (mod pos +x-no-of-thumbnails+))) (values (+ (* w x) +spacing+) (+ (* h y) +spacing+) (- (* w (1+ x)) +spacing+) (- (* h (1+ y)) +spacing+))))))))) (defmethod thumbnail-size ((frame inspector)) (multiple-value-bind (width height) (window-inside-size (get-frame-pane frame 'query-results)) (values (/ (- width 1) +x-no-of-thumbnails+) (/ (- height 1) +y-no-of-thumbnails+)))) (defclass foobar () ()) (defmethod draw-result ((result query-result) stream w h &key (fast-p t) text-p full-view) (set-current-map-position-and-radius (map-xcenter result) (map-ycenter result) (+ (map-radius result) 50)) (select-query-result result) (labels ((draw-it () (when *draw-thumbnails* (with-query-result-output (let ((*display-map-text-mode* text-p)) (draw-current-map-to-foreign-stream stream :fast-p fast-p :overview t :width w :height h)))))) (let ((bgink +background-ink+) (fgink +black+)) (if (not full-view) (progn (when (selected result) (setf bgink +red+) (setf fgink +black+)) (with-output-as-presentation (stream result 'query-result :single-box t :allow-sensitive-inferiors nil) (draw-rectangle* stream -7 -7 (+ 7 w) (+ 7 h) :ink bgink) (draw-rectangle* stream 0 0 w h :ink fgink :filled nil)) (with-drawing-options (stream :clipping-region (make-bounding-rectangle 0 0 (1+ w) (1+ h))) (with-output-as-presentation (stream result 'foobar :single-box nil :allow-sensitive-inferiors nil) (draw-it)))) (draw-it))))) (defmethod draw-overview ((frame inspector) stream) (with-slots (overview-pattern current-map-range overview-transformation) frame (multiple-value-bind (width height) (bounding-rectangle-size (bounding-rectangle (window-viewport stream))) (when (get-current-map) (with-overview-output (full-map-range) (recalculate-transformation stream :width width :height height) (with-map-viewer-frame (map-viewer) (draw-rectangle* stream 0 0 width height :ink +white+) (draw-current-map map-viewer stream :overview t :fast-p t :clear-p nil))))))) (defmethod draw-thumbnail ((result query-result)) (with-result-inspector (frame) (let ((stream (get-frame-pane frame 'query-results))) (when (map-on-display-p frame) (window-clear stream)) (setf (map-on-display-p frame) nil) (multiple-value-bind (xf yf xt yt) (get-position result) (when (and xf yf xt yt) (with-translation (stream xf yf) (draw-result result stream (- xt xf) (- yt yf)))))))) (define-presentation-method highlight-presentation ((obj query-result) record stream state) (declare (ignore state)) (let* ((obj (presentation-object record))) (multiple-value-bind (xf yf xt yt) (get-position obj) get - position liefern (draw-rectangle* stream xf yf xt yt :filled nil :ink +flipping-ink+ :line-thickness 10))))) (defun get-page-nr () (with-result-inspector (frame) (if (selected-page frame) (1+ (position (selected-page frame) (pages frame))) 0))) (defun abort-search (&optional button) (declare (ignore button)) (thematic-substrate::abort-all-queries)) (defun previous-page (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (let ((pos (position (selected-page frame) (pages frame)))) (unless (zerop pos) (setf (selected-page frame) (nth (1- pos) (pages frame))) (update-buttons)))))) (defun next-page (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (let ((rest (rest (member (selected-page frame) (pages frame))))) (when rest (setf (selected-page frame) (first rest)) (update-buttons))))) (defun delete-all-pages (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (setf (pages frame) nil (active-page frame) nil (selected-page frame) nil) (update-buttons))) (defun delete-page (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (setf (pages frame) (delete (selected-page frame) (pages frame))) (setf (selected-page frame) (first (pages frame))) (update-buttons)))) (defun delete-selected (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (dolist (obj (remove-if-not #'selected (objects (selected-page frame)))) (setf (objects (selected-page frame)) (delete obj (objects (selected-page frame))))) (if (objects (selected-page frame)) (update-buttons) (delete-page +button-delete-page+))))) (defun delete-unselected (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (dolist (obj (remove-if #'selected (objects (selected-page frame)))) (setf (objects (selected-page frame)) (delete obj (objects (selected-page frame))))) (if (objects (selected-page frame)) (update-buttons) (delete-page +button-delete-page+))))) (defun unselect-all (&optional button) (declare (ignore button)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (when (selected-page frame) (dolist (obj (objects (selected-page frame))) (setf (selected obj) nil)) (update-buttons)))) (defun button-draw-thumbnails (button value) (declare (ignore button)) (setf *draw-thumbnails* value) (with-result-inspector (frame) (redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t))) (defun button-show-bindings (button value) (declare (ignore button)) (setf *inspector-display-binding-names-mode* value) (with-result-inspector (frame) (redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t))) (defun button-solid-areas (button value) (declare (ignore button)) (setf *inspector-solid-areas* value) (with-result-inspector (frame) (redisplay-frame-pane frame (get-frame-pane frame 'query-results) :force-p t))) (defun button-permutations (button value) (declare (ignore button)) (setf *exclude-permutations* value)) (defun button-experimental (button value) (declare (ignore button)) (setf *experimental* value)) (defun lock-buttons () (dolist (button (list +button-previous+ +button-next+ +button-delete-all-pages+ +button-delete-page+ +button-delete-selected+ +button-delete-unselected+ +button-unselect-all+)) (deactivate-gadget button)) (activate-gadget +button-abort+) (show-search-progress 100) (setf *searching-active* t)) (defun unlock-buttons () (setf *searching-active* nil) (deactivate-gadget +button-abort+) (update-buttons) (show-search-progress 0 :force-p t)) (defun update-buttons () (with-result-inspector (frame) (unless *searching-active* (cond ((pages frame) (let ((nr (get-page-nr))) (if (= 1 nr) (deactivate-gadget +button-previous+) (activate-gadget +button-previous+)) (if (= nr (length (pages frame))) (deactivate-gadget +button-next+) (activate-gadget +button-next+)) (activate-gadget +button-delete-selected+) (activate-gadget +button-delete-unselected+) (activate-gadget +button-delete-page+) (activate-gadget +button-delete-all-pages+) (activate-gadget +button-unselect-all+))) (t (deactivate-gadget +button-previous+) (deactivate-gadget +button-next+) (deactivate-gadget +button-delete-all-pages+) (deactivate-gadget +button-delete-page+) (deactivate-gadget +button-delete-selected+) (deactivate-gadget +button-delete-unselected+) (deactivate-gadget +button-unselect-all+)))) (window-clear (get-frame-pane frame 'query-results)) (redisplay-frame-pane frame (get-frame-pane frame 'page-nr) :force-p t) (draw-query-results frame (get-frame-pane frame 'query-results)))) (defmethod show-page-nr ((frame inspector) stream) (format stream " Page No. ~A of ~A Pages." (get-page-nr) (length (pages frame)))) (defun make-query-result (vars binding) (with-result-inspector (inspector-frame) (let ((binding (mapcar #'(lambda (var object) (list var (etypecase object (symbol (get-associated-substrate-node (get-current-map) object)) (map-object object)))) vars binding))) (when (or (not (active-page inspector-frame)) (full (active-page inspector-frame))) (make-new-page)) (let* ((agg (make-aggregate (mapcar #'second binding) :hierarchicly-p nil)) (xcenter (x (pcenter agg))) (ycenter (y (pcenter agg))) (radius (max (+ +offset-radius+ (/ (- (x (pmax agg)) (x (pmin agg))) 2)) (+ +offset-radius+ (/ (- (y (pmax agg)) (y (pmin agg))) 2)))) (res-object (make-instance 'query-result :bindings binding :map-radius radius :map-xcenter xcenter :map-ycenter ycenter))) (pushend res-object (objects (active-page inspector-frame))) (delete-object agg) (when (eq (selected-page inspector-frame) (active-page inspector-frame)) (draw-thumbnail res-object)))))) (defun draw-selected-query-result () (with-result-inspector (frame) (let ((result (selected-query-result frame)) (stream (get-frame-pane frame 'infos))) (window-clear stream) (multiple-value-bind (w h) (window-inside-size stream) (when result (let ((*draw-thumbnails* t) (*display-map-text-mode* t)) (draw-result result stream (- w 2) (- h 2) :fast-p nil :text-p t :full-view t))))))) (defmethod draw-query-results ((frame inspector) stream) (declare (ignore stream)) (if (map-on-display-p frame) (com-inspector-show-map) (when (selected-page frame) (dolist (result (objects (selected-page frame))) (let ((*display-map-text-mode* nil)) (draw-thumbnail result)))))) (define-gesture-name :select-query-result :pointer-button (:left :shift)) (define-gesture-name :inspect-query-result :pointer-button :left) (define-inspector-command (com-inspector-query :name "Query") () (com-inspector-answer-query)) (define-inspector-command (com-inspector-answer-query :name "Answer Query") () (let ((query (accept 'form :prompt "Enter Query"))) (terpri *standard-input*) (let ((vois (accept '((sequence symbol) :separator #\Space) :prompt "Enter Variables"))) (inspector-answer-query query vois)))) (define-inspector-command (com-inspector-load-sqd-map :name "Load SQD Map") () (let ((file (file-selector "Load SQD Map" "maps:" "sqd"))) (when file (window-clear *standard-output*) (format *standard-output* "Attempting to load SQD map ~A!" file) (install-as-current-mapviewer-map (load-and-install-map file))))) (define-inspector-command (com-inspector-load-map :name "Load Map") () (let ((file (file-selector "Load Map" "maps:" "map"))) (when file (install-as-current-mapviewer-map (load-map file))))) (define-inspector-command (com-inspector-map :name "Map") () (com-inspector-show-map)) (define-inspector-command (com-inspector-show-map :name "Show Map") () (with-result-inspector (frame) (let ((stream (get-frame-pane frame 'query-results))) (setf (map-on-display-p frame) t) (unhighlight-all) (when (and *last-query* (is-map-query-p *last-query*)) (dolist (binding (result-bindings *last-query*)) (mapcar #'(lambda (var object) (let ((object (if (symbolp object) (get-associated-substrate-node (substrate *last-query*) object) object))) (when object (setf (geometry::bound-to object) var)))) (answer-pattern *last-query*) binding))) (window-clear stream) (draw-overview frame stream)))) (define-inspector-command (com-inspector-thumbnails :name "Thumbnails") () (com-inspector-show-thumbnails)) (define-inspector-command (com-inspector-show-thumbnails :name "Show Thumbnails") () (with-result-inspector (frame) (let ((stream (get-frame-pane frame 'query-results))) (setf (map-on-display-p frame) nil) (window-clear stream) (draw-query-results frame stream)))) (define-inspector-command (com-reload-ontology :name "Reload Ontology") () (load-geo-ontology)) (define-inspector-command (com-reload-queries :name "Reload Queries") () (load "q-queries.lisp")) (define-inspector-command (com-inspector-ontology :name "Ontology") () (com-inspector-show-ontology)) #+:midelora (define-inspector-command (com-inspector-show-ontology :name "Show Ontology") () (if (is-midelora-map-p *cur-map*) (dag::visualize-dag (taxonomy (find-tbox 'prover::oejendorf :error-p t))) (let ((taxonomy (racer-dag::get-racer-taxonomy 'racer-user::oejendorf))) (dag:visualize-dag taxonomy)))) #-:midelora (define-inspector-command (com-inspector-show-ontology :name "Show Ontology") () (let ((taxonomy (racer-dag::get-racer-taxonomy 'racer-user::oejendorf))) (dag:visualize-dag taxonomy))) (define-inspector-command (com-inspector-delete-page :name "Delete Page") () (delete-page)) (define-inspector-command (com-inspector-delete-all-pages :name "Delete All Pages") () (delete-all-pages)) (define-inspector-command (com-inspector-next-page :name "Next Page") () (next-page)) (define-inspector-command (com-inspector-prev-page :name "Previous Page") () (previous-page)) (define-inspector-command (com-inspector-show-query :name "Show Query") () (window-clear *standard-output*) (when *last-query* (terpri *standard-output*) (format t "Query: ") (write (unparse-query *last-query*) :pretty t :escape nil :readably nil) (format t "~%~% Variables: ") (write (answer-pattern *last-query*) :pretty t :escape nil :readably nil))) (define-inspector-command (com-inspector-show-code :name "Show Code") () (window-clear *standard-output*) (when *last-query* (dolist (query (cons *last-query* (thematic-substrate::all-subqueries *last-query*))) (pprint (source query) *standard-output*)))) (define-inspector-command (com-inspector-answer :name "Answer") () (com-inspector-show-answer)) (define-inspector-command (com-inspector-show-answer :name "Show Answer") () (let ((stream *standard-output*) ) (when *last-query* (run #'(lambda () (window-clear stream) (format stream "Last query returned ~A tuples: ~%" (length (result-bindings *last-query*))) (pprint (mapcar #'(lambda (binding) (mapcar #'(lambda (var object) (list var (if (symbolp object) object (name object)))) (answer-pattern *last-query*) binding)) (result-bindings *last-query*) ) stream)))))) (define-inspector-command (com-inspector-clear :name "Clear") () (window-clear *standard-output*) (window-clear *query-io*) (unhighlight-all) (setf *last-query* nil) (setf (map-on-display-p *application-frame*) nil) (delete-all-pages) (update-buttons)) (define-inspector-command (com-inspector-show-repository :name "Show Repository") () (show-qbox (get-current-map))) (define-inspector-command (com-inspector-clear-repository :name "Clear Repository") () (thematic-substrate::clear-repository (get-current-map))) (define-inspector-command (com-inspector-restart-map-viewer :name "Restart Map Viewer") () (map-viewer)) (define-inspector-command (com-inspector-quit :name "Quit") () (with-result-inspector (frame) (let ((yes-or-no (notify-user frame "Quit selected! Are you sure?" :style :question))) (when yes-or-no (setf *result-inspector-frame* nil) (frame-exit frame))))) (define-inspector-command (com-inspector-inspect-query-result) ((object 'query-result)) (select-query-result object) (draw-selected-query-result)) (defmethod select-query-result ((object query-result)) (with-result-inspector (frame) (setf (selected-query-result frame) object) (unhighlight-all) (dolist (tuple (bindings object)) (let ((object (second tuple)) (var (first tuple))) (setf (geometry::bound-to (if (symbolp object) (get-associated-substrate-node (substrate *last-query*) object) object)) var))))) (define-presentation-to-command-translator inspect-query-result (query-result com-inspector-inspect-query-result inspector :tester (() (not *searching-active*)) :echo t :maintain-history nil :gesture :inspect-query-result) (object) (list object)) (define-inspector-command (com-inspector-select-query-result) ((object 'query-result)) (setf (selected object) (not (selected object))) (com-inspector-inspect-query-result object) (draw-thumbnail object)) (define-presentation-to-command-translator select-query-result (query-result com-inspector-select-query-result inspector :echo nil :tester (() (not *searching-active*)) :maintain-history nil :gesture :select-query-result) (object) (list object)) (defmacro with-dlmaps-standard-settings (&body body) `(if *exclude-permutations* (with-nrql-settings (:abox-mirroring nil :query-optimization t :two-phase-query-processing-mode nil :told-information-querying nil :tuple-computation-mode :set-at-a-time :exclude-permutations t :query-repository nil :report-inconsistent-queries nil :report-tautological-queries nil :query-realization nil :check-abox-consistency nil :rewrite-to-dnf t) (racer:with-unique-name-assumption (let ((ts::*runtime-evaluation-p* nil) (ts::*compile-queries-p* nil)) ,@body))) (with-nrql-settings (:abox-mirroring nil :query-optimization t :two-phase-query-processing-mode nil :told-information-querying nil :tuple-computation-mode :set-at-a-time :exclude-permutations nil :query-repository nil :report-inconsistent-queries nil :report-tautological-queries nil :query-realization nil :check-abox-consistency nil :rewrite-to-dnf t) (racer:with-unique-name-assumption (let ((ts::*runtime-evaluation-p* nil) (ts::*compile-queries-p* nil)) ,@body))))) (defmacro with-dlmaps-experimental-settings (&body body) `(if *exclude-permutations* (with-nrql-settings (:query-optimization t :two-phase-query-processing-mode nil :tuple-computation-mode :set-at-a-time :exclude-permutations t :query-repository t :report-inconsistent-queries t :query-realization nil) (racer:with-unique-name-assumption (let ((ts::*runtime-evaluation-p* nil) (ts::*compile-queries-p* nil)) ,@body))) (with-nrql-settings (:query-optimization t :two-phase-query-processing-mode t :tuple-computation-mode :set-at-a-time :exclude-permutations nil :query-repository t :report-inconsistent-queries t :query-realization nil) (racer:with-unique-name-assumption (let ((ts::*runtime-evaluation-p* nil) (ts::*compile-queries-p* nil)) ,@body))))) (defun inspector-answer-query (query vois &optional doc) (present-query query vois) (terpri *standard-input*) (terpri *standard-input*) (in-substrate* (get-current-map)) (with-result-inspector (frame) (setf (map-on-display-p frame) nil) (delete-all-pages) (let ((*standard-output* (frame-standard-output frame)) (find-package :racer-user))) (window-clear *standard-output*) (terpri *standard-output*) (when doc (format t "Natürlichsprachlich:~%") (format t doc) (terpri *standard-output*) (terpri *standard-output*)) (format t "Query: ") (write query :pretty t :escape nil :readably nil) (format t "~%~% Variables: ") (write vois :pretty t :escape nil :readably nil) (terpri *standard-output*) (terpri *standard-output*) (pprint aus irgendwelchen ( locking ? ) blockiert die , wenn kein (run #'(lambda () (if *experimental* (with-dlmaps-experimental-settings (answer-query query vois)) (with-dlmaps-standard-settings (answer-query query vois))))))))) (defun present-query (q v) (let ((stream *standard-input* ) (*print-pretty* t)) (format stream "Command: Answer Query~%") (format stream "Enter Query: ") (present q 'form :stream stream) (terpri stream) (format stream "Enter Variables: ") (present v '(sequence symbol) :separator #\Space :stream stream))) (define-inspector-command (com-inspector-q1 :name "Q1") () (q1)) (define-inspector-command (com-inspector-q2 :name "Q2") () (q2)) (define-inspector-command (com-inspector-q3 :name "Q3") () (q3)) (define-inspector-command (com-inspector-q4 :name "Q4") () (q4)) (define-inspector-command (com-inspector-q5 :name "Q5") () (q5)) (define-inspector-command (com-inspector-q6 :name "Q6") () (q6)) (define-inspector-command (com-inspector-q7 :name "Q7") () (q7)) (define-inspector-command (com-inspector-q8 :name "Q8") () (q8)) (define-inspector-command (com-inspector-q9 :name "Q9") () (q9)) (define-inspector-command (com-inspector-q10 :name "Q10") () (q10)) (define-inspector-command (com-inspector-q11 :name "Q11") () (q11)) (define-inspector-command (com-inspector-q12 :name "Q12") () (q12)) (define-inspector-command (com-inspector-q13 :name "Q13") () (q13)) (define-inspector-command (com-inspector-q14 :name "Q14") () (q14)) (define-inspector-command (com-inspector-q15 :name "Q15") () (q15)) (define-inspector-command (com-inspector-q16 :name "Q16") () (q16)) (define-inspector-command (com-inspector-q17 :name "Q17") () (q17)) (define-inspector-command (com-inspector-q18 :name "Q18") () (q18)) (define-inspector-command (com-inspector-q19 :name "Q19") () (q19)) (define-inspector-command (com-inspector-q20 :name "Q20") () (q20))
3246c05d1922ca87e8a1964119fe7d8141860de33635f1426fb928edb08703d6
davdar/maam
Syntax.hs
module Lang.LamIf.Syntax where import FP newtype RawName = RawName { getRawName :: String } deriving (Eq, Ord) type SRawName = Stamped BdrNum RawName data GenName = GenName { genNameMark :: Maybe Int , genNameRawName :: RawName } deriving (Eq, Ord) newtype LocNum = LocNum Int deriving (Eq, Ord, PartialOrder, Peano) newtype BdrNum = BdrNum Int deriving (Eq, Ord, PartialOrder, Peano) type Name = Stamped BdrNum GenName srawNameToName :: SRawName -> Name srawNameToName (Stamped i x) = Stamped i $ GenName Nothing x data Lit = I Int | B Bool deriving (Eq, Ord) instance PartialOrder Lit where pcompare = discreteOrder makePrisms ''Lit data BinOp = Add | Sub | GTE deriving (Eq, Ord) instance PartialOrder BinOp where pcompare = discreteOrder data LBinOp = LBinOp { lbinOpOp :: BinOp , lbinOpLevel :: Int } deriving (Eq, Ord) data PreExp n e = Lit Lit | Var n | Lam n e | Prim LBinOp e e | Let n e e | App e e | If e e e | Tup e e | Pi1 e | Pi2 e deriving (Eq, Ord) type RawExp = Fix (PreExp RawName) type Exp = StampedFix LocNum (PreExp SRawName)
null
https://raw.githubusercontent.com/davdar/maam/2cc3ff3511a7a4daadcd44c60c4b08862c01e183/src/Lang/LamIf/Syntax.hs
haskell
module Lang.LamIf.Syntax where import FP newtype RawName = RawName { getRawName :: String } deriving (Eq, Ord) type SRawName = Stamped BdrNum RawName data GenName = GenName { genNameMark :: Maybe Int , genNameRawName :: RawName } deriving (Eq, Ord) newtype LocNum = LocNum Int deriving (Eq, Ord, PartialOrder, Peano) newtype BdrNum = BdrNum Int deriving (Eq, Ord, PartialOrder, Peano) type Name = Stamped BdrNum GenName srawNameToName :: SRawName -> Name srawNameToName (Stamped i x) = Stamped i $ GenName Nothing x data Lit = I Int | B Bool deriving (Eq, Ord) instance PartialOrder Lit where pcompare = discreteOrder makePrisms ''Lit data BinOp = Add | Sub | GTE deriving (Eq, Ord) instance PartialOrder BinOp where pcompare = discreteOrder data LBinOp = LBinOp { lbinOpOp :: BinOp , lbinOpLevel :: Int } deriving (Eq, Ord) data PreExp n e = Lit Lit | Var n | Lam n e | Prim LBinOp e e | Let n e e | App e e | If e e e | Tup e e | Pi1 e | Pi2 e deriving (Eq, Ord) type RawExp = Fix (PreExp RawName) type Exp = StampedFix LocNum (PreExp SRawName)
71a2fa785415fa071b16f37135c40747f35e3bc8958957341a90c02c45eded0e
Clozure/ccl-tests
union.lsp
;-*- Mode: Lisp -*- Author : Created : Sun Apr 20 07:41:24 2003 ;;;; Contains: Tests of UNION (in-package :cl-test) (compile-and-load "cons-aux.lsp") (deftest union.1 (union nil nil) nil) (deftest union.2 (union-with-check (list 'a) nil) (a)) (deftest union.3 (union-with-check (list 'a) (list 'a)) (a)) (deftest union-4 (union-with-check (list 1) (list 1)) (1)) (deftest union.5 (let ((x (list 'a 'b))) (union-with-check (list x) (list x))) ((a b))) (deftest union.6 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y))) (check-union x y result))) t) (deftest union.6-a (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test #'eq))) (check-union x y result))) t) (deftest union.7 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test #'eql))) (check-union x y result))) t) (deftest union.8 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test #'equal))) (check-union x y result))) t) (deftest union.9 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test-not (complement #'eql)))) (check-union x y result))) t) (deftest union.10 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test-not (complement #'equal)))) (check-union x y result))) t) (deftest union.11 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test-not (complement #'eq)))) (check-union x y result))) t) (deftest union.12 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y))) (check-union x y result))) t) (deftest union.13 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y :test #'equal))) (check-union x y result))) t) (deftest union.14 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y :test #'eql))) (check-union x y result))) t) (deftest union.15 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y :test-not (complement #'equal)))) (check-union x y result))) t) (deftest union.16 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y :test-not (complement #'eql)))) (check-union x y result))) t) (deftest union.17 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+))) (check-union x y result))) t) (deftest union.18 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+ :test #'equal))) (check-union x y result))) t) (deftest union.19 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+ :test #'eql))) (check-union x y result))) t) (deftest union.20 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+ :test-not (complement #'equal)))) (check-union x y result))) t) (deftest union.21 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+ :test-not (complement #'equal)))) (check-union x y result))) t) (deftest union.22 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y nil))) (check-union x y result))) t) (deftest union.23 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y '1+))) (check-union x y result))) t) ;; Do large numbers of random units (deftest union.24 (do-random-unions 100 100 200) nil) (deftest union.25 (let ((x (shuffle '(1 4 6 10 45 101))) (y (copy-list '(102 5 2 11 44 6)))) (let ((result (union-with-check x y :test #'(lambda (a b) (<= (abs (- a b)) 1))))) (and (not (eqt result 'failed)) (sort (sublis '((2 . 1) (5 . 4) (11 . 10) (45 . 44) (102 . 101)) (copy-list result)) #'<)))) (1 4 6 10 44 101)) Check that union uses eql , not equal or eq (deftest union.26 (let ((x 1000) (y 1000)) (loop while (not (typep x 'bignum)) do (progn (setf x (* x x)) (setf y (* y y)))) (notnot-mv (or (eqt x y) ;; if bignums are eq, the test is worthless (eql (length (union-with-check (list x) (list x))) 1)))) t) (deftest union.27 (union-with-check (list (copy-seq "aa")) (list (copy-seq "aa"))) ("aa" "aa")) ;; Check that union does not reverse the arguments to :test, :test-not (deftest union.28 (block fail (sort (union-with-check (list 1 2 3) (list 4 5 6) :test #'(lambda (x y) (when (< y x) (return-from fail 'fail)) (eql x y))) #'<)) (1 2 3 4 5 6)) (deftest union.29 (block fail (sort (union-with-check-and-key (list 1 2 3) (list 4 5 6) #'identity :test #'(lambda (x y) (when (< y x) (return-from fail 'fail)) (eql x y))) #'<)) (1 2 3 4 5 6)) (deftest union.30 (block fail (sort (union-with-check (list 1 2 3) (list 4 5 6) :test-not #'(lambda (x y) (when (< y x) (return-from fail 'fail)) (not (eql x y)))) #'<)) (1 2 3 4 5 6)) (deftest union.31 (block fail (sort (union-with-check-and-key (list 1 2 3) (list 4 5 6) #'identity :test-not #'(lambda (x y) (when (< y x) (return-from fail 'fail)) (not (eql x y)))) #'<)) (1 2 3 4 5 6)) (defharmless union.test-and-test-not.1 (union (list 1 4 8 10) (list 1 2 3 9 10 13) :test #'eql :test-not #'eql)) (defharmless union.test-and-test-not.2 (union (list 1 4 8 10) (list 1 2 3 9 10 13) :test-not #'eql :test #'eql)) ;;; Order of evaluation tests (deftest union.order.1 (let ((i 0) x y) (values (sort (union (progn (setf x (incf i)) (copy-list '(1 3 5))) (progn (setf y (incf i)) (copy-list '(2 5 8)))) #'<) i x y)) (1 2 3 5 8) 2 1 2) (deftest union.order.2 (let ((i 0) x y z w) (values (sort (union (progn (setf x (incf i)) (copy-list '(1 3 5))) (progn (setf y (incf i)) (copy-list '(2 5 8))) :test (progn (setf z (incf i)) #'eql) :key (progn (setf w (incf i)) #'identity)) #'<) i x y z w)) (1 2 3 5 8) 4 1 2 3 4) (deftest union.order.3 (let ((i 0) x y z w) (values (sort (union (progn (setf x (incf i)) (copy-list '(1 3 5))) (progn (setf y (incf i)) (copy-list '(2 5 8))) :key (progn (setf z (incf i)) #'identity) :test (progn (setf w (incf i)) #'eql)) #'<) i x y z w)) (1 2 3 5 8) 4 1 2 3 4) ;;; Keyword tests (deftest union.allow-other-keys.1 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :bad t :allow-other-keys "yes") #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.2 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys t :also-bad t) #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.3 (sort (union (list 1 2 3) (list 1 2 3) :allow-other-keys t :also-bad t :test #'(lambda (x y) (= x (+ y 100)))) #'<) (1 1 2 2 3 3)) (deftest union.allow-other-keys.4 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys t) #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.5 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys nil) #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.6 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys t :allow-other-keys nil) #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.7 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys t :allow-other-keys nil '#:x 1) #'<) (1 2 5 7 9 10 11 20)) (deftest union.keywords.9 (sort (union (list 1 2 3) (list 1 2 3) :test #'(lambda (x y) (= x (+ y 100))) :test #'eql) #'<) (1 1 2 2 3 3)) (def-fold-test union.fold.1 (union '(a b c d e) '(d x y a w c))) ;;; Error tests (deftest union.error.1 (signals-error (union) program-error) t) (deftest union.error.2 (signals-error (union nil) program-error) t) (deftest union.error.3 (signals-error (union nil nil :bad t) program-error) t) (deftest union.error.4 (signals-error (union nil nil :key) program-error) t) (deftest union.error.5 (signals-error (union nil nil 1 2) program-error) t) (deftest union.error.6 (signals-error (union nil nil :bad t :allow-other-keys nil) program-error) t) (deftest union.error.7 (signals-error (union (list 1 2) (list 3 4) :test #'identity) program-error) t) (deftest union.error.8 (signals-error (union (list 1 2) (list 3 4) :test-not #'identity) program-error) t) (deftest union.error.9 (signals-error (union (list 1 2) (list 3 4) :key #'cons) program-error) t) (deftest union.error.10 (signals-error (union (list 1 2) (list 3 4) :key #'car) type-error) t) (deftest union.error.11 (signals-error (union (list 1 2 3) (list* 4 5 6)) type-error) t) (deftest union.error.12 (signals-error (union (list* 1 2 3) (list 4 5 6)) type-error) t) The next two tests used to check for union with NIL , but arguably ;;; that goes beyond the 'be prepared to signal an error' requirement, since a union algorithm does n't have to traverse one argument ;;; if the other is the empty list. (deftest union.error.13 (check-type-error #'(lambda (x) (union x '(1 2))) #'listp) nil) (deftest union.error.14 (check-type-error #'(lambda (x) (union '(1 2) x)) #'listp) nil)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/union.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of UNION Do large numbers of random units if bignums are eq, the test is worthless Check that union does not reverse the arguments to :test, :test-not Order of evaluation tests Keyword tests Error tests that goes beyond the 'be prepared to signal an error' requirement, if the other is the empty list.
Author : Created : Sun Apr 20 07:41:24 2003 (in-package :cl-test) (compile-and-load "cons-aux.lsp") (deftest union.1 (union nil nil) nil) (deftest union.2 (union-with-check (list 'a) nil) (a)) (deftest union.3 (union-with-check (list 'a) (list 'a)) (a)) (deftest union-4 (union-with-check (list 1) (list 1)) (1)) (deftest union.5 (let ((x (list 'a 'b))) (union-with-check (list x) (list x))) ((a b))) (deftest union.6 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y))) (check-union x y result))) t) (deftest union.6-a (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test #'eq))) (check-union x y result))) t) (deftest union.7 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test #'eql))) (check-union x y result))) t) (deftest union.8 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test #'equal))) (check-union x y result))) t) (deftest union.9 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test-not (complement #'eql)))) (check-union x y result))) t) (deftest union.10 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test-not (complement #'equal)))) (check-union x y result))) t) (deftest union.11 (let ((x (copy-list '(a b c d e f))) (y (copy-list '(z c y a v b)))) (let ((result (union-with-check x y :test-not (complement #'eq)))) (check-union x y result))) t) (deftest union.12 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y))) (check-union x y result))) t) (deftest union.13 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y :test #'equal))) (check-union x y result))) t) (deftest union.14 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y :test #'eql))) (check-union x y result))) t) (deftest union.15 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y :test-not (complement #'equal)))) (check-union x y result))) t) (deftest union.16 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check x y :test-not (complement #'eql)))) (check-union x y result))) t) (deftest union.17 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+))) (check-union x y result))) t) (deftest union.18 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+ :test #'equal))) (check-union x y result))) t) (deftest union.19 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+ :test #'eql))) (check-union x y result))) t) (deftest union.20 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+ :test-not (complement #'equal)))) (check-union x y result))) t) (deftest union.21 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y #'1+ :test-not (complement #'equal)))) (check-union x y result))) t) (deftest union.22 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y nil))) (check-union x y result))) t) (deftest union.23 (let ((x (copy-list '(1 2 3 4 5 6 7))) (y (copy-list '(10 19 5 3 17 1001 2)))) (let ((result (union-with-check-and-key x y '1+))) (check-union x y result))) t) (deftest union.24 (do-random-unions 100 100 200) nil) (deftest union.25 (let ((x (shuffle '(1 4 6 10 45 101))) (y (copy-list '(102 5 2 11 44 6)))) (let ((result (union-with-check x y :test #'(lambda (a b) (<= (abs (- a b)) 1))))) (and (not (eqt result 'failed)) (sort (sublis '((2 . 1) (5 . 4) (11 . 10) (45 . 44) (102 . 101)) (copy-list result)) #'<)))) (1 4 6 10 44 101)) Check that union uses eql , not equal or eq (deftest union.26 (let ((x 1000) (y 1000)) (loop while (not (typep x 'bignum)) do (progn (setf x (* x x)) (setf y (* y y)))) (notnot-mv (or (eql (length (union-with-check (list x) (list x))) 1)))) t) (deftest union.27 (union-with-check (list (copy-seq "aa")) (list (copy-seq "aa"))) ("aa" "aa")) (deftest union.28 (block fail (sort (union-with-check (list 1 2 3) (list 4 5 6) :test #'(lambda (x y) (when (< y x) (return-from fail 'fail)) (eql x y))) #'<)) (1 2 3 4 5 6)) (deftest union.29 (block fail (sort (union-with-check-and-key (list 1 2 3) (list 4 5 6) #'identity :test #'(lambda (x y) (when (< y x) (return-from fail 'fail)) (eql x y))) #'<)) (1 2 3 4 5 6)) (deftest union.30 (block fail (sort (union-with-check (list 1 2 3) (list 4 5 6) :test-not #'(lambda (x y) (when (< y x) (return-from fail 'fail)) (not (eql x y)))) #'<)) (1 2 3 4 5 6)) (deftest union.31 (block fail (sort (union-with-check-and-key (list 1 2 3) (list 4 5 6) #'identity :test-not #'(lambda (x y) (when (< y x) (return-from fail 'fail)) (not (eql x y)))) #'<)) (1 2 3 4 5 6)) (defharmless union.test-and-test-not.1 (union (list 1 4 8 10) (list 1 2 3 9 10 13) :test #'eql :test-not #'eql)) (defharmless union.test-and-test-not.2 (union (list 1 4 8 10) (list 1 2 3 9 10 13) :test-not #'eql :test #'eql)) (deftest union.order.1 (let ((i 0) x y) (values (sort (union (progn (setf x (incf i)) (copy-list '(1 3 5))) (progn (setf y (incf i)) (copy-list '(2 5 8)))) #'<) i x y)) (1 2 3 5 8) 2 1 2) (deftest union.order.2 (let ((i 0) x y z w) (values (sort (union (progn (setf x (incf i)) (copy-list '(1 3 5))) (progn (setf y (incf i)) (copy-list '(2 5 8))) :test (progn (setf z (incf i)) #'eql) :key (progn (setf w (incf i)) #'identity)) #'<) i x y z w)) (1 2 3 5 8) 4 1 2 3 4) (deftest union.order.3 (let ((i 0) x y z w) (values (sort (union (progn (setf x (incf i)) (copy-list '(1 3 5))) (progn (setf y (incf i)) (copy-list '(2 5 8))) :key (progn (setf z (incf i)) #'identity) :test (progn (setf w (incf i)) #'eql)) #'<) i x y z w)) (1 2 3 5 8) 4 1 2 3 4) (deftest union.allow-other-keys.1 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :bad t :allow-other-keys "yes") #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.2 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys t :also-bad t) #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.3 (sort (union (list 1 2 3) (list 1 2 3) :allow-other-keys t :also-bad t :test #'(lambda (x y) (= x (+ y 100)))) #'<) (1 1 2 2 3 3)) (deftest union.allow-other-keys.4 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys t) #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.5 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys nil) #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.6 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys t :allow-other-keys nil) #'<) (1 2 5 7 9 10 11 20)) (deftest union.allow-other-keys.7 (sort (union (list 7 9 1 5) (list 10 11 9 20 1 2) :allow-other-keys t :allow-other-keys nil '#:x 1) #'<) (1 2 5 7 9 10 11 20)) (deftest union.keywords.9 (sort (union (list 1 2 3) (list 1 2 3) :test #'(lambda (x y) (= x (+ y 100))) :test #'eql) #'<) (1 1 2 2 3 3)) (def-fold-test union.fold.1 (union '(a b c d e) '(d x y a w c))) (deftest union.error.1 (signals-error (union) program-error) t) (deftest union.error.2 (signals-error (union nil) program-error) t) (deftest union.error.3 (signals-error (union nil nil :bad t) program-error) t) (deftest union.error.4 (signals-error (union nil nil :key) program-error) t) (deftest union.error.5 (signals-error (union nil nil 1 2) program-error) t) (deftest union.error.6 (signals-error (union nil nil :bad t :allow-other-keys nil) program-error) t) (deftest union.error.7 (signals-error (union (list 1 2) (list 3 4) :test #'identity) program-error) t) (deftest union.error.8 (signals-error (union (list 1 2) (list 3 4) :test-not #'identity) program-error) t) (deftest union.error.9 (signals-error (union (list 1 2) (list 3 4) :key #'cons) program-error) t) (deftest union.error.10 (signals-error (union (list 1 2) (list 3 4) :key #'car) type-error) t) (deftest union.error.11 (signals-error (union (list 1 2 3) (list* 4 5 6)) type-error) t) (deftest union.error.12 (signals-error (union (list* 1 2 3) (list 4 5 6)) type-error) t) The next two tests used to check for union with NIL , but arguably since a union algorithm does n't have to traverse one argument (deftest union.error.13 (check-type-error #'(lambda (x) (union x '(1 2))) #'listp) nil) (deftest union.error.14 (check-type-error #'(lambda (x) (union '(1 2) x)) #'listp) nil)
5cc43d0a8c5187b2da2bc850ba3e027e57eac5c88e00df0cbf572bba5788e3d7
yrashk/socket.io-erlang
socketio_http.erl
-module(socketio_http). -include_lib("../include/socketio.hrl"). -behaviour(gen_server). %% API -export([start_link/6]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, { default_http_handler, sessions, event_manager, sup, web_server_monitor, server_module, resource, port % very dirty hack }). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link(ServerModule, Port, Resource, SSL, {DefaultHttpHandler, Args}, Sup) -> gen_server:start_link(?MODULE, [ServerModule, Port, Resource, SSL, {DefaultHttpHandler, Args}, Sup], []); start_link(ServerModule, Port, Resource, SSL, DefaultHttpHandler, Sup) -> gen_server:start_link(?MODULE, [ServerModule, Port, Resource, SSL, DefaultHttpHandler, Sup], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Initializes the server %% ) - > { ok , State } | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([ServerModule, Port, Resource, SSL, DefaultHttpHandler, Sup]) -> Self = self(), process_flag(trap_exit, true), {ok, ServerPid} = apply(ServerModule, start_link, [[{port, Port}, {http_process, Self}, {resource, Resource}, {ssl, SSL}]]), WebServerRef = erlang:monitor(process, ServerPid), gen_server:cast(Self, acquire_event_manager), {ok, #state{ default_http_handler = DefaultHttpHandler, sessions = ets:new(socketio_sessions,[public]), sup = Sup, web_server_monitor = WebServerRef, server_module = ServerModule, resource = Resource, port = Port }}. %%-------------------------------------------------------------------- @private %% @doc %% Handling call messages %% , From , State ) - > %% {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call({request, 'GET', ["socket.io.js"|Resource], Req}, _From, #state{ server_module = ServerModule, resource = Resource } = State) -> Response = apply(ServerModule, file, [Req, filename:join([filename:dirname(code:which(?MODULE)), "..", "priv", "Socket.IO", "socket.io.js"])]), {reply, Response, State}; handle_call({request, 'GET', ["WebSocketMain.swf", "web-socket-js", "vendor", "lib"|Resource], Req}, _From, #state{ server_module = ServerModule, resource = Resource } = State) -> Response = apply(ServerModule, file, [Req, filename:join([filename:dirname(code:which(?MODULE)), "..", "priv", "Socket.IO", "lib", "vendor", "web-socket-js", "WebSocketMain.swf"])]), {reply, Response, State}; %% New XHR Polling request handle_call({request, 'GET', [_Random, "xhr-polling"|Resource], Req }, From, #state{ resource = Resource} = State) -> handle_call({session, generate, {'xhr-polling', Req}, socketio_transport_polling}, From, State); %% Returning XHR Polling handle_call({request, 'GET', [_Random, SessionId, "xhr-polling"|Resource], Req }, From, #state{ server_module = ServerModule, resource = Resource, sessions = Sessions } = State) -> case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:cast(Pid, {'xhr-polling', polling_request, Req, From}); _ -> gen_server:reply(From, apply(ServerModule, respond, [Req, 404, ""])) end, {noreply, State}; Polling data handle_call({request, 'POST', ["send", SessionId, "xhr-polling"|Resource], Req }, _From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> Response = case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:call(Pid, {'xhr-polling', data, Req}); _ -> apply(ServerModule, respond, [Req, 404, ""]) end, {reply, Response, State}; %% New JSONP Polling request handle_call({request, 'GET', [Index, _Random, "jsonp-polling"|Resource], Req }, From, #state{ resource = Resource} = State) -> handle_call({session, generate, {'jsonp-polling', {Req, Index}}, socketio_transport_polling}, From, State); Returning JSONP Polling handle_call({request, 'GET', [Index, _Random, SessionId, "jsonp-polling"|Resource], Req }, From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:cast(Pid, {'jsonp-polling', polling_request, {Req, Index}, From}); _ -> gen_server:reply(From, apply(ServerModule, respond, [Req, 404, ""])) end, {noreply, State}; Incoming JSONP Polling data handle_call({request, 'POST', [_Index, _Random, SessionId, "jsonp-polling"|Resource], Req }, _From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> Response = case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:call(Pid, {'jsonp-polling', data, Req}); _ -> apply(ServerModule, respond, [Req, 404, ""]) end, {reply, Response, State}; New XHR Multipart request handle_call({request, 'GET', ["xhr-multipart"|Resource], Req }, From, #state{ resource = Resource} = State) -> handle_call({session, generate, {'xhr-multipart', {Req, From}}, socketio_transport_xhr_multipart}, From, State), {noreply, State}; Incoming XHR Multipart data handle_call({request, 'POST', ["send", SessionId, "xhr-multipart"|Resource], Req }, _From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> Response = case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:call(Pid, {'xhr-multipart', data, Req}); _ -> apply(ServerModule, respond, [Req, 404, ""]) end, {reply, Response, State}; New htmlfile request handle_call({request, 'GET', [_Random, "htmlfile"|Resource], Req }, From, #state{ resource = Resource} = State) -> handle_call({session, generate, {'htmlfile', {Req, From}}, socketio_transport_htmlfile}, From, State), {noreply, State}; handle_call({request, 'POST', ["send", SessionId, "htmlfile"|Resource], Req }, _From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> Response = case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:call(Pid, {'htmlfile', data, Req}); _ -> apply(ServerModule, respond, [Req, 404, ""]) end, {reply, Response, State}; %% If we can't route it, let others deal with it handle_call({request, _Method, _Path, _Req} = Req, From, #state{ default_http_handler = {HttpHandler,Args} } = State) when is_atom(HttpHandler) -> handle_call(Req, From, State#state{ default_http_handler = fun(P1, P2, P3) -> apply(HttpHandler, handle_request, [P1, P2, P3 | Args]) end }); handle_call({request, _Method, _Path, _Req} = Req, From, #state{ default_http_handler = HttpHandler } = State) when is_atom(HttpHandler) -> handle_call(Req, From, State#state{ default_http_handler = fun(P1, P2, P3) -> HttpHandler:handle_request(P1, P2, P3) end }); handle_call({request, Method, Path, Req}, _From, #state{ default_http_handler = HttpHandler } = State) when is_function(HttpHandler) -> Response = HttpHandler(Method, lists:reverse(Path), Req), {reply, Response, State}; %% Sessions handle_call({session, generate, ConnectionReference, Transport}, _From, #state{ sup = Sup, sessions = Sessions, event_manager = EventManager, server_module = ServerModule, port = Port } = State) -> UUID = binary_to_list(ossp_uuid:make(v4, text)), {ok, Pid} = socketio_client:start(Sup, Transport, UUID, ServerModule, ConnectionReference, Port), link(Pid), ets:insert(Sessions, [{UUID, Pid}, {Pid, UUID}]), gen_event:notify(EventManager, {client, Pid}), {reply, {UUID, Pid}, State}; %% Event management handle_call(event_manager, _From, #state{ event_manager = EventMgr } = State) -> {reply, EventMgr, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling cast messages %% @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(acquire_event_manager, State) -> EventManager = socketio_listener:event_manager(listener(State)), {noreply, State#state{ event_manager = EventManager }}; handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling all non call/cast messages %% , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info({'EXIT', Pid, _}, #state{ event_manager = EventManager, sessions = Sessions } = State) -> case ets:lookup(Sessions, Pid) of [{Pid, UUID}] -> ets:delete(Sessions,UUID), ets:delete(Sessions,Pid), gen_event:notify(EventManager, {disconnect, Pid}); _ -> ignore end, {noreply, State}; If goes down , we stop socket.io handle_info({'DOWN', WebServerRef, _, _, _}, #state{ web_server_monitor = WebServerRef } = State) -> {stop, normal, State}; handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates with . The return value is ignored . %% , State ) - > void ( ) %% @end %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- @private %% @doc %% Convert process state when code is changed %% , State , Extra ) - > { ok , NewState } %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== listener(#state{ sup = Sup }) -> socketio_listener:server(Sup).
null
https://raw.githubusercontent.com/yrashk/socket.io-erlang/7a6c768a28cf18d58efd7abe0eb276a22dbc7974/src/socketio_http.erl
erlang
API gen_server callbacks very dirty hack =================================================================== API =================================================================== -------------------------------------------------------------------- @doc Starts the server @end -------------------------------------------------------------------- =================================================================== gen_server callbacks =================================================================== -------------------------------------------------------------------- @doc Initializes the server ignore | {stop, Reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling call messages {reply, Reply, State} | {stop, Reason, Reply, State} | {stop, Reason, State} @end -------------------------------------------------------------------- New XHR Polling request Returning XHR Polling New JSONP Polling request If we can't route it, let others deal with it Sessions Event management -------------------------------------------------------------------- @doc Handling cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling all non call/cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Convert process state when code is changed @end -------------------------------------------------------------------- =================================================================== ===================================================================
-module(socketio_http). -include_lib("../include/socketio.hrl"). -behaviour(gen_server). -export([start_link/6]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, { default_http_handler, sessions, event_manager, sup, web_server_monitor, server_module, resource, }). ( ) - > { ok , Pid } | ignore | { error , Error } start_link(ServerModule, Port, Resource, SSL, {DefaultHttpHandler, Args}, Sup) -> gen_server:start_link(?MODULE, [ServerModule, Port, Resource, SSL, {DefaultHttpHandler, Args}, Sup], []); start_link(ServerModule, Port, Resource, SSL, DefaultHttpHandler, Sup) -> gen_server:start_link(?MODULE, [ServerModule, Port, Resource, SSL, DefaultHttpHandler, Sup], []). @private ) - > { ok , State } | { ok , State , Timeout } | init([ServerModule, Port, Resource, SSL, DefaultHttpHandler, Sup]) -> Self = self(), process_flag(trap_exit, true), {ok, ServerPid} = apply(ServerModule, start_link, [[{port, Port}, {http_process, Self}, {resource, Resource}, {ssl, SSL}]]), WebServerRef = erlang:monitor(process, ServerPid), gen_server:cast(Self, acquire_event_manager), {ok, #state{ default_http_handler = DefaultHttpHandler, sessions = ets:new(socketio_sessions,[public]), sup = Sup, web_server_monitor = WebServerRef, server_module = ServerModule, resource = Resource, port = Port }}. @private , From , State ) - > { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({request, 'GET', ["socket.io.js"|Resource], Req}, _From, #state{ server_module = ServerModule, resource = Resource } = State) -> Response = apply(ServerModule, file, [Req, filename:join([filename:dirname(code:which(?MODULE)), "..", "priv", "Socket.IO", "socket.io.js"])]), {reply, Response, State}; handle_call({request, 'GET', ["WebSocketMain.swf", "web-socket-js", "vendor", "lib"|Resource], Req}, _From, #state{ server_module = ServerModule, resource = Resource } = State) -> Response = apply(ServerModule, file, [Req, filename:join([filename:dirname(code:which(?MODULE)), "..", "priv", "Socket.IO", "lib", "vendor", "web-socket-js", "WebSocketMain.swf"])]), {reply, Response, State}; handle_call({request, 'GET', [_Random, "xhr-polling"|Resource], Req }, From, #state{ resource = Resource} = State) -> handle_call({session, generate, {'xhr-polling', Req}, socketio_transport_polling}, From, State); handle_call({request, 'GET', [_Random, SessionId, "xhr-polling"|Resource], Req }, From, #state{ server_module = ServerModule, resource = Resource, sessions = Sessions } = State) -> case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:cast(Pid, {'xhr-polling', polling_request, Req, From}); _ -> gen_server:reply(From, apply(ServerModule, respond, [Req, 404, ""])) end, {noreply, State}; Polling data handle_call({request, 'POST', ["send", SessionId, "xhr-polling"|Resource], Req }, _From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> Response = case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:call(Pid, {'xhr-polling', data, Req}); _ -> apply(ServerModule, respond, [Req, 404, ""]) end, {reply, Response, State}; handle_call({request, 'GET', [Index, _Random, "jsonp-polling"|Resource], Req }, From, #state{ resource = Resource} = State) -> handle_call({session, generate, {'jsonp-polling', {Req, Index}}, socketio_transport_polling}, From, State); Returning JSONP Polling handle_call({request, 'GET', [Index, _Random, SessionId, "jsonp-polling"|Resource], Req }, From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:cast(Pid, {'jsonp-polling', polling_request, {Req, Index}, From}); _ -> gen_server:reply(From, apply(ServerModule, respond, [Req, 404, ""])) end, {noreply, State}; Incoming JSONP Polling data handle_call({request, 'POST', [_Index, _Random, SessionId, "jsonp-polling"|Resource], Req }, _From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> Response = case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:call(Pid, {'jsonp-polling', data, Req}); _ -> apply(ServerModule, respond, [Req, 404, ""]) end, {reply, Response, State}; New XHR Multipart request handle_call({request, 'GET', ["xhr-multipart"|Resource], Req }, From, #state{ resource = Resource} = State) -> handle_call({session, generate, {'xhr-multipart', {Req, From}}, socketio_transport_xhr_multipart}, From, State), {noreply, State}; Incoming XHR Multipart data handle_call({request, 'POST', ["send", SessionId, "xhr-multipart"|Resource], Req }, _From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> Response = case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:call(Pid, {'xhr-multipart', data, Req}); _ -> apply(ServerModule, respond, [Req, 404, ""]) end, {reply, Response, State}; New htmlfile request handle_call({request, 'GET', [_Random, "htmlfile"|Resource], Req }, From, #state{ resource = Resource} = State) -> handle_call({session, generate, {'htmlfile', {Req, From}}, socketio_transport_htmlfile}, From, State), {noreply, State}; handle_call({request, 'POST', ["send", SessionId, "htmlfile"|Resource], Req }, _From, #state{ resource = Resource, server_module = ServerModule, sessions = Sessions } = State) -> Response = case ets:lookup(Sessions, SessionId) of [{SessionId, Pid}] -> gen_server:call(Pid, {'htmlfile', data, Req}); _ -> apply(ServerModule, respond, [Req, 404, ""]) end, {reply, Response, State}; handle_call({request, _Method, _Path, _Req} = Req, From, #state{ default_http_handler = {HttpHandler,Args} } = State) when is_atom(HttpHandler) -> handle_call(Req, From, State#state{ default_http_handler = fun(P1, P2, P3) -> apply(HttpHandler, handle_request, [P1, P2, P3 | Args]) end }); handle_call({request, _Method, _Path, _Req} = Req, From, #state{ default_http_handler = HttpHandler } = State) when is_atom(HttpHandler) -> handle_call(Req, From, State#state{ default_http_handler = fun(P1, P2, P3) -> HttpHandler:handle_request(P1, P2, P3) end }); handle_call({request, Method, Path, Req}, _From, #state{ default_http_handler = HttpHandler } = State) when is_function(HttpHandler) -> Response = HttpHandler(Method, lists:reverse(Path), Req), {reply, Response, State}; handle_call({session, generate, ConnectionReference, Transport}, _From, #state{ sup = Sup, sessions = Sessions, event_manager = EventManager, server_module = ServerModule, port = Port } = State) -> UUID = binary_to_list(ossp_uuid:make(v4, text)), {ok, Pid} = socketio_client:start(Sup, Transport, UUID, ServerModule, ConnectionReference, Port), link(Pid), ets:insert(Sessions, [{UUID, Pid}, {Pid, UUID}]), gen_event:notify(EventManager, {client, Pid}), {reply, {UUID, Pid}, State}; handle_call(event_manager, _From, #state{ event_manager = EventMgr } = State) -> {reply, EventMgr, State}. @private @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(acquire_event_manager, State) -> EventManager = socketio_listener:event_manager(listener(State)), {noreply, State#state{ event_manager = EventManager }}; handle_cast(_Msg, State) -> {noreply, State}. @private , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info({'EXIT', Pid, _}, #state{ event_manager = EventManager, sessions = Sessions } = State) -> case ets:lookup(Sessions, Pid) of [{Pid, UUID}] -> ets:delete(Sessions,UUID), ets:delete(Sessions,Pid), gen_event:notify(EventManager, {disconnect, Pid}); _ -> ignore end, {noreply, State}; If goes down , we stop socket.io handle_info({'DOWN', WebServerRef, _, _, _}, #state{ web_server_monitor = WebServerRef } = State) -> {stop, normal, State}; handle_info(_Info, State) -> {noreply, State}. @private with . The return value is ignored . , State ) - > void ( ) terminate(_Reason, _State) -> ok. @private , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions listener(#state{ sup = Sup }) -> socketio_listener:server(Sup).
186f2cea2722c587184eab5510f2d6f9ad1041f405d9dc541fce4e51e43dbafb
Octachron/olivine
vk__extension_sig.ml
module type Device = sig val x: Vk__Types__Device.t end module type Instance = sig val x: Vk__Types__Instance.t end module type extension = sig val foreign: string -> ('a -> 'b) Ctypes.fn -> 'a -> 'b end module Foreign_device(X:Device): extension = struct let foreign name typ= let name = name in let open Ctypes in coerce (ptr void) (Foreign.funptr typ) @@ Vk__Core.get_device_proc_addr X.x name end module Foreign_instance(X:Instance): extension = struct let foreign name typ= let name = name in let open Ctypes in coerce (ptr void) (Foreign.funptr typ) @@ Vk__Core.get_instance_proc_addr (Some X.x) name end
null
https://raw.githubusercontent.com/Octachron/olivine/e93df595ad1e8bad5a8af689bac7d150753ab9fb/lib_aux/vk__extension_sig.ml
ocaml
module type Device = sig val x: Vk__Types__Device.t end module type Instance = sig val x: Vk__Types__Instance.t end module type extension = sig val foreign: string -> ('a -> 'b) Ctypes.fn -> 'a -> 'b end module Foreign_device(X:Device): extension = struct let foreign name typ= let name = name in let open Ctypes in coerce (ptr void) (Foreign.funptr typ) @@ Vk__Core.get_device_proc_addr X.x name end module Foreign_instance(X:Instance): extension = struct let foreign name typ= let name = name in let open Ctypes in coerce (ptr void) (Foreign.funptr typ) @@ Vk__Core.get_instance_proc_addr (Some X.x) name end
b2cf0fe132cb5e57bd09b6c68d1a382860a63538d37e5a5351eed842cab2a6fa
kelamg/HtDP2e-workthrough
ex200.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex200) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/batch-io) (require 2htdp/itunes) ; itunes export file from: (define ITUNES-LOCATION "IO/itunes.xml") the 2htdp / itunes library documentation , part 1 : An LTracks is one of : ; – '() ; – (cons Track LTracks) ;(define-struct track ; [name artist album time track# added play# played]) ;; A Track is a structure: ( make - track String String String N N Date N Date ) ;; interpretation An instance records in order: the track's ;; title, its producing artist, to which album it belongs, ;; its playing time in milliseconds, its position within the ;; album, the date it was added, how often it has been ;; played, and the date when it was last played ; ( define - struct date [ year month day hour minute second ] ) ;; A Date is a structure: ( make - date N N N N N N ) interpretation An instance records six pieces of information : the date 's year , month ( between 1 and 12 inclusive ) , ;; day (between 1 and 31), hour (between 0 and 23 ) , minute ( between 0 and 59 ) , and second ( also between 0 and 59 ) . (define AD1 (create-date 2017 11 3 1 55 34)) (define AD2 (create-date 2010 2 14 11 23 5)) (define AD3 (create-date 2011 12 19 23 50 42)) (define AD4 (create-date 2011 11 25 22 00 20)) (define AD5 (create-date 2012 10 22 9 59 55)) (define PD1 (create-date 2018 8 17 2 30 12)) (define PD2 (create-date 2015 12 5 15 47 58)) (define PD3 (create-date 2014 6 21 15 13 29)) (define PD4 (create-date 2017 3 30 17 45 22)) (define PD5 (create-date 2018 1 3 9 3 50)) (define T1 (create-track "I Hope I Sleep Tonight" "DJ Seinfeld" "Time Spent Away From U" 4060 1 AD1 323 PD1)) (define T2 (create-track "Beat It" "Michael Jackson" "Thriller" 4180 5 AD2 123 PD2)) (define T3 (create-track "Memory Lane" "Netsky" "UKF Drum & Bass 2010" 5350 1 AD3 148 PD3)) (define T4 (create-track "All of the Lights" "Kanye West" "My Beautiful Dark Twisted Fantasy" 5000 5 AD4 93 PD4)) (define T5 (create-track "Lose Yourself" "Eminem" "8 Mile: Music from and Inspired by the Motion Picture" 5200 1 AD5 231 PD5)) (define LT1 (list T1)) (define LT2 (list T1 T2 T3)) (define LT3 (list T1 T2 T3 T4 T5)) LTracks - > N ;; produces the total amount of playing time (in milliseconds) of lt (check-expect (total-time '()) 0) (check-expect (total-time LT1) (track-time T1)) (check-expect (total-time LT2) (+ (track-time T1) (track-time T2) (track-time T3))) (check-expect (total-time LT3) (+ (track-time T1) (track-time T2) (track-time T3) (track-time T4) (track-time T5))) (define (total-time lt) (cond [(empty? lt) 0] [else (+ (track-time (first lt)) (total-time (rest lt)))]))
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Arbitrarily-Large-Data/ex200.rkt
racket
about the language level of this file in a form that our tools can easily process. itunes export file from: – '() – (cons Track LTracks) (define-struct track [name artist album time track# added play# played]) A Track is a structure: interpretation An instance records in order: the track's title, its producing artist, to which album it belongs, its playing time in milliseconds, its position within the album, the date it was added, how often it has been played, and the date when it was last played A Date is a structure: day (between 1 and 31), hour (between 0 produces the total amount of playing time (in milliseconds) of lt
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex200) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/batch-io) (require 2htdp/itunes) (define ITUNES-LOCATION "IO/itunes.xml") the 2htdp / itunes library documentation , part 1 : An LTracks is one of : ( make - track String String String N N Date N Date ) ( define - struct date [ year month day hour minute second ] ) ( make - date N N N N N N ) interpretation An instance records six pieces of information : the date 's year , month ( between 1 and 12 inclusive ) , and 23 ) , minute ( between 0 and 59 ) , and second ( also between 0 and 59 ) . (define AD1 (create-date 2017 11 3 1 55 34)) (define AD2 (create-date 2010 2 14 11 23 5)) (define AD3 (create-date 2011 12 19 23 50 42)) (define AD4 (create-date 2011 11 25 22 00 20)) (define AD5 (create-date 2012 10 22 9 59 55)) (define PD1 (create-date 2018 8 17 2 30 12)) (define PD2 (create-date 2015 12 5 15 47 58)) (define PD3 (create-date 2014 6 21 15 13 29)) (define PD4 (create-date 2017 3 30 17 45 22)) (define PD5 (create-date 2018 1 3 9 3 50)) (define T1 (create-track "I Hope I Sleep Tonight" "DJ Seinfeld" "Time Spent Away From U" 4060 1 AD1 323 PD1)) (define T2 (create-track "Beat It" "Michael Jackson" "Thriller" 4180 5 AD2 123 PD2)) (define T3 (create-track "Memory Lane" "Netsky" "UKF Drum & Bass 2010" 5350 1 AD3 148 PD3)) (define T4 (create-track "All of the Lights" "Kanye West" "My Beautiful Dark Twisted Fantasy" 5000 5 AD4 93 PD4)) (define T5 (create-track "Lose Yourself" "Eminem" "8 Mile: Music from and Inspired by the Motion Picture" 5200 1 AD5 231 PD5)) (define LT1 (list T1)) (define LT2 (list T1 T2 T3)) (define LT3 (list T1 T2 T3 T4 T5)) LTracks - > N (check-expect (total-time '()) 0) (check-expect (total-time LT1) (track-time T1)) (check-expect (total-time LT2) (+ (track-time T1) (track-time T2) (track-time T3))) (check-expect (total-time LT3) (+ (track-time T1) (track-time T2) (track-time T3) (track-time T4) (track-time T5))) (define (total-time lt) (cond [(empty? lt) 0] [else (+ (track-time (first lt)) (total-time (rest lt)))]))
51c2522d87d6f9b17824d14c7453702a4aeb3b85360e26b888370be1a2276d12
project-oak/hafnium-verification
equality.mli
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) (** Constraints representing equivalence relations over uninterpreted functions and linear rational arithmetic *) type t [@@deriving compare, equal, sexp] val pp : t pp val pp_classes : t pp val ppx_classes : Var.strength -> t pp val ppx_classes_diff : Var.strength -> (t * t) pp include Invariant.S with type t := t val true_ : t (** The diagonal relation, which only equates each term with itself. *) val and_eq : Term.t -> Term.t -> t -> t (** Conjoin an equation to a relation. *) val and_ : t -> t -> t (** Conjunction. *) val or_ : t -> t -> t (** Disjunction. *) val rename : t -> Var.Subst.t -> t (** Apply a renaming substitution to the relation. *) val fv : t -> Var.Set.t (** The variables occurring in the terms of the relation. *) val is_true : t -> bool (** Test if the relation is diagonal. *) val is_false : t -> bool (** Test if the relation is empty / inconsistent. *) val entails_eq : t -> Term.t -> Term.t -> bool (** Test if an equation is entailed by a relation. *) val entails : t -> t -> bool * Test if one relation entails another . val class_of : t -> Term.t -> Term.t list (** Equivalence class of [e]: all the terms [f] in the relation such that [e = f] is implied by the relation. *) val normalize : t -> Term.t -> Term.t (** Normalize a term [e] to [e'] such that [e = e'] is implied by the relation, where [e'] and its subterms are expressed in terms of the relation's canonical representatives of each equivalence class. *) val difference : t -> Term.t -> Term.t -> Z.t option (** The difference as an offset. [difference r a b = Some k] if [r] implies [a = b+k], or [None] if [a] and [b] are not equal up to an integer offset. *) val fold_terms : t -> init:'a -> f:('a -> Term.t -> 'a) -> 'a
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/sledge/src/symbheap/equality.mli
ocaml
* Constraints representing equivalence relations over uninterpreted functions and linear rational arithmetic * The diagonal relation, which only equates each term with itself. * Conjoin an equation to a relation. * Conjunction. * Disjunction. * Apply a renaming substitution to the relation. * The variables occurring in the terms of the relation. * Test if the relation is diagonal. * Test if the relation is empty / inconsistent. * Test if an equation is entailed by a relation. * Equivalence class of [e]: all the terms [f] in the relation such that [e = f] is implied by the relation. * Normalize a term [e] to [e'] such that [e = e'] is implied by the relation, where [e'] and its subterms are expressed in terms of the relation's canonical representatives of each equivalence class. * The difference as an offset. [difference r a b = Some k] if [r] implies [a = b+k], or [None] if [a] and [b] are not equal up to an integer offset.
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) type t [@@deriving compare, equal, sexp] val pp : t pp val pp_classes : t pp val ppx_classes : Var.strength -> t pp val ppx_classes_diff : Var.strength -> (t * t) pp include Invariant.S with type t := t val true_ : t val and_eq : Term.t -> Term.t -> t -> t val and_ : t -> t -> t val or_ : t -> t -> t val rename : t -> Var.Subst.t -> t val fv : t -> Var.Set.t val is_true : t -> bool val is_false : t -> bool val entails_eq : t -> Term.t -> Term.t -> bool val entails : t -> t -> bool * Test if one relation entails another . val class_of : t -> Term.t -> Term.t list val normalize : t -> Term.t -> Term.t val difference : t -> Term.t -> Term.t -> Z.t option val fold_terms : t -> init:'a -> f:('a -> Term.t -> 'a) -> 'a
dc61910740a158cadc2dcc1eab34e9d52b4cc0c877a97ea15f7fc58c9f478bd7
fossas/fossa-cli
TextSpec.hs
module Extra.TextSpec ( spec, ) where import Data.Text.Extra import Test.Hspec qualified as Test import Prelude spec :: Test.Spec spec = do Test.describe "Text splitOnceOn" $ Test.it "should split a string once from the start" $ splitOnceOn "-" "1-2-3" `Test.shouldBe` ("1", "2-3") Test.describe "Text splitOnceonEnd" $ Test.it "should split a string once from the end" $ splitOnceOnEnd "-" "1-2-3" `Test.shouldBe` ("1-2", "3") Test.describe "Text dropPrefix" $ do Test.it "should drop a prefix when present" $ do dropPrefix "foo" "foobar" `Test.shouldBe` "bar" dropPrefix "foo" "foofoobar" `Test.shouldBe` "foobar" Test.it "should leave the string unchanged when the prefix is missing" $ do dropPrefix "foo" "bar" `Test.shouldBe` "bar" dropPrefix "foo" "" `Test.shouldBe` "" Test.describe "Text breakOnEndAndRemove" $ Test.it "should break a string from last needle (with last needle removed)" $ do breakOnEndAndRemove ":" "a:b" `Test.shouldBe` Just ("a", "b") breakOnEndAndRemove ":" "a:b:c" `Test.shouldBe` Just ("a:b", "c") breakOnEndAndRemove ":" "some.registry:5000/org/app:tag" `Test.shouldBe` Just ("some.registry:5000/org/app", "tag")
null
https://raw.githubusercontent.com/fossas/fossa-cli/be8839e734b813369c67183b286220a7f41a8481/test/Extra/TextSpec.hs
haskell
module Extra.TextSpec ( spec, ) where import Data.Text.Extra import Test.Hspec qualified as Test import Prelude spec :: Test.Spec spec = do Test.describe "Text splitOnceOn" $ Test.it "should split a string once from the start" $ splitOnceOn "-" "1-2-3" `Test.shouldBe` ("1", "2-3") Test.describe "Text splitOnceonEnd" $ Test.it "should split a string once from the end" $ splitOnceOnEnd "-" "1-2-3" `Test.shouldBe` ("1-2", "3") Test.describe "Text dropPrefix" $ do Test.it "should drop a prefix when present" $ do dropPrefix "foo" "foobar" `Test.shouldBe` "bar" dropPrefix "foo" "foofoobar" `Test.shouldBe` "foobar" Test.it "should leave the string unchanged when the prefix is missing" $ do dropPrefix "foo" "bar" `Test.shouldBe` "bar" dropPrefix "foo" "" `Test.shouldBe` "" Test.describe "Text breakOnEndAndRemove" $ Test.it "should break a string from last needle (with last needle removed)" $ do breakOnEndAndRemove ":" "a:b" `Test.shouldBe` Just ("a", "b") breakOnEndAndRemove ":" "a:b:c" `Test.shouldBe` Just ("a:b", "c") breakOnEndAndRemove ":" "some.registry:5000/org/app:tag" `Test.shouldBe` Just ("some.registry:5000/org/app", "tag")
f4831c6397c076171be3ba7b3d0a585e4c1c013729c3064516a1479e3bd51673
joelburget/lvca
List_nat.ml
module Language = struct let nat = [%lvca.abstract_syntax "nat := Z() | S(nat);"] let list = [%lvca.abstract_syntax "list a := Nil() | Cons(a; list a);"] let rec nat_to_list = function | Nonbinding . Operator ( _ , " Z " , [ ] ) - > Nonbinding . Operator ( ( ) , " Nil " , [ ] ) | Operator ( i , " S " , [ ] ) - > Operator ( ( ) , " Cons " , [ i ; nat_to_list ] ) | Operator _ | Primitive _ - > failwith " invariant violation " ; ; let rec list_to_nat = function | Nonbinding . Operator ( _ , " Nil " , [ ] ) - > Nonbinding . Operator ( None , " Z " , [ ] ) | Operator ( ( ) , " Cons " , [ i ; list ] ) - > Operator ( Some i , " S " , [ list_to_nat list ] ) | Operator _ | Primitive _ - > failwith " invariant violation " ; ; let rec nat_to_list = function | Nonbinding.Operator (_, "Z", []) -> Nonbinding.Operator ((), "Nil", []) | Operator (i, "S", [ nat ]) -> Operator ((), "Cons", [ i; nat_to_list nat ]) | Operator _ | Primitive _ -> failwith "invariant violation" ;; let rec list_to_nat = function | Nonbinding.Operator (_, "Nil", []) -> Nonbinding.Operator (None, "Z", []) | Operator ((), "Cons", [ i; list ]) -> Operator (Some i, "S", [ list_to_nat list ]) | Operator _ | Primitive _ -> failwith "invariant violation" ;; *) From this defn , should be able to derive list concatenation let core_sum = {|let rec sum = \(x : nat) (y : nat) -> match x with { | Z() -> y | S(x') -> S(sum x' y) }|} ;; From this defn , should be able to derive predecessor let core_tail = {|let tail = \(x : a list) -> match x with { | Cons(a; as) -> as | Nil() -> Nil } |} ;; end module Model = struct let initial_model = () end module View = struct open Brr.El let view _model = div [ txt' "TODO" ] end let stateless_view () = View.view Model.initial_model
null
https://raw.githubusercontent.com/joelburget/lvca/dc1a9b2fbaed013c5d57d7fe63dd4a05062c93d5/pages/List_nat.ml
ocaml
module Language = struct let nat = [%lvca.abstract_syntax "nat := Z() | S(nat);"] let list = [%lvca.abstract_syntax "list a := Nil() | Cons(a; list a);"] let rec nat_to_list = function | Nonbinding . Operator ( _ , " Z " , [ ] ) - > Nonbinding . Operator ( ( ) , " Nil " , [ ] ) | Operator ( i , " S " , [ ] ) - > Operator ( ( ) , " Cons " , [ i ; nat_to_list ] ) | Operator _ | Primitive _ - > failwith " invariant violation " ; ; let rec list_to_nat = function | Nonbinding . Operator ( _ , " Nil " , [ ] ) - > Nonbinding . Operator ( None , " Z " , [ ] ) | Operator ( ( ) , " Cons " , [ i ; list ] ) - > Operator ( Some i , " S " , [ list_to_nat list ] ) | Operator _ | Primitive _ - > failwith " invariant violation " ; ; let rec nat_to_list = function | Nonbinding.Operator (_, "Z", []) -> Nonbinding.Operator ((), "Nil", []) | Operator (i, "S", [ nat ]) -> Operator ((), "Cons", [ i; nat_to_list nat ]) | Operator _ | Primitive _ -> failwith "invariant violation" ;; let rec list_to_nat = function | Nonbinding.Operator (_, "Nil", []) -> Nonbinding.Operator (None, "Z", []) | Operator ((), "Cons", [ i; list ]) -> Operator (Some i, "S", [ list_to_nat list ]) | Operator _ | Primitive _ -> failwith "invariant violation" ;; *) From this defn , should be able to derive list concatenation let core_sum = {|let rec sum = \(x : nat) (y : nat) -> match x with { | Z() -> y | S(x') -> S(sum x' y) }|} ;; From this defn , should be able to derive predecessor let core_tail = {|let tail = \(x : a list) -> match x with { | Cons(a; as) -> as | Nil() -> Nil } |} ;; end module Model = struct let initial_model = () end module View = struct open Brr.El let view _model = div [ txt' "TODO" ] end let stateless_view () = View.view Model.initial_model
739f2a5a44eb93d692ecaf62bcd5857f96aa142183c4a4aeef24f6d2bcbb1e97
TheClimateCorporation/lemur
minimal-sample-jobdef.clj
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Minimal Sample ;;; This is a small example, sufficient for many jobs. ;;; See sample-jobdef.clj for a more complete example with docs on each option ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (use-base ; optional, lemur.base is always included automatically 'your.org.base) (catch-args :num-days "Number of days of history to run.") (defcluster sample-cluster :metajob-hipchat-room "marctest" :comment "This is a the Minimal Sample." ;:keep-alive? true :num-instances 1 :slave-instance-type "m1.xlarge" :master-instance-type "m1.large" :upload ["/tmp/junk/a/foo.txt" "/tmp/junk/a/bar.txt"]) (defstep sample-step :main-class "your.org.job.Main" ;A value for --num-days that is only relevant when running with the :test profile :test {:num-days 1} ; These are example args to be passed to your hadoop job (in the order listed ; below). See the ARGS section of sample-jobdef.clj for a complete explanation. :args.stations "./stationsfile" :args.days "${num-days}" :args.passthrough true :args.positional ["foo" "bar baz"] :args.data-uri true) (fire! sample-cluster sample-step) ; *** RESULT *** ; ; Running lemur local minimal-sample-jobdef.clj --num - days 8 --extra - opt - to - pass ; ; would result in something like: hadoop jar your.org.job . Main --stations ./stationsfile \ ; --days 8 \ --extra - opt - to - pass foo " bar baz " /tmp / minimal - sample-2012 - 01 - 27 - 8da30ff3 / data
null
https://raw.githubusercontent.com/TheClimateCorporation/lemur/00eb21b6f534ceefe354ab89042826188d156991/examples/minimal-sample-jobdef.clj
clojure
Minimal Sample This is a small example, sufficient for many jobs. See sample-jobdef.clj for a more complete example with docs on each option optional, lemur.base is always included automatically :keep-alive? true A value for --num-days that is only relevant when running with the :test profile These are example args to be passed to your hadoop job (in the order listed below). See the ARGS section of sample-jobdef.clj for a complete explanation. *** RESULT *** Running would result in something like: --days 8 \
(use-base 'your.org.base) (catch-args :num-days "Number of days of history to run.") (defcluster sample-cluster :metajob-hipchat-room "marctest" :comment "This is a the Minimal Sample." :num-instances 1 :slave-instance-type "m1.xlarge" :master-instance-type "m1.large" :upload ["/tmp/junk/a/foo.txt" "/tmp/junk/a/bar.txt"]) (defstep sample-step :main-class "your.org.job.Main" :test {:num-days 1} :args.stations "./stationsfile" :args.days "${num-days}" :args.passthrough true :args.positional ["foo" "bar baz"] :args.data-uri true) (fire! sample-cluster sample-step) lemur local minimal-sample-jobdef.clj --num - days 8 --extra - opt - to - pass hadoop jar your.org.job . Main --stations ./stationsfile \ --extra - opt - to - pass foo " bar baz " /tmp / minimal - sample-2012 - 01 - 27 - 8da30ff3 / data
9ff3eb948af30fe27b267844ee4b38319f6bcbec30693864c9c20910b310146a
engstrand-config/farg
packages.scm
(define-module (farg packages) #:use-module (guix packages) #:use-module (gnu packages imagemagick) #:use-module (gnu packages python-xyz)) HACK : Upstreamed pywal does not propagate imagemagick which ;; means that it is not available during runtime. (define-public python-pywal-farg (package (inherit python-pywal) (name "python-pywal-farg") (inputs '()) (propagated-inputs (list imagemagick))))
null
https://raw.githubusercontent.com/engstrand-config/farg/a6645960993583e65c4c882ad415ead544a466ef/farg/packages.scm
scheme
means that it is not available during runtime.
(define-module (farg packages) #:use-module (guix packages) #:use-module (gnu packages imagemagick) #:use-module (gnu packages python-xyz)) HACK : Upstreamed pywal does not propagate imagemagick which (define-public python-pywal-farg (package (inherit python-pywal) (name "python-pywal-farg") (inputs '()) (propagated-inputs (list imagemagick))))
2a8d27e2d96904b7996b74d0c6981478a2efb64d8f4af17963343a66476487e7
basho/riak_test
secondary_index_tests.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2012 Basho Technologies , Inc. %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(secondary_index_tests). -behavior(riak_test). -export([confirm/0]). -export([put_an_object/2, put_an_object/4, int_to_key/1, stream_pb/2, stream_pb/3, pb_query/3, http_query/2, http_query/3, http_stream/3, int_to_field1_bin/1, url/2, query_to_url/3, assertExactQuery/5, assertRangeQuery/7]). -include_lib("eunit/include/eunit.hrl"). -include_lib("riakc/include/riakc.hrl"). -define(BUCKET, <<"2ibucket">>). -define(KEYS(A), [int_to_key(A)]). -define(KEYS(A,B), [int_to_key(N) || N <- lists:seq(A,B)]). -define(KEYS(A,B,C), [int_to_key(N) || N <- lists:seq(A,B), C]). -define(KEYS(A,B,G1,G2), [int_to_key(N) || N <- lists:seq(A,B), G1, G2]). confirm() -> Nodes = rt:build_cluster(3), ?assertEqual(ok, rt:wait_until_nodes_ready(Nodes)), First test with sorting non - paginated results off by default SetResult = rpc:multicall(Nodes, application, set_env, [riak_kv, secondary_index_sort_default, false]), AOK = [ok || _ <- lists:seq(1, length(Nodes))], ?assertMatch({AOK, []}, SetResult), PBC = rt:pbc(hd(Nodes)), HTTPC = rt:httpc(hd(Nodes)), Clients = [{pb, PBC}, {http, HTTPC}], [put_an_object(PBC, N) || N <- lists:seq(0, 20)], K = fun int_to_key/1, assertExactQuery(Clients, ?KEYS(5), <<"field1_bin">>, <<"val5">>), assertExactQuery(Clients, ?KEYS(5), <<"field2_int">>, 5), assertExactQuery(Clients, ?KEYS(5, 9), <<"field3_int">>, 5), assertRangeQuery(Clients, ?KEYS(10, 18), <<"field1_bin">>, <<"val10">>, <<"val18">>), assertRangeQuery(Clients, ?KEYS(12), <<"field1_bin">>, <<"val10">>, <<"val18">>, <<"v...2">>), assertRangeQuery(Clients, ?KEYS(10, 19), <<"field2_int">>, 10, 19), assertRangeQuery(Clients, ?KEYS(10, 17), <<"$key">>, <<"obj10">>, <<"obj17">>), assertRangeQuery(Clients, ?KEYS(12), <<"$key">>, <<"obj10">>, <<"obj17">>, <<"ob..2">>), lager:info("Delete an object, verify deletion..."), ToDel = [<<"obj05">>, <<"obj11">>], [?assertMatch(ok, riakc_pb_socket:delete(PBC, ?BUCKET, KD)) || KD <- ToDel], lager:info("Make sure the tombstone is reaped..."), ?assertMatch(ok, rt:wait_until(fun() -> rt:pbc_really_deleted(PBC, ?BUCKET, ToDel) end)), assertExactQuery(Clients, [], <<"field1_bin">>, <<"val5">>), assertExactQuery(Clients, [], <<"field2_int">>, 5), assertExactQuery(Clients, ?KEYS(6, 9), <<"field3_int">>, 5), assertRangeQuery(Clients, ?KEYS(10, 18, N /= 11), <<"field1_bin">>, <<"val10">>, <<"val18">>), assertRangeQuery(Clients, ?KEYS(10), <<"field1_bin">>, <<"val10">>, <<"val18">>, <<"10$">>), assertRangeQuery(Clients, ?KEYS(10, 19, N /= 11), <<"field2_int">>, 10, 19), assertRangeQuery(Clients, ?KEYS(10, 17, N /= 11), <<"$key">>, <<"obj10">>, <<"obj17">>), assertRangeQuery(Clients, ?KEYS(12), <<"$key">>, <<"obj10">>, <<"obj17">>, <<"2">>), Verify the $ key index , and riak_kv#367 regression assertRangeQuery(Clients, ?KEYS(6), <<"$key">>, <<"obj06">>, <<"obj06">>), assertRangeQuery(Clients, ?KEYS(6,7), <<"$key">>, <<"obj06">>, <<"obj07">>), %% Exercise sort set to true by default SetResult2 = rpc:multicall(Nodes, application, set_env, [riak_kv, secondary_index_sort_default, true]), ?assertMatch({AOK, []}, SetResult2), assertExactQuery(Clients, ?KEYS(15, 19), <<"field3_int">>, 15, {undefined, true}), Keys ordered by val index term , since 2i order is { term , key } KsVal = [A || {_, A} <- lists:sort([{int_to_field1_bin(N), K(N)} || N <- lists:seq(0, 20), N /= 11, N /= 5])], assertRangeQuery(Clients, KsVal, <<"field1_bin">>, <<"val0">>, <<"val9">>, undefined, {undefined, true}), assertRangeQuery(Clients, ?KEYS(0, 20, N /= 11, N /= 5), <<"field2_int">>, 0, 20, undefined, {undefined, true}), assertRangeQuery(Clients, ?KEYS(0, 20, N /= 11, N /= 5), <<"$key">>, <<"obj00">>, <<"obj20">>, undefined, {undefined, true}), Verify bignum sort order in sext -- only ( riak_kv#499 ) TestIdxVal = 1362400142028, put_an_object(PBC, TestIdxVal), assertRangeQuery(Clients, [<<"obj1362400142028">>], <<"field2_int">>, 1000000000000, TestIdxVal), pass. assertExactQuery(Clients, Expected, Index, Value) -> assertExactQuery(Clients, Expected, Index, Value, {false, false}), assertExactQuery(Clients, Expected, Index, Value, {true, true}). assertExactQuery(Clients, Expected, Index, Value, Sorted) when is_list(Clients) -> [assertExactQuery(C, Expected, Index, Value, Sorted) || C <- Clients]; assertExactQuery({ClientType, Client}, Expected, Index, Value, {Sort, ExpectSorted}) -> lager:info("Searching Index ~p for ~p, sort: ~p ~p with client ~p", [Index, Value, Sort, ExpectSorted, ClientType]), {ok, ?INDEX_RESULTS{keys=Results}} = case ClientType of pb -> riakc_pb_socket:get_index_eq(Client, ?BUCKET, Index, Value, [{pagination_sort, Sort} || Sort /= undefined]); http -> rhc:get_index(Client, ?BUCKET, Index, Value, [{pagination_sort, Sort}]) end, ActualKeys = case ExpectSorted of true -> Results; _ -> lists:sort(Results) end, lager:info("Expected: ~p", [Expected]), lager:info("Actual : ~p", [Results]), lager:info("Sorted : ~p", [ActualKeys]), ?assertEqual(Expected, ActualKeys). assertRangeQuery(Clients, Expected, Index, StartValue, EndValue) -> assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, undefined). assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, Re) -> assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, Re, {false, false}), assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, Re, {true, true}). assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, Re, Sort) when is_list(Clients) -> [assertRangeQuery(C, Expected, Index, StartValue, EndValue, Re, Sort) || C <- Clients]; assertRangeQuery({ClientType, Client}, Expected, Index, StartValue, EndValue, Re, {Sort, ExpectSorted}) -> lager:info("Searching Index ~p for ~p-~p re:~p, sort: ~p, ~p with ~p client", [Index, StartValue, EndValue, Re, Sort, ExpectSorted, ClientType]), {ok, ?INDEX_RESULTS{keys=Results}} = case ClientType of pb -> riakc_pb_socket:get_index_range(Client, ?BUCKET, Index, StartValue, EndValue, [{term_regex, Re} || Re /= undefined] ++ [{pagination_sort, Sort} || Sort /= undefined]); http -> rhc:get_index(Client, ?BUCKET, Index, {StartValue, EndValue}, [{term_regex, Re} || Re /= undefined] ++ [{pagination_sort, Sort}]) end, ActualKeys = case ExpectSorted of true -> Results; _ -> lists:sort(Results) end, lager:info("Expected: ~p", [Expected]), lager:info("Actual : ~p", [Results]), lager:info("Sorted : ~p", [ActualKeys]), ?assertEqual(Expected, ActualKeys). general 2i utility put_an_object(Pid, N) -> Key = int_to_key(N), Data = list_to_binary(io_lib:format("data~p", [N])), BinIndex = int_to_field1_bin(N), Indexes = [{"field1_bin", BinIndex}, {"field2_int", N}, every 5 items indexed together {"field3_int", N - (N rem 5)} ], put_an_object(Pid, Key, Data, Indexes). put_an_object(Pid, Key, Data, Indexes) when is_list(Indexes) -> lager:info("Putting object ~p", [Key]), MetaData = dict:from_list([{<<"index">>, Indexes}]), Robj0 = riakc_obj:new(?BUCKET, Key), Robj1 = riakc_obj:update_value(Robj0, Data), Robj2 = riakc_obj:update_metadata(Robj1, MetaData), riakc_pb_socket:put(Pid, Robj2); put_an_object(Pid, Key, IntIndex, BinIndex) when is_integer(IntIndex), is_binary(BinIndex) -> put_an_object(Pid, Key, Key, [{"field1_bin", BinIndex},{"field2_int", IntIndex}]). int_to_key(N) -> case N < 100 of true -> list_to_binary(io_lib:format("obj~2..0B", [N])); _ -> list_to_binary(io_lib:format("obj~p", [N])) end. int_to_field1_bin(N) -> list_to_binary(io_lib:format("val~p", [N])). stream_pb(Pid, Q) -> pb_query(Pid, Q, [stream]), stream_loop(). stream_pb(Pid, Q, Opts) -> pb_query(Pid, Q, [stream|Opts]), stream_loop(). stream_loop() -> stream_loop(orddict:new()). stream_loop(Acc) -> receive {_Ref, {done, undefined}} -> {ok, orddict:to_list(Acc)}; {_Ref, {done, Continuation}} -> {ok, orddict:store(continuation, Continuation, Acc)}; {_Ref, ?INDEX_STREAM_RESULT{terms=undefined, keys=Keys}} -> Acc2 = orddict:update(keys, fun(Existing) -> Existing++Keys end, Keys, Acc), stream_loop(Acc2); {_Ref, ?INDEX_STREAM_RESULT{terms=Results}} -> Acc2 = orddict:update(results, fun(Existing) -> Existing++Results end, Results, Acc), stream_loop(Acc2); {_Ref, {ok, ?INDEX_STREAM_BODY_RESULT{objects=Objects}}} -> Acc2 = orddict:update(results, fun(Existing) -> Existing++Objects end, Objects, Acc), stream_loop(Acc2); {_Ref, {error, <<"{error,timeout}">>}} -> {error, timeout}; {_Ref, Wat} -> lager:info("got a wat ~p", [Wat]), stream_loop(Acc) end. pb_query(Pid, {Field, Val}, Opts) -> riakc_pb_socket:get_index_eq(Pid, ?BUCKET, Field, Val, Opts); pb_query(Pid, {Field, Start, End}, Opts) -> riakc_pb_socket:get_index_range(Pid, ?BUCKET, Field, Start, End, Opts). http_stream(NodePath, Query, Opts) -> http_query(NodePath, Query, [{stream, true} | Opts], stream). http_query(NodePath, Q) -> http_query(NodePath, Q, []). http_query(NodePath, Query, Opts) -> http_query(NodePath, Query, Opts, undefined). http_query(NodePath, Query, Opts, Pid) -> http_get(query_to_url(NodePath, Query, Opts), Pid). query_to_url(NodePath, {Field, Value}, Opts) -> QString = opts_to_qstring(Opts, []), Flag = case is_integer(Value) of true -> "w"; false -> "s" end, url("~s/buckets/~s/index/~s/~"++Flag++"~s", [NodePath, ?BUCKET, Field, Value, QString]); query_to_url(NodePath, {Field, Start, End}, Opts) -> QString = opts_to_qstring(Opts, []), Flag = case is_integer(Start) of true -> "w"; false -> "s" end, url("~s/buckets/~s/index/~s/~"++Flag++"/~"++Flag++"~s", [NodePath, ?BUCKET, Field, Start, End, QString]). url(Format, Elements) -> Path = io_lib:format(Format, Elements), lists:flatten(Path). http_get(Url, undefined) -> lager:info("getting ~p", [Url]), {ok,{{"HTTP/1.1",200,"OK"}, _, Body}} = httpc:request(Url), {struct, Result} = mochijson2:decode(Body), Result; http_get(Url, stream) -> lager:info("streaming ~p", [Url]), {ok, Ref} = httpc:request(get, {Url, []}, [], [{stream, self}, {sync, false}]), start_http_stream(Ref). opts_to_qstring([], QString) -> QString; opts_to_qstring([Opt|Rest], []) -> QOpt = opt_to_string("?", Opt), opts_to_qstring(Rest, QOpt); opts_to_qstring([Opt|Rest], QString) -> QOpt = opt_to_string("&", Opt), opts_to_qstring(Rest, QString++QOpt). opt_to_string(Sep, {Name, Value}) when is_integer(Value) -> io_lib:format(Sep++"~s=~p", [Name, Value]); opt_to_string(Sep, {Name, Value})-> io_lib:format(Sep++"~s=~s", [Name, url_encode(Value)]); opt_to_string(Sep, Name) -> io_lib:format(Sep++"~s=~s", [Name, true]). url_encode(Val) when is_binary(Val) -> url_encode(binary_to_list(Val)); url_encode(Val) when is_atom(Val) -> url_encode(atom_to_list(Val)); url_encode(Val) -> ibrowse_lib:url_encode(Val). start_http_stream(Ref) -> receive {http, {Ref, stream_start, Headers}} -> Boundary = get_boundary(proplists:get_value("content-type", Headers)), http_stream_loop(Ref, <<>>, Boundary); Other -> lager:error("Unexpected message ~p", [Other]), {error, unknown_message} after 60000 -> {error, timeout_local} end. http_stream_loop(Ref, Acc, {Boundary, BLen}=B) -> receive {http, {Ref, stream, Chunk}} -> http_stream_loop(Ref, <<Acc/binary,Chunk/binary>>, B); {http, {Ref, stream_end, _Headers}} -> Parts = binary:split(Acc,[ <<"\r\n--", Boundary:BLen/bytes, "\r\nContent-Type: application/json\r\n\r\n">>, <<"\r\n--", Boundary:BLen/bytes,"--\r\n">> ], [global, trim]), lists:foldl(fun(<<>>, Results) -> Results; (Part, Results) -> {struct, Result} = mochijson2:decode(Part), orddict:merge(fun(_K, V1, V2) -> V1 ++ V2 end, Results, Result) end, [], Parts); Other -> lager:error("Unexpected message ~p", [Other]), {error, unknown_message} after 60000 -> {error, timeout_local} end. get_boundary("multipart/mixed;boundary=" ++ Boundary) -> B = list_to_binary(Boundary), {B, byte_size(B)}; get_boundary(_) -> undefined.
null
https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/secondary_index_tests.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- Exercise sort set to true by default
Copyright ( c ) 2012 Basho Technologies , Inc. This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(secondary_index_tests). -behavior(riak_test). -export([confirm/0]). -export([put_an_object/2, put_an_object/4, int_to_key/1, stream_pb/2, stream_pb/3, pb_query/3, http_query/2, http_query/3, http_stream/3, int_to_field1_bin/1, url/2, query_to_url/3, assertExactQuery/5, assertRangeQuery/7]). -include_lib("eunit/include/eunit.hrl"). -include_lib("riakc/include/riakc.hrl"). -define(BUCKET, <<"2ibucket">>). -define(KEYS(A), [int_to_key(A)]). -define(KEYS(A,B), [int_to_key(N) || N <- lists:seq(A,B)]). -define(KEYS(A,B,C), [int_to_key(N) || N <- lists:seq(A,B), C]). -define(KEYS(A,B,G1,G2), [int_to_key(N) || N <- lists:seq(A,B), G1, G2]). confirm() -> Nodes = rt:build_cluster(3), ?assertEqual(ok, rt:wait_until_nodes_ready(Nodes)), First test with sorting non - paginated results off by default SetResult = rpc:multicall(Nodes, application, set_env, [riak_kv, secondary_index_sort_default, false]), AOK = [ok || _ <- lists:seq(1, length(Nodes))], ?assertMatch({AOK, []}, SetResult), PBC = rt:pbc(hd(Nodes)), HTTPC = rt:httpc(hd(Nodes)), Clients = [{pb, PBC}, {http, HTTPC}], [put_an_object(PBC, N) || N <- lists:seq(0, 20)], K = fun int_to_key/1, assertExactQuery(Clients, ?KEYS(5), <<"field1_bin">>, <<"val5">>), assertExactQuery(Clients, ?KEYS(5), <<"field2_int">>, 5), assertExactQuery(Clients, ?KEYS(5, 9), <<"field3_int">>, 5), assertRangeQuery(Clients, ?KEYS(10, 18), <<"field1_bin">>, <<"val10">>, <<"val18">>), assertRangeQuery(Clients, ?KEYS(12), <<"field1_bin">>, <<"val10">>, <<"val18">>, <<"v...2">>), assertRangeQuery(Clients, ?KEYS(10, 19), <<"field2_int">>, 10, 19), assertRangeQuery(Clients, ?KEYS(10, 17), <<"$key">>, <<"obj10">>, <<"obj17">>), assertRangeQuery(Clients, ?KEYS(12), <<"$key">>, <<"obj10">>, <<"obj17">>, <<"ob..2">>), lager:info("Delete an object, verify deletion..."), ToDel = [<<"obj05">>, <<"obj11">>], [?assertMatch(ok, riakc_pb_socket:delete(PBC, ?BUCKET, KD)) || KD <- ToDel], lager:info("Make sure the tombstone is reaped..."), ?assertMatch(ok, rt:wait_until(fun() -> rt:pbc_really_deleted(PBC, ?BUCKET, ToDel) end)), assertExactQuery(Clients, [], <<"field1_bin">>, <<"val5">>), assertExactQuery(Clients, [], <<"field2_int">>, 5), assertExactQuery(Clients, ?KEYS(6, 9), <<"field3_int">>, 5), assertRangeQuery(Clients, ?KEYS(10, 18, N /= 11), <<"field1_bin">>, <<"val10">>, <<"val18">>), assertRangeQuery(Clients, ?KEYS(10), <<"field1_bin">>, <<"val10">>, <<"val18">>, <<"10$">>), assertRangeQuery(Clients, ?KEYS(10, 19, N /= 11), <<"field2_int">>, 10, 19), assertRangeQuery(Clients, ?KEYS(10, 17, N /= 11), <<"$key">>, <<"obj10">>, <<"obj17">>), assertRangeQuery(Clients, ?KEYS(12), <<"$key">>, <<"obj10">>, <<"obj17">>, <<"2">>), Verify the $ key index , and riak_kv#367 regression assertRangeQuery(Clients, ?KEYS(6), <<"$key">>, <<"obj06">>, <<"obj06">>), assertRangeQuery(Clients, ?KEYS(6,7), <<"$key">>, <<"obj06">>, <<"obj07">>), SetResult2 = rpc:multicall(Nodes, application, set_env, [riak_kv, secondary_index_sort_default, true]), ?assertMatch({AOK, []}, SetResult2), assertExactQuery(Clients, ?KEYS(15, 19), <<"field3_int">>, 15, {undefined, true}), Keys ordered by val index term , since 2i order is { term , key } KsVal = [A || {_, A} <- lists:sort([{int_to_field1_bin(N), K(N)} || N <- lists:seq(0, 20), N /= 11, N /= 5])], assertRangeQuery(Clients, KsVal, <<"field1_bin">>, <<"val0">>, <<"val9">>, undefined, {undefined, true}), assertRangeQuery(Clients, ?KEYS(0, 20, N /= 11, N /= 5), <<"field2_int">>, 0, 20, undefined, {undefined, true}), assertRangeQuery(Clients, ?KEYS(0, 20, N /= 11, N /= 5), <<"$key">>, <<"obj00">>, <<"obj20">>, undefined, {undefined, true}), Verify bignum sort order in sext -- only ( riak_kv#499 ) TestIdxVal = 1362400142028, put_an_object(PBC, TestIdxVal), assertRangeQuery(Clients, [<<"obj1362400142028">>], <<"field2_int">>, 1000000000000, TestIdxVal), pass. assertExactQuery(Clients, Expected, Index, Value) -> assertExactQuery(Clients, Expected, Index, Value, {false, false}), assertExactQuery(Clients, Expected, Index, Value, {true, true}). assertExactQuery(Clients, Expected, Index, Value, Sorted) when is_list(Clients) -> [assertExactQuery(C, Expected, Index, Value, Sorted) || C <- Clients]; assertExactQuery({ClientType, Client}, Expected, Index, Value, {Sort, ExpectSorted}) -> lager:info("Searching Index ~p for ~p, sort: ~p ~p with client ~p", [Index, Value, Sort, ExpectSorted, ClientType]), {ok, ?INDEX_RESULTS{keys=Results}} = case ClientType of pb -> riakc_pb_socket:get_index_eq(Client, ?BUCKET, Index, Value, [{pagination_sort, Sort} || Sort /= undefined]); http -> rhc:get_index(Client, ?BUCKET, Index, Value, [{pagination_sort, Sort}]) end, ActualKeys = case ExpectSorted of true -> Results; _ -> lists:sort(Results) end, lager:info("Expected: ~p", [Expected]), lager:info("Actual : ~p", [Results]), lager:info("Sorted : ~p", [ActualKeys]), ?assertEqual(Expected, ActualKeys). assertRangeQuery(Clients, Expected, Index, StartValue, EndValue) -> assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, undefined). assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, Re) -> assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, Re, {false, false}), assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, Re, {true, true}). assertRangeQuery(Clients, Expected, Index, StartValue, EndValue, Re, Sort) when is_list(Clients) -> [assertRangeQuery(C, Expected, Index, StartValue, EndValue, Re, Sort) || C <- Clients]; assertRangeQuery({ClientType, Client}, Expected, Index, StartValue, EndValue, Re, {Sort, ExpectSorted}) -> lager:info("Searching Index ~p for ~p-~p re:~p, sort: ~p, ~p with ~p client", [Index, StartValue, EndValue, Re, Sort, ExpectSorted, ClientType]), {ok, ?INDEX_RESULTS{keys=Results}} = case ClientType of pb -> riakc_pb_socket:get_index_range(Client, ?BUCKET, Index, StartValue, EndValue, [{term_regex, Re} || Re /= undefined] ++ [{pagination_sort, Sort} || Sort /= undefined]); http -> rhc:get_index(Client, ?BUCKET, Index, {StartValue, EndValue}, [{term_regex, Re} || Re /= undefined] ++ [{pagination_sort, Sort}]) end, ActualKeys = case ExpectSorted of true -> Results; _ -> lists:sort(Results) end, lager:info("Expected: ~p", [Expected]), lager:info("Actual : ~p", [Results]), lager:info("Sorted : ~p", [ActualKeys]), ?assertEqual(Expected, ActualKeys). general 2i utility put_an_object(Pid, N) -> Key = int_to_key(N), Data = list_to_binary(io_lib:format("data~p", [N])), BinIndex = int_to_field1_bin(N), Indexes = [{"field1_bin", BinIndex}, {"field2_int", N}, every 5 items indexed together {"field3_int", N - (N rem 5)} ], put_an_object(Pid, Key, Data, Indexes). put_an_object(Pid, Key, Data, Indexes) when is_list(Indexes) -> lager:info("Putting object ~p", [Key]), MetaData = dict:from_list([{<<"index">>, Indexes}]), Robj0 = riakc_obj:new(?BUCKET, Key), Robj1 = riakc_obj:update_value(Robj0, Data), Robj2 = riakc_obj:update_metadata(Robj1, MetaData), riakc_pb_socket:put(Pid, Robj2); put_an_object(Pid, Key, IntIndex, BinIndex) when is_integer(IntIndex), is_binary(BinIndex) -> put_an_object(Pid, Key, Key, [{"field1_bin", BinIndex},{"field2_int", IntIndex}]). int_to_key(N) -> case N < 100 of true -> list_to_binary(io_lib:format("obj~2..0B", [N])); _ -> list_to_binary(io_lib:format("obj~p", [N])) end. int_to_field1_bin(N) -> list_to_binary(io_lib:format("val~p", [N])). stream_pb(Pid, Q) -> pb_query(Pid, Q, [stream]), stream_loop(). stream_pb(Pid, Q, Opts) -> pb_query(Pid, Q, [stream|Opts]), stream_loop(). stream_loop() -> stream_loop(orddict:new()). stream_loop(Acc) -> receive {_Ref, {done, undefined}} -> {ok, orddict:to_list(Acc)}; {_Ref, {done, Continuation}} -> {ok, orddict:store(continuation, Continuation, Acc)}; {_Ref, ?INDEX_STREAM_RESULT{terms=undefined, keys=Keys}} -> Acc2 = orddict:update(keys, fun(Existing) -> Existing++Keys end, Keys, Acc), stream_loop(Acc2); {_Ref, ?INDEX_STREAM_RESULT{terms=Results}} -> Acc2 = orddict:update(results, fun(Existing) -> Existing++Results end, Results, Acc), stream_loop(Acc2); {_Ref, {ok, ?INDEX_STREAM_BODY_RESULT{objects=Objects}}} -> Acc2 = orddict:update(results, fun(Existing) -> Existing++Objects end, Objects, Acc), stream_loop(Acc2); {_Ref, {error, <<"{error,timeout}">>}} -> {error, timeout}; {_Ref, Wat} -> lager:info("got a wat ~p", [Wat]), stream_loop(Acc) end. pb_query(Pid, {Field, Val}, Opts) -> riakc_pb_socket:get_index_eq(Pid, ?BUCKET, Field, Val, Opts); pb_query(Pid, {Field, Start, End}, Opts) -> riakc_pb_socket:get_index_range(Pid, ?BUCKET, Field, Start, End, Opts). http_stream(NodePath, Query, Opts) -> http_query(NodePath, Query, [{stream, true} | Opts], stream). http_query(NodePath, Q) -> http_query(NodePath, Q, []). http_query(NodePath, Query, Opts) -> http_query(NodePath, Query, Opts, undefined). http_query(NodePath, Query, Opts, Pid) -> http_get(query_to_url(NodePath, Query, Opts), Pid). query_to_url(NodePath, {Field, Value}, Opts) -> QString = opts_to_qstring(Opts, []), Flag = case is_integer(Value) of true -> "w"; false -> "s" end, url("~s/buckets/~s/index/~s/~"++Flag++"~s", [NodePath, ?BUCKET, Field, Value, QString]); query_to_url(NodePath, {Field, Start, End}, Opts) -> QString = opts_to_qstring(Opts, []), Flag = case is_integer(Start) of true -> "w"; false -> "s" end, url("~s/buckets/~s/index/~s/~"++Flag++"/~"++Flag++"~s", [NodePath, ?BUCKET, Field, Start, End, QString]). url(Format, Elements) -> Path = io_lib:format(Format, Elements), lists:flatten(Path). http_get(Url, undefined) -> lager:info("getting ~p", [Url]), {ok,{{"HTTP/1.1",200,"OK"}, _, Body}} = httpc:request(Url), {struct, Result} = mochijson2:decode(Body), Result; http_get(Url, stream) -> lager:info("streaming ~p", [Url]), {ok, Ref} = httpc:request(get, {Url, []}, [], [{stream, self}, {sync, false}]), start_http_stream(Ref). opts_to_qstring([], QString) -> QString; opts_to_qstring([Opt|Rest], []) -> QOpt = opt_to_string("?", Opt), opts_to_qstring(Rest, QOpt); opts_to_qstring([Opt|Rest], QString) -> QOpt = opt_to_string("&", Opt), opts_to_qstring(Rest, QString++QOpt). opt_to_string(Sep, {Name, Value}) when is_integer(Value) -> io_lib:format(Sep++"~s=~p", [Name, Value]); opt_to_string(Sep, {Name, Value})-> io_lib:format(Sep++"~s=~s", [Name, url_encode(Value)]); opt_to_string(Sep, Name) -> io_lib:format(Sep++"~s=~s", [Name, true]). url_encode(Val) when is_binary(Val) -> url_encode(binary_to_list(Val)); url_encode(Val) when is_atom(Val) -> url_encode(atom_to_list(Val)); url_encode(Val) -> ibrowse_lib:url_encode(Val). start_http_stream(Ref) -> receive {http, {Ref, stream_start, Headers}} -> Boundary = get_boundary(proplists:get_value("content-type", Headers)), http_stream_loop(Ref, <<>>, Boundary); Other -> lager:error("Unexpected message ~p", [Other]), {error, unknown_message} after 60000 -> {error, timeout_local} end. http_stream_loop(Ref, Acc, {Boundary, BLen}=B) -> receive {http, {Ref, stream, Chunk}} -> http_stream_loop(Ref, <<Acc/binary,Chunk/binary>>, B); {http, {Ref, stream_end, _Headers}} -> Parts = binary:split(Acc,[ <<"\r\n--", Boundary:BLen/bytes, "\r\nContent-Type: application/json\r\n\r\n">>, <<"\r\n--", Boundary:BLen/bytes,"--\r\n">> ], [global, trim]), lists:foldl(fun(<<>>, Results) -> Results; (Part, Results) -> {struct, Result} = mochijson2:decode(Part), orddict:merge(fun(_K, V1, V2) -> V1 ++ V2 end, Results, Result) end, [], Parts); Other -> lager:error("Unexpected message ~p", [Other]), {error, unknown_message} after 60000 -> {error, timeout_local} end. get_boundary("multipart/mixed;boundary=" ++ Boundary) -> B = list_to_binary(Boundary), {B, byte_size(B)}; get_boundary(_) -> undefined.
152f65d48128956a34eba1443eebec53b80527a964122a3637d91c4281a58449
semilin/layoup
CTGAP-3.0.lisp
(MAKE-LAYOUT :NAME "CTGAP-3.0" :MATRIX (APPLY #'KEY-MATRIX '("vplcfkuoyj" "rntsd'aeih" "zbmgwx,.;q")) :SHIFT-MATRIX NIL :KEYBOARD NIL)
null
https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/CTGAP-3.0.lisp
lisp
(MAKE-LAYOUT :NAME "CTGAP-3.0" :MATRIX (APPLY #'KEY-MATRIX '("vplcfkuoyj" "rntsd'aeih" "zbmgwx,.;q")) :SHIFT-MATRIX NIL :KEYBOARD NIL)
1e04e5cda860bd8ccd82b59499f8bf0682c9331c1241222d2bc92edb79193782
namin/3-proto-lisp
boot.lsp
(cl:in-package 3-proto-lisp) (3pl:read-normalize-print)
null
https://raw.githubusercontent.com/namin/3-proto-lisp/203f9eb14ee1c48061f25c204965a63622bdac38/boot.lsp
lisp
(cl:in-package 3-proto-lisp) (3pl:read-normalize-print)
ca97fbf714ed85cdae50def350345f6905f48e11d40a1cfb8b24aaa3ce5e7d6c
day8/re-frame-test
test.cljc
(ns day8.re-frame.test #?(:cljs (:require-macros day8.re-frame.test)) (:require #?(:cljs [cljs.test :as test] :clj [clojure.test :as test]) [re-frame.core :as rf] [re-frame.router :as rf.router] [re-frame.db :as rf.db] [re-frame.interop :as rf.int]) #?(:clj (:import [java.util.concurrent Executors TimeUnit]))) ;;;; ;;;; General test utils ;;;; (defn- dequeue! "Dequeue an item from a persistent queue which is stored as the value in queue-atom. Returns the item, and updates the atom with the new queue value. If the queue is empty, does not alter it and returns nil." [queue-atom] (let [queue @queue-atom] (when (seq queue) (if (compare-and-set! queue-atom queue (pop queue)) (peek queue) (recur queue-atom))))) ;;;; ;;;; Async tests ;;;; (def ^:dynamic *test-timeout* 5000) (def test-context* "`test-context*` is used to communicate internal details of the test between `run-test-async*` and `wait-for*`." (atom nil)) (defn set-test-context [tc] (reset! test-context* tc)) (defn clear-test-context [] (reset! test-context* nil)) #?(:clj (defmacro with-temp-re-frame-state "Run `body`, but discard whatever effects it may have on re-frame's internal state (by resetting `app-db` and re-frame's various different types of handlers after `body` has run). Note: you *can't* use this macro to clean up a JS async test, since the macro will perform the cleanup before your async code actually has a chance to run. `run-test-async` will automatically do this cleanup for you." [& body] `(let [restore-fn# (rf/make-restore-fn)] (try ~@body (finally (clear-test-context) (restore-fn#)))))) (defn run-test-async* [f] (let [initial-test-context {:wait-for-depth 0 :max-wait-for-depth 0 :now-waiting-for nil}] #?(:clj (with-temp-re-frame-state (let [done-promise (promise) executor (Executors/newSingleThreadExecutor) fail-ex (atom nil) initial-test-context (assoc initial-test-context :done #(deliver done-promise ::done))] (with-redefs [rf.int/executor executor] ;; Execute the test code itself on the same thread as the ;; re-frame event handlers run, so that we accurately simulate the single - threaded JS environment and also so ;; that we don't have to worry about making the JVM implementation of the re - frame EventQueue thread - safe . (rf.int/next-tick #(try (set-test-context initial-test-context) (f) (catch Throwable t (reset! fail-ex t)))) (let [result (deref done-promise *test-timeout* ::timeout)] (.shutdown executor) (when-not (.awaitTermination executor 5 TimeUnit/SECONDS) (throw (ex-info (str "Couldn't cleanly shut down the re-frame event queue's " "executor. Possibly this could result in a polluted " "`app-db` for other tests. Probably it means you're " "doing something very strange in an event handler. " "(Catching InterruptedException, for a start.)") {}))) (if-let [ex @fail-ex] (throw ex) (test/is (not= ::timeout result) (str "Test timed out after " *test-timeout* "ms" (when-let [ev (:now-waiting-for @test-context*)] (str ", waiting for " (pr-str ev) "."))))))))) :cljs (test/async done (let [restore-fn (rf/make-restore-fn)] (set-test-context (assoc initial-test-context :done (fn [] (clear-test-context) (restore-fn) (done)))) (f)))))) (defmacro run-test-async "Run `body` as an async re-frame test. The async nature means you'll need to use `wait-for` any time you want to make any assertions that should be true *after* an event has been handled. It's assumed that there will be at least one `wait-for` in the body of your test (otherwise you don't need this macro at all). Note: unlike regular ClojureScript `cljs.test/async` tests, `wait-for` takes care of calling `(done)` for you: you don't need to do anything specific to handle the fact that your test is asynchronous, other than make sure that all your assertions happen with `wait-for` blocks. This macro will automatically clean up any changes to re-frame state made within the test body, as per `with-temp-re-frame-state` (except that the way it's done here *does* work for async tests, whereas that macro used by itself doesn't)." [& body] `(run-test-async* (fn [] ~@body))) (defn- as-callback-pred "Interprets the acceptable input values for `wait-for`'s `ok-ids` and `failure-ids` params to produce a predicate function on an event. See `wait-for` for details." [callback-pred] (when callback-pred (cond (or (set? callback-pred) (vector? callback-pred)) (fn [event] (some (fn [pred] (pred event)) (map as-callback-pred (seq callback-pred)))) (fn? callback-pred) callback-pred (keyword? callback-pred) (fn [[event-id _]] (= callback-pred event-id)) :else (throw (ex-info (str (pr-str callback-pred) " isn't an event predicate") {:callback-pred callback-pred}))))) (defn wait-for* "This function is an implementation detail: in your async tests (within a `run-test-async`), you should use the `wait-for` macro instead. (For synchronous tests within `run-test-sync`, you don't need this capability at all.) Installs `callback` as a re-frame post-event callback handler, called as soon as any event matching `ok-ids` is handled. Aborts the test as a failure if any event matching `failure-ids` is handled. Since this is intended for use in asynchronous tests: it will return immediately after installing the callback -- it doesn't *actually* wait. Note that `wait-for*` tracks whether, during your callback, you call `wait-for*` again. If you *don't*, then, given the way asynchronous tests work, your test must necessarily be finished. So `wait-for*` will call `(done)` for you." [ok-ids failure-ids callback] ;; `:wait-for-depth` and `:max-wait-for-depth` are used together to track how ;; "deep" we are in callback functions as the test progresses. We increment ;; `:max-wait-for-depth` before installing a post-event callback handler, then ;; after the event later occurs and the callback handler subsequently runs, we ;; check whether it has been incremented further (indicating another ;; `wait-for*` callback handler has been installed). If it *hasn't*, since ;; `wait-for*` only makes sense in a tail position, this means the test is ;; complete, and we can call `(done)`, saving the test author the trouble of ;; passing `done` through every single callback. (let [{done :done wait-for-depth :max-wait-for-depth :as test-context} (swap! test-context* update :max-wait-for-depth inc)] (let [ok-pred (as-callback-pred ok-ids) fail-pred (as-callback-pred failure-ids) cb-id (gensym "wait-for-cb-fn")] (rf/add-post-event-callback cb-id (#?(:cljs fn :clj bound-fn) [event _] ;; (taoensso.timbre/warn "post-event-callback: " event) (cond (and fail-pred (not (test/is (not (fail-pred event)) "Received failure event"))) (do (rf/remove-post-event-callback cb-id) (swap! test-context* assoc :now-waiting-for nil) (done)) (ok-pred event) (do (rf/remove-post-event-callback cb-id) (swap! test-context* assoc :now-waiting-for nil) (callback event) (when (= wait-for-depth (:max-wait-for-depth @test-context*)) ;; `callback` has completed with no `wait-for*` ;; calls, so we're not waiting for anything ;; further. Given that `wait-for*` calls are ;; only valid in tail position, the test must ;; now be finished. (done))) ;; Test is not interested this event, but we still ;; need to wait for the one we *are* interested in. :else nil))) (swap! test-context* assoc :now-waiting-for ok-ids)))) (defmacro wait-for "Execute `body` once an event identified by the predicate(s) `ids` has been handled. `ids` and `failure-ids` are means to identify an event. Normally, each would be a simple keyword or a set of keywords. If an event with event-id of (or in) `ids` is handled, the test will continue by executing the body. If an event with an event-id of (or in) `failure-ids` is handled, the test will abort and fail. IMPORTANT NOTE: due to the way async tests in re-frame work, code you want executed after the event you're waiting for has to happen in the `body` of the `wait-for` (in an implicit callback), not just lexically after the the `wait-for` call. In practice, this means `wait-for` must always be in a tail position. Eg: (run-test-async (dispatch [:get-user 2]) (wait-for [#{:got-user} #{:no-such-user :system-unavailable} event] (is (= (:username @(subscribe [:user])) \"johnny\"))) ;; Don't put code here, it will run *before* the event you're waiting ;; for. ) Acceptable inputs for `ids` and `failure-ids` are: - `:some-event-id` => matches an event with that ID - `#{:some-event-id :other-event-id}` => matches an event with any of the given IDs - `[:some-event-id :other-event-id]` => ditto (checks in order) - `(fn [event] ,,,) => uses the function as a predicate - `[(fn [event] ,,,) (fn [event] ,,,)]` => tries each predicate in turn, matching an event which matches at least one predicate - `#{:some-event-id (fn [event] ,,,)}` => tries each Note that because we're liberal about whether you supply `failure-ids` and/or `event-sym`, if you do choose to supply only one, and you want that one to be `event-sym`, you can't supply it as a destructuring form (because we can't disambiguate that from a vector of `failure-ids`). You can just supply `nil` as `failure-ids` in this case, and then you'll be able to destructure." [[ids failure-ids event-sym :as argv] & body] (let [[failure-ids event-sym] (case (count argv) 3 [failure-ids event-sym] 2 (if (symbol? (second argv)) [nil (second argv)] [(second argv) (gensym "event")]) 1 [nil (gensym "event")] 0 (throw (ex-info "wait-for needs to know what to wait for!" {})))] `(wait-for* ~ids ~failure-ids (fn [~event-sym] ~@body)))) ;;;; Sync tests ;;;; (def ^{:dynamic true, :private true} *handling* false) (defn run-test-sync* [f] (day8.re-frame.test/with-temp-re-frame-state Bypass the actual re - frame EventQueue and use a local alternative over ;; which we have full control. (let [my-queue (atom rf.int/empty-queue) new-dispatch (fn [argv] (swap! my-queue conj argv) (when-not *handling* (binding [*handling* true] (loop [] (when-let [queue-head (dequeue! my-queue)] (rf.router/dispatch-sync queue-head) (recur))))))] (with-redefs [rf/dispatch new-dispatch rf.router/dispatch new-dispatch] (f))))) (defmacro run-test-sync "Execute `body` as a test, where each `dispatch` call is executed synchronously (via `dispatch-sync`), and any subsequent dispatches which are caused by that dispatch are also fully handled/executed prior to control flow returning to your test. Think of it kind of as though every `dispatch` in your app had been magically turned into `dispatch-sync`, and re-frame had lifted the restriction that says you can't call `dispatch-sync` from within an event handler. Note that this is *not* achieved with blocking. It relies on you not doing anything asynchronous (such as an actual AJAX call or `js/setTimeout`) directly in your event handlers. In a real app running in the real browser, of course that won't apply, so this might seem useless at first. But if you're a well-behaved re-framer, all of your asynchronous stuff (which is by definition side-effecty) will happen in effectful event handlers installed with `reg-fx`. Which works very nicely: in your tests, install an alternative version of those effectful event handlers which behaves synchronously. For maximum coolness, you might want to consider running your tests on the JVM and installing a `reg-fx` handler which actually invokes your JVM Clojure server-side Ring handler where your in-browser code would make an AJAX call." [& body] `(run-test-sync* (fn [] ~@body)))
null
https://raw.githubusercontent.com/day8/re-frame-test/3238d7e2907f0effba005f79e801ea519f77be0c/src/day8/re_frame/test.cljc
clojure
General test utils Async tests Execute the test code itself on the same thread as the re-frame event handlers run, so that we accurately that we don't have to worry about making the JVM `:wait-for-depth` and `:max-wait-for-depth` are used together to track how "deep" we are in callback functions as the test progresses. We increment `:max-wait-for-depth` before installing a post-event callback handler, then after the event later occurs and the callback handler subsequently runs, we check whether it has been incremented further (indicating another `wait-for*` callback handler has been installed). If it *hasn't*, since `wait-for*` only makes sense in a tail position, this means the test is complete, and we can call `(done)`, saving the test author the trouble of passing `done` through every single callback. (taoensso.timbre/warn "post-event-callback: " event) `callback` has completed with no `wait-for*` calls, so we're not waiting for anything further. Given that `wait-for*` calls are only valid in tail position, the test must now be finished. Test is not interested this event, but we still need to wait for the one we *are* interested in. Don't put code here, it will run *before* the event you're waiting for. which we have full control.
(ns day8.re-frame.test #?(:cljs (:require-macros day8.re-frame.test)) (:require #?(:cljs [cljs.test :as test] :clj [clojure.test :as test]) [re-frame.core :as rf] [re-frame.router :as rf.router] [re-frame.db :as rf.db] [re-frame.interop :as rf.int]) #?(:clj (:import [java.util.concurrent Executors TimeUnit]))) (defn- dequeue! "Dequeue an item from a persistent queue which is stored as the value in queue-atom. Returns the item, and updates the atom with the new queue value. If the queue is empty, does not alter it and returns nil." [queue-atom] (let [queue @queue-atom] (when (seq queue) (if (compare-and-set! queue-atom queue (pop queue)) (peek queue) (recur queue-atom))))) (def ^:dynamic *test-timeout* 5000) (def test-context* "`test-context*` is used to communicate internal details of the test between `run-test-async*` and `wait-for*`." (atom nil)) (defn set-test-context [tc] (reset! test-context* tc)) (defn clear-test-context [] (reset! test-context* nil)) #?(:clj (defmacro with-temp-re-frame-state "Run `body`, but discard whatever effects it may have on re-frame's internal state (by resetting `app-db` and re-frame's various different types of handlers after `body` has run). Note: you *can't* use this macro to clean up a JS async test, since the macro will perform the cleanup before your async code actually has a chance to run. `run-test-async` will automatically do this cleanup for you." [& body] `(let [restore-fn# (rf/make-restore-fn)] (try ~@body (finally (clear-test-context) (restore-fn#)))))) (defn run-test-async* [f] (let [initial-test-context {:wait-for-depth 0 :max-wait-for-depth 0 :now-waiting-for nil}] #?(:clj (with-temp-re-frame-state (let [done-promise (promise) executor (Executors/newSingleThreadExecutor) fail-ex (atom nil) initial-test-context (assoc initial-test-context :done #(deliver done-promise ::done))] (with-redefs [rf.int/executor executor] simulate the single - threaded JS environment and also so implementation of the re - frame EventQueue thread - safe . (rf.int/next-tick #(try (set-test-context initial-test-context) (f) (catch Throwable t (reset! fail-ex t)))) (let [result (deref done-promise *test-timeout* ::timeout)] (.shutdown executor) (when-not (.awaitTermination executor 5 TimeUnit/SECONDS) (throw (ex-info (str "Couldn't cleanly shut down the re-frame event queue's " "executor. Possibly this could result in a polluted " "`app-db` for other tests. Probably it means you're " "doing something very strange in an event handler. " "(Catching InterruptedException, for a start.)") {}))) (if-let [ex @fail-ex] (throw ex) (test/is (not= ::timeout result) (str "Test timed out after " *test-timeout* "ms" (when-let [ev (:now-waiting-for @test-context*)] (str ", waiting for " (pr-str ev) "."))))))))) :cljs (test/async done (let [restore-fn (rf/make-restore-fn)] (set-test-context (assoc initial-test-context :done (fn [] (clear-test-context) (restore-fn) (done)))) (f)))))) (defmacro run-test-async "Run `body` as an async re-frame test. The async nature means you'll need to use `wait-for` any time you want to make any assertions that should be true *after* an event has been handled. It's assumed that there will be at least one `wait-for` in the body of your test (otherwise you don't need this macro at all). Note: unlike regular ClojureScript `cljs.test/async` tests, `wait-for` takes care of calling `(done)` for you: you don't need to do anything specific to handle the fact that your test is asynchronous, other than make sure that all your assertions happen with `wait-for` blocks. This macro will automatically clean up any changes to re-frame state made within the test body, as per `with-temp-re-frame-state` (except that the way it's done here *does* work for async tests, whereas that macro used by itself doesn't)." [& body] `(run-test-async* (fn [] ~@body))) (defn- as-callback-pred "Interprets the acceptable input values for `wait-for`'s `ok-ids` and `failure-ids` params to produce a predicate function on an event. See `wait-for` for details." [callback-pred] (when callback-pred (cond (or (set? callback-pred) (vector? callback-pred)) (fn [event] (some (fn [pred] (pred event)) (map as-callback-pred (seq callback-pred)))) (fn? callback-pred) callback-pred (keyword? callback-pred) (fn [[event-id _]] (= callback-pred event-id)) :else (throw (ex-info (str (pr-str callback-pred) " isn't an event predicate") {:callback-pred callback-pred}))))) (defn wait-for* "This function is an implementation detail: in your async tests (within a `run-test-async`), you should use the `wait-for` macro instead. (For synchronous tests within `run-test-sync`, you don't need this capability at all.) Installs `callback` as a re-frame post-event callback handler, called as soon as any event matching `ok-ids` is handled. Aborts the test as a failure if any event matching `failure-ids` is handled. Since this is intended for use in asynchronous tests: it will return immediately after installing the callback -- it doesn't *actually* wait. Note that `wait-for*` tracks whether, during your callback, you call `wait-for*` again. If you *don't*, then, given the way asynchronous tests work, your test must necessarily be finished. So `wait-for*` will call `(done)` for you." [ok-ids failure-ids callback] (let [{done :done wait-for-depth :max-wait-for-depth :as test-context} (swap! test-context* update :max-wait-for-depth inc)] (let [ok-pred (as-callback-pred ok-ids) fail-pred (as-callback-pred failure-ids) cb-id (gensym "wait-for-cb-fn")] (rf/add-post-event-callback cb-id (#?(:cljs fn :clj bound-fn) [event _] (cond (and fail-pred (not (test/is (not (fail-pred event)) "Received failure event"))) (do (rf/remove-post-event-callback cb-id) (swap! test-context* assoc :now-waiting-for nil) (done)) (ok-pred event) (do (rf/remove-post-event-callback cb-id) (swap! test-context* assoc :now-waiting-for nil) (callback event) (when (= wait-for-depth (:max-wait-for-depth @test-context*)) (done))) :else nil))) (swap! test-context* assoc :now-waiting-for ok-ids)))) (defmacro wait-for "Execute `body` once an event identified by the predicate(s) `ids` has been handled. `ids` and `failure-ids` are means to identify an event. Normally, each would be a simple keyword or a set of keywords. If an event with event-id of (or in) `ids` is handled, the test will continue by executing the body. If an event with an event-id of (or in) `failure-ids` is handled, the test will abort and fail. IMPORTANT NOTE: due to the way async tests in re-frame work, code you want executed after the event you're waiting for has to happen in the `body` of the `wait-for` (in an implicit callback), not just lexically after the the `wait-for` call. In practice, this means `wait-for` must always be in a tail position. Eg: (run-test-async (dispatch [:get-user 2]) (wait-for [#{:got-user} #{:no-such-user :system-unavailable} event] (is (= (:username @(subscribe [:user])) \"johnny\"))) ) Acceptable inputs for `ids` and `failure-ids` are: - `:some-event-id` => matches an event with that ID - `#{:some-event-id :other-event-id}` => matches an event with any of the given IDs - `[:some-event-id :other-event-id]` => ditto (checks in order) - `(fn [event] ,,,) => uses the function as a predicate - `[(fn [event] ,,,) (fn [event] ,,,)]` => tries each predicate in turn, matching an event which matches at least one predicate - `#{:some-event-id (fn [event] ,,,)}` => tries each Note that because we're liberal about whether you supply `failure-ids` and/or `event-sym`, if you do choose to supply only one, and you want that one to be `event-sym`, you can't supply it as a destructuring form (because we can't disambiguate that from a vector of `failure-ids`). You can just supply `nil` as `failure-ids` in this case, and then you'll be able to destructure." [[ids failure-ids event-sym :as argv] & body] (let [[failure-ids event-sym] (case (count argv) 3 [failure-ids event-sym] 2 (if (symbol? (second argv)) [nil (second argv)] [(second argv) (gensym "event")]) 1 [nil (gensym "event")] 0 (throw (ex-info "wait-for needs to know what to wait for!" {})))] `(wait-for* ~ids ~failure-ids (fn [~event-sym] ~@body)))) Sync tests (def ^{:dynamic true, :private true} *handling* false) (defn run-test-sync* [f] (day8.re-frame.test/with-temp-re-frame-state Bypass the actual re - frame EventQueue and use a local alternative over (let [my-queue (atom rf.int/empty-queue) new-dispatch (fn [argv] (swap! my-queue conj argv) (when-not *handling* (binding [*handling* true] (loop [] (when-let [queue-head (dequeue! my-queue)] (rf.router/dispatch-sync queue-head) (recur))))))] (with-redefs [rf/dispatch new-dispatch rf.router/dispatch new-dispatch] (f))))) (defmacro run-test-sync "Execute `body` as a test, where each `dispatch` call is executed synchronously (via `dispatch-sync`), and any subsequent dispatches which are caused by that dispatch are also fully handled/executed prior to control flow returning to your test. Think of it kind of as though every `dispatch` in your app had been magically turned into `dispatch-sync`, and re-frame had lifted the restriction that says you can't call `dispatch-sync` from within an event handler. Note that this is *not* achieved with blocking. It relies on you not doing anything asynchronous (such as an actual AJAX call or `js/setTimeout`) directly in your event handlers. In a real app running in the real browser, of course that won't apply, so this might seem useless at first. But if you're a well-behaved re-framer, all of your asynchronous stuff (which is by definition side-effecty) will happen in effectful event handlers installed with `reg-fx`. Which works very nicely: in your tests, install an alternative version of those effectful event handlers which behaves synchronously. For maximum coolness, you might want to consider running your tests on the JVM and installing a `reg-fx` handler which actually invokes your JVM Clojure server-side Ring handler where your in-browser code would make an AJAX call." [& body] `(run-test-sync* (fn [] ~@body)))
2ed7d9be352a1ca4778813b0062226689a0c5cbdef1f9fc627e82cd160d06470
fare/command-line-arguments
pkgdcl.lisp
#+xcvb (module ()) (cl:defpackage :command-line-arguments (:use :cl :uiop) (:export #:*command-line-arguments* #:*command-line-options* #:*command-line-option-specification* #:process-command-line-options #:compute-and-process-command-line-options #:get-command-line-arguments #:handle-command-line #:show-option-help #:define-command #:command-line-arity ))
null
https://raw.githubusercontent.com/fare/command-line-arguments/fbac862fb01c0e368141204f3f639920462c23fe/pkgdcl.lisp
lisp
#+xcvb (module ()) (cl:defpackage :command-line-arguments (:use :cl :uiop) (:export #:*command-line-arguments* #:*command-line-options* #:*command-line-option-specification* #:process-command-line-options #:compute-and-process-command-line-options #:get-command-line-arguments #:handle-command-line #:show-option-help #:define-command #:command-line-arity ))
fb60efa5aa08e9b7b06befc11d2792db5ba7adc53f6d448c071cecf22e274df7
riak-haskell-client/riak-haskell-client
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import Criterion.Main import Network.Riak.Connection.Pool as Pool (Pool, create, withConnection) import Network.Riak.Connection (defaultClient) import Network.Riak.CRDT import qualified Data.ByteString.Char8 as B import Control.Applicative import Control.Monad import Data.Maybe import Data.String import qualified Data.List.NonEmpty as NEL import Data.Semigroup main :: IO () main = benchmarks >>= defaultMain bucket = "bench" benchmarks = do pool <- Pool.create defaultClient 1 1 1 already <- Pool.withConnection pool $ \c -> get c "counters" bucket "__setup" when (isNothing already) $ setup pool pure [crdt pool] setup :: Pool -> IO () setup pool = Pool.withConnection pool $ \c -> do setupSetN c "10" 10 setupSetN c "100" 100 setupSetN c "1000" 1000 setupMapN_elem c "1" 1 setupMapN_elem c "10-elem" 10 setupMapN_elem c "100-elem" 100 setupMapN_elem c "1000-elem" 1000 setupMapN_nest c "10-depth" 10 setupMapN_nest c "100-depth" 100 setupMapN_nest c "1000-depth" 1000 sendModify c "counters" bucket "__setup" [CounterInc 1] putStrLn "Bench env set up." -- | * Common things -- | Key names setK n = fromString $ show n mapElemK n = fromString $ show n <> "-elem" mapDepthK n = fromString $ show n <> "-depth" -- | Map things nestedMapPath n = MapPath . NEL.fromList $ [ fromString (show i) | i <- [1..n] ] setupSetN c key n = sequence_ [ sendModify c "sets" bucket key [SetAdd (B.pack $ show i)] | i <- [1..n] ] -- | n-elem map with counters setupMapN_elem c key n = sendModify c "maps" bucket key ops where ops = [MapUpdate (MapPath $ (fromString $ show i) :| []) (MapCounterOp $ CounterInc 1) | i <- [1..n] ] -- | n-depth map with a counter setupMapN_nest c key n = sendModify c "maps" bucket key [op] where op = MapUpdate (nestedMapPath n) (MapCounterOp $ CounterInc 1) crdt :: Pool -> Benchmark crdt pool = bgroup "CRDT" [ bgroup "get" [ bench "get a non-existent counter" . nfIO $ pooled getEmpty ], bgroup "counters" [ bench "get a counter" . nfIO $ pooled getCounter ], bgroup "sets" [ bench "get a 10-elem set" . nfIO $ pooled getSet10, bench "get a 100-elem set" . nfIO $ pooled getSet100, bench "get a 1000-elem set" . nfIO $ pooled getSet1000, bench "1000-set add+remove an elem cycle" . nfIO $ pooled set1kAddRemove ], bgroup "maps" [ bgroup "get" [ bench "get a trivial map" . nfIO . pooled $ get1Map, bench "get a 10-elem map" . nfIO . pooled $ getNMap 10, bench "get a 100-elem map" . nfIO . pooled $ getNMap 100, bench "get a 1000-elem map" . nfIO . pooled $ getNMap 1000, bench "get a 10-depth map" . nfIO . pooled $ getDMap 10, bench "get a 100-depth map" . nfIO . pooled $ getDMap 100, bench "get a 1000-depth map" . nfIO . pooled $ getDMap 1000 ], bgroup "update" [ bench "update a counter inside 10-elem map" . nfIO . pooled $ updateNMap 10, bench "update a counter inside 100-elem map" . nfIO . pooled $ updateNMap 100, bench "update a counter inside 1000-elem map" . nfIO . pooled $ updateNMap 1000, bench "update a counter inside 10-depth map" . nfIO . pooled $ updateDMap 10, bench "update a counter inside 100-depth map" . nfIO . pooled $ updateDMap 100, bench "update a counter inside 1000-depth map" . nfIO . pooled $ updateDMap 1000 ] ] ] where pooled = Pool.withConnection pool getEmpty c = get c "counters" "not here" "never was" getCounter c = get c "counters" "xxx" "yyy" getSet10 c = get c "sets" bucket "10" getSet100 c = get c "sets" bucket "100" getSet1000 c = get c "sets" bucket "1000" set1kAddRemove c = sequence_ [ sendModify c "sets" bucket "1000" [o] | o <- [SetAdd "foo", SetRemove "foo"] ] get1Map c = get c "maps" bucket "1" getNMap n c = get c "maps" bucket (mapElemK n) getDMap n c = get c "maps" bucket (mapDepthK n) updateNMap n c = setupMapN_elem c (mapElemK n) n updateDMap n c = setupMapN_nest c (mapDepthK n) n
null
https://raw.githubusercontent.com/riak-haskell-client/riak-haskell-client/a1eafc4c16b85a98b2d29e306165f4d93819609f/riak/benchmarks/Main.hs
haskell
# LANGUAGE OverloadedStrings # | * Common things | Key names | Map things | n-elem map with counters | n-depth map with a counter
module Main where import Criterion.Main import Network.Riak.Connection.Pool as Pool (Pool, create, withConnection) import Network.Riak.Connection (defaultClient) import Network.Riak.CRDT import qualified Data.ByteString.Char8 as B import Control.Applicative import Control.Monad import Data.Maybe import Data.String import qualified Data.List.NonEmpty as NEL import Data.Semigroup main :: IO () main = benchmarks >>= defaultMain bucket = "bench" benchmarks = do pool <- Pool.create defaultClient 1 1 1 already <- Pool.withConnection pool $ \c -> get c "counters" bucket "__setup" when (isNothing already) $ setup pool pure [crdt pool] setup :: Pool -> IO () setup pool = Pool.withConnection pool $ \c -> do setupSetN c "10" 10 setupSetN c "100" 100 setupSetN c "1000" 1000 setupMapN_elem c "1" 1 setupMapN_elem c "10-elem" 10 setupMapN_elem c "100-elem" 100 setupMapN_elem c "1000-elem" 1000 setupMapN_nest c "10-depth" 10 setupMapN_nest c "100-depth" 100 setupMapN_nest c "1000-depth" 1000 sendModify c "counters" bucket "__setup" [CounterInc 1] putStrLn "Bench env set up." setK n = fromString $ show n mapElemK n = fromString $ show n <> "-elem" mapDepthK n = fromString $ show n <> "-depth" nestedMapPath n = MapPath . NEL.fromList $ [ fromString (show i) | i <- [1..n] ] setupSetN c key n = sequence_ [ sendModify c "sets" bucket key [SetAdd (B.pack $ show i)] | i <- [1..n] ] setupMapN_elem c key n = sendModify c "maps" bucket key ops where ops = [MapUpdate (MapPath $ (fromString $ show i) :| []) (MapCounterOp $ CounterInc 1) | i <- [1..n] ] setupMapN_nest c key n = sendModify c "maps" bucket key [op] where op = MapUpdate (nestedMapPath n) (MapCounterOp $ CounterInc 1) crdt :: Pool -> Benchmark crdt pool = bgroup "CRDT" [ bgroup "get" [ bench "get a non-existent counter" . nfIO $ pooled getEmpty ], bgroup "counters" [ bench "get a counter" . nfIO $ pooled getCounter ], bgroup "sets" [ bench "get a 10-elem set" . nfIO $ pooled getSet10, bench "get a 100-elem set" . nfIO $ pooled getSet100, bench "get a 1000-elem set" . nfIO $ pooled getSet1000, bench "1000-set add+remove an elem cycle" . nfIO $ pooled set1kAddRemove ], bgroup "maps" [ bgroup "get" [ bench "get a trivial map" . nfIO . pooled $ get1Map, bench "get a 10-elem map" . nfIO . pooled $ getNMap 10, bench "get a 100-elem map" . nfIO . pooled $ getNMap 100, bench "get a 1000-elem map" . nfIO . pooled $ getNMap 1000, bench "get a 10-depth map" . nfIO . pooled $ getDMap 10, bench "get a 100-depth map" . nfIO . pooled $ getDMap 100, bench "get a 1000-depth map" . nfIO . pooled $ getDMap 1000 ], bgroup "update" [ bench "update a counter inside 10-elem map" . nfIO . pooled $ updateNMap 10, bench "update a counter inside 100-elem map" . nfIO . pooled $ updateNMap 100, bench "update a counter inside 1000-elem map" . nfIO . pooled $ updateNMap 1000, bench "update a counter inside 10-depth map" . nfIO . pooled $ updateDMap 10, bench "update a counter inside 100-depth map" . nfIO . pooled $ updateDMap 100, bench "update a counter inside 1000-depth map" . nfIO . pooled $ updateDMap 1000 ] ] ] where pooled = Pool.withConnection pool getEmpty c = get c "counters" "not here" "never was" getCounter c = get c "counters" "xxx" "yyy" getSet10 c = get c "sets" bucket "10" getSet100 c = get c "sets" bucket "100" getSet1000 c = get c "sets" bucket "1000" set1kAddRemove c = sequence_ [ sendModify c "sets" bucket "1000" [o] | o <- [SetAdd "foo", SetRemove "foo"] ] get1Map c = get c "maps" bucket "1" getNMap n c = get c "maps" bucket (mapElemK n) getDMap n c = get c "maps" bucket (mapDepthK n) updateNMap n c = setupMapN_elem c (mapElemK n) n updateDMap n c = setupMapN_nest c (mapDepthK n) n
bc9905fde1da8d5b9a063af1cad0d5cac3e0e576f1327b97bde3df743bb0dd61
victorvianna/mini-gcc
ptree.mli
(* Arbres de syntaxe abstraite issus du parsing *) type loc = Lexing.position * Lexing.position type ident = { id: string; id_loc: loc } type typ = | Tint | Tstructp of ident type unop = | Unot | Uminus type binop = | Beq | Bneq | Blt | Ble | Bgt | Bge | Badd | Bsub | Bmul | Bdiv | Band | Bor type expr = { expr_node: expr_node; expr_loc : loc } and expr_node = | Econst of int32 | Eright of lvalue | Eassign of lvalue * expr | Eunop of unop * expr | Ebinop of binop * expr * expr | Ecall of ident * expr list | Esizeof of ident and lvalue = | Lident of ident | Larrow of expr * ident type decl_var = typ * ident type stmt = { stmt_node: stmt_node; stmt_loc : loc } and stmt_node = | Sskip | Sexpr of expr | Sif of expr * stmt * stmt | Swhile of expr * stmt | Sblock of block | Sreturn of expr and block = decl_var list * stmt list type decl_struct = ident * decl_var list type decl_fun = { fun_typ : typ; fun_name : ident; fun_formals : decl_var list; fun_body : block } type decl = | Dstruct of decl_struct | Dfun of decl_fun type file = decl list
null
https://raw.githubusercontent.com/victorvianna/mini-gcc/04659816d0a1097ae12b57243572fff9e91c0b13/ptree.mli
ocaml
Arbres de syntaxe abstraite issus du parsing
type loc = Lexing.position * Lexing.position type ident = { id: string; id_loc: loc } type typ = | Tint | Tstructp of ident type unop = | Unot | Uminus type binop = | Beq | Bneq | Blt | Ble | Bgt | Bge | Badd | Bsub | Bmul | Bdiv | Band | Bor type expr = { expr_node: expr_node; expr_loc : loc } and expr_node = | Econst of int32 | Eright of lvalue | Eassign of lvalue * expr | Eunop of unop * expr | Ebinop of binop * expr * expr | Ecall of ident * expr list | Esizeof of ident and lvalue = | Lident of ident | Larrow of expr * ident type decl_var = typ * ident type stmt = { stmt_node: stmt_node; stmt_loc : loc } and stmt_node = | Sskip | Sexpr of expr | Sif of expr * stmt * stmt | Swhile of expr * stmt | Sblock of block | Sreturn of expr and block = decl_var list * stmt list type decl_struct = ident * decl_var list type decl_fun = { fun_typ : typ; fun_name : ident; fun_formals : decl_var list; fun_body : block } type decl = | Dstruct of decl_struct | Dfun of decl_fun type file = decl list
6b1936fa33e8b472198d9ae9885d4cd8366574d329b4cabbd17d919c07779904
def-/time.gif
LZWEncoding.hs
# LANGUAGE BangPatterns , CPP # module Codec.Picture.Gif.LZWEncoding( lzwEncode ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative( (<$>) ) import Data.Monoid( mempty ) #endif import Control.Monad.ST( runST ) import qualified Data.ByteString.Lazy as L import Data.Maybe( fromMaybe ) import Data.Word( Word8 ) #if MIN_VERSION_containers(0,5,0) import qualified Data.IntMap.Strict as I #else import qualified Data.IntMap as I #endif import qualified Data.Vector.Storable as V import Codec.Picture.BitWriter type Trie = I.IntMap TrieNode data TrieNode = TrieNode { trieIndex :: {-# UNPACK #-} !Int , trieSub :: !Trie } emptyNode :: TrieNode emptyNode = TrieNode { trieIndex = -1 , trieSub = mempty } initialTrie :: Trie initialTrie = I.fromList [(i, emptyNode { trieIndex = i }) | i <- [0 .. 255]] lookupUpdate :: V.Vector Word8 -> Int -> Int -> Trie -> (Int, Int, Trie) lookupUpdate vector freeIndex firstIndex trie = matchUpdate $ go trie 0 firstIndex where matchUpdate (lzwOutputIndex, nextReadIndex, sub) = (lzwOutputIndex, nextReadIndex, fromMaybe trie sub) maxi = V.length vector go !currentTrie !prevIndex !index | index >= maxi = (prevIndex, index, Nothing) | otherwise = case I.lookup val currentTrie of Just (TrieNode ix subTable) -> let (lzwOutputIndex, nextReadIndex, newTable) = go subTable ix $ index + 1 tableUpdater t = I.insert val (TrieNode ix t) currentTrie in (lzwOutputIndex, nextReadIndex, tableUpdater <$> newTable) Nothing | index == maxi -> (prevIndex, index, Nothing) | otherwise -> (prevIndex, index, Just $ I.insert val newNode currentTrie) where val = fromIntegral $ vector `V.unsafeIndex` index newNode = emptyNode { trieIndex = freeIndex } lzwEncode :: Int -> V.Vector Word8 -> L.ByteString lzwEncode initialKeySize vec = runST $ do bitWriter <- newWriteStateRef let updateCodeSize 12 writeIdx _ | writeIdx == 2 ^ (12 :: Int) - 1 = do writeBitsGif bitWriter (fromIntegral clearCode) 12 return (startCodeSize, firstFreeIndex, initialTrie) updateCodeSize codeSize writeIdx trie | writeIdx == 2 ^ codeSize = return (codeSize + 1, writeIdx + 1, trie) | otherwise = return (codeSize, writeIdx + 1, trie) go readIndex (codeSize, _, _) | readIndex >= maxi = writeBitsGif bitWriter (fromIntegral endOfInfo) codeSize go !readIndex (!codeSize, !writeIndex, !trie) = do let (indexToWrite, endIndex, trie') = lookuper writeIndex readIndex trie writeBitsGif bitWriter (fromIntegral indexToWrite) codeSize updateCodeSize codeSize writeIndex trie' >>= go endIndex writeBitsGif bitWriter (fromIntegral clearCode) startCodeSize go 0 (startCodeSize, firstFreeIndex, initialTrie) finalizeBoolWriter bitWriter where maxi = V.length vec startCodeSize = initialKeySize + 1 clearCode = 2 ^ initialKeySize :: Int endOfInfo = clearCode + 1 firstFreeIndex = endOfInfo + 1 lookuper = lookupUpdate vec
null
https://raw.githubusercontent.com/def-/time.gif/24bd06b2d496f1e45345f6489e80c679b8a7497b/Codec/Picture/Gif/LZWEncoding.hs
haskell
# UNPACK #
# LANGUAGE BangPatterns , CPP # module Codec.Picture.Gif.LZWEncoding( lzwEncode ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative( (<$>) ) import Data.Monoid( mempty ) #endif import Control.Monad.ST( runST ) import qualified Data.ByteString.Lazy as L import Data.Maybe( fromMaybe ) import Data.Word( Word8 ) #if MIN_VERSION_containers(0,5,0) import qualified Data.IntMap.Strict as I #else import qualified Data.IntMap as I #endif import qualified Data.Vector.Storable as V import Codec.Picture.BitWriter type Trie = I.IntMap TrieNode data TrieNode = TrieNode , trieSub :: !Trie } emptyNode :: TrieNode emptyNode = TrieNode { trieIndex = -1 , trieSub = mempty } initialTrie :: Trie initialTrie = I.fromList [(i, emptyNode { trieIndex = i }) | i <- [0 .. 255]] lookupUpdate :: V.Vector Word8 -> Int -> Int -> Trie -> (Int, Int, Trie) lookupUpdate vector freeIndex firstIndex trie = matchUpdate $ go trie 0 firstIndex where matchUpdate (lzwOutputIndex, nextReadIndex, sub) = (lzwOutputIndex, nextReadIndex, fromMaybe trie sub) maxi = V.length vector go !currentTrie !prevIndex !index | index >= maxi = (prevIndex, index, Nothing) | otherwise = case I.lookup val currentTrie of Just (TrieNode ix subTable) -> let (lzwOutputIndex, nextReadIndex, newTable) = go subTable ix $ index + 1 tableUpdater t = I.insert val (TrieNode ix t) currentTrie in (lzwOutputIndex, nextReadIndex, tableUpdater <$> newTable) Nothing | index == maxi -> (prevIndex, index, Nothing) | otherwise -> (prevIndex, index, Just $ I.insert val newNode currentTrie) where val = fromIntegral $ vector `V.unsafeIndex` index newNode = emptyNode { trieIndex = freeIndex } lzwEncode :: Int -> V.Vector Word8 -> L.ByteString lzwEncode initialKeySize vec = runST $ do bitWriter <- newWriteStateRef let updateCodeSize 12 writeIdx _ | writeIdx == 2 ^ (12 :: Int) - 1 = do writeBitsGif bitWriter (fromIntegral clearCode) 12 return (startCodeSize, firstFreeIndex, initialTrie) updateCodeSize codeSize writeIdx trie | writeIdx == 2 ^ codeSize = return (codeSize + 1, writeIdx + 1, trie) | otherwise = return (codeSize, writeIdx + 1, trie) go readIndex (codeSize, _, _) | readIndex >= maxi = writeBitsGif bitWriter (fromIntegral endOfInfo) codeSize go !readIndex (!codeSize, !writeIndex, !trie) = do let (indexToWrite, endIndex, trie') = lookuper writeIndex readIndex trie writeBitsGif bitWriter (fromIntegral indexToWrite) codeSize updateCodeSize codeSize writeIndex trie' >>= go endIndex writeBitsGif bitWriter (fromIntegral clearCode) startCodeSize go 0 (startCodeSize, firstFreeIndex, initialTrie) finalizeBoolWriter bitWriter where maxi = V.length vec startCodeSize = initialKeySize + 1 clearCode = 2 ^ initialKeySize :: Int endOfInfo = clearCode + 1 firstFreeIndex = endOfInfo + 1 lookuper = lookupUpdate vec
28e70e114c3d7aa4ccd1e40b17f81e8503b5363eec73e95e9129071a41240376
intolerable/intolerable-bot
Bot.hs
module Bot where import Args import Control.Applicative.Trans.Either import Control.Concurrent.WriteSem import Control.Concurrent import Control.Concurrent.Async import Control.Exception (catchJust) import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Reader import Data.Binary import Data.Char import Data.Classifier.NaiveBayes (NaiveBayes) import Data.Coerce import Data.Default.Class import Data.Function (fix) import Data.Maybe import Data.Monoid ((<>)) import Data.Text (Text) import Data.Time.Clock import Data.Time.Format import Data.Yaml import Reddit hiding (failWith, bans) import Reddit.Types.Comment (PostComments(..), CommentReference(..)) import Reddit.Types.Listing import Reddit.Types.Subreddit (SubredditName(..)) import Reddit.Types.User (Username(..)) import System.Exit import System.IO import System.IO.Error import qualified Data.Bounded.Set as Bounded import qualified Data.Classifier.NaiveBayes as NB import qualified Data.Counter as Counter import qualified Data.Map as Map import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified Reddit.Types.Comment as Comment import qualified Reddit.Types.Post as Post data ConcreteSettings = ConcreteSettings { username :: Username , password :: Password , subreddit :: SubredditName , replyText :: ReplyText , refreshTime :: RefreshTime , bans :: [Username] , classifier :: Maybe (NaiveBayes Bool Text) , useClassifier :: Bool , verboseOutput :: Bool } deriving (Show) main :: IO () main = do hSetBuffering stdout NoBuffering hSetBuffering stderr NoBuffering ConfigFile fp <- optionsFromArgs decodeFileEither fp >>= \case Left err -> do print err exitFailure Right (Config b m) -> do resolvedSettings <- mapM confirm $ resolve b m let (lefts, rights) = Map.mapEither id resolvedSettings if Map.null lefts then do sem <- newWriteSemIO void $ mapConcurrently (\(k, s) -> run sem (s k)) $ Map.toList rights else do Map.foldrWithKey handleError (return ()) lefts exitFailure handleError :: SubredditName -> [Text] -> IO () -> IO () handleError (R r) errs m = m >> do Text.putStrLn $ pluralize errs "Error" <> " with settings for subreddit /r/" <> r <> ":" forM_ errs $ \err -> Text.putStr $ " - " <> err pluralize :: [a] -> Text -> Text pluralize [_] x = x pluralize _ x = x <> "s" confirm :: Settings -> IO (Either [Text] (SubredditName -> ConcreteSettings)) confirm (Settings u p r b t c x v) = runEitherA $ subredditLastSettings <$> justOr ["Missing username"] u <*> justOr ["Missing password"] p <*> loadReply r <*> pure (fromMaybe 5 t) <*> loadBans b <*> sequenceA (fmap loadClassifier c) <*> pure x <*> pure (fromMaybe False v) subredditLastSettings :: Username -> Password -> ReplyText -> RefreshTime -> [Username] -> Maybe (NaiveBayes Bool Text) -> Bool -> Bool -> SubredditName -> ConcreteSettings subredditLastSettings u p r t b n x v s = ConcreteSettings u p s r t b n x v loadBans :: [Bans] -> EitherA [Text] IO [Username] loadBans = fmap concat . sequenceA . map f where f (BansList us) = pure us f (BansFilePath fp) = EitherA $ decodeFileEither fp >>= \case Left err -> return $ Left [Text.pack $ show err] Right xs -> return $ Right $ map Username xs loadReply :: Maybe Reply -> EitherA [Text] IO ReplyText loadReply x = case x of Just r -> case r of ReplyLiteral lit -> pure lit ReplyFilePath fp -> readReplyFile fp Nothing -> failWith ["Missing reply"] readReplyFile :: FilePath -> EitherA [Text] IO ReplyText readReplyFile fp = EitherA $ catchJust f (Right <$> Text.readFile fp) (return . Left . return) where f (isDoesNotExistError -> True) = Just "Reply file does not exist" f (isPermissionError -> True) = Just "Incorrect permissions for reply file" f _ = Nothing loadClassifier :: FilePath -> EitherA [Text] IO (NaiveBayes Bool Text) loadClassifier fp = EitherA $ f <$> decodeFileOrFail fp where f (Left _) = Left ["Classifier could not be read"] f (Right x) = pure x run :: WriteSem -> ConcreteSettings -> IO () run sem settings = withAsync (loopWith (forever $ commentsLoop sem) sem settings) $ \c -> case classifier settings of Just _ -> withAsync (loopWith (forever $ postsLoop sem) sem settings) $ \p -> void $ waitBoth c p Nothing -> wait c loopWith :: RedditT (ReaderT ConcreteSettings IO) () -> WriteSem -> ConcreteSettings -> IO () loopWith act sem settings = do res <- flip runReaderT settings $ runResumeRedditWith def { customUserAgent = Just "intolerable-bot v0.1.0.0" , loginMethod = Credentials (coerce (username settings)) (password settings) , rateLimitingEnabled = False } act case res of Left (APIError CredentialsError, _) -> withWriteSem sem $ Text.putStrLn $ "Username / password details incorrect for /r/" <> coerce (subreddit settings) Left (err, Nothing) -> do liftIO $ print err (5 * refreshTime settings) `seconds` threadDelay loopWith act sem settings Left (err, Just resume) -> do liftIO $ print err loopWith resume sem settings Right () -> return () postsLoop :: WriteSem -> RedditT (ReaderT ConcreteSettings IO) () postsLoop sem = do u <- lift $ asks username r <- lift $ asks subreddit t <- lift $ asks refreshTime rt <- lift $ asks replyText cls <- lift $ asks (fromJust . classifier) use <- lift $ asks useClassifier withInitial (Bounded.empty 500) $ \loop set -> do Listing _ _ ps <- getPosts' (Options Nothing (Just 100)) New (Just r) writeLogEntry sem r "got listing" let news = filter (\x -> not $ Bounded.member (Post.postID x) set) ps forM_ news $ \p -> unless (Post.author p == u) $ case Post.content p of Post.SelfPost m _ -> do let c = Counter.fromList $ process m case NB.test cls c of Just True -> if use then do PostComments _ cs <- getPostComments $ Post.postID p actuals <- resolveComments (Post.postID p) cs unless (any ((== u) . Comment.author) actuals) $ do botReply <- reply p rt writeLogEntry sem r $ mconcat [ "Auto-responded to " , coerce $ Post.postID p , " (" , coerce botReply , ")" ] else writeLogEntry sem r $ mconcat [ "Possible AI match @ " , coerce $ Post.postID p ] _ -> return () _ -> return () unless (null news) $ writeLogEntry sem r "got listing" t `seconds` threadDelay loop $ Bounded.insertAll (Post.postID <$> news) set commentsLoop :: WriteSem -> RedditT (ReaderT ConcreteSettings IO) () commentsLoop sem = do r <- lift $ asks subreddit t <- lift $ asks refreshTime withInitial (Bounded.empty 500) $ \loop set -> do Listing _ _ cs <- getNewComments' (Options Nothing (Just 100)) (Just r) let news = filter (\x -> not $ Bounded.member (Comment.commentID x) set) cs mapM_ (commentResponder sem) news unless (null news) $ writeLogEntry sem r "dealt with new comments" t `seconds` threadDelay loop $ Bounded.insertAll (Comment.commentID <$> news) set commentResponder :: WriteSem -> Comment -> RedditT (ReaderT ConcreteSettings IO) () commentResponder sem c = do u <- lift $ asks username r <- lift $ asks subreddit rt <- lift $ asks replyText bs <- lift $ asks bans when (shouldRespond u (Comment.body c)) $ unless (Comment.author c `elem` bs) $ do writeLogEntry sem r "found a comment" (selfpost, sibs) <- getSiblingComments c unless (any ((== u) . Comment.author) sibs) $ do writeLogEntry sem r $ "found a comment we didn't already respond to: " <> coerce (Comment.commentID c) case Comment.inReplyTo c of Just parentComment -> reply parentComment rt >>= logReply r Nothing -> when selfpost $ reply (Comment.parentLink c) rt >>= logReply r where logReply r botReply = writeLogEntry sem r $ mconcat [ "Responded to " , coerce (Comment.commentID c) , " by " , coerce (Comment.author c) , " (" , coerce botReply , ")" ] getSiblingComments :: MonadIO m => Comment -> RedditT m (Bool, [Comment]) getSiblingComments c = do let parent = Comment.parentLink c PostComments p cs <- case Comment.inReplyTo c of Just parentComment -> getPostSubComments parent parentComment >>= \case PostComments p (com:_) -> do Listing _ _ cs <- mconcat <$> map Comment.replies <$> resolveComments parent [com] return $ PostComments p cs x -> return x Nothing -> getPostComments parent case Post.content p of Post.SelfPost _ _ -> (,) True <$> resolveComments parent cs _ -> (,) (isJust (Comment.inReplyTo c)) <$> resolveComments parent cs resolveComments :: MonadIO m => PostID -> [CommentReference] -> RedditT m [Comment] resolveComments p refs = concat <$> mapM f refs where f (Actual c) = return [c] f (Reference _ cs) = do moreComments <- getMoreChildren p cs resolveComments p moreComments shouldRespond :: Username -> Text -> Bool shouldRespond (Username u) = Text.isInfixOf (Text.toCaseFold $ "u/" <> u) . Text.toCaseFold withInitial :: a -> ((a -> b) -> a -> b) -> b withInitial = flip fix seconds :: MonadIO m => Int -> (Int -> IO ()) -> m () n `seconds` f = liftIO $ f $ n * 1000000 writeLogEntry :: MonadIO m => WriteSem -> SubredditName -> Text -> m () writeLogEntry sem (R r) t = do time <- liftIO getCurrentTime let space = " " withWriteSem sem $ mapM_ Text.putStr [ makeTime time , space , "/r/" , r , ": " , t , "\n" ] makeTime :: UTCTime -> Text makeTime t = Text.pack $ formatTime defaultTimeLocale (iso8601DateFormat (Just "%H:%M:%S")) t process :: Text -> [Text] process = filter (not . Text.null) . map (Text.map toLower . Text.filter isAlpha) . concatMap (Text.splitOn ".") . Text.splitOn " " . Text.filter (not . (== '-'))
null
https://raw.githubusercontent.com/intolerable/intolerable-bot/245f687ea8c6d7af5e74f412409bae4a75b816fb/src/Bot.hs
haskell
module Bot where import Args import Control.Applicative.Trans.Either import Control.Concurrent.WriteSem import Control.Concurrent import Control.Concurrent.Async import Control.Exception (catchJust) import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Reader import Data.Binary import Data.Char import Data.Classifier.NaiveBayes (NaiveBayes) import Data.Coerce import Data.Default.Class import Data.Function (fix) import Data.Maybe import Data.Monoid ((<>)) import Data.Text (Text) import Data.Time.Clock import Data.Time.Format import Data.Yaml import Reddit hiding (failWith, bans) import Reddit.Types.Comment (PostComments(..), CommentReference(..)) import Reddit.Types.Listing import Reddit.Types.Subreddit (SubredditName(..)) import Reddit.Types.User (Username(..)) import System.Exit import System.IO import System.IO.Error import qualified Data.Bounded.Set as Bounded import qualified Data.Classifier.NaiveBayes as NB import qualified Data.Counter as Counter import qualified Data.Map as Map import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified Reddit.Types.Comment as Comment import qualified Reddit.Types.Post as Post data ConcreteSettings = ConcreteSettings { username :: Username , password :: Password , subreddit :: SubredditName , replyText :: ReplyText , refreshTime :: RefreshTime , bans :: [Username] , classifier :: Maybe (NaiveBayes Bool Text) , useClassifier :: Bool , verboseOutput :: Bool } deriving (Show) main :: IO () main = do hSetBuffering stdout NoBuffering hSetBuffering stderr NoBuffering ConfigFile fp <- optionsFromArgs decodeFileEither fp >>= \case Left err -> do print err exitFailure Right (Config b m) -> do resolvedSettings <- mapM confirm $ resolve b m let (lefts, rights) = Map.mapEither id resolvedSettings if Map.null lefts then do sem <- newWriteSemIO void $ mapConcurrently (\(k, s) -> run sem (s k)) $ Map.toList rights else do Map.foldrWithKey handleError (return ()) lefts exitFailure handleError :: SubredditName -> [Text] -> IO () -> IO () handleError (R r) errs m = m >> do Text.putStrLn $ pluralize errs "Error" <> " with settings for subreddit /r/" <> r <> ":" forM_ errs $ \err -> Text.putStr $ " - " <> err pluralize :: [a] -> Text -> Text pluralize [_] x = x pluralize _ x = x <> "s" confirm :: Settings -> IO (Either [Text] (SubredditName -> ConcreteSettings)) confirm (Settings u p r b t c x v) = runEitherA $ subredditLastSettings <$> justOr ["Missing username"] u <*> justOr ["Missing password"] p <*> loadReply r <*> pure (fromMaybe 5 t) <*> loadBans b <*> sequenceA (fmap loadClassifier c) <*> pure x <*> pure (fromMaybe False v) subredditLastSettings :: Username -> Password -> ReplyText -> RefreshTime -> [Username] -> Maybe (NaiveBayes Bool Text) -> Bool -> Bool -> SubredditName -> ConcreteSettings subredditLastSettings u p r t b n x v s = ConcreteSettings u p s r t b n x v loadBans :: [Bans] -> EitherA [Text] IO [Username] loadBans = fmap concat . sequenceA . map f where f (BansList us) = pure us f (BansFilePath fp) = EitherA $ decodeFileEither fp >>= \case Left err -> return $ Left [Text.pack $ show err] Right xs -> return $ Right $ map Username xs loadReply :: Maybe Reply -> EitherA [Text] IO ReplyText loadReply x = case x of Just r -> case r of ReplyLiteral lit -> pure lit ReplyFilePath fp -> readReplyFile fp Nothing -> failWith ["Missing reply"] readReplyFile :: FilePath -> EitherA [Text] IO ReplyText readReplyFile fp = EitherA $ catchJust f (Right <$> Text.readFile fp) (return . Left . return) where f (isDoesNotExistError -> True) = Just "Reply file does not exist" f (isPermissionError -> True) = Just "Incorrect permissions for reply file" f _ = Nothing loadClassifier :: FilePath -> EitherA [Text] IO (NaiveBayes Bool Text) loadClassifier fp = EitherA $ f <$> decodeFileOrFail fp where f (Left _) = Left ["Classifier could not be read"] f (Right x) = pure x run :: WriteSem -> ConcreteSettings -> IO () run sem settings = withAsync (loopWith (forever $ commentsLoop sem) sem settings) $ \c -> case classifier settings of Just _ -> withAsync (loopWith (forever $ postsLoop sem) sem settings) $ \p -> void $ waitBoth c p Nothing -> wait c loopWith :: RedditT (ReaderT ConcreteSettings IO) () -> WriteSem -> ConcreteSettings -> IO () loopWith act sem settings = do res <- flip runReaderT settings $ runResumeRedditWith def { customUserAgent = Just "intolerable-bot v0.1.0.0" , loginMethod = Credentials (coerce (username settings)) (password settings) , rateLimitingEnabled = False } act case res of Left (APIError CredentialsError, _) -> withWriteSem sem $ Text.putStrLn $ "Username / password details incorrect for /r/" <> coerce (subreddit settings) Left (err, Nothing) -> do liftIO $ print err (5 * refreshTime settings) `seconds` threadDelay loopWith act sem settings Left (err, Just resume) -> do liftIO $ print err loopWith resume sem settings Right () -> return () postsLoop :: WriteSem -> RedditT (ReaderT ConcreteSettings IO) () postsLoop sem = do u <- lift $ asks username r <- lift $ asks subreddit t <- lift $ asks refreshTime rt <- lift $ asks replyText cls <- lift $ asks (fromJust . classifier) use <- lift $ asks useClassifier withInitial (Bounded.empty 500) $ \loop set -> do Listing _ _ ps <- getPosts' (Options Nothing (Just 100)) New (Just r) writeLogEntry sem r "got listing" let news = filter (\x -> not $ Bounded.member (Post.postID x) set) ps forM_ news $ \p -> unless (Post.author p == u) $ case Post.content p of Post.SelfPost m _ -> do let c = Counter.fromList $ process m case NB.test cls c of Just True -> if use then do PostComments _ cs <- getPostComments $ Post.postID p actuals <- resolveComments (Post.postID p) cs unless (any ((== u) . Comment.author) actuals) $ do botReply <- reply p rt writeLogEntry sem r $ mconcat [ "Auto-responded to " , coerce $ Post.postID p , " (" , coerce botReply , ")" ] else writeLogEntry sem r $ mconcat [ "Possible AI match @ " , coerce $ Post.postID p ] _ -> return () _ -> return () unless (null news) $ writeLogEntry sem r "got listing" t `seconds` threadDelay loop $ Bounded.insertAll (Post.postID <$> news) set commentsLoop :: WriteSem -> RedditT (ReaderT ConcreteSettings IO) () commentsLoop sem = do r <- lift $ asks subreddit t <- lift $ asks refreshTime withInitial (Bounded.empty 500) $ \loop set -> do Listing _ _ cs <- getNewComments' (Options Nothing (Just 100)) (Just r) let news = filter (\x -> not $ Bounded.member (Comment.commentID x) set) cs mapM_ (commentResponder sem) news unless (null news) $ writeLogEntry sem r "dealt with new comments" t `seconds` threadDelay loop $ Bounded.insertAll (Comment.commentID <$> news) set commentResponder :: WriteSem -> Comment -> RedditT (ReaderT ConcreteSettings IO) () commentResponder sem c = do u <- lift $ asks username r <- lift $ asks subreddit rt <- lift $ asks replyText bs <- lift $ asks bans when (shouldRespond u (Comment.body c)) $ unless (Comment.author c `elem` bs) $ do writeLogEntry sem r "found a comment" (selfpost, sibs) <- getSiblingComments c unless (any ((== u) . Comment.author) sibs) $ do writeLogEntry sem r $ "found a comment we didn't already respond to: " <> coerce (Comment.commentID c) case Comment.inReplyTo c of Just parentComment -> reply parentComment rt >>= logReply r Nothing -> when selfpost $ reply (Comment.parentLink c) rt >>= logReply r where logReply r botReply = writeLogEntry sem r $ mconcat [ "Responded to " , coerce (Comment.commentID c) , " by " , coerce (Comment.author c) , " (" , coerce botReply , ")" ] getSiblingComments :: MonadIO m => Comment -> RedditT m (Bool, [Comment]) getSiblingComments c = do let parent = Comment.parentLink c PostComments p cs <- case Comment.inReplyTo c of Just parentComment -> getPostSubComments parent parentComment >>= \case PostComments p (com:_) -> do Listing _ _ cs <- mconcat <$> map Comment.replies <$> resolveComments parent [com] return $ PostComments p cs x -> return x Nothing -> getPostComments parent case Post.content p of Post.SelfPost _ _ -> (,) True <$> resolveComments parent cs _ -> (,) (isJust (Comment.inReplyTo c)) <$> resolveComments parent cs resolveComments :: MonadIO m => PostID -> [CommentReference] -> RedditT m [Comment] resolveComments p refs = concat <$> mapM f refs where f (Actual c) = return [c] f (Reference _ cs) = do moreComments <- getMoreChildren p cs resolveComments p moreComments shouldRespond :: Username -> Text -> Bool shouldRespond (Username u) = Text.isInfixOf (Text.toCaseFold $ "u/" <> u) . Text.toCaseFold withInitial :: a -> ((a -> b) -> a -> b) -> b withInitial = flip fix seconds :: MonadIO m => Int -> (Int -> IO ()) -> m () n `seconds` f = liftIO $ f $ n * 1000000 writeLogEntry :: MonadIO m => WriteSem -> SubredditName -> Text -> m () writeLogEntry sem (R r) t = do time <- liftIO getCurrentTime let space = " " withWriteSem sem $ mapM_ Text.putStr [ makeTime time , space , "/r/" , r , ": " , t , "\n" ] makeTime :: UTCTime -> Text makeTime t = Text.pack $ formatTime defaultTimeLocale (iso8601DateFormat (Just "%H:%M:%S")) t process :: Text -> [Text] process = filter (not . Text.null) . map (Text.map toLower . Text.filter isAlpha) . concatMap (Text.splitOn ".") . Text.splitOn " " . Text.filter (not . (== '-'))
6a2058fc2644ac33b5598a3b33974a8eb6270aa188fc743c5782c30d0928cf48
typedclojure/typedclojure
local.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.cljc.checker.check.local (:require [typed.cljc.checker.local-result :as local-result] [typed.cljc.checker.utils :as u])) (defn check-local [{sym :name :as expr} expected] (assoc expr u/expr-type (local-result/local-result expr sym expected)))
null
https://raw.githubusercontent.com/typedclojure/typedclojure/45556897356f3c9cbc7b1b6b4df263086a9d5803/typed/clj.checker/src/typed/cljc/checker/check/local.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.
Copyright ( c ) , contributors . (ns typed.cljc.checker.check.local (:require [typed.cljc.checker.local-result :as local-result] [typed.cljc.checker.utils :as u])) (defn check-local [{sym :name :as expr} expected] (assoc expr u/expr-type (local-result/local-result expr sym expected)))
69c83278d324a975511dda6102c1a41d07fcdd5bbe4a81922bd3135b36ab1f2d
mejgun/haskell-tdlib
GetEmojiReaction.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Query.GetEmojiReaction where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U -- | Returns information about a emoji reaction . Returns a 404 error if the reaction is not found @emoji Text representation of the reaction data GetEmojiReaction = GetEmojiReaction { -- | emoji :: Maybe String } deriving (Eq) instance Show GetEmojiReaction where show GetEmojiReaction { emoji = emoji_ } = "GetEmojiReaction" ++ U.cc [ U.p "emoji" emoji_ ] instance T.ToJSON GetEmojiReaction where toJSON GetEmojiReaction { emoji = emoji_ } = A.object [ "@type" A..= T.String "getEmojiReaction", "emoji" A..= emoji_ ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/e5c8059a74f88073b27dbfafb6908de0729af110/src/TD/Query/GetEmojiReaction.hs
haskell
# LANGUAGE OverloadedStrings # | | |
module TD.Query.GetEmojiReaction where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U Returns information about a emoji reaction . Returns a 404 error if the reaction is not found @emoji Text representation of the reaction data GetEmojiReaction = GetEmojiReaction emoji :: Maybe String } deriving (Eq) instance Show GetEmojiReaction where show GetEmojiReaction { emoji = emoji_ } = "GetEmojiReaction" ++ U.cc [ U.p "emoji" emoji_ ] instance T.ToJSON GetEmojiReaction where toJSON GetEmojiReaction { emoji = emoji_ } = A.object [ "@type" A..= T.String "getEmojiReaction", "emoji" A..= emoji_ ]
88709873b6a92f7c1d01ddf0ac6dc7bd4cb0bd21a1b42c17b2c4fec177dab787
kana/sicp
ex-4.32.scm
Exercise 4.32 . Give some examples that illustrate the difference between the streams of chapter 3 and the ` ` lazier '' lazy lists described in this ;;; section. How can you take advantage of this extra laziness? ; We can construct linear lists of infinite length with the streams, ; but we can construct trees of infinite depth with the lazier lazy lists. ; For example... (load "./sec-4.1.1.scm") (load "./sec-4.1.2.scm") (load "./sec-4.1.3.scm") (load "./sec-4.1.4.scm") (load "./sec-4.2.2.scm") (define code '((define (cons x y) (lambda (m) (m x y))) (define (car z) (z (lambda (p q) p))) (define (cdr z) (z (lambda (p q) q))) (define (make-tree value left right) (cons value (cons left right))) (define nil-tree (make-tree "X" "X" "X")) (define (nil-tree? tree) (eq? tree nil-tree)) (define (tree-value tree) (car tree)) (define (tree-left tree) (car (cdr tree))) (define (tree-right tree) (cdr (cdr tree))) (define (make-random-tree value) (make-tree value (if (= (modulo value 5) 0) nil-tree (make-random-tree (+ value 3))) (if (= (modulo value 8) 0) nil-tree (make-random-tree (* value 2))))) (define (display-tree tree depth-limit) (define (go tree d) (cond ((nil-tree? tree) (print (indent d "-"))) (else (print (indent d (tree-value tree))) (cond ((>= (+ d 1) depth-limit) (print (indent d "..."))) (else (print (indent d "Left:")) (go (tree-left tree) (+ d 1)) (print (indent d "Right:")) (go (tree-right tree) (+ d 1))))))) (go tree 0)) (display-tree (make-random-tree 3) 3) (display-tree (make-random-tree 3) 8) )) (define (main args) (for-each (lambda (expr) (print expr) (print "==> " (actual-value expr the-global-environment))) code))
null
https://raw.githubusercontent.com/kana/sicp/912bda4276995492ffc2ec971618316701e196f6/ex-4.32.scm
scheme
section. How can you take advantage of this extra laziness? We can construct linear lists of infinite length with the streams, but we can construct trees of infinite depth with the lazier lazy lists. For example...
Exercise 4.32 . Give some examples that illustrate the difference between the streams of chapter 3 and the ` ` lazier '' lazy lists described in this (load "./sec-4.1.1.scm") (load "./sec-4.1.2.scm") (load "./sec-4.1.3.scm") (load "./sec-4.1.4.scm") (load "./sec-4.2.2.scm") (define code '((define (cons x y) (lambda (m) (m x y))) (define (car z) (z (lambda (p q) p))) (define (cdr z) (z (lambda (p q) q))) (define (make-tree value left right) (cons value (cons left right))) (define nil-tree (make-tree "X" "X" "X")) (define (nil-tree? tree) (eq? tree nil-tree)) (define (tree-value tree) (car tree)) (define (tree-left tree) (car (cdr tree))) (define (tree-right tree) (cdr (cdr tree))) (define (make-random-tree value) (make-tree value (if (= (modulo value 5) 0) nil-tree (make-random-tree (+ value 3))) (if (= (modulo value 8) 0) nil-tree (make-random-tree (* value 2))))) (define (display-tree tree depth-limit) (define (go tree d) (cond ((nil-tree? tree) (print (indent d "-"))) (else (print (indent d (tree-value tree))) (cond ((>= (+ d 1) depth-limit) (print (indent d "..."))) (else (print (indent d "Left:")) (go (tree-left tree) (+ d 1)) (print (indent d "Right:")) (go (tree-right tree) (+ d 1))))))) (go tree 0)) (display-tree (make-random-tree 3) 3) (display-tree (make-random-tree 3) 8) )) (define (main args) (for-each (lambda (expr) (print expr) (print "==> " (actual-value expr the-global-environment))) code))
e1cbc1cd777b07e8cf11f8b2b36c38734278dd86c34cc31b4f6b8176f1fa464a
racket/plot
low-level-tests.rkt
#lang racket (module typed-tests typed/racket (require typed/rackunit (except-in racket/date find-seconds) plot plot/utils plot/private/common/utils plot/private/common/math plot/private/common/date-time plot/private/common/format) (require/typed racket/date [find-seconds (-> Integer Integer Integer Integer Integer Integer Boolean Integer)]) (check-equal? (linear-seq 1 1 2) '(1 1)) (check-equal? (linear-seq 0 1 2 #:start? #t #:end? #t) '(0 1)) (check-equal? (linear-seq 0 1 2 #:start? #t #:end? #f) '(0 2/3)) (check-equal? (linear-seq 0 1 2 #:start? #f #:end? #t) '(1/3 1)) (check-equal? (linear-seq 0 1 2 #:start? #f #:end? #f) '(1/4 3/4)) (check-equal? (linear-seq 1 0 2 #:start? #t #:end? #t) '(1 0)) (check-equal? (linear-seq 1 0 2 #:start? #t #:end? #f) '(1 1/3)) (check-equal? (linear-seq 1 0 2 #:start? #f #:end? #t) '(2/3 0)) (check-equal? (linear-seq 1 0 2 #:start? #f #:end? #f) '(3/4 1/4)) ;; ================================================================================================= ;; Formatting (check-equal? (int-str->e-str "") "0") (check-equal? (int-str->e-str "0") "0") (check-equal? (int-str->e-str "10") "1×10\u00b9") (check-equal? (frac-str->e-str "") "0") (check-equal? (frac-str->e-str "0") "0") (check-equal? (frac-str->e-str "00") "0") (check-equal? (frac-str->e-str "1") "1×10\u207b\u00b9") (check-equal? (frac-str->e-str "01") "1×10\u207b\u00b2") ;; ================================================================================================= ;; Date rounding (check-equal? (utc-seconds-round-year (find-seconds 0 0 12 2 7 1970 #f)) (find-seconds 0 0 0 1 1 1970 #f)) (check-equal? (utc-seconds-round-year (find-seconds 0 0 13 2 7 1970 #f)) (find-seconds 0 0 0 1 1 1971 #f)) A leap year 's middle is a half day earlier on the calendar : (check-equal? (utc-seconds-round-year (find-seconds 0 0 0 2 7 1976 #f)) (find-seconds 0 0 0 1 1 1976 #f)) (check-equal? (utc-seconds-round-year (find-seconds 0 0 1 2 7 1976 #f)) (find-seconds 0 0 0 1 1 1977 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 0 16 1 2010 #f)) (find-seconds 0 0 0 1 1 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 0 17 1 2010 #f)) (find-seconds 0 0 0 1 2 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 12 16 1 2010 #f)) (find-seconds 0 0 0 1 1 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 13 16 1 2010 #f)) (find-seconds 0 0 0 1 2 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 0 16 12 2010 #f)) (find-seconds 0 0 0 1 12 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 0 17 12 2010 #f)) (find-seconds 0 0 0 1 1 2011 #f)) ;; ================================================================================================= Time conversion (check-equal? (seconds->plot-time 0) (plot-time 0 0 0 0)) (check-equal? (seconds->plot-time #e59.999999) (plot-time #e59.999999 0 0 0)) (check-equal? (seconds->plot-time 60) (plot-time 0 1 0 0)) (check-equal? (seconds->plot-time #e60.000001) (plot-time #e0.000001 1 0 0)) (check-equal? (seconds->plot-time #e119.999999) (plot-time #e59.999999 1 0 0)) (check-equal? (seconds->plot-time 120) (plot-time 0 2 0 0)) (check-equal? (seconds->plot-time #e120.000001) (plot-time #e0.000001 2 0 0)) (check-equal? (seconds->plot-time 3599) (plot-time 59 59 0 0)) (check-equal? (seconds->plot-time 3600) (plot-time 0 0 1 0)) (check-equal? (seconds->plot-time 3601) (plot-time 1 0 1 0)) (check-equal? (seconds->plot-time (- seconds-per-day 1)) (plot-time 59 59 23 0)) (check-equal? (seconds->plot-time seconds-per-day) (plot-time 0 0 0 1)) (check-equal? (seconds->plot-time (- seconds-per-day)) (plot-time 0 0 0 -1)) (check-equal? (seconds->plot-time (- (- seconds-per-day) 1)) (plot-time 59 59 23 -2)) (define sec-secs (sequence->list (in-range -60 61 #e0.571123))) (define min-secs (sequence->list (in-range (- seconds-per-hour) (+ seconds-per-hour 1) (* #e0.571123 seconds-per-minute)))) (define hour-secs (sequence->list (in-range (- seconds-per-day) (+ seconds-per-day 1) (* #e0.571123 seconds-per-hour)))) (define day-secs (sequence->list (in-range (- seconds-per-week) (+ seconds-per-week 1) (* #e0.571123 seconds-per-day)))) (check-equal? (map (compose plot-time->seconds seconds->plot-time) sec-secs) sec-secs) (check-equal? (map (compose plot-time->seconds seconds->plot-time) min-secs) min-secs) (check-equal? (map (compose plot-time->seconds seconds->plot-time) hour-secs) hour-secs) (check-equal? (map (compose plot-time->seconds seconds->plot-time) day-secs) day-secs) ;; ================================================================================================= ;; Intervals (check-false (ivl-rational? (ivl #f #f))) (check-false (ivl-rational? (ivl +nan.0 +nan.0))) (check-true (ivl-empty? (ivl-meet empty-ivl (ivl 0 3)))) ;;; ivl-meet (similar to an intersection) ;; All specified (check-true (ivl-empty? (ivl-meet (ivl 0 1) (ivl 2 3)))) (check-equal? (ivl-meet (ivl 0 2) (ivl 1 3)) (ivl 1 2)) (check-equal? (ivl-meet (ivl 0 3) (ivl 1 2)) (ivl 1 2)) ;; One not specified < --- 1 2 -- 3 (check-true (ivl-empty? (ivl-meet (ivl #f 1) (ivl 2 3)))) 0 -- 1 2 --- > (check-true (ivl-empty? (ivl-meet (ivl 0 1) (ivl 2 #f)))) < -------- 2 1 ------- 3 (check-equal? (ivl-meet (ivl #f 2) (ivl 1 3)) (ivl 1 2)) 2 --- > 0 ------------ 3 (check-equal? (ivl-meet (ivl 2 #f) (ivl 0 3)) (ivl 2 3)) < ------------- 3 1 -- 2 (check-equal? (ivl-meet (ivl #f 3) (ivl 1 2)) (ivl 1 2)) ;; 0 -------------> 1 -- 2 (check-equal? (ivl-meet (ivl 0 #f) (ivl 1 2)) (ivl 1 2)) Two not specified < --- 1 2 --- > (check-true (ivl-empty? (ivl-meet (ivl #f 1) (ivl 2 #f)))) ;; <--------------> 1 -- 2 (check-equal? (ivl-meet (ivl #f #f) (ivl 1 2)) (ivl 1 2)) 1 -------- > < -------- 2 (check-equal? (ivl-meet (ivl 1 #f) (ivl #f 2)) (ivl 1 2)) < -------- 2 < ------------- 3 (check-equal? (ivl-meet (ivl #f 2) (ivl #f 3)) (ivl #f 2)) ;; 0 -------------> 1 -------- > (check-equal? (ivl-meet (ivl 0 #f) (ivl 1 #f)) (ivl 1 #f)) Three not specified ;; <--------------> 1 -------- > (check-equal? (ivl-meet (ivl #f #f) (ivl 1 #f)) (ivl 1 #f)) ;; <--------------> < -------- 2 (check-equal? (ivl-meet (ivl #f #f) (ivl #f 2)) (ivl #f 2)) Four not specified (check-equal? (ivl-meet (ivl #f #f) (ivl #f #f)) (ivl #f #f)) One infinite < --- 1 2 -- 3 (check-true (ivl-empty? (ivl-meet (ivl -inf.0 1) (ivl 2 3)))) 0 -- 1 2 --- > (check-true (ivl-empty? (ivl-meet (ivl 0 1) (ivl 2 +inf.0)))) < -------- 2 1 ------- 3 (check-equal? (ivl-meet (ivl -inf.0 2) (ivl 1 3)) (ivl 1 2)) 2 --- > 0 ------------ 3 (check-equal? (ivl-meet (ivl 2 +inf.0) (ivl 0 3)) (ivl 2 3)) < ------------- 3 1 -- 2 (check-equal? (ivl-meet (ivl -inf.0 3) (ivl 1 2)) (ivl 1 2)) ;; 0 -------------> 1 -- 2 (check-equal? (ivl-meet (ivl 0 +inf.0) (ivl 1 2)) (ivl 1 2)) Two infinite < --- 1 2 --- > (check-true (ivl-empty? (ivl-meet (ivl -inf.0 1) (ivl 2 +inf.0)))) ;; <--------------> 1 -- 2 (check-equal? (ivl-meet (ivl -inf.0 +inf.0) (ivl 1 2)) (ivl 1 2)) 1 -------- > < -------- 2 (check-equal? (ivl-meet (ivl 1 +inf.0) (ivl -inf.0 2)) (ivl 1 2)) < -------- 2 < ------------- 3 (check-equal? (ivl-meet (ivl -inf.0 2) (ivl -inf.0 3)) (ivl -inf.0 2)) ;; 0 -------------> 1 -------- > (check-equal? (ivl-meet (ivl 0 +inf.0) (ivl 1 +inf.0)) (ivl 1 +inf.0)) Three infinite ;; <--------------> 1 -------- > (check-equal? (ivl-meet (ivl -inf.0 +inf.0) (ivl 1 +inf.0)) (ivl 1 +inf.0)) ;; <--------------> < -------- 2 (check-equal? (ivl-meet (ivl -inf.0 +inf.0) (ivl -inf.0 2)) (ivl -inf.0 2)) Four infinite (check-equal? (ivl-meet (ivl -inf.0 +inf.0) (ivl -inf.0 +inf.0)) (ivl -inf.0 +inf.0)) ;;; ivl-join (similar to a union) (check-true (ivl-empty? (ivl-join empty-ivl empty-ivl))) (check-equal? (ivl-join empty-ivl (ivl 0 3)) (ivl 0 3)) ;; All specified (check-equal? (ivl-join (ivl 0 1) (ivl 2 3)) (ivl 0 3)) (check-equal? (ivl-join (ivl 0 2) (ivl 1 3)) (ivl 0 3)) (check-equal? (ivl-join (ivl 0 3) (ivl 1 2)) (ivl 0 3)) ;; One not specified < --- 1 2 -- 3 (check-equal? (ivl-join (ivl #f 1) (ivl 2 3)) (ivl 2 3)) 0 -- 1 2 --- > (check-equal? (ivl-join (ivl 0 1) (ivl 2 #f)) (ivl 0 1)) < -------- 2 1 ------- 3 (check-equal? (ivl-join (ivl #f 2) (ivl 1 3)) (ivl 1 3)) 2 --- > 0 ------------ 3 (check-equal? (ivl-join (ivl 2 #f) (ivl 0 3)) (ivl 0 3)) < ------------- 3 1 -- 2 (check-equal? (ivl-join (ivl #f 3) (ivl 1 2)) (ivl 1 3)) ;; 0 -------------> 1 -- 2 (check-equal? (ivl-join (ivl 0 #f) (ivl 1 2)) (ivl 0 2)) Two not specified < --- 1 2 --- > (check-equal? (ivl-join (ivl #f 1) (ivl 2 #f)) (ivl 1 2)) ;; <--------------> 1 -- 2 (check-equal? (ivl-join (ivl #f #f) (ivl 1 2)) (ivl 1 2)) 1 -------- > < -------- 2 (check-equal? (ivl-join (ivl 1 #f) (ivl #f 2)) (ivl 1 2)) < -------- 2 < ------------- 3 (check-equal? (ivl-join (ivl #f 2) (ivl #f 3)) (ivl #f 3)) ;; 0 -------------> 1 -------- > (check-equal? (ivl-join (ivl 0 #f) (ivl 1 #f)) (ivl 0 #f)) Three not specified ;; <--------------> 1 -------- > (check-equal? (ivl-join (ivl #f #f) (ivl 1 #f)) (ivl 1 #f)) ;; <--------------> < -------- 2 (check-equal? (ivl-join (ivl #f #f) (ivl #f 2)) (ivl #f 2)) Four not specified (check-equal? (ivl-join (ivl #f #f) (ivl #f #f)) (ivl #f #f)) One infinite < --- 1 2 -- 3 (check-equal? (ivl-join (ivl -inf.0 1) (ivl 2 3)) (ivl -inf.0 3)) 0 -- 1 2 --- > (check-equal? (ivl-join (ivl 0 1) (ivl 2 +inf.0)) (ivl 0 +inf.0)) < -------- 2 1 ------- 3 (check-equal? (ivl-join (ivl -inf.0 2) (ivl 1 3)) (ivl -inf.0 3)) 2 --- > 0 ------------ 3 (check-equal? (ivl-join (ivl 2 +inf.0) (ivl 0 3)) (ivl 0 +inf.0)) < ------------- 3 1 -- 2 (check-equal? (ivl-join (ivl -inf.0 3) (ivl 1 2)) (ivl -inf.0 3)) ;; 0 -------------> 1 -- 2 (check-equal? (ivl-join (ivl 0 +inf.0) (ivl 1 2)) (ivl 0 +inf.0)) Two infinite ;; <--------------> 1 -- 2 (check-equal? (ivl-join (ivl -inf.0 +inf.0) (ivl 1 2)) (ivl -inf.0 +inf.0)) 1 -------- > < -------- 2 (check-equal? (ivl-join (ivl 1 +inf.0) (ivl -inf.0 2)) (ivl -inf.0 +inf.0)) < --- 1 2 --- > (check-equal? (ivl-join (ivl -inf.0 1) (ivl 2 +inf.0)) (ivl -inf.0 +inf.0)) < -------- 2 < ------------- 3 (check-equal? (ivl-join (ivl -inf.0 2) (ivl -inf.0 3)) (ivl -inf.0 3)) ;; 0 -------------> 1 -------- > (check-equal? (ivl-join (ivl 0 +inf.0) (ivl 1 +inf.0)) (ivl 0 +inf.0)) Three infinite ;; <--------------> 1 -------- > (check-equal? (ivl-join (ivl -inf.0 +inf.0) (ivl 1 +inf.0)) (ivl -inf.0 +inf.0)) ;; <--------------> < -------- 2 (check-equal? (ivl-join (ivl -inf.0 +inf.0) (ivl -inf.0 2)) (ivl -inf.0 +inf.0)) Four infinite (check-equal? (ivl-join (ivl -inf.0 +inf.0) (ivl -inf.0 +inf.0)) (ivl -inf.0 +inf.0)) ;; ================================================================================================= ;; Vectors (check-true (vector-andmap zero? #(0 0 0 0))) (check-false (vector-andmap zero? #(0 0 1 0))) (check-true (vector-andmap (λ ([x : Integer] [y : Integer]) (and (= x 1) (= y 2))) #(1 1 1 1) #(2 2 2 2))) (check-false (vector-andmap (λ ([x : Integer] [y : Integer]) (and (= x 1) (= y 2))) #(1 1 1 1) #(2 1 2 2))) (check-true (vector-ormap zero? #(0 0 1 0))) (check-false (vector-ormap zero? #(1 1 1 1))) (check-true (vector-ormap (λ ([x : Integer] [y : Integer]) (and (= x 1) (= y 2))) #(0 0 1 0) #(0 0 2 0))) (check-false (vector-ormap (λ ([x : Integer] [y : Integer]) (and (= x 1) (= y 2))) #(0 0 1 0) #(0 2 0 0))) ) (module untyped-tests racket (require rackunit plot/no-gui plot/private/gui/worker-thread) (check-exn exn:fail:contract? (λ () (vector-field (λ (v [z 0]) v) -4 4 -4 4)) "Exception should be 'two of the clauses in the or/c might both match' or similar") ;; ================================================================================================= ;; Worker threads (let () (define wt (make-worker-thread (match-lambda [(list x y z) (sleep 0.1) (+ x y z)]))) (collect-garbage) (collect-garbage) (check-true (worker-thread-waiting? wt)) (check-true (worker-thread-put wt (list 1 2 3))) (check-true (worker-thread-working? wt)) (check-equal? (worker-thread-get wt) 6) (check-true (worker-thread-put wt (list 1 2 3))) (check-false (worker-thread-try-put wt (list 10 20 30))) (check-exn exn? (λ () (worker-thread-put wt (list 10 20 30)))) (check-false (worker-thread-try-get wt)) (sleep 0.2) (check-equal? (worker-thread-try-get wt) 6) (check-true (worker-thread-put wt (list 10 20 30))) (check-equal? (worker-thread-send wt (list 1 2 3)) 6) (check-exn exn? (λ () (worker-thread-get wt))) (check-false (worker-thread-try-get wt)) (check-true (worker-thread-try-put wt (list 1 2 3))) (sleep 0.2) (check-false (worker-thread-try-put wt (list 10 20 30))) (check-equal? (worker-thread-wait wt) (void)) (check-true (worker-thread-put wt (list 1 2))) (check-exn exn? (λ () (worker-thread-get wt))) ) ) (require 'typed-tests) (require 'untyped-tests)
null
https://raw.githubusercontent.com/racket/plot/c4126001f2c609e36c3aa12f300e9c673ab1a806/plot-test/plot/tests/low-level-tests.rkt
racket
================================================================================================= Formatting ================================================================================================= Date rounding ================================================================================================= ================================================================================================= Intervals ivl-meet (similar to an intersection) All specified One not specified 0 -------------> <--------------> 0 -------------> <--------------> <--------------> 0 -------------> <--------------> 0 -------------> <--------------> <--------------> ivl-join (similar to a union) All specified One not specified 0 -------------> <--------------> 0 -------------> <--------------> <--------------> 0 -------------> <--------------> 0 -------------> <--------------> <--------------> ================================================================================================= Vectors ================================================================================================= Worker threads
#lang racket (module typed-tests typed/racket (require typed/rackunit (except-in racket/date find-seconds) plot plot/utils plot/private/common/utils plot/private/common/math plot/private/common/date-time plot/private/common/format) (require/typed racket/date [find-seconds (-> Integer Integer Integer Integer Integer Integer Boolean Integer)]) (check-equal? (linear-seq 1 1 2) '(1 1)) (check-equal? (linear-seq 0 1 2 #:start? #t #:end? #t) '(0 1)) (check-equal? (linear-seq 0 1 2 #:start? #t #:end? #f) '(0 2/3)) (check-equal? (linear-seq 0 1 2 #:start? #f #:end? #t) '(1/3 1)) (check-equal? (linear-seq 0 1 2 #:start? #f #:end? #f) '(1/4 3/4)) (check-equal? (linear-seq 1 0 2 #:start? #t #:end? #t) '(1 0)) (check-equal? (linear-seq 1 0 2 #:start? #t #:end? #f) '(1 1/3)) (check-equal? (linear-seq 1 0 2 #:start? #f #:end? #t) '(2/3 0)) (check-equal? (linear-seq 1 0 2 #:start? #f #:end? #f) '(3/4 1/4)) (check-equal? (int-str->e-str "") "0") (check-equal? (int-str->e-str "0") "0") (check-equal? (int-str->e-str "10") "1×10\u00b9") (check-equal? (frac-str->e-str "") "0") (check-equal? (frac-str->e-str "0") "0") (check-equal? (frac-str->e-str "00") "0") (check-equal? (frac-str->e-str "1") "1×10\u207b\u00b9") (check-equal? (frac-str->e-str "01") "1×10\u207b\u00b2") (check-equal? (utc-seconds-round-year (find-seconds 0 0 12 2 7 1970 #f)) (find-seconds 0 0 0 1 1 1970 #f)) (check-equal? (utc-seconds-round-year (find-seconds 0 0 13 2 7 1970 #f)) (find-seconds 0 0 0 1 1 1971 #f)) A leap year 's middle is a half day earlier on the calendar : (check-equal? (utc-seconds-round-year (find-seconds 0 0 0 2 7 1976 #f)) (find-seconds 0 0 0 1 1 1976 #f)) (check-equal? (utc-seconds-round-year (find-seconds 0 0 1 2 7 1976 #f)) (find-seconds 0 0 0 1 1 1977 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 0 16 1 2010 #f)) (find-seconds 0 0 0 1 1 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 0 17 1 2010 #f)) (find-seconds 0 0 0 1 2 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 12 16 1 2010 #f)) (find-seconds 0 0 0 1 1 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 13 16 1 2010 #f)) (find-seconds 0 0 0 1 2 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 0 16 12 2010 #f)) (find-seconds 0 0 0 1 12 2010 #f)) (check-equal? (utc-seconds-round-month (find-seconds 0 0 0 17 12 2010 #f)) (find-seconds 0 0 0 1 1 2011 #f)) Time conversion (check-equal? (seconds->plot-time 0) (plot-time 0 0 0 0)) (check-equal? (seconds->plot-time #e59.999999) (plot-time #e59.999999 0 0 0)) (check-equal? (seconds->plot-time 60) (plot-time 0 1 0 0)) (check-equal? (seconds->plot-time #e60.000001) (plot-time #e0.000001 1 0 0)) (check-equal? (seconds->plot-time #e119.999999) (plot-time #e59.999999 1 0 0)) (check-equal? (seconds->plot-time 120) (plot-time 0 2 0 0)) (check-equal? (seconds->plot-time #e120.000001) (plot-time #e0.000001 2 0 0)) (check-equal? (seconds->plot-time 3599) (plot-time 59 59 0 0)) (check-equal? (seconds->plot-time 3600) (plot-time 0 0 1 0)) (check-equal? (seconds->plot-time 3601) (plot-time 1 0 1 0)) (check-equal? (seconds->plot-time (- seconds-per-day 1)) (plot-time 59 59 23 0)) (check-equal? (seconds->plot-time seconds-per-day) (plot-time 0 0 0 1)) (check-equal? (seconds->plot-time (- seconds-per-day)) (plot-time 0 0 0 -1)) (check-equal? (seconds->plot-time (- (- seconds-per-day) 1)) (plot-time 59 59 23 -2)) (define sec-secs (sequence->list (in-range -60 61 #e0.571123))) (define min-secs (sequence->list (in-range (- seconds-per-hour) (+ seconds-per-hour 1) (* #e0.571123 seconds-per-minute)))) (define hour-secs (sequence->list (in-range (- seconds-per-day) (+ seconds-per-day 1) (* #e0.571123 seconds-per-hour)))) (define day-secs (sequence->list (in-range (- seconds-per-week) (+ seconds-per-week 1) (* #e0.571123 seconds-per-day)))) (check-equal? (map (compose plot-time->seconds seconds->plot-time) sec-secs) sec-secs) (check-equal? (map (compose plot-time->seconds seconds->plot-time) min-secs) min-secs) (check-equal? (map (compose plot-time->seconds seconds->plot-time) hour-secs) hour-secs) (check-equal? (map (compose plot-time->seconds seconds->plot-time) day-secs) day-secs) (check-false (ivl-rational? (ivl #f #f))) (check-false (ivl-rational? (ivl +nan.0 +nan.0))) (check-true (ivl-empty? (ivl-meet empty-ivl (ivl 0 3)))) (check-true (ivl-empty? (ivl-meet (ivl 0 1) (ivl 2 3)))) (check-equal? (ivl-meet (ivl 0 2) (ivl 1 3)) (ivl 1 2)) (check-equal? (ivl-meet (ivl 0 3) (ivl 1 2)) (ivl 1 2)) < --- 1 2 -- 3 (check-true (ivl-empty? (ivl-meet (ivl #f 1) (ivl 2 3)))) 0 -- 1 2 --- > (check-true (ivl-empty? (ivl-meet (ivl 0 1) (ivl 2 #f)))) < -------- 2 1 ------- 3 (check-equal? (ivl-meet (ivl #f 2) (ivl 1 3)) (ivl 1 2)) 2 --- > 0 ------------ 3 (check-equal? (ivl-meet (ivl 2 #f) (ivl 0 3)) (ivl 2 3)) < ------------- 3 1 -- 2 (check-equal? (ivl-meet (ivl #f 3) (ivl 1 2)) (ivl 1 2)) 1 -- 2 (check-equal? (ivl-meet (ivl 0 #f) (ivl 1 2)) (ivl 1 2)) Two not specified < --- 1 2 --- > (check-true (ivl-empty? (ivl-meet (ivl #f 1) (ivl 2 #f)))) 1 -- 2 (check-equal? (ivl-meet (ivl #f #f) (ivl 1 2)) (ivl 1 2)) 1 -------- > < -------- 2 (check-equal? (ivl-meet (ivl 1 #f) (ivl #f 2)) (ivl 1 2)) < -------- 2 < ------------- 3 (check-equal? (ivl-meet (ivl #f 2) (ivl #f 3)) (ivl #f 2)) 1 -------- > (check-equal? (ivl-meet (ivl 0 #f) (ivl 1 #f)) (ivl 1 #f)) Three not specified 1 -------- > (check-equal? (ivl-meet (ivl #f #f) (ivl 1 #f)) (ivl 1 #f)) < -------- 2 (check-equal? (ivl-meet (ivl #f #f) (ivl #f 2)) (ivl #f 2)) Four not specified (check-equal? (ivl-meet (ivl #f #f) (ivl #f #f)) (ivl #f #f)) One infinite < --- 1 2 -- 3 (check-true (ivl-empty? (ivl-meet (ivl -inf.0 1) (ivl 2 3)))) 0 -- 1 2 --- > (check-true (ivl-empty? (ivl-meet (ivl 0 1) (ivl 2 +inf.0)))) < -------- 2 1 ------- 3 (check-equal? (ivl-meet (ivl -inf.0 2) (ivl 1 3)) (ivl 1 2)) 2 --- > 0 ------------ 3 (check-equal? (ivl-meet (ivl 2 +inf.0) (ivl 0 3)) (ivl 2 3)) < ------------- 3 1 -- 2 (check-equal? (ivl-meet (ivl -inf.0 3) (ivl 1 2)) (ivl 1 2)) 1 -- 2 (check-equal? (ivl-meet (ivl 0 +inf.0) (ivl 1 2)) (ivl 1 2)) Two infinite < --- 1 2 --- > (check-true (ivl-empty? (ivl-meet (ivl -inf.0 1) (ivl 2 +inf.0)))) 1 -- 2 (check-equal? (ivl-meet (ivl -inf.0 +inf.0) (ivl 1 2)) (ivl 1 2)) 1 -------- > < -------- 2 (check-equal? (ivl-meet (ivl 1 +inf.0) (ivl -inf.0 2)) (ivl 1 2)) < -------- 2 < ------------- 3 (check-equal? (ivl-meet (ivl -inf.0 2) (ivl -inf.0 3)) (ivl -inf.0 2)) 1 -------- > (check-equal? (ivl-meet (ivl 0 +inf.0) (ivl 1 +inf.0)) (ivl 1 +inf.0)) Three infinite 1 -------- > (check-equal? (ivl-meet (ivl -inf.0 +inf.0) (ivl 1 +inf.0)) (ivl 1 +inf.0)) < -------- 2 (check-equal? (ivl-meet (ivl -inf.0 +inf.0) (ivl -inf.0 2)) (ivl -inf.0 2)) Four infinite (check-equal? (ivl-meet (ivl -inf.0 +inf.0) (ivl -inf.0 +inf.0)) (ivl -inf.0 +inf.0)) (check-true (ivl-empty? (ivl-join empty-ivl empty-ivl))) (check-equal? (ivl-join empty-ivl (ivl 0 3)) (ivl 0 3)) (check-equal? (ivl-join (ivl 0 1) (ivl 2 3)) (ivl 0 3)) (check-equal? (ivl-join (ivl 0 2) (ivl 1 3)) (ivl 0 3)) (check-equal? (ivl-join (ivl 0 3) (ivl 1 2)) (ivl 0 3)) < --- 1 2 -- 3 (check-equal? (ivl-join (ivl #f 1) (ivl 2 3)) (ivl 2 3)) 0 -- 1 2 --- > (check-equal? (ivl-join (ivl 0 1) (ivl 2 #f)) (ivl 0 1)) < -------- 2 1 ------- 3 (check-equal? (ivl-join (ivl #f 2) (ivl 1 3)) (ivl 1 3)) 2 --- > 0 ------------ 3 (check-equal? (ivl-join (ivl 2 #f) (ivl 0 3)) (ivl 0 3)) < ------------- 3 1 -- 2 (check-equal? (ivl-join (ivl #f 3) (ivl 1 2)) (ivl 1 3)) 1 -- 2 (check-equal? (ivl-join (ivl 0 #f) (ivl 1 2)) (ivl 0 2)) Two not specified < --- 1 2 --- > (check-equal? (ivl-join (ivl #f 1) (ivl 2 #f)) (ivl 1 2)) 1 -- 2 (check-equal? (ivl-join (ivl #f #f) (ivl 1 2)) (ivl 1 2)) 1 -------- > < -------- 2 (check-equal? (ivl-join (ivl 1 #f) (ivl #f 2)) (ivl 1 2)) < -------- 2 < ------------- 3 (check-equal? (ivl-join (ivl #f 2) (ivl #f 3)) (ivl #f 3)) 1 -------- > (check-equal? (ivl-join (ivl 0 #f) (ivl 1 #f)) (ivl 0 #f)) Three not specified 1 -------- > (check-equal? (ivl-join (ivl #f #f) (ivl 1 #f)) (ivl 1 #f)) < -------- 2 (check-equal? (ivl-join (ivl #f #f) (ivl #f 2)) (ivl #f 2)) Four not specified (check-equal? (ivl-join (ivl #f #f) (ivl #f #f)) (ivl #f #f)) One infinite < --- 1 2 -- 3 (check-equal? (ivl-join (ivl -inf.0 1) (ivl 2 3)) (ivl -inf.0 3)) 0 -- 1 2 --- > (check-equal? (ivl-join (ivl 0 1) (ivl 2 +inf.0)) (ivl 0 +inf.0)) < -------- 2 1 ------- 3 (check-equal? (ivl-join (ivl -inf.0 2) (ivl 1 3)) (ivl -inf.0 3)) 2 --- > 0 ------------ 3 (check-equal? (ivl-join (ivl 2 +inf.0) (ivl 0 3)) (ivl 0 +inf.0)) < ------------- 3 1 -- 2 (check-equal? (ivl-join (ivl -inf.0 3) (ivl 1 2)) (ivl -inf.0 3)) 1 -- 2 (check-equal? (ivl-join (ivl 0 +inf.0) (ivl 1 2)) (ivl 0 +inf.0)) Two infinite 1 -- 2 (check-equal? (ivl-join (ivl -inf.0 +inf.0) (ivl 1 2)) (ivl -inf.0 +inf.0)) 1 -------- > < -------- 2 (check-equal? (ivl-join (ivl 1 +inf.0) (ivl -inf.0 2)) (ivl -inf.0 +inf.0)) < --- 1 2 --- > (check-equal? (ivl-join (ivl -inf.0 1) (ivl 2 +inf.0)) (ivl -inf.0 +inf.0)) < -------- 2 < ------------- 3 (check-equal? (ivl-join (ivl -inf.0 2) (ivl -inf.0 3)) (ivl -inf.0 3)) 1 -------- > (check-equal? (ivl-join (ivl 0 +inf.0) (ivl 1 +inf.0)) (ivl 0 +inf.0)) Three infinite 1 -------- > (check-equal? (ivl-join (ivl -inf.0 +inf.0) (ivl 1 +inf.0)) (ivl -inf.0 +inf.0)) < -------- 2 (check-equal? (ivl-join (ivl -inf.0 +inf.0) (ivl -inf.0 2)) (ivl -inf.0 +inf.0)) Four infinite (check-equal? (ivl-join (ivl -inf.0 +inf.0) (ivl -inf.0 +inf.0)) (ivl -inf.0 +inf.0)) (check-true (vector-andmap zero? #(0 0 0 0))) (check-false (vector-andmap zero? #(0 0 1 0))) (check-true (vector-andmap (λ ([x : Integer] [y : Integer]) (and (= x 1) (= y 2))) #(1 1 1 1) #(2 2 2 2))) (check-false (vector-andmap (λ ([x : Integer] [y : Integer]) (and (= x 1) (= y 2))) #(1 1 1 1) #(2 1 2 2))) (check-true (vector-ormap zero? #(0 0 1 0))) (check-false (vector-ormap zero? #(1 1 1 1))) (check-true (vector-ormap (λ ([x : Integer] [y : Integer]) (and (= x 1) (= y 2))) #(0 0 1 0) #(0 0 2 0))) (check-false (vector-ormap (λ ([x : Integer] [y : Integer]) (and (= x 1) (= y 2))) #(0 0 1 0) #(0 2 0 0))) ) (module untyped-tests racket (require rackunit plot/no-gui plot/private/gui/worker-thread) (check-exn exn:fail:contract? (λ () (vector-field (λ (v [z 0]) v) -4 4 -4 4)) "Exception should be 'two of the clauses in the or/c might both match' or similar") (let () (define wt (make-worker-thread (match-lambda [(list x y z) (sleep 0.1) (+ x y z)]))) (collect-garbage) (collect-garbage) (check-true (worker-thread-waiting? wt)) (check-true (worker-thread-put wt (list 1 2 3))) (check-true (worker-thread-working? wt)) (check-equal? (worker-thread-get wt) 6) (check-true (worker-thread-put wt (list 1 2 3))) (check-false (worker-thread-try-put wt (list 10 20 30))) (check-exn exn? (λ () (worker-thread-put wt (list 10 20 30)))) (check-false (worker-thread-try-get wt)) (sleep 0.2) (check-equal? (worker-thread-try-get wt) 6) (check-true (worker-thread-put wt (list 10 20 30))) (check-equal? (worker-thread-send wt (list 1 2 3)) 6) (check-exn exn? (λ () (worker-thread-get wt))) (check-false (worker-thread-try-get wt)) (check-true (worker-thread-try-put wt (list 1 2 3))) (sleep 0.2) (check-false (worker-thread-try-put wt (list 10 20 30))) (check-equal? (worker-thread-wait wt) (void)) (check-true (worker-thread-put wt (list 1 2))) (check-exn exn? (λ () (worker-thread-get wt))) ) ) (require 'typed-tests) (require 'untyped-tests)
028a5f45a756ff312c124eba767eb305bd633876e2e1ea4bd5856627b31ffb31
cxphoe/SICP-solutions
3.8.rkt
(define (delay value) (let ((previous value)) (lambda (x) (begin (set! previous value) (set! value (+ value x)) previous)))) (define f1 (delay 0)) (define f2 (delay 0)) (+ (f1 0) (f1 1)) (+ (f2 1) (f2 0))
null
https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%203-Modeling%20with%20Mutable%20Data/1.Assignment%20and%20Local%20state/3.8.rkt
racket
(define (delay value) (let ((previous value)) (lambda (x) (begin (set! previous value) (set! value (+ value x)) previous)))) (define f1 (delay 0)) (define f2 (delay 0)) (+ (f1 0) (f1 1)) (+ (f2 1) (f2 0))
d1257c50105864395fad9474e141ec6f7c8e5698e70d39a115532b1f5ee54525
antono/guix-debian
geeqie.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2013 < > ;;; ;;; 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 geeqie) #:use-module (guix packages) #:use-module (guix download) #:use-module ((guix licenses) #:renamer (symbol-prefix-proc 'l:)) #:use-module (guix build-system gnu) #:use-module (gnu packages pkg-config) #:use-module (gnu packages glib) #:use-module (gnu packages gtk) #:use-module (gnu packages image) #:use-module ((gnu packages ghostscript) #:select (lcms)) #:use-module (gnu packages compression) #:use-module (gnu packages xml)) (define-public exiv2 ; XXX: move elsewhere? (package (name "exiv2") (version "0.23") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "04bbg2cg6mgcyz435zamx37sp5zw44n2alb59ki1daz71f851yl1")))) (build-system gnu-build-system) (arguments '(#:tests? #f)) ; no `check' target (propagated-inputs `(("expat" ,expat) ("zlib" ,zlib))) (home-page "/") (synopsis "Library and command-line utility to manage image metadata") (description "Exiv2 is a C++ library and a command line utility to manage image metadata. It provides fast and easy read and write access to the Exif, IPTC and XMP metadata of images in various formats.") Files under ` xmpsdk ' are a copy of Adobe 's XMP SDK , licensed under the 3 - clause BSD license : < > . ;; The core is GPLv2+: </+source/exiv2/+copyright>. (license l:gpl2+))) (define-public geeqie (package (name "geeqie") (version "1.1") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.gz")) (sha256 (base32 "1kzy39z9505xkayyx7rjj2wda76xy3ch1s5z35zn8yli54ffhi2m")))) (build-system gnu-build-system) (inputs ( " " , ) ("lcms" ,lcms) ("exiv2" ,exiv2) ("libpng" ,libpng) ("gtk+" ,gtk+-2))) (native-inputs `(("intltool" ,intltool) ("pkg-config" ,pkg-config))) (home-page "") (synopsis "Lightweight GTK+ based image viewer") (description "Geeqie is a lightweight GTK+ based image viewer for Unix like operating systems. It features: EXIF, IPTC and XMP metadata browsing and editing easy integration with other software ; geeqie works on files and directories, there is no need to import images; fast preview for many raw image formats; tools for image comparison, sorting and managing photo collection. Geeqie was initially based on GQview.") (license l:gpl2+)))
null
https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/geeqie.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. XXX: move elsewhere? no `check' target The core is GPLv2+: </+source/exiv2/+copyright>. geeqie works on files fast preview for many raw tools for image comparison, sorting and managing photo
Copyright © 2013 < > 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 geeqie) #:use-module (guix packages) #:use-module (guix download) #:use-module ((guix licenses) #:renamer (symbol-prefix-proc 'l:)) #:use-module (guix build-system gnu) #:use-module (gnu packages pkg-config) #:use-module (gnu packages glib) #:use-module (gnu packages gtk) #:use-module (gnu packages image) #:use-module ((gnu packages ghostscript) #:select (lcms)) #:use-module (gnu packages compression) #:use-module (gnu packages xml)) (package (name "exiv2") (version "0.23") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "04bbg2cg6mgcyz435zamx37sp5zw44n2alb59ki1daz71f851yl1")))) (build-system gnu-build-system) (propagated-inputs `(("expat" ,expat) ("zlib" ,zlib))) (home-page "/") (synopsis "Library and command-line utility to manage image metadata") (description "Exiv2 is a C++ library and a command line utility to manage image metadata. It provides fast and easy read and write access to the Exif, IPTC and XMP metadata of images in various formats.") Files under ` xmpsdk ' are a copy of Adobe 's XMP SDK , licensed under the 3 - clause BSD license : < > . (license l:gpl2+))) (define-public geeqie (package (name "geeqie") (version "1.1") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.gz")) (sha256 (base32 "1kzy39z9505xkayyx7rjj2wda76xy3ch1s5z35zn8yli54ffhi2m")))) (build-system gnu-build-system) (inputs ( " " , ) ("lcms" ,lcms) ("exiv2" ,exiv2) ("libpng" ,libpng) ("gtk+" ,gtk+-2))) (native-inputs `(("intltool" ,intltool) ("pkg-config" ,pkg-config))) (home-page "") (synopsis "Lightweight GTK+ based image viewer") (description "Geeqie is a lightweight GTK+ based image viewer for Unix like operating systems. It features: EXIF, IPTC and XMP metadata browsing and editing collection. Geeqie was initially based on GQview.") (license l:gpl2+)))
a514e03d737a46a20b7c79ef069ebdd9a5cd7fc39c2967fbe3531aa44a75fd47
wireapp/saml2-web-sso
MockResponse.hs
{-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -Wno - incomplete - uni - patterns # module SAML2.WebSSO.Test.MockResponse where import Control.Lens import Control.Monad.IO.Class import Data.Generics.Uniplate.Data import Data.String.Conversions import Data.UUID as UUID import GHC.Stack import SAML2.Util import SAML2.WebSSO import Text.Hamlet.XML (xml) import Text.XML import Text.XML.DSig newtype SignedAuthnResponse = SignedAuthnResponse {fromSignedAuthnResponse :: Document} deriving (Eq, Show) -- | See tests on how this is used. mkAuthnResponse :: (HasCallStack, HasMonadSign m, HasLogger m, HasCreateUUID m, HasNow m) => SignPrivCreds -> IdPConfig extra -> SPMetadata -> AuthnRequest -> Bool -> m SignedAuthnResponse mkAuthnResponse creds idp spmeta areq grant = do subj <- unspecifiedNameID . UUID.toText <$> createUUID mkAuthnResponseWithSubj subj creds idp spmeta areq grant -- | Replace the 'NameID' child of the 'Subject' with a given one. -- -- (There is some code sharing between this and 'mkAuthnResponseWithRawSubj', but reducing it would -- make both functions more complex.) mkAuthnResponseWithSubj :: forall extra m. (HasCallStack, HasMonadSign m, HasCreateUUID m, HasNow m) => NameID -> SignPrivCreds -> IdPConfig extra -> SPMetadata -> AuthnRequest -> Bool -> m SignedAuthnResponse mkAuthnResponseWithSubj subj = mkAuthnResponseWithModif modif id where modif = transformBis [ [ transformer $ \case el@(Element "{urn:oasis:names:tc:SAML:2.0:assertion}Subject" _ _) -> case parse [NodeElement el] of Right (Subject _ sc) -> nodesToElem . render $ Subject subj sc Left bad -> error $ show bad other -> other ] ] -- | Delete all children of 'Subject' and insert some new ones. mkAuthnResponseWithRawSubj :: forall extra m. (HasCallStack, HasMonadSign m, HasCreateUUID m, HasNow m) => [Node] -> SignPrivCreds -> IdPConfig extra -> SPMetadata -> AuthnRequest -> Bool -> m SignedAuthnResponse mkAuthnResponseWithRawSubj subj = mkAuthnResponseWithModif modif id where modif = transformBis [ [ transformer $ \case (Element tag@"{urn:oasis:names:tc:SAML:2.0:assertion}Subject" attrs _) -> Element tag attrs subj other -> other ] ] mkAuthnResponseWithModif :: (HasCallStack, HasMonadSign m, HasCreateUUID m, HasNow m) => ([Node] -> [Node]) -> ([Node] -> [Node]) -> SignPrivCreds -> IdPConfig extra -> SPMetadata -> AuthnRequest -> Bool -> m SignedAuthnResponse mkAuthnResponseWithModif modifUnsignedAssertion modifAll creds idp sp authnreq grantAccess = do let freshNCName = ("_" <>) . UUID.toText <$> createUUID assertionUuid <- freshNCName respUuid <- freshNCName now <- getNow let issueInstant = renderTime now expires = renderTime $ 3600 `addTime` now idpissuer :: ST = idp ^. idpMetadata . edIssuer . fromIssuer . to renderURI recipient :: ST = sp ^. spResponseURL . to renderURI spissuer :: ST = authnreq ^. rqIssuer . fromIssuer . to renderURI inResponseTo = escapeXmlText . fromID $ authnreq ^. rqID status | grantAccess = "urn:oasis:names:tc:SAML:2.0:status:Success" | otherwise = "urn:oasis:names:tc:SAML:2.0:status:Requester" assertion :: [Node] <- liftIO $ signElementIOAt 1 creds . modifUnsignedAssertion . repairNamespaces $ [xml| <Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0" ID="#{assertionUuid}" IssueInstant="#{issueInstant}"> <Issuer> #{idpissuer} <Subject> <NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"> #{""} <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> <SubjectConfirmationData InResponseTo="#{inResponseTo}" NotOnOrAfter="#{expires}" Recipient="#{recipient}"> <Conditions NotBefore="#{issueInstant}" NotOnOrAfter="#{expires}"> <AudienceRestriction> <Audience> #{spissuer} <AuthnStatement AuthnInstant="#{issueInstant}" SessionIndex="_e9ae1025-bc03-4b5a-943c-c9fcb8730b21"> <AuthnContext> <AuthnContextClassRef> urn:oasis:names:tc:SAML:2.0:ac:classes:Password |] let authnResponse :: Element [NodeElement authnResponse] = modifAll . repairNamespaces $ [xml| <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="#{respUuid}" Version="2.0" Destination="#{recipient}" InResponseTo="#{inResponseTo}" IssueInstant="#{issueInstant}"> <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion"> #{idpissuer} <samlp:Status> <samlp:StatusCode Value="#{status}"> ^{assertion} |] pure . SignedAuthnResponse $ mkDocument authnResponse
null
https://raw.githubusercontent.com/wireapp/saml2-web-sso/ac88b934bb4a91d4d4bb90c620277188e4087043/src/SAML2/WebSSO/Test/MockResponse.hs
haskell
# LANGUAGE OverloadedStrings # | See tests on how this is used. | Replace the 'NameID' child of the 'Subject' with a given one. (There is some code sharing between this and 'mkAuthnResponseWithRawSubj', but reducing it would make both functions more complex.) | Delete all children of 'Subject' and insert some new ones.
# OPTIONS_GHC -Wno - incomplete - uni - patterns # module SAML2.WebSSO.Test.MockResponse where import Control.Lens import Control.Monad.IO.Class import Data.Generics.Uniplate.Data import Data.String.Conversions import Data.UUID as UUID import GHC.Stack import SAML2.Util import SAML2.WebSSO import Text.Hamlet.XML (xml) import Text.XML import Text.XML.DSig newtype SignedAuthnResponse = SignedAuthnResponse {fromSignedAuthnResponse :: Document} deriving (Eq, Show) mkAuthnResponse :: (HasCallStack, HasMonadSign m, HasLogger m, HasCreateUUID m, HasNow m) => SignPrivCreds -> IdPConfig extra -> SPMetadata -> AuthnRequest -> Bool -> m SignedAuthnResponse mkAuthnResponse creds idp spmeta areq grant = do subj <- unspecifiedNameID . UUID.toText <$> createUUID mkAuthnResponseWithSubj subj creds idp spmeta areq grant mkAuthnResponseWithSubj :: forall extra m. (HasCallStack, HasMonadSign m, HasCreateUUID m, HasNow m) => NameID -> SignPrivCreds -> IdPConfig extra -> SPMetadata -> AuthnRequest -> Bool -> m SignedAuthnResponse mkAuthnResponseWithSubj subj = mkAuthnResponseWithModif modif id where modif = transformBis [ [ transformer $ \case el@(Element "{urn:oasis:names:tc:SAML:2.0:assertion}Subject" _ _) -> case parse [NodeElement el] of Right (Subject _ sc) -> nodesToElem . render $ Subject subj sc Left bad -> error $ show bad other -> other ] ] mkAuthnResponseWithRawSubj :: forall extra m. (HasCallStack, HasMonadSign m, HasCreateUUID m, HasNow m) => [Node] -> SignPrivCreds -> IdPConfig extra -> SPMetadata -> AuthnRequest -> Bool -> m SignedAuthnResponse mkAuthnResponseWithRawSubj subj = mkAuthnResponseWithModif modif id where modif = transformBis [ [ transformer $ \case (Element tag@"{urn:oasis:names:tc:SAML:2.0:assertion}Subject" attrs _) -> Element tag attrs subj other -> other ] ] mkAuthnResponseWithModif :: (HasCallStack, HasMonadSign m, HasCreateUUID m, HasNow m) => ([Node] -> [Node]) -> ([Node] -> [Node]) -> SignPrivCreds -> IdPConfig extra -> SPMetadata -> AuthnRequest -> Bool -> m SignedAuthnResponse mkAuthnResponseWithModif modifUnsignedAssertion modifAll creds idp sp authnreq grantAccess = do let freshNCName = ("_" <>) . UUID.toText <$> createUUID assertionUuid <- freshNCName respUuid <- freshNCName now <- getNow let issueInstant = renderTime now expires = renderTime $ 3600 `addTime` now idpissuer :: ST = idp ^. idpMetadata . edIssuer . fromIssuer . to renderURI recipient :: ST = sp ^. spResponseURL . to renderURI spissuer :: ST = authnreq ^. rqIssuer . fromIssuer . to renderURI inResponseTo = escapeXmlText . fromID $ authnreq ^. rqID status | grantAccess = "urn:oasis:names:tc:SAML:2.0:status:Success" | otherwise = "urn:oasis:names:tc:SAML:2.0:status:Requester" assertion :: [Node] <- liftIO $ signElementIOAt 1 creds . modifUnsignedAssertion . repairNamespaces $ [xml| <Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0" ID="#{assertionUuid}" IssueInstant="#{issueInstant}"> <Issuer> #{idpissuer} <Subject> <NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"> #{""} <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> <SubjectConfirmationData InResponseTo="#{inResponseTo}" NotOnOrAfter="#{expires}" Recipient="#{recipient}"> <Conditions NotBefore="#{issueInstant}" NotOnOrAfter="#{expires}"> <AudienceRestriction> <Audience> #{spissuer} <AuthnStatement AuthnInstant="#{issueInstant}" SessionIndex="_e9ae1025-bc03-4b5a-943c-c9fcb8730b21"> <AuthnContext> <AuthnContextClassRef> urn:oasis:names:tc:SAML:2.0:ac:classes:Password |] let authnResponse :: Element [NodeElement authnResponse] = modifAll . repairNamespaces $ [xml| <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="#{respUuid}" Version="2.0" Destination="#{recipient}" InResponseTo="#{inResponseTo}" IssueInstant="#{issueInstant}"> <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion"> #{idpissuer} <samlp:Status> <samlp:StatusCode Value="#{status}"> ^{assertion} |] pure . SignedAuthnResponse $ mkDocument authnResponse
69f62ab81b5966e8e1ff555289bc95becad6d03ba38926b90a3992cf21456210
ocaml-batteries-team/batteries-included
batOrd.mli
type order = Lt | Eq | Gt * An algebraic datatype for ordering . Traditional OCaml code , under the influence of C comparison functions , has used int - returning comparisons ( < 0 , 0 or > 0 ) . Using an algebraic datatype instead is actually nicer , both for comparison producers ( no arbitrary choice of a positive and negative value ) and consumers ( nice pattern - matching elimination ) . Traditional OCaml code, under the influence of C comparison functions, has used int-returning comparisons (< 0, 0 or > 0). Using an algebraic datatype instead is actually nicer, both for comparison producers (no arbitrary choice of a positive and negative value) and consumers (nice pattern-matching elimination). *) type 'a ord = 'a -> 'a -> order (** The type of ordering functions returning an [order] variant. *) type 'a comp = 'a -> 'a -> int * The legacy int - returning comparisons : - compare a b < 0 means a < b - compare a b = 0 means a = b - compare a b > 0 means a > b - compare a b < 0 means a < b - compare a b = 0 means a = b - compare a b > 0 means a > b *) module type Comp = sig type t val compare : t comp end * We use [ compare ] as member name instead of [ comp ] , so that the Comp modules can be used as the legacy OrderedType interface . Comp modules can be used as the legacy OrderedType interface. *) module type Ord = sig type t val ord : t ord end val ord0 : int -> order val ord : 'a comp -> 'a ord (** Returns a variant ordering from a legacy comparison *) module Ord : functor (Comp : Comp) -> Ord with type t = Comp.t val comp0 : order -> int val comp : 'a ord -> 'a comp (** Returns an legacy comparison from a variant ordering *) module Comp : functor (Ord : Ord) -> Comp with type t = Ord.t val poly_comp : 'a comp val poly_ord : 'a ord val poly : 'a ord * Polymorphic comparison functions , based on the [ Pervasives.compare ] function from inria 's stdlib , have polymorphic types : they claim to be able to compare values of any type . In practice , they work for only some types , may fail on function types and may not terminate on cyclic values . They work by runtime magic , inspecting the values in an untyped way . While being an useful hack for base types and simple composite types ( say [ ( int * float ) list ] , they do not play well with functions , type abstractions , and structures that would need a finer notion of equality / comparison . For example , if one represent sets as balanced binary tree , one may want set with equal elements but different balancings to be equal , which would not be the case using the polymorphic equality function . When possible , you should therefore avoid relying on these polymorphic comparison functions . You should be especially careful if your data structure may later evolve to allow cyclic data structures or functions . [Pervasives.compare] function from inria's stdlib, have polymorphic types: they claim to be able to compare values of any type. In practice, they work for only some types, may fail on function types and may not terminate on cyclic values. They work by runtime magic, inspecting the values in an untyped way. While being an useful hack for base types and simple composite types (say [(int * float) list], they do not play well with functions, type abstractions, and structures that would need a finer notion of equality/comparison. For example, if one represent sets as balanced binary tree, one may want set with equal elements but different balancings to be equal, which would not be the case using the polymorphic equality function. When possible, you should therefore avoid relying on these polymorphic comparison functions. You should be especially careful if your data structure may later evolve to allow cyclic data structures or functions. *) val rev_ord0 : order -> order val rev_comp0 : int -> int val rev_ord : 'a ord -> 'a ord val rev_comp : 'a comp -> 'a comp val rev : 'a ord -> 'a ord (** Reverse a given ordering. If [Int.ord] sorts integer by increasing order, [rev Int.ord] will sort them by decreasing order. *) module RevOrd (Ord : Ord) : Ord with type t = Ord.t module RevComp (Comp : Comp) : Comp with type t = Comp.t module Rev (Ord : Ord) : Ord with type t = Ord.t type 'a eq = 'a -> 'a -> bool (** The type for equality function. All ordered types also support equality, as equality can be derived from ordering. However, there are also cases where elements may be compared for equality, but have no natural ordering. It is therefore useful to provide equality as an independent notion. *) val eq_ord0 : order -> bool val eq_comp0 : int -> bool val eq_ord : 'a ord -> 'a eq val eq_comp : 'a comp -> 'a eq val eq : 'a ord -> 'a eq (** Derives an equality function from an ordering function. *) module type Eq = sig type t val eq : t eq end module EqOrd (Ord : Ord) : Eq with type t = Ord.t module EqComp (Comp : Comp) : Eq with type t = Comp.t module Eq (Ord : Ord) : Eq with type t = Ord.t type 'a choice = 'a -> 'a -> 'a (** choice functions, see [min] and [max]. *) val min_ord : 'a ord -> 'a choice val max_ord : 'a ord -> 'a choice val min_comp : 'a comp -> 'a choice val max_comp : 'a comp -> 'a choice val min : 'a ord -> 'a choice * [ min ord ] will choose the smallest element , according to [ ord ] . For example , [ min Int.ord 1 2 ] will return [ 1 ] . { [ ( * the minimum element of a list For example, [min Int.ord 1 2] will return [1]. {[ (* the minimum element of a list *) let list_min ord = List.reduce (min ord) ]} *) val max : 'a ord -> 'a choice (** [max ord] will choose the biggest element according to [ord]. *) val bin_comp : 'a comp -> 'a -> 'a -> 'b comp -> 'b -> 'b -> int val bin_ord : 'a ord -> 'a -> 'a -> 'b ord -> 'b -> 'b -> order (** binary lifting of the comparison function, using lexicographic order: [bin_ord ord1 v1 v1' ord2 v2 v2'] is [ord2 v2 v2'] if [ord1 v1 v1' = Eq], and [ord1 v1 v1'] otherwise. *) val bin_eq : 'a eq -> 'a -> 'a -> 'b eq -> 'b -> 'b -> bool val map_eq : ('a -> 'b) -> 'b eq -> 'a eq val map_comp : ('a -> 'b) -> 'b comp -> 'a comp val map_ord : ('a -> 'b) -> 'b ord -> 'a ord * These functions extend an existing equality / comparison / ordering to a new domain through a mapping function . For example , to order sets by their cardinality , use [ map_ord Set.cardinal Int.ord ] . The input of the mapping function is the type you want to compare , so this is the reverse of [ List.map ] . a new domain through a mapping function. For example, to order sets by their cardinality, use [map_ord Set.cardinal Int.ord]. The input of the mapping function is the type you want to compare, so this is the reverse of [List.map]. *) module Incubator : sig val eq_by : ('a -> 'b) -> 'a eq val comp_by : ('a -> 'b) -> 'a comp val ord_by : ('a -> 'b) -> 'a ord * Build a [ eq ] , [ cmp ] or [ ord ] function from a projection function . For example , if you wanted to compare integers based on their lowest 4 bits , you could write [ let cmp_bot4 = cmp_by ( fun x - > x land 0xf ) ] and use cmp_bot4 as the desired integer comparator . For example, if you wanted to compare integers based on their lowest 4 bits, you could write [let cmp_bot4 = cmp_by (fun x -> x land 0xf)] and use cmp_bot4 as the desired integer comparator. *) end
null
https://raw.githubusercontent.com/ocaml-batteries-team/batteries-included/f143ef5ec583d87d538b8f06f06d046d64555e90/src/batOrd.mli
ocaml
* The type of ordering functions returning an [order] variant. * Returns a variant ordering from a legacy comparison * Returns an legacy comparison from a variant ordering * Reverse a given ordering. If [Int.ord] sorts integer by increasing order, [rev Int.ord] will sort them by decreasing order. * The type for equality function. All ordered types also support equality, as equality can be derived from ordering. However, there are also cases where elements may be compared for equality, but have no natural ordering. It is therefore useful to provide equality as an independent notion. * Derives an equality function from an ordering function. * choice functions, see [min] and [max]. the minimum element of a list * [max ord] will choose the biggest element according to [ord]. * binary lifting of the comparison function, using lexicographic order: [bin_ord ord1 v1 v1' ord2 v2 v2'] is [ord2 v2 v2'] if [ord1 v1 v1' = Eq], and [ord1 v1 v1'] otherwise.
type order = Lt | Eq | Gt * An algebraic datatype for ordering . Traditional OCaml code , under the influence of C comparison functions , has used int - returning comparisons ( < 0 , 0 or > 0 ) . Using an algebraic datatype instead is actually nicer , both for comparison producers ( no arbitrary choice of a positive and negative value ) and consumers ( nice pattern - matching elimination ) . Traditional OCaml code, under the influence of C comparison functions, has used int-returning comparisons (< 0, 0 or > 0). Using an algebraic datatype instead is actually nicer, both for comparison producers (no arbitrary choice of a positive and negative value) and consumers (nice pattern-matching elimination). *) type 'a ord = 'a -> 'a -> order type 'a comp = 'a -> 'a -> int * The legacy int - returning comparisons : - compare a b < 0 means a < b - compare a b = 0 means a = b - compare a b > 0 means a > b - compare a b < 0 means a < b - compare a b = 0 means a = b - compare a b > 0 means a > b *) module type Comp = sig type t val compare : t comp end * We use [ compare ] as member name instead of [ comp ] , so that the Comp modules can be used as the legacy OrderedType interface . Comp modules can be used as the legacy OrderedType interface. *) module type Ord = sig type t val ord : t ord end val ord0 : int -> order val ord : 'a comp -> 'a ord module Ord : functor (Comp : Comp) -> Ord with type t = Comp.t val comp0 : order -> int val comp : 'a ord -> 'a comp module Comp : functor (Ord : Ord) -> Comp with type t = Ord.t val poly_comp : 'a comp val poly_ord : 'a ord val poly : 'a ord * Polymorphic comparison functions , based on the [ Pervasives.compare ] function from inria 's stdlib , have polymorphic types : they claim to be able to compare values of any type . In practice , they work for only some types , may fail on function types and may not terminate on cyclic values . They work by runtime magic , inspecting the values in an untyped way . While being an useful hack for base types and simple composite types ( say [ ( int * float ) list ] , they do not play well with functions , type abstractions , and structures that would need a finer notion of equality / comparison . For example , if one represent sets as balanced binary tree , one may want set with equal elements but different balancings to be equal , which would not be the case using the polymorphic equality function . When possible , you should therefore avoid relying on these polymorphic comparison functions . You should be especially careful if your data structure may later evolve to allow cyclic data structures or functions . [Pervasives.compare] function from inria's stdlib, have polymorphic types: they claim to be able to compare values of any type. In practice, they work for only some types, may fail on function types and may not terminate on cyclic values. They work by runtime magic, inspecting the values in an untyped way. While being an useful hack for base types and simple composite types (say [(int * float) list], they do not play well with functions, type abstractions, and structures that would need a finer notion of equality/comparison. For example, if one represent sets as balanced binary tree, one may want set with equal elements but different balancings to be equal, which would not be the case using the polymorphic equality function. When possible, you should therefore avoid relying on these polymorphic comparison functions. You should be especially careful if your data structure may later evolve to allow cyclic data structures or functions. *) val rev_ord0 : order -> order val rev_comp0 : int -> int val rev_ord : 'a ord -> 'a ord val rev_comp : 'a comp -> 'a comp val rev : 'a ord -> 'a ord module RevOrd (Ord : Ord) : Ord with type t = Ord.t module RevComp (Comp : Comp) : Comp with type t = Comp.t module Rev (Ord : Ord) : Ord with type t = Ord.t type 'a eq = 'a -> 'a -> bool val eq_ord0 : order -> bool val eq_comp0 : int -> bool val eq_ord : 'a ord -> 'a eq val eq_comp : 'a comp -> 'a eq val eq : 'a ord -> 'a eq module type Eq = sig type t val eq : t eq end module EqOrd (Ord : Ord) : Eq with type t = Ord.t module EqComp (Comp : Comp) : Eq with type t = Comp.t module Eq (Ord : Ord) : Eq with type t = Ord.t type 'a choice = 'a -> 'a -> 'a val min_ord : 'a ord -> 'a choice val max_ord : 'a ord -> 'a choice val min_comp : 'a comp -> 'a choice val max_comp : 'a comp -> 'a choice val min : 'a ord -> 'a choice * [ min ord ] will choose the smallest element , according to [ ord ] . For example , [ min Int.ord 1 2 ] will return [ 1 ] . { [ ( * the minimum element of a list For example, [min Int.ord 1 2] will return [1]. {[ let list_min ord = List.reduce (min ord) ]} *) val max : 'a ord -> 'a choice val bin_comp : 'a comp -> 'a -> 'a -> 'b comp -> 'b -> 'b -> int val bin_ord : 'a ord -> 'a -> 'a -> 'b ord -> 'b -> 'b -> order val bin_eq : 'a eq -> 'a -> 'a -> 'b eq -> 'b -> 'b -> bool val map_eq : ('a -> 'b) -> 'b eq -> 'a eq val map_comp : ('a -> 'b) -> 'b comp -> 'a comp val map_ord : ('a -> 'b) -> 'b ord -> 'a ord * These functions extend an existing equality / comparison / ordering to a new domain through a mapping function . For example , to order sets by their cardinality , use [ map_ord Set.cardinal Int.ord ] . The input of the mapping function is the type you want to compare , so this is the reverse of [ List.map ] . a new domain through a mapping function. For example, to order sets by their cardinality, use [map_ord Set.cardinal Int.ord]. The input of the mapping function is the type you want to compare, so this is the reverse of [List.map]. *) module Incubator : sig val eq_by : ('a -> 'b) -> 'a eq val comp_by : ('a -> 'b) -> 'a comp val ord_by : ('a -> 'b) -> 'a ord * Build a [ eq ] , [ cmp ] or [ ord ] function from a projection function . For example , if you wanted to compare integers based on their lowest 4 bits , you could write [ let cmp_bot4 = cmp_by ( fun x - > x land 0xf ) ] and use cmp_bot4 as the desired integer comparator . For example, if you wanted to compare integers based on their lowest 4 bits, you could write [let cmp_bot4 = cmp_by (fun x -> x land 0xf)] and use cmp_bot4 as the desired integer comparator. *) end
d52b611cc3cc6e0b20fe2b4d65238ef838bdf7de7ba11af8fbb7ea3cb6445ce2
mdsebald/link_blox_app
lblx_template.erl
% INSTRUCTIONS: Copy this module and modify as appropriate % for the function this block will perform. % Comments marked "INSTRUCTIONS:" may be deleted % Instructions: Follow the formatting of the @doc comment block exactly as shown It is used for generating LinkBlox web pages %%% @doc BLOCKTYPE INSTRUCTIONS : Insert a one line description of the block here %%% DESCRIPTION %%% INSTRUCTIONS: Insert description of block operation here %%% Use as many lines as necessary %%% LINKS INSTRUCTIONS : Insert URL(s ) here , ( one per line ) %%% for links to external resources related to this block %%% such as hardware data sheets, etc. %%% @end % INSTRUCTIONS: Modify to match new block type module name % All block type module names must begin with "lblx_" to uniquely identify them as LinkBlox block type modules . % % To allow the user to identify and create blocks, in each language module used: % add a <module name => block type name string> pair to the block_type_names ( ) map in each Language Module , % Add a <module name => block type description> string pair to the block_type_descrs ( ) map in each Language Module , -module(lblx_template). -author("Your Name"). % INSTRUCTIONS: Adjust path to hrl file as needed -include("../block_state.hrl"). %% ==================================================================== %% API functions %% ==================================================================== INSTRUCTIONS : The following 10 functions must be implemented and exported by all block types -export([groups/0, version/0]). -export([create/2, create/4, create/5, upgrade/1, initialize/1, execute/2, delete/1]). % INSTRUCTIONS: Optional custom message handling functions. If the block type needs to handle custom messages , not currently handled by block_server ( ) , % export the necessary function(s) here, and create the function(s) below. % Otherwise, delete this line. -export([handle_call/3, handle_cast/2, handle_info/2]). INSTRUCTIONS : Classify block type , by assigning it to one or more groups groups() -> [none]. INSTRUCTIONS : Add a block type description string to each Language Module , % INSTRUCTIONS: Set block type version number. % Use pattern: Major.Minor.Patch % When a block is created, the Config version attribute value % is set to this version. % When a block is loaded from a config file, the version attribute value % is compared to this. % If the versions are different, the upgrade() function is called. version() -> "0.1.0". %% Merge the block type specific, Config, Input, and Output attributes %% with the common Config, Input, and Output attributes, that all block types have -spec default_configs(BlockName :: block_name(), Description :: string()) -> config_attribs(). default_configs(BlockName, Description) -> attrib_utils:merge_attribute_lists( block_common:configs(BlockName, ?MODULE, version(), Description), [ % INTRUCTIONS: Insert block type specific config attribute tuples here % Config attribute tuples consist of a value name and a value % Example: {gpio_pin, {0}} Array Example : { start_rows , [ { 1 } , { 2 } ] } % The block is (re) initialized, when any config value is modified. {config1, {"Example Value"}} ]). -spec default_inputs() -> input_attribs(). default_inputs() -> attrib_utils:merge_attribute_lists( block_common:inputs(), [ % INTRUCTIONS: Insert block type specific input attribute tuples here % Input attribute tuples consist of a value name, a value, and a default value Example : { hi_limit , { 100 , { 100 } } } % Array Example: {inputs, [{empty, {empty}}, {empty, {empty}}]} {input1, {"Example Input Value", {"Example Input Value"}}} ]). -spec default_outputs() -> output_attribs(). default_outputs() -> attrib_utils:merge_attribute_lists( block_common:outputs(), [ % INTRUCTIONS: Insert block type specific output attribute tuples here % Output attribute tuples consist of a value name, a calculated value, % and a list of links to block input values % Output values are always set to 'null' and empty link list on creation % Example: {dwell, {null, []}} % Array Example: {digit, [{null, []}, {null, []}]} {output1, {null, []}} ]). %% %% Create a set of block attributes for this block type. Init attributes are used to override the default attribute values %% and to add attributes to the lists of default attributes %% -spec create(BlockName :: block_name(), Description :: string()) -> block_defn(). create(BlockName, Description) -> create(BlockName, Description, [], [], []). -spec create(BlockName :: block_name(), Description :: string(), InitConfig :: config_attribs(), InitInputs :: input_attribs()) -> block_defn(). create(BlockName, Description, InitConfig, InitInputs) -> create(BlockName, Description, InitConfig, InitInputs, []). -spec create(BlockName :: block_name(), Description :: string(), InitConfig :: config_attribs(), InitInputs :: input_attribs(), InitOutputs :: output_attribs()) -> block_defn(). create(BlockName, Description, InitConfig, InitInputs, InitOutputs) -> % Update Default Config, Input, Output, and Private attribute values % with the initial values passed into this function. % % If any of the intial attributes do not already exist in the % default attribute lists, merge_attribute_lists() will create them. Config = attrib_utils:merge_attribute_lists(default_configs(BlockName, Description), InitConfig), Inputs = attrib_utils:merge_attribute_lists(default_inputs(), InitInputs), Outputs = attrib_utils:merge_attribute_lists(default_outputs(), InitOutputs), % This is the block definition, {Config, Inputs, Outputs}. %% %% Upgrade block attribute values, when block code and block data versions are different %% -spec upgrade(BlockDefn :: block_defn()) -> {ok, block_defn()} | {error, atom()}. upgrade({Config, Inputs, Outputs}) -> % INSTRUCTIONS: This function is called, on block creation, when the % module's version does not match the version in the block's config data. % Depending on the version(s) perform any necessary adjustments to the % block's attributes, to make it compatible with the current block type's code. % If upgrading the attributes is not possible, return an error and reason. ModuleVer = version(), {BlockName, BlockModule, ConfigVer} = config_utils:name_module_version(Config), BlockType = type_utils:type_name(BlockModule), case attrib_utils:set_value(Config, version, version()) of {ok, UpdConfig} -> m_logger:info(block_type_upgraded_from_ver_to, [BlockName, BlockType, ConfigVer, ModuleVer]), {ok, {UpdConfig, Inputs, Outputs}}; {error, Reason} -> m_logger:error(err_upgrading_block_type_from_ver_to, [Reason, BlockName, BlockType, ConfigVer, ModuleVer]), {error, Reason} end. %% Initialize block values %% Perform any setup here as needed before starting execution %% -spec initialize(BlockState :: block_state()) -> block_state(). initialize({Config, Inputs, Outputs, Private}) -> % INSTRUCTIONS: Perform block type specific initializations here % Add and intialize private attributes here Outputs1 = output_utils:set_value_status(Outputs, null, initialed), Private1 = Private, % This is the block state {Config, Inputs, Outputs1, Private1}. %% %% Execute the block specific functionality %% -spec execute(BlockState :: block_state(), ExecMethod :: exec_method()) -> block_state(). execute({Config, Inputs, Outputs, Private}, disable) -> % INSTRUCTIONS: If block's disable input value changes to true, % this function will be called. % Normally, just set all outputs to null, and set status output to disabled. % If block controls external resource(s) (i.e. hardware or external apps), % you may need to disable or default those resource(s) in this function. % As in the main execute() function, only the Outputs or Private % attrib values may be modified. Outputs1 = output_utils:update_all_outputs(Outputs, null, disabled), {Config, Inputs, Outputs1, Private}; execute({Config, Inputs, Outputs, Private}, _ExecMethod) -> % INSTRUCTIONS: Perform block type specific actions here, % read input value(s) calculate new output value(s) % set block output status and value % Example block execution: read input1 and set value output to same , and set status output to normal , unless error encountered reading input1 case input_utils:get_any_type(Inputs, input1) of {ok, InputVal} -> Outputs1 = output_utils:set_value_normal(Outputs, InputVal); {error, _Reason} -> Outputs1 = output_utils:set_value_status(Outputs, null, input_err) end, % Return updated block state {Config, Inputs, Outputs1, Private}. %% %% Delete the block %% -spec delete(BlockState :: block_state()) -> block_defn(). delete({Config, Inputs, Outputs, _Private}) -> % INSTRUCTIONS: Perform any block type specific delete functionality here % Return block definition, (Block state less Private values) % in case calling function wants to reuse them. % % Private values are created in the block initialization routine % So they should be deleted here {Config, Inputs, Outputs}. % INSTRUCTIONS: If needed, implement block type specific message handling functions here. % These function(s) are typically requrired for block types that interact with 3rd party libraries , external hardware , blocks on other nodes , or timers . % See: lblx_mqtt_pub_sub and lblx_gpio_di block types for examples If all of the messages are already handled in the block_server module , % these handle_*() functions are not required, and may be deleted. %% %% Handle block type specific call message(s) %% -spec handle_call(Request :: term(), From :: {pid(), Tag :: term()}, BlockState :: block_state()) -> {reply, ok, block_state()}. handle_call(Request, From, BlockState) -> {BlockName, BlockModule} = config_utils:name_module(BlockState), m_logger:warning(block_type_name_unknown_call_msg_from, [BlockModule, BlockName, Request, From]), {reply, ok, BlockState}. %% %% Handle block type specific cast message(s) %% -spec handle_cast(Msg :: term(), BlockState :: block_state()) -> {noreply, block_state()}. handle_cast(Msg, BlockState) -> {BlockName, BlockModule} = config_utils:name_module(BlockState), m_logger:warning(block_type_name_unknown_cast_msg, [BlockModule, BlockName, Msg]), {noreply, BlockState}. %% %% Handle block type specific info message(s) %% -spec handle_info(Info :: term(), BlockState :: block_state()) -> {noreply, block_state()}. handle_info(Info, BlockState) -> {BlockName, BlockModule} = config_utils:name_module(BlockState), m_logger:warning(block_type_name_unknown_info_msg, [BlockModule, BlockName, Info]), {noreply, BlockState}. %% ==================================================================== Internal functions %% ==================================================================== %% ==================================================================== %% Tests %% ==================================================================== % INSTRUCTIONS: Create unit tests here. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). % INSTRUCTIONS: include this test fixture to exercise the block's input to output functionality -include("block_io_test_gen.hrl"). % INSTRUCTIONS: % test_sets() is a list of tuples. Each tuple defines one I / O test , and contains an atom and 3 lists . % The atom is the execution method , default value input_cos . ( See the block_state.hrl module for a list of execution methods ) % The first list contains { config value i d , value } tuples . % The second list contains { input value i d , value } tuples , that the inputs of the block % will be set to before executing the block. % The third list contains { output value i d , value } tuples , that represent % the expected output values after executing the block % % Each tuple exec_method / config / input / output values tuple represents a test. % % A test consists of setting the input values to the input values of the list, % executing the block, and comparing the actual output values to the expected output values list % % The block state is preserved between each test, and used in the subsequent test. % Any input value IDs not specified in the input list, will not be modified before the test % Any output value IDs not specified in the output list, will not be compared after the test % % Execution method, config value list, and input value list are optional. % The expected output values list is mandatory % If the config values list is included, there must be and input values list too. % Empty lists are allowed % test_sets() -> [ {input_cos, [{config1, 123}], [{input1, "I/O Unit Test 1"}], [{status, normal}, {value, "I/O Unit Test 1"}]}, {input_cos, [], [{input1, "I/O Unit Test 2"}], [{status, normal}, {value, "I/O Unit Test 2"}]} ]. -endif.
null
https://raw.githubusercontent.com/mdsebald/link_blox_app/64034fa5854759ad16625b93e3dde65a9c65f615/src/block_types/lblx_template.erl
erlang
INSTRUCTIONS: Copy this module and modify as appropriate for the function this block will perform. Comments marked "INSTRUCTIONS:" may be deleted Instructions: Follow the formatting of the @doc comment block exactly as shown @doc DESCRIPTION INSTRUCTIONS: Insert description of block operation here Use as many lines as necessary LINKS for links to external resources related to this block such as hardware data sheets, etc. @end INSTRUCTIONS: Modify to match new block type module name All block type module names must begin with "lblx_" To allow the user to identify and create blocks, in each language module used: add a <module name => block type name string> pair Add a <module name => block type description> string pair INSTRUCTIONS: Adjust path to hrl file as needed ==================================================================== API functions ==================================================================== INSTRUCTIONS: Optional custom message handling functions. export the necessary function(s) here, and create the function(s) below. Otherwise, delete this line. INSTRUCTIONS: Set block type version number. Use pattern: Major.Minor.Patch When a block is created, the Config version attribute value is set to this version. When a block is loaded from a config file, the version attribute value is compared to this. If the versions are different, the upgrade() function is called. Merge the block type specific, Config, Input, and Output attributes with the common Config, Input, and Output attributes, that all block types have INTRUCTIONS: Insert block type specific config attribute tuples here Config attribute tuples consist of a value name and a value Example: {gpio_pin, {0}} The block is (re) initialized, when any config value is modified. INTRUCTIONS: Insert block type specific input attribute tuples here Input attribute tuples consist of a value name, a value, and a default value Array Example: {inputs, [{empty, {empty}}, {empty, {empty}}]} INTRUCTIONS: Insert block type specific output attribute tuples here Output attribute tuples consist of a value name, a calculated value, and a list of links to block input values Output values are always set to 'null' and empty link list on creation Example: {dwell, {null, []}} Array Example: {digit, [{null, []}, {null, []}]} Create a set of block attributes for this block type. and to add attributes to the lists of default attributes Update Default Config, Input, Output, and Private attribute values with the initial values passed into this function. If any of the intial attributes do not already exist in the default attribute lists, merge_attribute_lists() will create them. This is the block definition, Upgrade block attribute values, when block code and block data versions are different INSTRUCTIONS: This function is called, on block creation, when the module's version does not match the version in the block's config data. Depending on the version(s) perform any necessary adjustments to the block's attributes, to make it compatible with the current block type's code. If upgrading the attributes is not possible, return an error and reason. Perform any setup here as needed before starting execution INSTRUCTIONS: Perform block type specific initializations here Add and intialize private attributes here This is the block state Execute the block specific functionality INSTRUCTIONS: If block's disable input value changes to true, this function will be called. Normally, just set all outputs to null, and set status output to disabled. If block controls external resource(s) (i.e. hardware or external apps), you may need to disable or default those resource(s) in this function. As in the main execute() function, only the Outputs or Private attrib values may be modified. INSTRUCTIONS: Perform block type specific actions here, read input value(s) calculate new output value(s) set block output status and value Example block execution: Return updated block state Delete the block INSTRUCTIONS: Perform any block type specific delete functionality here Return block definition, (Block state less Private values) in case calling function wants to reuse them. Private values are created in the block initialization routine So they should be deleted here INSTRUCTIONS: If needed, implement block type specific message handling functions here. These function(s) are typically requrired for block types that See: lblx_mqtt_pub_sub and lblx_gpio_di block types for examples these handle_*() functions are not required, and may be deleted. Handle block type specific call message(s) Handle block type specific cast message(s) Handle block type specific info message(s) ==================================================================== ==================================================================== ==================================================================== Tests ==================================================================== INSTRUCTIONS: Create unit tests here. INSTRUCTIONS: include this test fixture to exercise the block's input to output functionality INSTRUCTIONS: test_sets() is a list of tuples. will be set to before executing the block. the expected output values after executing the block Each tuple exec_method / config / input / output values tuple represents a test. A test consists of setting the input values to the input values of the list, executing the block, and comparing the actual output values to the expected output values list The block state is preserved between each test, and used in the subsequent test. Any input value IDs not specified in the input list, will not be modified before the test Any output value IDs not specified in the output list, will not be compared after the test Execution method, config value list, and input value list are optional. The expected output values list is mandatory If the config values list is included, there must be and input values list too. Empty lists are allowed
It is used for generating LinkBlox web pages BLOCKTYPE INSTRUCTIONS : Insert a one line description of the block here INSTRUCTIONS : Insert URL(s ) here , ( one per line ) to uniquely identify them as LinkBlox block type modules . to the block_type_names ( ) map in each Language Module , to the block_type_descrs ( ) map in each Language Module , -module(lblx_template). -author("Your Name"). -include("../block_state.hrl"). INSTRUCTIONS : The following 10 functions must be implemented and exported by all block types -export([groups/0, version/0]). -export([create/2, create/4, create/5, upgrade/1, initialize/1, execute/2, delete/1]). If the block type needs to handle custom messages , not currently handled by block_server ( ) , -export([handle_call/3, handle_cast/2, handle_info/2]). INSTRUCTIONS : Classify block type , by assigning it to one or more groups groups() -> [none]. INSTRUCTIONS : Add a block type description string to each Language Module , version() -> "0.1.0". -spec default_configs(BlockName :: block_name(), Description :: string()) -> config_attribs(). default_configs(BlockName, Description) -> attrib_utils:merge_attribute_lists( block_common:configs(BlockName, ?MODULE, version(), Description), [ Array Example : { start_rows , [ { 1 } , { 2 } ] } {config1, {"Example Value"}} ]). -spec default_inputs() -> input_attribs(). default_inputs() -> attrib_utils:merge_attribute_lists( block_common:inputs(), [ Example : { hi_limit , { 100 , { 100 } } } {input1, {"Example Input Value", {"Example Input Value"}}} ]). -spec default_outputs() -> output_attribs(). default_outputs() -> attrib_utils:merge_attribute_lists( block_common:outputs(), [ {output1, {null, []}} ]). Init attributes are used to override the default attribute values -spec create(BlockName :: block_name(), Description :: string()) -> block_defn(). create(BlockName, Description) -> create(BlockName, Description, [], [], []). -spec create(BlockName :: block_name(), Description :: string(), InitConfig :: config_attribs(), InitInputs :: input_attribs()) -> block_defn(). create(BlockName, Description, InitConfig, InitInputs) -> create(BlockName, Description, InitConfig, InitInputs, []). -spec create(BlockName :: block_name(), Description :: string(), InitConfig :: config_attribs(), InitInputs :: input_attribs(), InitOutputs :: output_attribs()) -> block_defn(). create(BlockName, Description, InitConfig, InitInputs, InitOutputs) -> Config = attrib_utils:merge_attribute_lists(default_configs(BlockName, Description), InitConfig), Inputs = attrib_utils:merge_attribute_lists(default_inputs(), InitInputs), Outputs = attrib_utils:merge_attribute_lists(default_outputs(), InitOutputs), {Config, Inputs, Outputs}. -spec upgrade(BlockDefn :: block_defn()) -> {ok, block_defn()} | {error, atom()}. upgrade({Config, Inputs, Outputs}) -> ModuleVer = version(), {BlockName, BlockModule, ConfigVer} = config_utils:name_module_version(Config), BlockType = type_utils:type_name(BlockModule), case attrib_utils:set_value(Config, version, version()) of {ok, UpdConfig} -> m_logger:info(block_type_upgraded_from_ver_to, [BlockName, BlockType, ConfigVer, ModuleVer]), {ok, {UpdConfig, Inputs, Outputs}}; {error, Reason} -> m_logger:error(err_upgrading_block_type_from_ver_to, [Reason, BlockName, BlockType, ConfigVer, ModuleVer]), {error, Reason} end. Initialize block values -spec initialize(BlockState :: block_state()) -> block_state(). initialize({Config, Inputs, Outputs, Private}) -> Outputs1 = output_utils:set_value_status(Outputs, null, initialed), Private1 = Private, {Config, Inputs, Outputs1, Private1}. -spec execute(BlockState :: block_state(), ExecMethod :: exec_method()) -> block_state(). execute({Config, Inputs, Outputs, Private}, disable) -> Outputs1 = output_utils:update_all_outputs(Outputs, null, disabled), {Config, Inputs, Outputs1, Private}; execute({Config, Inputs, Outputs, Private}, _ExecMethod) -> read input1 and set value output to same , and set status output to normal , unless error encountered reading input1 case input_utils:get_any_type(Inputs, input1) of {ok, InputVal} -> Outputs1 = output_utils:set_value_normal(Outputs, InputVal); {error, _Reason} -> Outputs1 = output_utils:set_value_status(Outputs, null, input_err) end, {Config, Inputs, Outputs1, Private}. -spec delete(BlockState :: block_state()) -> block_defn(). delete({Config, Inputs, Outputs, _Private}) -> {Config, Inputs, Outputs}. interact with 3rd party libraries , external hardware , blocks on other nodes , or timers . If all of the messages are already handled in the block_server module , -spec handle_call(Request :: term(), From :: {pid(), Tag :: term()}, BlockState :: block_state()) -> {reply, ok, block_state()}. handle_call(Request, From, BlockState) -> {BlockName, BlockModule} = config_utils:name_module(BlockState), m_logger:warning(block_type_name_unknown_call_msg_from, [BlockModule, BlockName, Request, From]), {reply, ok, BlockState}. -spec handle_cast(Msg :: term(), BlockState :: block_state()) -> {noreply, block_state()}. handle_cast(Msg, BlockState) -> {BlockName, BlockModule} = config_utils:name_module(BlockState), m_logger:warning(block_type_name_unknown_cast_msg, [BlockModule, BlockName, Msg]), {noreply, BlockState}. -spec handle_info(Info :: term(), BlockState :: block_state()) -> {noreply, block_state()}. handle_info(Info, BlockState) -> {BlockName, BlockModule} = config_utils:name_module(BlockState), m_logger:warning(block_type_name_unknown_info_msg, [BlockModule, BlockName, Info]), {noreply, BlockState}. Internal functions -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -include("block_io_test_gen.hrl"). Each tuple defines one I / O test , and contains an atom and 3 lists . The atom is the execution method , default value input_cos . ( See the block_state.hrl module for a list of execution methods ) The first list contains { config value i d , value } tuples . The second list contains { input value i d , value } tuples , that the inputs of the block The third list contains { output value i d , value } tuples , that represent test_sets() -> [ {input_cos, [{config1, 123}], [{input1, "I/O Unit Test 1"}], [{status, normal}, {value, "I/O Unit Test 1"}]}, {input_cos, [], [{input1, "I/O Unit Test 2"}], [{status, normal}, {value, "I/O Unit Test 2"}]} ]. -endif.
364bab26f6cedb937ce860ea8cb42e5b772cec395d04251042396cc3a8fcb42a
splittist/docxplora
sml-namespaces.lisp
;;;; sml-namespaces.lisp (in-package #:sml) (defparameter *workbook-namespaces* '((nil . "") ("r" . "") ("mc" . "-compatibility/2006") ("x14ac" . "") ("x15" . "") ("x16r2" . "") ("xr" . "") ("xr2" . "") ("xr3" . "") ("xr4" . "") ("xr6" . "") ("xr10" . "") ("xlrd" . "") ("xda" . "") )) (defparameter *workbook-ignorables* '(("mc:Ignorable" . "x15 xr xr6 xr10 xr2")))
null
https://raw.githubusercontent.com/splittist/docxplora/1c843677f243ae9d2e4a71cac27859dcc1381075/sml/sml-namespaces.lisp
lisp
sml-namespaces.lisp
(in-package #:sml) (defparameter *workbook-namespaces* '((nil . "") ("r" . "") ("mc" . "-compatibility/2006") ("x14ac" . "") ("x15" . "") ("x16r2" . "") ("xr" . "") ("xr2" . "") ("xr3" . "") ("xr4" . "") ("xr6" . "") ("xr10" . "") ("xlrd" . "") ("xda" . "") )) (defparameter *workbook-ignorables* '(("mc:Ignorable" . "x15 xr xr6 xr10 xr2")))
c55ab93b2b9e6feeced867ab000d60b532148b8cbb4bca675080b524dda04170
bytekid/mkbtt
selectionParser.mli
type token = | SIZE_MAX | SIZE_SUM | SUM | MIN | CP | DATA | ELABEL | FLOAT of (string) | RANDOM | COUNT | PLUS | MINUS | TIMESTAMP | E | R | C | LPAREN | RPAREN | COMMA | COLON | EOF val start : (Lexing.lexbuf -> token) -> Lexing.lexbuf -> SelectionStrategy.t
null
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mkbtt/selectionParser.mli
ocaml
type token = | SIZE_MAX | SIZE_SUM | SUM | MIN | CP | DATA | ELABEL | FLOAT of (string) | RANDOM | COUNT | PLUS | MINUS | TIMESTAMP | E | R | C | LPAREN | RPAREN | COMMA | COLON | EOF val start : (Lexing.lexbuf -> token) -> Lexing.lexbuf -> SelectionStrategy.t
55451a8310507fd33b109ccedfb2ee95c4fde549f26d9a342c51ad3e9d6fdd5c
noinia/hgeometry
Webview.hs
{-# LANGUAGE OverloadedStrings #-} module Language.Javascript.JSaddle.Webview where import Control.Concurrent import qualified Data.Text as T (unpack, pack) import qualified Graphics.UI.Webviewhs as WHS import Language.Javascript.JSaddle (JSM, Results) import qualified Language.Javascript.JSaddle.Warp as JSaddle import System.Directory (getCurrentDirectory) -------------------------------------------------------------------------------- run :: Int -> JSM () -> IO () run port main = do -- pwd <- getCurrentDirectory -- let uri = "file://" <> T.pack pwd <> "/" let uri = ":" <> (T.pack $ show port) _thdId <- forkIO $ JSaddle.run port main WHS.createWindowAndBlock WHS.WindowParams { WHS.windowParamsTitle = "JSaddle" , WHS.windowParamsUri = uri , WHS.windowParamsWidth = 1600 , WHS.windowParamsHeight = 1000 , WHS.windowParamsResizable = False , WHS.windowParamsDebuggable = True }
null
https://raw.githubusercontent.com/noinia/hgeometry/a6abecb1ce4a7fd96b25cc1a5c65cd4257ecde7a/hgeometry-web/src/Language/Javascript/JSaddle/Webview.hs
haskell
# LANGUAGE OverloadedStrings # ------------------------------------------------------------------------------ pwd <- getCurrentDirectory let uri = "file://" <> T.pack pwd <> "/"
module Language.Javascript.JSaddle.Webview where import Control.Concurrent import qualified Data.Text as T (unpack, pack) import qualified Graphics.UI.Webviewhs as WHS import Language.Javascript.JSaddle (JSM, Results) import qualified Language.Javascript.JSaddle.Warp as JSaddle import System.Directory (getCurrentDirectory) run :: Int -> JSM () -> IO () run port main = do let uri = ":" <> (T.pack $ show port) _thdId <- forkIO $ JSaddle.run port main WHS.createWindowAndBlock WHS.WindowParams { WHS.windowParamsTitle = "JSaddle" , WHS.windowParamsUri = uri , WHS.windowParamsWidth = 1600 , WHS.windowParamsHeight = 1000 , WHS.windowParamsResizable = False , WHS.windowParamsDebuggable = True }
cecb7fcc09826692c75430c899c409d59cb2cc3d37d0888202cfb8f2595ad15f
pascal-knodel/haskell-craft
E'7'30.hs
-- -- -- ----------------- -- Exercise 7.30. ----------------- -- -- -- module E'7'30 where import Prelude hiding ( getLine ) import E'7'27 ( Line , Word , getLine , dropLine ) import GHC.List ( elem , splitAt ) import Data.List.Split ( splitOneOf ) import Test.QuickCheck Note : there is a problem with the Craft3e-0.1.0.10 release , it occurs if a word is longer than " " : GHCi > -- Craft3e-0.1.0.10 : -- < 100 ( ? ) let words = [ [ ' -'| _ < - [ 1 .. 100 ] ] ] splitLines words -- Craft3e-0.1.0.10: -- lineLength < 100 (?) let words = [ ['-'| _<- [ 1 .. 100 ] ] ] splitLines words -} -- 'endless loop of [[] ..]' -- Subchapter 7.6 (relevant definitions of it): whitespace :: [Char] whitespace = ['\n', '\t', ' '] lineLength :: Int lineLength = 30 dropSpace :: String -> String dropSpace [] = [] dropSpace string@( character : remainingCharacters ) | character `elem` whitespace = dropSpace remainingCharacters | otherwise = string getWord :: String -> String getWord [] = [] getWord ( character : remainingCharacters ) | character `elem` whitespace = [] | otherwise = character : getWord remainingCharacters dropWord :: String -> String dropWord [] = [] dropWord string@( character : remainingCharacters ) | character `elem` whitespace = string | otherwise = dropWord remainingCharacters splitWords :: String -> [Word] splitWords string = split (dropSpace string) split :: String -> [Word] split [] = [] split string = (getWord string) : split ( dropSpace (dropWord string) ) splitLines :: [Word] -> [Line] splitLines [] = [] splitLines words = (getLine lineLength words) : splitLines (dropLine lineLength words) -- ... -- +-%3E+[String] Note : There is a function " words " in the Prelude library . -- Besides the different set of white space characters -- this is the standard function to go with. splitWords' :: String -> [Word] splitWords' string = notEmptyWords where words :: [Word] words = splitOneOf whitespace string notEmptyWords :: [Word] notEmptyWords = [ word | word <- words, word /= "" ] prop_splitWords :: String -> Bool prop_splitWords string = splitWords string == splitWords' string GHCi > quickCheck splitAfter = splitAt -- Just aliasing / another name for the same function. splitIntoLines :: [String] -> [[String]] splitIntoLines [] = [] splitIntoLines words = line : splitIntoLines remainingWords where ( line , remainingWords ) = splitAfter lastWordInLine words :: ( Line , [Word] ) lastWordInLine :: Int lastWordInLine = countWordsForLine words lineLength countWordsForLine :: [String] -> Int -> Int countWordsForLine words maximumLineLength = countWordsForLine' words maximumLineLength 0 countWordsForLine' :: [String] -> Int -> Int -> Int countWordsForLine' [] _ _ = 0 Accumulates line - lengths in the third argument to " countWordsForLine ' " . | (currentLineLength + length word) <= maximumLineLength = 1 + countWordsForLine' remainingWords maximumLineLength (currentLineLength + length word + 1) | otherwise = 0 GHCi > let words = [ " 123456789 " | _ < - [ 1 .. 10 ] ] splitIntoLines [ ] splitIntoLines words lineLength let words = [ "123456789" | _ <- [1 .. 10] ] splitIntoLines [] splitIntoLines words -} 30 -- [] -- -- [ [ " 123456789 " , " 123456789 " , " 123456789 " ] , [ " 123456789 " , " 123456789 " , " 123456789 " ] , [ " 123456789 " , " 123456789 " , " 123456789 " ] , [ " 123456789 " ] -- ] prop_splitLines :: [Word] -> Property prop_splitLines words = [] == [ word | word <- words, length word > lineLength ] -- If no word is longer than the maximum line length then: ==> splitLines words == splitIntoLines words GHCi > quickCheck prop_splitLines GHCi > quickCheck prop_splitWords quickCheck prop_splitLines quickCheck prop_splitWords quickCheck prop_splitLines -}
null
https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/_/links/E'7'30.hs
haskell
--------------- Exercise 7.30. --------------- Craft3e-0.1.0.10 : < 100 ( ? ) Craft3e-0.1.0.10: lineLength < 100 (?) 'endless loop of [[] ..]' Subchapter 7.6 (relevant definitions of it): ... +-%3E+[String] Besides the different set of white space characters this is the standard function to go with. Just aliasing / another name for the same function. [] [ ] If no word is longer than the maximum line length then:
module E'7'30 where import Prelude hiding ( getLine ) import E'7'27 ( Line , Word , getLine , dropLine ) import GHC.List ( elem , splitAt ) import Data.List.Split ( splitOneOf ) import Test.QuickCheck Note : there is a problem with the Craft3e-0.1.0.10 release , it occurs if a word is longer than " " : GHCi > let words = [ [ ' -'| _ < - [ 1 .. 100 ] ] ] splitLines words let words = [ ['-'| _<- [ 1 .. 100 ] ] ] splitLines words -} whitespace :: [Char] whitespace = ['\n', '\t', ' '] lineLength :: Int lineLength = 30 dropSpace :: String -> String dropSpace [] = [] dropSpace string@( character : remainingCharacters ) | character `elem` whitespace = dropSpace remainingCharacters | otherwise = string getWord :: String -> String getWord [] = [] getWord ( character : remainingCharacters ) | character `elem` whitespace = [] | otherwise = character : getWord remainingCharacters dropWord :: String -> String dropWord [] = [] dropWord string@( character : remainingCharacters ) | character `elem` whitespace = string | otherwise = dropWord remainingCharacters splitWords :: String -> [Word] splitWords string = split (dropSpace string) split :: String -> [Word] split [] = [] split string = (getWord string) : split ( dropSpace (dropWord string) ) splitLines :: [Word] -> [Line] splitLines [] = [] splitLines words = (getLine lineLength words) : splitLines (dropLine lineLength words) Note : There is a function " words " in the Prelude library . splitWords' :: String -> [Word] splitWords' string = notEmptyWords where words :: [Word] words = splitOneOf whitespace string notEmptyWords :: [Word] notEmptyWords = [ word | word <- words, word /= "" ] prop_splitWords :: String -> Bool prop_splitWords string = splitWords string == splitWords' string GHCi > quickCheck splitIntoLines :: [String] -> [[String]] splitIntoLines [] = [] splitIntoLines words = line : splitIntoLines remainingWords where ( line , remainingWords ) = splitAfter lastWordInLine words :: ( Line , [Word] ) lastWordInLine :: Int lastWordInLine = countWordsForLine words lineLength countWordsForLine :: [String] -> Int -> Int countWordsForLine words maximumLineLength = countWordsForLine' words maximumLineLength 0 countWordsForLine' :: [String] -> Int -> Int -> Int countWordsForLine' [] _ _ = 0 Accumulates line - lengths in the third argument to " countWordsForLine ' " . | (currentLineLength + length word) <= maximumLineLength = 1 + countWordsForLine' remainingWords maximumLineLength (currentLineLength + length word + 1) | otherwise = 0 GHCi > let words = [ " 123456789 " | _ < - [ 1 .. 10 ] ] splitIntoLines [ ] splitIntoLines words lineLength let words = [ "123456789" | _ <- [1 .. 10] ] splitIntoLines [] splitIntoLines words -} 30 [ " 123456789 " , " 123456789 " , " 123456789 " ] , [ " 123456789 " , " 123456789 " , " 123456789 " ] , [ " 123456789 " , " 123456789 " , " 123456789 " ] , [ " 123456789 " ] prop_splitLines :: [Word] -> Property prop_splitLines words = [] == [ word | word <- words, length word > lineLength ] ==> splitLines words == splitIntoLines words GHCi > quickCheck prop_splitLines GHCi > quickCheck prop_splitWords quickCheck prop_splitLines quickCheck prop_splitWords quickCheck prop_splitLines -}
61ee9aeae60f92b8f886727a931f181a6afb918e806f3fca472c966c847702fa
pbrisbin/yesod-paginator
Main.hs
# LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # OPTIONS_GHC -Wno - missing - deriving - strategies # # OPTIONS_GHC -Wno - missing - local - signatures # {-# OPTIONS_GHC -Wno-unused-top-binds #-} module Main ( main ) where import Prelude import Network.Wai.Handler.Warp (run) import Yesod import Yesod.Paginator data App = App mkYesod "App" [parseRoutes| / RootR GET |] instance Yesod App where approot = ApprootRelative defaultLayout widget = do pc <- widgetToPageContent widget withUrlRenderer [hamlet|$newline never $doctype 5 <html lang="en"> <head> <meta charset="utf-8"> <title>#{pageTitle pc} Get Boostrap from CDN -- > <link href="" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw==" crossorigin="anonymous"> ^{pageHead pc} <body> <div .container> ^{pageBody pc} |] getRootR :: Handler Html getRootR = do let things' = [1 .. 1142] :: [Int] pages <- paginate 3 things' defaultLayout $ do setTitle "My title" [whamlet|$newline never <h1>Pagination Examples <h2>The things: <ul> $forall thing <- pageItems $ pagesCurrent pages <li>Thing #{show thing} <h2>Simple navigation <div .pagination> ^{simple 10 pages} <h2>Ellipsed navigation <div .pagination> ^{ellipsed 10 pages} |] main :: IO () main = run 3000 =<< toWaiApp App
null
https://raw.githubusercontent.com/pbrisbin/yesod-paginator/7c9aa7981bd5252b919737f2f61546b3b41d14d9/example/Main.hs
haskell
# LANGUAGE OverloadedStrings # # OPTIONS_GHC -Wno-unused-top-binds # >
# LANGUAGE MultiParamTypeClasses # # LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # OPTIONS_GHC -Wno - missing - deriving - strategies # # OPTIONS_GHC -Wno - missing - local - signatures # module Main ( main ) where import Prelude import Network.Wai.Handler.Warp (run) import Yesod import Yesod.Paginator data App = App mkYesod "App" [parseRoutes| / RootR GET |] instance Yesod App where approot = ApprootRelative defaultLayout widget = do pc <- widgetToPageContent widget withUrlRenderer [hamlet|$newline never $doctype 5 <html lang="en"> <head> <meta charset="utf-8"> <title>#{pageTitle pc} <link href="" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw==" crossorigin="anonymous"> ^{pageHead pc} <body> <div .container> ^{pageBody pc} |] getRootR :: Handler Html getRootR = do let things' = [1 .. 1142] :: [Int] pages <- paginate 3 things' defaultLayout $ do setTitle "My title" [whamlet|$newline never <h1>Pagination Examples <h2>The things: <ul> $forall thing <- pageItems $ pagesCurrent pages <li>Thing #{show thing} <h2>Simple navigation <div .pagination> ^{simple 10 pages} <h2>Ellipsed navigation <div .pagination> ^{ellipsed 10 pages} |] main :: IO () main = run 3000 =<< toWaiApp App
ea2b2cdcc309a134e2bae13bb2d4b7735c74e88eb88d40d74a699906f7cc13a9
bortexz/resocket
resocket.clj
(ns bortexz.resocket (:require [clojure.core.async :as a]) (:import (java.net.http WebSocket$Listener WebSocket$Builder HttpClient WebSocket) (java.io ByteArrayOutputStream) (java.nio.channels Channels) (java.nio ByteBuffer) (java.time Duration) (java.net URI ConnectException))) ;; Impl ;; (defprotocol -Sendable "Implementation detail. Protocol for sending different message types." (-send [data ws])) (extend-protocol -Sendable (Class/forName "[B") (-send [data ^WebSocket ws] (.sendBinary ws (ByteBuffer/wrap data) true)) CharSequence (-send [data ^WebSocket ws] (.sendText ws data true))) (defn- signal-closed [{:keys [input output closed]} {:keys [ping pong]} close-args] (a/put! closed close-args) (run! a/close! [input output ping pong])) (defn- abort [conn ka-chs {::keys [-abort!]}] (-abort! (:ws conn)) (signal-closed conn ka-chs {:close-type :abort})) (defn- text-handler [input parse-input] (let [sb (StringBuilder.)] (fn [data last?] (.append sb data) (when last? (a/>!! input (parse-input (.toString sb))) (.setLength sb 0) nil)))) (defn- binary-handler [input parse-input] (let [baos (ByteArrayOutputStream.) baosc (Channels/newChannel baos)] (fn [data last?] (.write baosc data) (when last? (a/>!! input (parse-input (.toByteArray baos))) (.reset baos)) nil))) (defn- build-listener [{:keys [input] :as conn} {:keys [pong] :as ka-chs} {:keys [input-parser]}] (let [handle-text (text-handler input input-parser) handle-binary (binary-handler input input-parser)] (reify WebSocket$Listener (onText [_ ws data last?] (handle-text data last?) (.request ws 1) nil) (onBinary [_ ws data last?] (handle-binary data last?) (.request ws 1) nil) (onPong [_ ws data] (a/>!! pong data) (.request ws 1) nil) (onClose [_ _ status description] (signal-closed conn ka-chs {:close-type :on-close :status status :description description}) nil) (onError [_ _ err] (signal-closed conn ka-chs {:close-type :on-error :error err}) nil)))) (defn- send-process [{:keys [output closed ws] :as conn} {:keys [ping] :as ka-chs} {:keys [output-parser ex-handler close-timeout] ::keys [-ping! -close! -send!] :as opts}] (a/thread (loop [] (let [[v p] (a/alts!! [ping output])] (when (not (.isOutputClosed ^WebSocket ws)) (try (condp = p output (if (some? v) @(-send! ws (output-parser v)) (do @(-close! ws) (when (pos-int? close-timeout) (a/alt!! [closed (a/timeout close-timeout)] ([_ p] (when-not (= p closed) (abort conn ka-chs opts))))))) ping @(-ping! ws v)) (catch Exception e (ex-handler (ex-info "Error sending output" {:val v :port (if (= p ping) :ping :output) :error e})))) (recur)))))) (defn- heartbeat-process [conn {:keys [ping pong] :as ka-chs} {:keys [ping-interval ping-timeout ping-payload] :as opts}] (a/go-loop [pending-pong? false timer (a/timeout ping-interval)] (a/alt! [timer pong] ([v p] (condp = p timer (if pending-pong? (abort conn ka-chs opts) (do (a/>! ping ping-payload) (if ping-timeout (recur true (a/timeout ping-timeout)) (recur false (a/timeout ping-interval))))) pong (when (some? v) (recur false (a/timeout ping-interval)))))))) (def ^:private default-connection-opts {:ping-interval 30000 :ping-timeout 10000 :ping-payload (byte-array []) :connect-timeout 30000 :close-timeout 10000 :input-parser identity :output-parser identity :ex-handler (fn [ex] (-> (Thread/currentThread) .getUncaughtExceptionHandler (.uncaughtException (Thread/currentThread) ex)) nil)}) (def ^:private -default-websocket-fns {::-ping! (fn [ws data] (.sendPing ^WebSocket ws (ByteBuffer/wrap data))) ::-close! (fn [ws] (.sendClose ^WebSocket ws WebSocket/NORMAL_CLOSURE "")) ::-send! (fn [ws data] (-send data ws)) ::-abort! (fn [ws] (.abort ^WebSocket ws))}) (defn- with-headers ^WebSocket$Builder [builder headers] (reduce-kv (fn [^WebSocket$Builder b ^String hk ^String hv] (.header b hk hv)) builder headers)) (defn- create-ws [url {:keys [http-client connect-timeout headers subprotocols listener]}] (let [^HttpClient http-client (if (instance? HttpClient http-client) http-client (HttpClient/newHttpClient))] (cond-> (.newWebSocketBuilder http-client) connect-timeout (.connectTimeout (Duration/ofMillis connect-timeout)) (seq subprotocols) (.subprotocols (first subprotocols) (into-array String (rest subprotocols))) headers (with-headers headers) true (.buildAsync (URI/create url) listener)))) ;; ;; Public API ;; (defn connection "creates a websocket connection given `url` and (optional) `opts`. If successful, returns a map of: - `ws` wrapped jdk11 websocket. - `input` chan of received messages. Closed when the connection closes. - `output` chan to send messages, and close the connection (closing the chan). Closed when connection is closed. - `closed` promise-chan that will be delivered once the connection is closed with a map of: - `close-type` either `#{:on-close :on-error :abort}`. `:abort` is used when aborting connection through heartbeat-timeout or close-timeout elapsed (see `opts` below). - (when close-type :on-close) `status` and `description` - (when close-type :on-error) `error` If an exception happens when opening a connection, returns a map of: - `error` the exception that was thrown Available opts: - `ping-interval` milliseconds interval to send ping frames to the server. Defaults 30000 (30 secs). - `ping-timeout` if ellapsed milliseconds without receiving a pong, aborts the connection. Defaults 10000 (10 secs). - `ping-payload` ping frame byte-array. Defaults to empty byte-array. - `http-client` java.net.http.HttpClient instance to use, it will create a default one if not specified. - `connect-timeout` timeout in milliseconds to wait for establish a connection. Defaults to 30000 (30 secs) - `headers` map string->string with headers to use in http-client - `subprotocols` coll of string subprotocols to use - `input-buf` int/buffer to use on input chan. Unbuffered by default. - `output-buf` int/buffer to use on output chan. Unbuffered by default. - `input-parser` unary fn that will be called with complete messages received (either byte-array or string) and parses it before putting it into input chan. Defaults to identity. - `output-parser` unary fn that will be called with output messages before sending them through the websocket. Must return a String (for sending text) or a byte-array (for sending binary). Defaults to identity. - `close-timeout` (optional) millisecond to wait before aborting the connection after closing the output. Defaults to 10000 (10 secs). - `ex-handler` (optional) unary fn called with errors happening on internal calls to the jdk11 websocket. Defaults to use uncaught exception handler. Errors are wrapped in an ExceptionInfo that contains :val, :port and :error on its data." ([url] (connection url {})) ([url {:keys [ping-interval ping-timeout ping-payload http-client connect-timeout headers subprotocols input-buf output-buf input-parser output-parser close-timeout ex-handler] :as opts}] (let [opts (merge default-connection-opts -default-websocket-fns opts) input (a/chan input-buf) output (a/chan output-buf) ping (a/chan) pong (a/chan (a/dropping-buffer 1)) closed (a/promise-chan) conn {:input input :output output :closed closed} ka-chs {:ping ping :pong pong}] (a/thread (try (let [ws @(create-ws url (merge opts {:listener (build-listener conn ka-chs opts)})) conn (assoc conn :ws ws)] (send-process conn ka-chs opts) (when ping-interval (heartbeat-process conn ka-chs opts)) conn) (catch Exception e {:error (ex-cause e)})))))) (defn reconnector "Creates a reconnector process that will create a new connection when the previous one has been closed. If creating a new connection fails, then function `on-error-retry-fn?` will be called with the error, and if it does not return true, the reconnector will be closed. If it returns true, then `retry-ms-fn` is called with the current attempt, and must return an integer or nil. If returns integer, reconnector will wait that amount of milliseconds to retry a new connection. If it returns nil, the reconnector will be closed. Returns map of: - `connections` unbuffered chan of new connections. Will be closed when the reconnector is closed. - `close` promise-chan that will close the reconnector when delivered or closed. It will close currently active connection if there's one. - `closed?` promise-chan that will be delivered with `true` when the reconnector is closed. Available opts: - `get-url` called each time a new connection is attempted to get the url to be used on [[connection]]. - `get-opts` called each time a new connection is attempted to get the options to be used on [[connection]]. - `retry-ms-fn` unary fn called with the current attempt at reconnecting, starting at 1. It must return a numer of milliseconds to wait before retrying a new connection, or nil to close the reconnector. Defaults to 5000 (5 secs). - `on-error-retry-fn?` unary fn called with error when creating a new connection. Must return true to start a retry timeout to retry, otherwise the reconnector will be closed. Note: It is called with the original Exception unwrapped, which will be an ExecutionException from the CompletableFuture returned by creating a new Websocket in JDK11. You might want to get the wrapped exception for more details `(ex-cause <error>)`. Defaults to returning logical true when the wrapped exception is either a java.net.ConnectException or java.net.http.HttpTimeoutException, false otherwise." [{:keys [retry-ms-fn on-error-retry-fn? get-url get-opts] :or {retry-ms-fn (constantly 5000) on-error-retry-fn? (fn [err] (let [ex (ex-cause err)] (or (instance? java.net.ConnectException ex) (instance? java.net.http.HttpTimeoutException ex)))) get-opts (constantly nil)}}] (let [connections (a/chan) close (a/promise-chan) closed? (a/promise-chan) close! (fn [] (a/close! connections) (a/put! closed? true))] (a/go-loop [retry-att 0 conn nil] (if (some? conn) (let [{conn-closed :closed conn-output :output} conn [_ p] (a/alts! [conn-closed close])] (condp = p conn-closed (recur 0 nil) close (do (a/close! conn-output) (a/<! conn-closed) (close!)))) (let [retry-ms (if (pos? retry-att) (retry-ms-fn retry-att) 0) timer? (pos? retry-ms) retry? (or (and (not timer?) retry-ms (zero? retry-ms)) (and timer? (a/alt! [(a/timeout retry-ms) close] ([_ p] (not= p close)))))] (if retry? (let [{:keys [error] :as conn} (a/<! (connection (get-url) (get-opts)))] (if-not error (do (a/>! connections conn) (recur 0 conn)) (if (on-error-retry-fn? error) (recur (inc retry-att) nil) (close!)))) (close!))))) {:connections connections :close close :closed? closed?}))
null
https://raw.githubusercontent.com/bortexz/resocket/67cfea0e3c69a3a3c91160d5795e067a221d358a/src/bortexz/resocket.clj
clojure
Public API
(ns bortexz.resocket (:require [clojure.core.async :as a]) (:import (java.net.http WebSocket$Listener WebSocket$Builder HttpClient WebSocket) (java.io ByteArrayOutputStream) (java.nio.channels Channels) (java.nio ByteBuffer) (java.time Duration) (java.net URI ConnectException))) Impl (defprotocol -Sendable "Implementation detail. Protocol for sending different message types." (-send [data ws])) (extend-protocol -Sendable (Class/forName "[B") (-send [data ^WebSocket ws] (.sendBinary ws (ByteBuffer/wrap data) true)) CharSequence (-send [data ^WebSocket ws] (.sendText ws data true))) (defn- signal-closed [{:keys [input output closed]} {:keys [ping pong]} close-args] (a/put! closed close-args) (run! a/close! [input output ping pong])) (defn- abort [conn ka-chs {::keys [-abort!]}] (-abort! (:ws conn)) (signal-closed conn ka-chs {:close-type :abort})) (defn- text-handler [input parse-input] (let [sb (StringBuilder.)] (fn [data last?] (.append sb data) (when last? (a/>!! input (parse-input (.toString sb))) (.setLength sb 0) nil)))) (defn- binary-handler [input parse-input] (let [baos (ByteArrayOutputStream.) baosc (Channels/newChannel baos)] (fn [data last?] (.write baosc data) (when last? (a/>!! input (parse-input (.toByteArray baos))) (.reset baos)) nil))) (defn- build-listener [{:keys [input] :as conn} {:keys [pong] :as ka-chs} {:keys [input-parser]}] (let [handle-text (text-handler input input-parser) handle-binary (binary-handler input input-parser)] (reify WebSocket$Listener (onText [_ ws data last?] (handle-text data last?) (.request ws 1) nil) (onBinary [_ ws data last?] (handle-binary data last?) (.request ws 1) nil) (onPong [_ ws data] (a/>!! pong data) (.request ws 1) nil) (onClose [_ _ status description] (signal-closed conn ka-chs {:close-type :on-close :status status :description description}) nil) (onError [_ _ err] (signal-closed conn ka-chs {:close-type :on-error :error err}) nil)))) (defn- send-process [{:keys [output closed ws] :as conn} {:keys [ping] :as ka-chs} {:keys [output-parser ex-handler close-timeout] ::keys [-ping! -close! -send!] :as opts}] (a/thread (loop [] (let [[v p] (a/alts!! [ping output])] (when (not (.isOutputClosed ^WebSocket ws)) (try (condp = p output (if (some? v) @(-send! ws (output-parser v)) (do @(-close! ws) (when (pos-int? close-timeout) (a/alt!! [closed (a/timeout close-timeout)] ([_ p] (when-not (= p closed) (abort conn ka-chs opts))))))) ping @(-ping! ws v)) (catch Exception e (ex-handler (ex-info "Error sending output" {:val v :port (if (= p ping) :ping :output) :error e})))) (recur)))))) (defn- heartbeat-process [conn {:keys [ping pong] :as ka-chs} {:keys [ping-interval ping-timeout ping-payload] :as opts}] (a/go-loop [pending-pong? false timer (a/timeout ping-interval)] (a/alt! [timer pong] ([v p] (condp = p timer (if pending-pong? (abort conn ka-chs opts) (do (a/>! ping ping-payload) (if ping-timeout (recur true (a/timeout ping-timeout)) (recur false (a/timeout ping-interval))))) pong (when (some? v) (recur false (a/timeout ping-interval)))))))) (def ^:private default-connection-opts {:ping-interval 30000 :ping-timeout 10000 :ping-payload (byte-array []) :connect-timeout 30000 :close-timeout 10000 :input-parser identity :output-parser identity :ex-handler (fn [ex] (-> (Thread/currentThread) .getUncaughtExceptionHandler (.uncaughtException (Thread/currentThread) ex)) nil)}) (def ^:private -default-websocket-fns {::-ping! (fn [ws data] (.sendPing ^WebSocket ws (ByteBuffer/wrap data))) ::-close! (fn [ws] (.sendClose ^WebSocket ws WebSocket/NORMAL_CLOSURE "")) ::-send! (fn [ws data] (-send data ws)) ::-abort! (fn [ws] (.abort ^WebSocket ws))}) (defn- with-headers ^WebSocket$Builder [builder headers] (reduce-kv (fn [^WebSocket$Builder b ^String hk ^String hv] (.header b hk hv)) builder headers)) (defn- create-ws [url {:keys [http-client connect-timeout headers subprotocols listener]}] (let [^HttpClient http-client (if (instance? HttpClient http-client) http-client (HttpClient/newHttpClient))] (cond-> (.newWebSocketBuilder http-client) connect-timeout (.connectTimeout (Duration/ofMillis connect-timeout)) (seq subprotocols) (.subprotocols (first subprotocols) (into-array String (rest subprotocols))) headers (with-headers headers) true (.buildAsync (URI/create url) listener)))) (defn connection "creates a websocket connection given `url` and (optional) `opts`. If successful, returns a map of: - `ws` wrapped jdk11 websocket. - `input` chan of received messages. Closed when the connection closes. - `output` chan to send messages, and close the connection (closing the chan). Closed when connection is closed. - `closed` promise-chan that will be delivered once the connection is closed with a map of: - `close-type` either `#{:on-close :on-error :abort}`. `:abort` is used when aborting connection through heartbeat-timeout or close-timeout elapsed (see `opts` below). - (when close-type :on-close) `status` and `description` - (when close-type :on-error) `error` If an exception happens when opening a connection, returns a map of: - `error` the exception that was thrown Available opts: - `ping-interval` milliseconds interval to send ping frames to the server. Defaults 30000 (30 secs). - `ping-timeout` if ellapsed milliseconds without receiving a pong, aborts the connection. Defaults 10000 (10 secs). - `ping-payload` ping frame byte-array. Defaults to empty byte-array. - `http-client` java.net.http.HttpClient instance to use, it will create a default one if not specified. - `connect-timeout` timeout in milliseconds to wait for establish a connection. Defaults to 30000 (30 secs) - `headers` map string->string with headers to use in http-client - `subprotocols` coll of string subprotocols to use - `input-buf` int/buffer to use on input chan. Unbuffered by default. - `output-buf` int/buffer to use on output chan. Unbuffered by default. - `input-parser` unary fn that will be called with complete messages received (either byte-array or string) and parses it before putting it into input chan. Defaults to identity. - `output-parser` unary fn that will be called with output messages before sending them through the websocket. Must return a String (for sending text) or a byte-array (for sending binary). Defaults to identity. - `close-timeout` (optional) millisecond to wait before aborting the connection after closing the output. Defaults to 10000 (10 secs). - `ex-handler` (optional) unary fn called with errors happening on internal calls to the jdk11 websocket. Defaults to use uncaught exception handler. Errors are wrapped in an ExceptionInfo that contains :val, :port and :error on its data." ([url] (connection url {})) ([url {:keys [ping-interval ping-timeout ping-payload http-client connect-timeout headers subprotocols input-buf output-buf input-parser output-parser close-timeout ex-handler] :as opts}] (let [opts (merge default-connection-opts -default-websocket-fns opts) input (a/chan input-buf) output (a/chan output-buf) ping (a/chan) pong (a/chan (a/dropping-buffer 1)) closed (a/promise-chan) conn {:input input :output output :closed closed} ka-chs {:ping ping :pong pong}] (a/thread (try (let [ws @(create-ws url (merge opts {:listener (build-listener conn ka-chs opts)})) conn (assoc conn :ws ws)] (send-process conn ka-chs opts) (when ping-interval (heartbeat-process conn ka-chs opts)) conn) (catch Exception e {:error (ex-cause e)})))))) (defn reconnector "Creates a reconnector process that will create a new connection when the previous one has been closed. If creating a new connection fails, then function `on-error-retry-fn?` will be called with the error, and if it does not return true, the reconnector will be closed. If it returns true, then `retry-ms-fn` is called with the current attempt, and must return an integer or nil. If returns integer, reconnector will wait that amount of milliseconds to retry a new connection. If it returns nil, the reconnector will be closed. Returns map of: - `connections` unbuffered chan of new connections. Will be closed when the reconnector is closed. - `close` promise-chan that will close the reconnector when delivered or closed. It will close currently active connection if there's one. - `closed?` promise-chan that will be delivered with `true` when the reconnector is closed. Available opts: - `get-url` called each time a new connection is attempted to get the url to be used on [[connection]]. - `get-opts` called each time a new connection is attempted to get the options to be used on [[connection]]. - `retry-ms-fn` unary fn called with the current attempt at reconnecting, starting at 1. It must return a numer of milliseconds to wait before retrying a new connection, or nil to close the reconnector. Defaults to 5000 (5 secs). - `on-error-retry-fn?` unary fn called with error when creating a new connection. Must return true to start a retry timeout to retry, otherwise the reconnector will be closed. Note: It is called with the original Exception unwrapped, which will be an ExecutionException from the CompletableFuture returned by creating a new Websocket in JDK11. You might want to get the wrapped exception for more details `(ex-cause <error>)`. Defaults to returning logical true when the wrapped exception is either a java.net.ConnectException or java.net.http.HttpTimeoutException, false otherwise." [{:keys [retry-ms-fn on-error-retry-fn? get-url get-opts] :or {retry-ms-fn (constantly 5000) on-error-retry-fn? (fn [err] (let [ex (ex-cause err)] (or (instance? java.net.ConnectException ex) (instance? java.net.http.HttpTimeoutException ex)))) get-opts (constantly nil)}}] (let [connections (a/chan) close (a/promise-chan) closed? (a/promise-chan) close! (fn [] (a/close! connections) (a/put! closed? true))] (a/go-loop [retry-att 0 conn nil] (if (some? conn) (let [{conn-closed :closed conn-output :output} conn [_ p] (a/alts! [conn-closed close])] (condp = p conn-closed (recur 0 nil) close (do (a/close! conn-output) (a/<! conn-closed) (close!)))) (let [retry-ms (if (pos? retry-att) (retry-ms-fn retry-att) 0) timer? (pos? retry-ms) retry? (or (and (not timer?) retry-ms (zero? retry-ms)) (and timer? (a/alt! [(a/timeout retry-ms) close] ([_ p] (not= p close)))))] (if retry? (let [{:keys [error] :as conn} (a/<! (connection (get-url) (get-opts)))] (if-not error (do (a/>! connections conn) (recur 0 conn)) (if (on-error-retry-fn? error) (recur (inc retry-att) nil) (close!)))) (close!))))) {:connections connections :close close :closed? closed?}))
486d18570aee48324efa10b84578e90d0296c71501f4f9e80394c63c95a60637
bcc32/advent-of-code
main.ml
open! Core open! Async open! Import let parse_line = let re = let open Re in compile (seq [ group (rep1 wordc); str " => "; group (rep1 wordc) ]) in fun line -> let group = Re.exec re line in let lhs = Re.Group.get group 1 in let rhs = Re.Group.get group 2 in lhs, rhs ;; let parse_lines lines = let replacements, rest = List.split_while lines ~f:(Fn.non String.is_empty) |> Tuple2.map_fst ~f:(List.map ~f:parse_line) in let rest = List.tl_exn rest in let init = List.hd_exn rest in replacements, init ;; let input = Lazy_deferred.create (fun () -> Reader.file_contents "input.txt" >>| String.split_lines >>| parse_lines) ;; let do_all_replacements replacements init = let results = String.Hash_set.create () in List.iter replacements ~f:(fun (lhs, rhs) -> let lhs_pat = let open Re in compile (str lhs) in Re.Seq.all lhs_pat init |> Seq.iter (fun group -> let before = String.sub init ~pos:0 ~len:(Re.Group.start group 0) in let after = String.subo init ~pos:(Re.Group.stop group 0) in let s = before ^ rhs ^ after in Hash_set.add results s)); results ;; let a () = let%bind input = Lazy_deferred.force_exn input in let replacements, init = input in let set = do_all_replacements replacements init in print_s [%sexp (Hash_set.length set : int)]; return () ;; let%expect_test "a" = let%bind () = a () in [%expect {| 509 |}]; return () ;; let b () = let%bind input = Lazy_deferred.force_exn input in let replacements, start = input in let replacements = List.sort replacements ~compare:(Comparable.lift ~f:snd (Comparable.lift ~f:String.length Int.descending)) |> List.map ~f:(Tuple2.map_snd ~f:(fun rhs -> String.Search_pattern.create rhs)) in let queue = Pairing_heap.create ~cmp:(Comparable.lift ~f:fst (Comparable.lift ~f:String.length Int.compare)) () in Pairing_heap.add queue (start, 0); let ans = with_return (fun { return } -> while not (Pairing_heap.is_empty queue) do let start, dist = Pairing_heap.pop_exn queue in if String.equal start "e" then return dist; List.iter replacements ~f:(fun (lhs, rhs) -> Option.iter (String.Search_pattern.index rhs ~in_:start) ~f:(fun index -> let rhs_len = String.length (String.Search_pattern.pattern rhs) in let str = String.sub start ~pos:0 ~len:index ^ lhs ^ String.drop_prefix start (index + rhs_len) in Pairing_heap.add queue (str, dist + 1))) done; assert false) in print_s [%sexp (ans : int)]; return () ;; let%expect_test "b" = let%bind () = b () in [%expect {| 195 |}]; return () ;;
null
https://raw.githubusercontent.com/bcc32/advent-of-code/86a9387c3d6be2afe07d2657a0607749217b1b77/2015/day_19/main.ml
ocaml
open! Core open! Async open! Import let parse_line = let re = let open Re in compile (seq [ group (rep1 wordc); str " => "; group (rep1 wordc) ]) in fun line -> let group = Re.exec re line in let lhs = Re.Group.get group 1 in let rhs = Re.Group.get group 2 in lhs, rhs ;; let parse_lines lines = let replacements, rest = List.split_while lines ~f:(Fn.non String.is_empty) |> Tuple2.map_fst ~f:(List.map ~f:parse_line) in let rest = List.tl_exn rest in let init = List.hd_exn rest in replacements, init ;; let input = Lazy_deferred.create (fun () -> Reader.file_contents "input.txt" >>| String.split_lines >>| parse_lines) ;; let do_all_replacements replacements init = let results = String.Hash_set.create () in List.iter replacements ~f:(fun (lhs, rhs) -> let lhs_pat = let open Re in compile (str lhs) in Re.Seq.all lhs_pat init |> Seq.iter (fun group -> let before = String.sub init ~pos:0 ~len:(Re.Group.start group 0) in let after = String.subo init ~pos:(Re.Group.stop group 0) in let s = before ^ rhs ^ after in Hash_set.add results s)); results ;; let a () = let%bind input = Lazy_deferred.force_exn input in let replacements, init = input in let set = do_all_replacements replacements init in print_s [%sexp (Hash_set.length set : int)]; return () ;; let%expect_test "a" = let%bind () = a () in [%expect {| 509 |}]; return () ;; let b () = let%bind input = Lazy_deferred.force_exn input in let replacements, start = input in let replacements = List.sort replacements ~compare:(Comparable.lift ~f:snd (Comparable.lift ~f:String.length Int.descending)) |> List.map ~f:(Tuple2.map_snd ~f:(fun rhs -> String.Search_pattern.create rhs)) in let queue = Pairing_heap.create ~cmp:(Comparable.lift ~f:fst (Comparable.lift ~f:String.length Int.compare)) () in Pairing_heap.add queue (start, 0); let ans = with_return (fun { return } -> while not (Pairing_heap.is_empty queue) do let start, dist = Pairing_heap.pop_exn queue in if String.equal start "e" then return dist; List.iter replacements ~f:(fun (lhs, rhs) -> Option.iter (String.Search_pattern.index rhs ~in_:start) ~f:(fun index -> let rhs_len = String.length (String.Search_pattern.pattern rhs) in let str = String.sub start ~pos:0 ~len:index ^ lhs ^ String.drop_prefix start (index + rhs_len) in Pairing_heap.add queue (str, dist + 1))) done; assert false) in print_s [%sexp (ans : int)]; return () ;; let%expect_test "b" = let%bind () = b () in [%expect {| 195 |}]; return () ;;
00ba456871e07f696a2feb008111bc36597defae847c3e1b4ff9ecf508efbb28
cyclone-scheme/clojurian
test.scm
(import (scheme base) (scheme inexact) (srfi 1) (cyclone test) (cyclone clojurian)) Original tests by on ;; (define add1 (lambda (x) (+ 1 x))) (test-group "clojurian-syntax" (test (vector 1 2) (doto (make-vector 2) (vector-set! 0 1) (vector-set! 1 2))) (test 'foo (doto 'foo))) (test-group "" (test 1.0 (-> 99 (/ 11) (/ 9))) (test '(1 2 3 4) (->* (values 1 2) (list 3) (append '(4)))) (test 3 (as-> 3 x)) (test 2.0 (as-> 1 x (+ x 3) (/ x 2))) (test 5.0 (-> 10 (* 2) (as-> state (/ state 4)))) (test 7 (-> 10 (- 3))) (test -7 (->> 10 (- 3))) (test 9 (->> 1 (+ 2) (* 3))) (test -1 (-> 1 -)) (test 2.0 (-> 14 (+ 2) sqrt (- 2))) (test '(1 2) (->* (values 1 2) list)) (test 9 (->> '(1 2 3) (map add1) (fold + 0))) (test -1 (->> 1 -)) (test '((foo . 100) (bar . 200)) (->>* (values '(foo bar) '(100 200)) (map cons))) (test '("a" "b") (->>* (values 'a 'b) list (map symbol->string))) (test 9 (and-> 1 (+ 2) (* 3))) (test -1 (and-> 1 -)) (test #f (and-> #f not)) (test 2 (and-> (assq 'x '((x . 1))) cdr add1)) (test #f (and-> (assq 'x '((y . 1))) cdr add1))) (test-group "if-let & if-let*" (test 2 (if-let (x 1) (+ x x) 9)) (test 9 (if-let (x #f) (+ x x) 9)) (test (list 3 6) (if-let* ((foo 3) (bar (* foo 2))) (list foo bar) 'wrong)) (test 'wrong (if-let* ((foo #f) (bar (* foo 2))) (list foo bar) 'wrong)) (test #f (if-let (x #t) #f 'wrong)) (test #f (if-let* ((x #t)) #f 'wrong)))
null
https://raw.githubusercontent.com/cyclone-scheme/clojurian/ae389f911702d075f521288a13947daa2786f3eb/test.scm
scheme
(import (scheme base) (scheme inexact) (srfi 1) (cyclone test) (cyclone clojurian)) Original tests by on (define add1 (lambda (x) (+ 1 x))) (test-group "clojurian-syntax" (test (vector 1 2) (doto (make-vector 2) (vector-set! 0 1) (vector-set! 1 2))) (test 'foo (doto 'foo))) (test-group "" (test 1.0 (-> 99 (/ 11) (/ 9))) (test '(1 2 3 4) (->* (values 1 2) (list 3) (append '(4)))) (test 3 (as-> 3 x)) (test 2.0 (as-> 1 x (+ x 3) (/ x 2))) (test 5.0 (-> 10 (* 2) (as-> state (/ state 4)))) (test 7 (-> 10 (- 3))) (test -7 (->> 10 (- 3))) (test 9 (->> 1 (+ 2) (* 3))) (test -1 (-> 1 -)) (test 2.0 (-> 14 (+ 2) sqrt (- 2))) (test '(1 2) (->* (values 1 2) list)) (test 9 (->> '(1 2 3) (map add1) (fold + 0))) (test -1 (->> 1 -)) (test '((foo . 100) (bar . 200)) (->>* (values '(foo bar) '(100 200)) (map cons))) (test '("a" "b") (->>* (values 'a 'b) list (map symbol->string))) (test 9 (and-> 1 (+ 2) (* 3))) (test -1 (and-> 1 -)) (test #f (and-> #f not)) (test 2 (and-> (assq 'x '((x . 1))) cdr add1)) (test #f (and-> (assq 'x '((y . 1))) cdr add1))) (test-group "if-let & if-let*" (test 2 (if-let (x 1) (+ x x) 9)) (test 9 (if-let (x #f) (+ x x) 9)) (test (list 3 6) (if-let* ((foo 3) (bar (* foo 2))) (list foo bar) 'wrong)) (test 'wrong (if-let* ((foo #f) (bar (* foo 2))) (list foo bar) 'wrong)) (test #f (if-let (x #t) #f 'wrong)) (test #f (if-let* ((x #t)) #f 'wrong)))
ebbc4f64c287724533375ce9bf6c28cf14396bae188533f3879d3a0af6835abc
gilith/hol-light
grobner.ml
(* ========================================================================= *) (* Generic Grobner basis algorithm. *) (* *) (* Whatever the instantiation, it basically solves the universal theory of *) (* the complex numbers, or equivalently something like the theory of all *) (* commutative cancellation semirings with no nilpotent elements and having *) (* characteristic zero. We could do "all rings" by a more elaborate integer *) (* version of Grobner bases, but I don't have any useful applications. *) (* *) ( c ) Copyright , 1998 - 2007 (* ========================================================================= *) needs "normalizer.ml";; (* ------------------------------------------------------------------------- *) (* Type for recording history, i.e. how a polynomial was obtained. *) (* ------------------------------------------------------------------------- *) type history = Start of int | Mmul of (num * (int list)) * history | Add of history * history;; (* ------------------------------------------------------------------------- *) (* Overall function; everything else is local. *) (* ------------------------------------------------------------------------- *) let RING_AND_IDEAL_CONV = (* ----------------------------------------------------------------------- *) (* Monomial ordering. *) (* ----------------------------------------------------------------------- *) let morder_lt = let rec lexorder l1 l2 = match (l1,l2) with [],[] -> false | (x1::o1,x2::o2) -> x1 > x2 || x1 = x2 && lexorder o1 o2 | _ -> failwith "morder: inconsistent monomial lengths" in fun m1 m2 -> let n1 = itlist (+) m1 0 and n2 = itlist (+) m2 0 in n1 < n2 || n1 = n2 && lexorder m1 m2 in (* ----------------------------------------------------------------------- *) (* Arithmetic on canonical polynomials. *) (* ----------------------------------------------------------------------- *) let grob_neg = map (fun (c,m) -> (minus_num c,m)) in let rec grob_add l1 l2 = match (l1,l2) with ([],l2) -> l2 | (l1,[]) -> l1 | ((c1,m1)::o1,(c2,m2)::o2) -> if m1 = m2 then let c = c1+/c2 and rest = grob_add o1 o2 in if c =/ num_0 then rest else (c,m1)::rest else if morder_lt m2 m1 then (c1,m1)::(grob_add o1 l2) else (c2,m2)::(grob_add l1 o2) in let grob_sub l1 l2 = grob_add l1 (grob_neg l2) in let grob_mmul (c1,m1) (c2,m2) = (c1*/c2,map2 (+) m1 m2) in let rec grob_cmul cm pol = map (grob_mmul cm) pol in let rec grob_mul l1 l2 = match l1 with [] -> [] | (h1::t1) -> grob_add (grob_cmul h1 l2) (grob_mul t1 l2) in let grob_inv l = match l with [c,vs] when forall (fun x -> x = 0) vs -> if c =/ num_0 then failwith "grob_inv: division by zero" else [num_1 // c,vs] | _ -> failwith "grob_inv: non-constant divisor polynomial" in let grob_div l1 l2 = match l2 with [c,l] when forall (fun x -> x = 0) l -> if c =/ num_0 then failwith "grob_div: division by zero" else grob_cmul (num_1 // c,l) l1 | _ -> failwith "grob_div: non-constant divisor polynomial" in let rec grob_pow vars l n = if n < 0 then failwith "grob_pow: negative power" else if n = 0 then [num_1,map (fun v -> 0) vars] else grob_mul l (grob_pow vars l (n - 1)) in (* ----------------------------------------------------------------------- *) Monomial division operation . (* ----------------------------------------------------------------------- *) let mdiv (c1,m1) (c2,m2) = (c1//c2, map2 (fun n1 n2 -> if n1 < n2 then failwith "mdiv" else n1-n2) m1 m2) in (* ----------------------------------------------------------------------- *) Lowest common multiple of two monomials . (* ----------------------------------------------------------------------- *) let mlcm (c1,m1) (c2,m2) = (num_1,map2 max m1 m2) in (* ----------------------------------------------------------------------- *) Reduce monomial cm by polynomial pol , returning replacement for . (* ----------------------------------------------------------------------- *) let reduce1 cm (pol,hpol) = match pol with [] -> failwith "reduce1" | cm1::cms -> try let (c,m) = mdiv cm cm1 in (grob_cmul (minus_num c,m) cms, Mmul((minus_num c,m),hpol)) with Failure _ -> failwith "reduce1" in (* ----------------------------------------------------------------------- *) (* Try this for all polynomials in a basis. *) (* ----------------------------------------------------------------------- *) let reduceb cm basis = tryfind (fun p -> reduce1 cm p) basis in (* ----------------------------------------------------------------------- *) (* Reduction of a polynomial (always picking largest monomial possible). *) (* ----------------------------------------------------------------------- *) let rec reduce basis (pol,hist) = match pol with [] -> (pol,hist) | cm::ptl -> try let q,hnew = reduceb cm basis in reduce basis (grob_add q ptl,Add(hnew,hist)) with Failure _ -> let q,hist' = reduce basis (ptl,hist) in cm::q,hist' in (* ----------------------------------------------------------------------- *) (* Check for orthogonality w.r.t. LCM. *) (* ----------------------------------------------------------------------- *) let orthogonal l p1 p2 = snd l = snd(grob_mmul (hd p1) (hd p2)) in (* ----------------------------------------------------------------------- *) Compute S - polynomial of two polynomials . (* ----------------------------------------------------------------------- *) let spoly cm ph1 ph2 = match (ph1,ph2) with ([],h),p -> ([],h) | p,([],h) -> ([],h) | (cm1::ptl1,his1),(cm2::ptl2,his2) -> (grob_sub (grob_cmul (mdiv cm cm1) ptl1) (grob_cmul (mdiv cm cm2) ptl2), Add(Mmul(mdiv cm cm1,his1), Mmul(mdiv (minus_num(fst cm),snd cm) cm2,his2))) in (* ----------------------------------------------------------------------- *) (* Make a polynomial monic. *) (* ----------------------------------------------------------------------- *) let monic (pol,hist) = if pol = [] then (pol,hist) else let c',m' = hd pol in (map (fun (c,m) -> (c//c',m)) pol, Mmul((num_1 // c',map (K 0) m'),hist)) in (* ----------------------------------------------------------------------- *) (* The most popular heuristic is to order critical pairs by LCM monomial. *) (* ----------------------------------------------------------------------- *) let forder ((c1,m1),_) ((c2,m2),_) = morder_lt m1 m2 in (* ----------------------------------------------------------------------- *) (* Stupid stuff forced on us by lack of equality test on num type. *) (* ----------------------------------------------------------------------- *) let rec poly_lt p q = match (p,q) with p,[] -> false | [],q -> true | (c1,m1)::o1,(c2,m2)::o2 -> c1 </ c2 || c1 =/ c2 && (m1 < m2 || m1 = m2 && poly_lt o1 o2) in let align ((p,hp),(q,hq)) = if poly_lt p q then ((p,hp),(q,hq)) else ((q,hq),(p,hp)) in let poly_eq p1 p2 = forall2 (fun (c1,m1) (c2,m2) -> c1 =/ c2 && m1 = m2) p1 p2 in let memx ((p1,h1),(p2,h2)) ppairs = not (exists (fun ((q1,_),(q2,_)) -> poly_eq p1 q1 && poly_eq p2 q2) ppairs) in (* ----------------------------------------------------------------------- *) Buchberger 's second criterion . (* ----------------------------------------------------------------------- *) let criterion2 basis (lcm,((p1,h1),(p2,h2))) opairs = exists (fun g -> not(poly_eq (fst g) p1) && not(poly_eq (fst g) p2) && can (mdiv lcm) (hd(fst g)) && not(memx (align(g,(p1,h1))) (map snd opairs)) && not(memx (align(g,(p2,h2))) (map snd opairs))) basis in (* ----------------------------------------------------------------------- *) (* Test for hitting constant polynomial. *) (* ----------------------------------------------------------------------- *) let constant_poly p = length p = 1 && forall ((=) 0) (snd(hd p)) in (* ----------------------------------------------------------------------- *) (* Grobner basis algorithm. *) (* ----------------------------------------------------------------------- *) let rec grobner_basis basis pairs = Format.print_string(string_of_int(length basis)^" basis elements and "^ string_of_int(length pairs)^" critical pairs"); Format.print_newline(); match pairs with [] -> basis | (l,(p1,p2))::opairs -> let (sp,hist as sph) = monic (reduce basis (spoly l p1 p2)) in if sp = [] || criterion2 basis (l,(p1,p2)) opairs then grobner_basis basis opairs else if constant_poly sp then grobner_basis (sph::basis) [] else let rawcps = map (fun p -> mlcm (hd(fst p)) (hd sp),align(p,sph)) basis in let newcps = filter (fun (l,(p,q)) -> not(orthogonal l (fst p) (fst q))) rawcps in grobner_basis (sph::basis) (merge forder opairs (mergesort forder newcps)) in (* ----------------------------------------------------------------------- *) Interreduce initial polynomials . (* ----------------------------------------------------------------------- *) let rec grobner_interreduce rpols ipols = match ipols with [] -> map monic (rev rpols) | p::ps -> let p' = reduce (rpols @ ps) p in if fst p' = [] then grobner_interreduce rpols ps else grobner_interreduce (p'::rpols) ps in (* ----------------------------------------------------------------------- *) (* Overall function. *) (* ----------------------------------------------------------------------- *) let grobner pols = let npols = map2 (fun p n -> p,Start n) pols (0--(length pols - 1)) in let phists = filter (fun (p,_) -> p <> []) npols in let bas = grobner_interreduce [] (map monic phists) in let prs0 = allpairs (fun x y -> x,y) bas bas in let prs1 = filter (fun ((x,_),(y,_)) -> poly_lt x y) prs0 in let prs2 = map (fun (p,q) -> mlcm (hd(fst p)) (hd(fst q)),(p,q)) prs1 in let prs3 = filter (fun (l,(p,q)) -> not(orthogonal l (fst p) (fst q))) prs2 in grobner_basis bas (mergesort forder prs3) in (* ----------------------------------------------------------------------- *) (* Get proof of contradiction from Grobner basis. *) (* ----------------------------------------------------------------------- *) let grobner_refute pols = let gb = grobner pols in snd(find (fun (p,h) -> length p = 1 && forall ((=)0) (snd(hd p))) gb) in (* ----------------------------------------------------------------------- *) (* Turn proof into a certificate as sum of multipliers. *) (* *) (* In principle this is very inefficient: in a heavily shared proof it may *) (* make the same calculation many times. Could add a cache or something. *) (* ----------------------------------------------------------------------- *) let rec resolve_proof vars prf = match prf with Start(-1) -> [] | Start m -> [m,[num_1,map (K 0) vars]] | Mmul(pol,lin) -> let lis = resolve_proof vars lin in map (fun (n,p) -> n,grob_cmul pol p) lis | Add(lin1,lin2) -> let lis1 = resolve_proof vars lin1 and lis2 = resolve_proof vars lin2 in let dom = setify(union (map fst lis1) (map fst lis2)) in map (fun n -> let a = try assoc n lis1 with Failure _ -> [] and b = try assoc n lis2 with Failure _ -> [] in n,grob_add a b) dom in (* ----------------------------------------------------------------------- *) Run the procedure and produce Weak Nullstellensatz certificate . (* ----------------------------------------------------------------------- *) let grobner_weak vars pols = let cert = resolve_proof vars (grobner_refute pols) in let l = itlist (itlist (lcm_num o denominator o fst) o snd) cert (num_1) in l,map (fun (i,p) -> i,map (fun (d,m) -> (l*/d,m)) p) cert in (* ----------------------------------------------------------------------- *) (* Prove polynomial is in ideal generated by others, using Grobner basis. *) (* ----------------------------------------------------------------------- *) let grobner_ideal vars pols pol = let pol',h = reduce (grobner pols) (grob_neg pol,Start(-1)) in if pol' <> [] then failwith "grobner_ideal: not in the ideal" else resolve_proof vars h in (* ----------------------------------------------------------------------- *) Produce Strong Nullstellensatz certificate for a power of pol . (* ----------------------------------------------------------------------- *) let grobner_strong vars pols pol = if pol = [] then 1,num_1,[] else let vars' = (concl TRUTH)::vars in let grob_z = [num_1,1::(map (fun x -> 0) vars)] and grob_1 = [num_1,(map (fun x -> 0) vars')] and augment = map (fun (c,m) -> (c,0::m)) in let pols' = map augment pols and pol' = augment pol in let allpols = (grob_sub (grob_mul grob_z pol') grob_1)::pols' in let l,cert = grobner_weak vars' allpols in let d = itlist (itlist (max o hd o snd) o snd) cert 0 in let transform_monomial (c,m) = grob_cmul (c,tl m) (grob_pow vars pol (d - hd m)) in let transform_polynomial q = itlist (grob_add o transform_monomial) q [] in let cert' = map (fun (c,q) -> c-1,transform_polynomial q) (filter (fun (k,_) -> k <> 0) cert) in d,l,cert' in (* ----------------------------------------------------------------------- *) (* Overall parametrized universal procedure for (semi)rings. *) We return an IDEAL_CONV and the actual ring prover . (* ----------------------------------------------------------------------- *) let pth_step = prove (`!(add:A->A->A) (mul:A->A->A) (n0:A). (!x. mul n0 x = n0) /\ (!x y z. (add x y = add x z) <=> (y = z)) /\ (!w x y z. (add (mul w y) (mul x z) = add (mul w z) (mul x y)) <=> (w = x) \/ (y = z)) ==> (!a b c d. ~(a = b) /\ ~(c = d) <=> ~(add (mul a c) (mul b d) = add (mul a d) (mul b c))) /\ (!n a b c d. ~(n = n0) ==> (a = b) /\ ~(c = d) ==> ~(add a (mul n c) = add b (mul n d)))`, REPEAT GEN_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[GSYM DE_MORGAN_THM] THEN REPEAT GEN_TAC THEN DISCH_TAC THEN STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o SPECL [`n0:A`; `n:A`; `d:A`; `c:A`]) THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN ASM_SIMP_TAC[]) and FINAL_RULE = MATCH_MP(TAUT `(p ==> F) ==> (~q = p) ==> q`) and false_tm = `F` in let rec refute_disj rfn tm = match tm with Comb(Comb(Const("\\/",_),l),r) -> DISJ_CASES (ASSUME tm) (refute_disj rfn l) (refute_disj rfn r) | _ -> rfn tm in fun (ring_dest_const,ring_mk_const,RING_EQ_CONV, ring_neg_tm,ring_add_tm,ring_sub_tm, ring_inv_tm,ring_mul_tm,ring_div_tm,ring_pow_tm, RING_INTEGRAL,RABINOWITSCH_THM,RING_NORMALIZE_CONV) -> let INITIAL_CONV = TOP_DEPTH_CONV BETA_CONV THENC PRESIMP_CONV THENC CONDS_ELIM_CONV THENC NNF_CONV THENC (if is_iff(snd(strip_forall(concl RABINOWITSCH_THM))) then GEN_REWRITE_CONV ONCE_DEPTH_CONV [RABINOWITSCH_THM] else ALL_CONV) THENC GEN_REWRITE_CONV REDEPTH_CONV [AND_FORALL_THM; LEFT_AND_FORALL_THM; RIGHT_AND_FORALL_THM; LEFT_OR_FORALL_THM; RIGHT_OR_FORALL_THM; OR_EXISTS_THM; LEFT_OR_EXISTS_THM; RIGHT_OR_EXISTS_THM; LEFT_AND_EXISTS_THM; RIGHT_AND_EXISTS_THM] in let ring_dest_neg t = let l,r = dest_comb t in if l = ring_neg_tm then r else failwith "ring_dest_neg" and ring_dest_inv t = let l,r = dest_comb t in if l = ring_inv_tm then r else failwith "ring_dest_inv" and ring_dest_add = dest_binop ring_add_tm and ring_mk_add = mk_binop ring_add_tm and ring_dest_sub = dest_binop ring_sub_tm and ring_dest_mul = dest_binop ring_mul_tm and ring_mk_mul = mk_binop ring_mul_tm and ring_dest_div = dest_binop ring_div_tm and ring_dest_pow = dest_binop ring_pow_tm and ring_mk_pow = mk_binop ring_pow_tm in let rec grobvars tm acc = if can ring_dest_const tm then acc else if can ring_dest_neg tm then grobvars (rand tm) acc else if can ring_dest_pow tm && is_numeral (rand tm) then grobvars (lhand tm) acc else if can ring_dest_add tm || can ring_dest_sub tm || can ring_dest_mul tm then grobvars (lhand tm) (grobvars (rand tm) acc) else if can ring_dest_inv tm then let gvs = grobvars (rand tm) [] in if gvs = [] then acc else tm::acc else if can ring_dest_div tm then let lvs = grobvars (lhand tm) acc and gvs = grobvars (rand tm) [] in if gvs = [] then lvs else tm::acc else tm::acc in let rec grobify_term vars tm = try if not(mem tm vars) then failwith "" else [num_1,map (fun i -> if i = tm then 1 else 0) vars] with Failure _ -> try let x = ring_dest_const tm in if x =/ num_0 then [] else [x,map (fun v -> 0) vars] with Failure _ -> try grob_neg(grobify_term vars (ring_dest_neg tm)) with Failure _ -> try grob_inv(grobify_term vars (ring_dest_inv tm)) with Failure _ -> try let l,r = ring_dest_add tm in grob_add (grobify_term vars l) (grobify_term vars r) with Failure _ -> try let l,r = ring_dest_sub tm in grob_sub (grobify_term vars l) (grobify_term vars r) with Failure _ -> try let l,r = ring_dest_mul tm in grob_mul (grobify_term vars l) (grobify_term vars r) with Failure _ -> try let l,r = ring_dest_div tm in grob_div (grobify_term vars l) (grobify_term vars r) with Failure _ -> try let l,r = ring_dest_pow tm in grob_pow vars (grobify_term vars l) (dest_small_numeral r) with Failure _ -> failwith "grobify_term: unknown or invalid term" in let grobify_equation vars tm = let l,r = dest_eq tm in grob_sub (grobify_term vars l) (grobify_term vars r) in let grobify_equations tm = let cjs = conjuncts tm in let rawvars = itlist (fun eq a -> grobvars (lhand eq) (grobvars (rand eq) a)) cjs [] in let vars = sort (fun x y -> x < y) (setify rawvars) in vars,map (grobify_equation vars) cjs in let holify_polynomial = let holify_varpow (v,n) = if n = 1 then v else ring_mk_pow v (mk_small_numeral n) in let holify_monomial vars (c,m) = let xps = map holify_varpow (filter (fun (_,n) -> n <> 0) (zip vars m)) in end_itlist ring_mk_mul (ring_mk_const c :: xps) in let holify_polynomial vars p = if p = [] then ring_mk_const (num_0) else end_itlist ring_mk_add (map (holify_monomial vars) p) in holify_polynomial in let (pth_idom,pth_ine) = CONJ_PAIR(MATCH_MP pth_step RING_INTEGRAL) in let IDOM_RULE = CONV_RULE(REWR_CONV pth_idom) in let PROVE_NZ n = EQF_ELIM(RING_EQ_CONV (mk_eq(ring_mk_const n,ring_mk_const(num_0)))) in let NOT_EQ_01 = PROVE_NZ (num_1) and INE_RULE n = MATCH_MP(MATCH_MP pth_ine (PROVE_NZ n)) and MK_ADD th1 th2 = MK_COMB(AP_TERM ring_add_tm th1,th2) in let execute_proof vars eths prf = let x,th1 = SPEC_VAR(CONJUNCT1(CONJUNCT2 RING_INTEGRAL)) in let y,th2 = SPEC_VAR th1 in let z,th3 = SPEC_VAR th2 in let SUB_EQ_RULE = GEN_REWRITE_RULE I [SYM(INST [mk_comb(ring_neg_tm,z),x] th3)] in let initpols = map (CONV_RULE(BINOP_CONV RING_NORMALIZE_CONV) o SUB_EQ_RULE) eths in let ADD_RULE th1 th2 = CONV_RULE (BINOP_CONV RING_NORMALIZE_CONV) (MK_COMB(AP_TERM ring_add_tm th1,th2)) and MUL_RULE vars m th = CONV_RULE (BINOP_CONV RING_NORMALIZE_CONV) (AP_TERM (mk_comb(ring_mul_tm,holify_polynomial vars [m])) th) in let execache = ref [] in let memoize prf x = (execache := (prf,x)::(!execache)); x in let rec assoceq a l = match l with [] -> failwith "assoceq" | (x,y)::t -> if x==a then y else assoceq a t in let rec run_proof vars prf = try assoceq prf (!execache) with Failure _ -> (match prf with Start m -> el m initpols | Add(p1,p2) -> memoize prf (ADD_RULE (run_proof vars p1) (run_proof vars p2)) | Mmul(m,p2) -> memoize prf (MUL_RULE vars m (run_proof vars p2))) in let th = run_proof vars prf in execache := []; CONV_RULE RING_EQ_CONV th in let REFUTE tm = if tm = false_tm then ASSUME tm else let nths0,eths0 = partition (is_neg o concl) (CONJUNCTS(ASSUME tm)) in let nths = filter (is_eq o rand o concl) nths0 and eths = filter (is_eq o concl) eths0 in if eths = [] then let th1 = end_itlist (fun th1 th2 -> IDOM_RULE(CONJ th1 th2)) nths in let th2 = CONV_RULE(RAND_CONV(BINOP_CONV RING_NORMALIZE_CONV)) th1 in let l,r = dest_eq(rand(concl th2)) in EQ_MP (EQF_INTRO th2) (REFL l) else if nths = [] && not(is_var ring_neg_tm) then let vars,pols = grobify_equations(list_mk_conj(map concl eths)) in execute_proof vars eths (grobner_refute pols) else let vars,l,cert,noteqth = if nths = [] then let vars,pols = grobify_equations(list_mk_conj(map concl eths)) in let l,cert = grobner_weak vars pols in vars,l,cert,NOT_EQ_01 else let nth = end_itlist (fun th1 th2 -> IDOM_RULE(CONJ th1 th2)) nths in let vars,pol::pols = grobify_equations(list_mk_conj(rand(concl nth)::map concl eths)) in let deg,l,cert = grobner_strong vars pols pol in let th1 = CONV_RULE(RAND_CONV(BINOP_CONV RING_NORMALIZE_CONV)) nth in let th2 = funpow deg (IDOM_RULE o CONJ th1) NOT_EQ_01 in vars,l,cert,th2 in Format.print_string("Translating certificate to HOL inferences"); Format.print_newline(); let cert_pos = map (fun (i,p) -> i,filter (fun (c,m) -> c >/ num_0) p) cert and cert_neg = map (fun (i,p) -> i,map (fun (c,m) -> minus_num c,m) (filter (fun (c,m) -> c </ num_0) p)) cert in let herts_pos = map (fun (i,p) -> i,holify_polynomial vars p) cert_pos and herts_neg = map (fun (i,p) -> i,holify_polynomial vars p) cert_neg in let thm_fn pols = if pols = [] then REFL(ring_mk_const num_0) else end_itlist MK_ADD (map (fun (i,p) -> AP_TERM(mk_comb(ring_mul_tm,p)) (el i eths)) pols) in let th1 = thm_fn herts_pos and th2 = thm_fn herts_neg in let th3 = CONJ(MK_ADD (SYM th1) th2) noteqth in let th4 = CONV_RULE (RAND_CONV(BINOP_CONV RING_NORMALIZE_CONV)) (INE_RULE l th3) in let l,r = dest_eq(rand(concl th4)) in EQ_MP (EQF_INTRO th4) (REFL l) in let ring_ty = snd(dest_fun_ty(snd(dest_fun_ty(type_of ring_add_tm)))) in let RING tm = let avs = filter ((=) ring_ty o type_of) (frees tm) in let tm' = list_mk_forall(avs,tm) in let th1 = INITIAL_CONV(mk_neg tm') in let evs,bod = strip_exists(rand(concl th1)) in if is_forall bod then failwith "RING: non-universal formula" else let th1a = WEAK_DNF_CONV bod in let boda = rand(concl th1a) in let th2a = refute_disj REFUTE boda in let th2b = TRANS th1a (EQF_INTRO(NOT_INTRO(DISCH boda th2a))) in let th2 = UNDISCH(NOT_ELIM(EQF_ELIM th2b)) in let finbod,th3 = let rec CHOOSES evs (etm,th) = match evs with [] -> (etm,th) | ev::oevs -> let etm',th' = CHOOSES oevs (etm,th) in mk_exists(ev,etm'),CHOOSE (ev,ASSUME (mk_exists(ev,etm'))) th' in CHOOSES evs (bod,th2) in SPECL avs (MATCH_MP (FINAL_RULE (DISCH finbod th3)) th1) and ideal tms tm = let rawvars = itlist grobvars (tm::tms) [] in let vars = sort (fun x y -> x < y) (setify rawvars) in let pols = map (grobify_term vars) tms and pol = grobify_term vars tm in let cert = grobner_ideal vars pols pol in map (fun n -> let p = assocd n cert [] in holify_polynomial vars p) (0--(length pols-1)) in RING,ideal;; (* ----------------------------------------------------------------------- *) (* Separate out the cases. *) (* ----------------------------------------------------------------------- *) let RING parms = fst(RING_AND_IDEAL_CONV parms);; let ideal_cofactors parms = snd(RING_AND_IDEAL_CONV parms);; (* ------------------------------------------------------------------------- *) Simplify a natural number assertion to eliminate conditionals , DIV , MOD , PRE , cutoff subtraction , EVEN and ODD . Try to do it in a way that makes (* new quantifiers universal. At the moment we don't split "<=>" which would *) make this quantifier selection work there too ; better to do NNF first if you care . This also applies to EVEN and ODD . (* ------------------------------------------------------------------------- *) let NUM_SIMPLIFY_CONV = let pre_tm = `PRE` and div_tm = `(DIV):num->num->num` and mod_tm = `(MOD):num->num->num` and p_tm = `P:num->bool` and n_tm = `n:num` and m_tm = `m:num` and q_tm = `P:num->num->bool` and a_tm = `a:num` and b_tm = `b:num` in let is_pre tm = is_comb tm && rator tm = pre_tm and is_sub = is_binop `(-):num->num->num` and is_divmod = let is_div = is_binop div_tm and is_mod = is_binop mod_tm in fun tm -> is_div tm || is_mod tm and contains_quantifier = can (find_term (fun t -> is_forall t || is_exists t || is_uexists t)) and BETA2_CONV = RATOR_CONV BETA_CONV THENC BETA_CONV * * and PRE_ELIM_THM '' = CONV_RULE ( RAND_CONV NNF_CONV ) PRE_ELIM_THM and SUB_ELIM_THM '' = CONV_RULE ( RAND_CONV NNF_CONV ) SUB_ELIM_THM and DIVMOD_ELIM_THM '' = CONV_RULE ( RAND_CONV NNF_CONV ) DIVMOD_ELIM_THM * * and PRE_ELIM_THM'' = CONV_RULE (RAND_CONV NNF_CONV) PRE_ELIM_THM and SUB_ELIM_THM'' = CONV_RULE (RAND_CONV NNF_CONV) SUB_ELIM_THM and DIVMOD_ELIM_THM'' = CONV_RULE (RAND_CONV NNF_CONV) DIVMOD_ELIM_THM ***) and pth_evenodd = prove (`(EVEN(x) <=> (!y. ~(x = SUC(2 * y)))) /\ (ODD(x) <=> (!y. ~(x = 2 * y))) /\ (~EVEN(x) <=> (!y. ~(x = 2 * y))) /\ (~ODD(x) <=> (!y. ~(x = SUC(2 * y))))`, REWRITE_TAC[GSYM NOT_EXISTS_THM; GSYM EVEN_EXISTS; GSYM ODD_EXISTS] THEN REWRITE_TAC[NOT_EVEN; NOT_ODD]) in let rec NUM_MULTIPLY_CONV pos tm = if is_forall tm || is_exists tm || is_uexists tm then BINDER_CONV (NUM_MULTIPLY_CONV pos) tm else if is_imp tm && contains_quantifier tm then COMB2_CONV (RAND_CONV(NUM_MULTIPLY_CONV(not pos))) (NUM_MULTIPLY_CONV pos) tm else if (is_conj tm || is_disj tm || is_iff tm) && contains_quantifier tm then BINOP_CONV (NUM_MULTIPLY_CONV pos) tm else if is_neg tm && not pos && contains_quantifier tm then RAND_CONV (NUM_MULTIPLY_CONV (not pos)) tm else * * try let t = find_term ( fun t - > is_pre t & & free_in t tm ) tm in let ty = type_of t in let v = in let p = mk_abs(v , subst [ v , t ] tm ) in let = if pos then PRE_ELIM_THM '' else PRE_ELIM_THM ' in let th1 = INST [ p , p_tm ; rand t , n_tm ] in let th2 = CONV_RULE(COMB2_CONV ( RAND_CONV BETA_CONV ) ( BINDER_CONV(RAND_CONV BETA_CONV ) ) ) th1 in CONV_RULE(RAND_CONV ( NUM_MULTIPLY_CONV pos ) ) th2 with Failure _ - > try let t = find_term ( fun t - > is_sub t & & free_in t tm ) tm in let ty = type_of t in let v = in let p = mk_abs(v , subst [ v , t ] tm ) in let = if pos then SUB_ELIM_THM '' else SUB_ELIM_THM ' in let th1 = INST [ p , p_tm ; lhand t , a_tm ; rand t , b_tm ] in let th2 = CONV_RULE(COMB2_CONV ( RAND_CONV BETA_CONV ) ( BINDER_CONV(RAND_CONV BETA_CONV ) ) ) th1 in CONV_RULE(RAND_CONV ( NUM_MULTIPLY_CONV pos ) ) th2 with Failure _ - > try let t = find_term ( fun t - > is_divmod t & & free_in t tm ) tm in let x = lhand t and y = rand t in let dtm = mk_comb(mk_comb(div_tm , x),y ) and mtm = mk_comb(mk_comb(mod_tm , x),y ) in let vd = genvar(type_of dtm ) and vm = genvar(type_of mtm ) in let p = list_mk_abs([vd;vm],subst[vd , dtm ; vm , mtm ] tm ) in let = if pos then DIVMOD_ELIM_THM '' else DIVMOD_ELIM_THM ' in let th1 = INST [ p , q_tm ; x , m_tm ; y , n_tm ] in let th2 = CONV_RULE(COMB2_CONV(RAND_CONV BETA2_CONV ) ( funpow 2 BINDER_CONV(RAND_CONV BETA2_CONV ) ) ) th1 in CONV_RULE(RAND_CONV ( NUM_MULTIPLY_CONV pos ) ) th2 with Failure _ - > * * try let t = find_term (fun t -> is_pre t && free_in t tm) tm in let ty = type_of t in let v = genvar ty in let p = mk_abs(v,subst [v,t] tm) in let th0 = if pos then PRE_ELIM_THM'' else PRE_ELIM_THM' in let th1 = INST [p,p_tm; rand t,n_tm] th0 in let th2 = CONV_RULE(COMB2_CONV (RAND_CONV BETA_CONV) (BINDER_CONV(RAND_CONV BETA_CONV))) th1 in CONV_RULE(RAND_CONV (NUM_MULTIPLY_CONV pos)) th2 with Failure _ -> try let t = find_term (fun t -> is_sub t && free_in t tm) tm in let ty = type_of t in let v = genvar ty in let p = mk_abs(v,subst [v,t] tm) in let th0 = if pos then SUB_ELIM_THM'' else SUB_ELIM_THM' in let th1 = INST [p,p_tm; lhand t,a_tm; rand t,b_tm] th0 in let th2 = CONV_RULE(COMB2_CONV (RAND_CONV BETA_CONV) (BINDER_CONV(RAND_CONV BETA_CONV))) th1 in CONV_RULE(RAND_CONV (NUM_MULTIPLY_CONV pos)) th2 with Failure _ -> try let t = find_term (fun t -> is_divmod t && free_in t tm) tm in let x = lhand t and y = rand t in let dtm = mk_comb(mk_comb(div_tm,x),y) and mtm = mk_comb(mk_comb(mod_tm,x),y) in let vd = genvar(type_of dtm) and vm = genvar(type_of mtm) in let p = list_mk_abs([vd;vm],subst[vd,dtm; vm,mtm] tm) in let th0 = if pos then DIVMOD_ELIM_THM'' else DIVMOD_ELIM_THM' in let th1 = INST [p,q_tm; x,m_tm; y,n_tm] th0 in let th2 = CONV_RULE(COMB2_CONV(RAND_CONV BETA2_CONV) (funpow 2 BINDER_CONV(RAND_CONV BETA2_CONV))) th1 in CONV_RULE(RAND_CONV (NUM_MULTIPLY_CONV pos)) th2 with Failure _ -> ***) REFL tm in NUM_REDUCE_CONV THENC CONDS_CELIM_CONV THENC NNF_CONV THENC NUM_MULTIPLY_CONV true THENC NUM_REDUCE_CONV THENC GEN_REWRITE_CONV ONCE_DEPTH_CONV [pth_evenodd];; (* ----------------------------------------------------------------------- *) (* Natural number version of ring procedure with this normalization. *) (* ----------------------------------------------------------------------- *) let NUM_RING = let NUM_INTEGRAL_LEMMA = prove (`((w : num) = x + d) /\ (y = z + e) ==> ((w * y + x * z = w * z + x * y) <=> (w = x) \/ (y = z))`, DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a : num) + b + c + d + e = a + c + e + b + d`] THEN REWRITE_TAC[EQ_ADD_LCANCEL; EQ_ADD_LCANCEL_0; MULT_EQ_0]) in let NUM_INTEGRAL = prove (`(!x : num. 0 * x = 0) /\ (!x y z : num. (x + y = x + z) <=> (y = z)) /\ (!w x y z : num. (w * y + x * z = w * z + x * y) <=> (w = x) \/ (y = z))`, REWRITE_TAC[MULT_CLAUSES; EQ_ADD_LCANCEL] THEN REPEAT GEN_TAC THEN DISJ_CASES_TAC (SPECL [`w:num`; `x:num`] LE_CASES) THEN DISJ_CASES_TAC (SPECL [`y:num`; `z:num`] LE_CASES) THEN REPEAT(FIRST_X_ASSUM (CHOOSE_THEN SUBST1_TAC o REWRITE_RULE[LE_EXISTS])) THEN ASM_MESON_TAC[NUM_INTEGRAL_LEMMA; ADD_SYM; MULT_SYM]) in let rawring = RING(dest_numeral,mk_numeral,NUM_EQ_CONV, genvar bool_ty,`(+):num->num->num`,genvar bool_ty, genvar bool_ty,`( * ):num->num->num`,genvar bool_ty, `(EXP):num->num->num`, NUM_INTEGRAL,TRUTH,NUM_NORMALIZE_CONV) in let initconv = NUM_SIMPLIFY_CONV THENC GEN_REWRITE_CONV DEPTH_CONV [ADD1] and t_tm = `T` in fun tm -> let th = initconv tm in if rand(concl th) = t_tm then th else EQ_MP (SYM th) (rawring(rand(concl th)));;
null
https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/grobner.ml
ocaml
========================================================================= Generic Grobner basis algorithm. Whatever the instantiation, it basically solves the universal theory of the complex numbers, or equivalently something like the theory of all commutative cancellation semirings with no nilpotent elements and having characteristic zero. We could do "all rings" by a more elaborate integer version of Grobner bases, but I don't have any useful applications. ========================================================================= ------------------------------------------------------------------------- Type for recording history, i.e. how a polynomial was obtained. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Overall function; everything else is local. ------------------------------------------------------------------------- ----------------------------------------------------------------------- Monomial ordering. ----------------------------------------------------------------------- ----------------------------------------------------------------------- Arithmetic on canonical polynomials. ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- Try this for all polynomials in a basis. ----------------------------------------------------------------------- ----------------------------------------------------------------------- Reduction of a polynomial (always picking largest monomial possible). ----------------------------------------------------------------------- ----------------------------------------------------------------------- Check for orthogonality w.r.t. LCM. ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- Make a polynomial monic. ----------------------------------------------------------------------- ----------------------------------------------------------------------- The most popular heuristic is to order critical pairs by LCM monomial. ----------------------------------------------------------------------- ----------------------------------------------------------------------- Stupid stuff forced on us by lack of equality test on num type. ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- Test for hitting constant polynomial. ----------------------------------------------------------------------- ----------------------------------------------------------------------- Grobner basis algorithm. ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- Overall function. ----------------------------------------------------------------------- ----------------------------------------------------------------------- Get proof of contradiction from Grobner basis. ----------------------------------------------------------------------- ----------------------------------------------------------------------- Turn proof into a certificate as sum of multipliers. In principle this is very inefficient: in a heavily shared proof it may make the same calculation many times. Could add a cache or something. ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- Prove polynomial is in ideal generated by others, using Grobner basis. ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- ----------------------------------------------------------------------- Overall parametrized universal procedure for (semi)rings. ----------------------------------------------------------------------- ----------------------------------------------------------------------- Separate out the cases. ----------------------------------------------------------------------- ------------------------------------------------------------------------- new quantifiers universal. At the moment we don't split "<=>" which would ------------------------------------------------------------------------- ----------------------------------------------------------------------- Natural number version of ring procedure with this normalization. -----------------------------------------------------------------------
( c ) Copyright , 1998 - 2007 needs "normalizer.ml";; type history = Start of int | Mmul of (num * (int list)) * history | Add of history * history;; let RING_AND_IDEAL_CONV = let morder_lt = let rec lexorder l1 l2 = match (l1,l2) with [],[] -> false | (x1::o1,x2::o2) -> x1 > x2 || x1 = x2 && lexorder o1 o2 | _ -> failwith "morder: inconsistent monomial lengths" in fun m1 m2 -> let n1 = itlist (+) m1 0 and n2 = itlist (+) m2 0 in n1 < n2 || n1 = n2 && lexorder m1 m2 in let grob_neg = map (fun (c,m) -> (minus_num c,m)) in let rec grob_add l1 l2 = match (l1,l2) with ([],l2) -> l2 | (l1,[]) -> l1 | ((c1,m1)::o1,(c2,m2)::o2) -> if m1 = m2 then let c = c1+/c2 and rest = grob_add o1 o2 in if c =/ num_0 then rest else (c,m1)::rest else if morder_lt m2 m1 then (c1,m1)::(grob_add o1 l2) else (c2,m2)::(grob_add l1 o2) in let grob_sub l1 l2 = grob_add l1 (grob_neg l2) in let grob_mmul (c1,m1) (c2,m2) = (c1*/c2,map2 (+) m1 m2) in let rec grob_cmul cm pol = map (grob_mmul cm) pol in let rec grob_mul l1 l2 = match l1 with [] -> [] | (h1::t1) -> grob_add (grob_cmul h1 l2) (grob_mul t1 l2) in let grob_inv l = match l with [c,vs] when forall (fun x -> x = 0) vs -> if c =/ num_0 then failwith "grob_inv: division by zero" else [num_1 // c,vs] | _ -> failwith "grob_inv: non-constant divisor polynomial" in let grob_div l1 l2 = match l2 with [c,l] when forall (fun x -> x = 0) l -> if c =/ num_0 then failwith "grob_div: division by zero" else grob_cmul (num_1 // c,l) l1 | _ -> failwith "grob_div: non-constant divisor polynomial" in let rec grob_pow vars l n = if n < 0 then failwith "grob_pow: negative power" else if n = 0 then [num_1,map (fun v -> 0) vars] else grob_mul l (grob_pow vars l (n - 1)) in Monomial division operation . let mdiv (c1,m1) (c2,m2) = (c1//c2, map2 (fun n1 n2 -> if n1 < n2 then failwith "mdiv" else n1-n2) m1 m2) in Lowest common multiple of two monomials . let mlcm (c1,m1) (c2,m2) = (num_1,map2 max m1 m2) in Reduce monomial cm by polynomial pol , returning replacement for . let reduce1 cm (pol,hpol) = match pol with [] -> failwith "reduce1" | cm1::cms -> try let (c,m) = mdiv cm cm1 in (grob_cmul (minus_num c,m) cms, Mmul((minus_num c,m),hpol)) with Failure _ -> failwith "reduce1" in let reduceb cm basis = tryfind (fun p -> reduce1 cm p) basis in let rec reduce basis (pol,hist) = match pol with [] -> (pol,hist) | cm::ptl -> try let q,hnew = reduceb cm basis in reduce basis (grob_add q ptl,Add(hnew,hist)) with Failure _ -> let q,hist' = reduce basis (ptl,hist) in cm::q,hist' in let orthogonal l p1 p2 = snd l = snd(grob_mmul (hd p1) (hd p2)) in Compute S - polynomial of two polynomials . let spoly cm ph1 ph2 = match (ph1,ph2) with ([],h),p -> ([],h) | p,([],h) -> ([],h) | (cm1::ptl1,his1),(cm2::ptl2,his2) -> (grob_sub (grob_cmul (mdiv cm cm1) ptl1) (grob_cmul (mdiv cm cm2) ptl2), Add(Mmul(mdiv cm cm1,his1), Mmul(mdiv (minus_num(fst cm),snd cm) cm2,his2))) in let monic (pol,hist) = if pol = [] then (pol,hist) else let c',m' = hd pol in (map (fun (c,m) -> (c//c',m)) pol, Mmul((num_1 // c',map (K 0) m'),hist)) in let forder ((c1,m1),_) ((c2,m2),_) = morder_lt m1 m2 in let rec poly_lt p q = match (p,q) with p,[] -> false | [],q -> true | (c1,m1)::o1,(c2,m2)::o2 -> c1 </ c2 || c1 =/ c2 && (m1 < m2 || m1 = m2 && poly_lt o1 o2) in let align ((p,hp),(q,hq)) = if poly_lt p q then ((p,hp),(q,hq)) else ((q,hq),(p,hp)) in let poly_eq p1 p2 = forall2 (fun (c1,m1) (c2,m2) -> c1 =/ c2 && m1 = m2) p1 p2 in let memx ((p1,h1),(p2,h2)) ppairs = not (exists (fun ((q1,_),(q2,_)) -> poly_eq p1 q1 && poly_eq p2 q2) ppairs) in Buchberger 's second criterion . let criterion2 basis (lcm,((p1,h1),(p2,h2))) opairs = exists (fun g -> not(poly_eq (fst g) p1) && not(poly_eq (fst g) p2) && can (mdiv lcm) (hd(fst g)) && not(memx (align(g,(p1,h1))) (map snd opairs)) && not(memx (align(g,(p2,h2))) (map snd opairs))) basis in let constant_poly p = length p = 1 && forall ((=) 0) (snd(hd p)) in let rec grobner_basis basis pairs = Format.print_string(string_of_int(length basis)^" basis elements and "^ string_of_int(length pairs)^" critical pairs"); Format.print_newline(); match pairs with [] -> basis | (l,(p1,p2))::opairs -> let (sp,hist as sph) = monic (reduce basis (spoly l p1 p2)) in if sp = [] || criterion2 basis (l,(p1,p2)) opairs then grobner_basis basis opairs else if constant_poly sp then grobner_basis (sph::basis) [] else let rawcps = map (fun p -> mlcm (hd(fst p)) (hd sp),align(p,sph)) basis in let newcps = filter (fun (l,(p,q)) -> not(orthogonal l (fst p) (fst q))) rawcps in grobner_basis (sph::basis) (merge forder opairs (mergesort forder newcps)) in Interreduce initial polynomials . let rec grobner_interreduce rpols ipols = match ipols with [] -> map monic (rev rpols) | p::ps -> let p' = reduce (rpols @ ps) p in if fst p' = [] then grobner_interreduce rpols ps else grobner_interreduce (p'::rpols) ps in let grobner pols = let npols = map2 (fun p n -> p,Start n) pols (0--(length pols - 1)) in let phists = filter (fun (p,_) -> p <> []) npols in let bas = grobner_interreduce [] (map monic phists) in let prs0 = allpairs (fun x y -> x,y) bas bas in let prs1 = filter (fun ((x,_),(y,_)) -> poly_lt x y) prs0 in let prs2 = map (fun (p,q) -> mlcm (hd(fst p)) (hd(fst q)),(p,q)) prs1 in let prs3 = filter (fun (l,(p,q)) -> not(orthogonal l (fst p) (fst q))) prs2 in grobner_basis bas (mergesort forder prs3) in let grobner_refute pols = let gb = grobner pols in snd(find (fun (p,h) -> length p = 1 && forall ((=)0) (snd(hd p))) gb) in let rec resolve_proof vars prf = match prf with Start(-1) -> [] | Start m -> [m,[num_1,map (K 0) vars]] | Mmul(pol,lin) -> let lis = resolve_proof vars lin in map (fun (n,p) -> n,grob_cmul pol p) lis | Add(lin1,lin2) -> let lis1 = resolve_proof vars lin1 and lis2 = resolve_proof vars lin2 in let dom = setify(union (map fst lis1) (map fst lis2)) in map (fun n -> let a = try assoc n lis1 with Failure _ -> [] and b = try assoc n lis2 with Failure _ -> [] in n,grob_add a b) dom in Run the procedure and produce Weak Nullstellensatz certificate . let grobner_weak vars pols = let cert = resolve_proof vars (grobner_refute pols) in let l = itlist (itlist (lcm_num o denominator o fst) o snd) cert (num_1) in l,map (fun (i,p) -> i,map (fun (d,m) -> (l*/d,m)) p) cert in let grobner_ideal vars pols pol = let pol',h = reduce (grobner pols) (grob_neg pol,Start(-1)) in if pol' <> [] then failwith "grobner_ideal: not in the ideal" else resolve_proof vars h in Produce Strong Nullstellensatz certificate for a power of pol . let grobner_strong vars pols pol = if pol = [] then 1,num_1,[] else let vars' = (concl TRUTH)::vars in let grob_z = [num_1,1::(map (fun x -> 0) vars)] and grob_1 = [num_1,(map (fun x -> 0) vars')] and augment = map (fun (c,m) -> (c,0::m)) in let pols' = map augment pols and pol' = augment pol in let allpols = (grob_sub (grob_mul grob_z pol') grob_1)::pols' in let l,cert = grobner_weak vars' allpols in let d = itlist (itlist (max o hd o snd) o snd) cert 0 in let transform_monomial (c,m) = grob_cmul (c,tl m) (grob_pow vars pol (d - hd m)) in let transform_polynomial q = itlist (grob_add o transform_monomial) q [] in let cert' = map (fun (c,q) -> c-1,transform_polynomial q) (filter (fun (k,_) -> k <> 0) cert) in d,l,cert' in We return an IDEAL_CONV and the actual ring prover . let pth_step = prove (`!(add:A->A->A) (mul:A->A->A) (n0:A). (!x. mul n0 x = n0) /\ (!x y z. (add x y = add x z) <=> (y = z)) /\ (!w x y z. (add (mul w y) (mul x z) = add (mul w z) (mul x y)) <=> (w = x) \/ (y = z)) ==> (!a b c d. ~(a = b) /\ ~(c = d) <=> ~(add (mul a c) (mul b d) = add (mul a d) (mul b c))) /\ (!n a b c d. ~(n = n0) ==> (a = b) /\ ~(c = d) ==> ~(add a (mul n c) = add b (mul n d)))`, REPEAT GEN_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[GSYM DE_MORGAN_THM] THEN REPEAT GEN_TAC THEN DISCH_TAC THEN STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o SPECL [`n0:A`; `n:A`; `d:A`; `c:A`]) THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN ASM_SIMP_TAC[]) and FINAL_RULE = MATCH_MP(TAUT `(p ==> F) ==> (~q = p) ==> q`) and false_tm = `F` in let rec refute_disj rfn tm = match tm with Comb(Comb(Const("\\/",_),l),r) -> DISJ_CASES (ASSUME tm) (refute_disj rfn l) (refute_disj rfn r) | _ -> rfn tm in fun (ring_dest_const,ring_mk_const,RING_EQ_CONV, ring_neg_tm,ring_add_tm,ring_sub_tm, ring_inv_tm,ring_mul_tm,ring_div_tm,ring_pow_tm, RING_INTEGRAL,RABINOWITSCH_THM,RING_NORMALIZE_CONV) -> let INITIAL_CONV = TOP_DEPTH_CONV BETA_CONV THENC PRESIMP_CONV THENC CONDS_ELIM_CONV THENC NNF_CONV THENC (if is_iff(snd(strip_forall(concl RABINOWITSCH_THM))) then GEN_REWRITE_CONV ONCE_DEPTH_CONV [RABINOWITSCH_THM] else ALL_CONV) THENC GEN_REWRITE_CONV REDEPTH_CONV [AND_FORALL_THM; LEFT_AND_FORALL_THM; RIGHT_AND_FORALL_THM; LEFT_OR_FORALL_THM; RIGHT_OR_FORALL_THM; OR_EXISTS_THM; LEFT_OR_EXISTS_THM; RIGHT_OR_EXISTS_THM; LEFT_AND_EXISTS_THM; RIGHT_AND_EXISTS_THM] in let ring_dest_neg t = let l,r = dest_comb t in if l = ring_neg_tm then r else failwith "ring_dest_neg" and ring_dest_inv t = let l,r = dest_comb t in if l = ring_inv_tm then r else failwith "ring_dest_inv" and ring_dest_add = dest_binop ring_add_tm and ring_mk_add = mk_binop ring_add_tm and ring_dest_sub = dest_binop ring_sub_tm and ring_dest_mul = dest_binop ring_mul_tm and ring_mk_mul = mk_binop ring_mul_tm and ring_dest_div = dest_binop ring_div_tm and ring_dest_pow = dest_binop ring_pow_tm and ring_mk_pow = mk_binop ring_pow_tm in let rec grobvars tm acc = if can ring_dest_const tm then acc else if can ring_dest_neg tm then grobvars (rand tm) acc else if can ring_dest_pow tm && is_numeral (rand tm) then grobvars (lhand tm) acc else if can ring_dest_add tm || can ring_dest_sub tm || can ring_dest_mul tm then grobvars (lhand tm) (grobvars (rand tm) acc) else if can ring_dest_inv tm then let gvs = grobvars (rand tm) [] in if gvs = [] then acc else tm::acc else if can ring_dest_div tm then let lvs = grobvars (lhand tm) acc and gvs = grobvars (rand tm) [] in if gvs = [] then lvs else tm::acc else tm::acc in let rec grobify_term vars tm = try if not(mem tm vars) then failwith "" else [num_1,map (fun i -> if i = tm then 1 else 0) vars] with Failure _ -> try let x = ring_dest_const tm in if x =/ num_0 then [] else [x,map (fun v -> 0) vars] with Failure _ -> try grob_neg(grobify_term vars (ring_dest_neg tm)) with Failure _ -> try grob_inv(grobify_term vars (ring_dest_inv tm)) with Failure _ -> try let l,r = ring_dest_add tm in grob_add (grobify_term vars l) (grobify_term vars r) with Failure _ -> try let l,r = ring_dest_sub tm in grob_sub (grobify_term vars l) (grobify_term vars r) with Failure _ -> try let l,r = ring_dest_mul tm in grob_mul (grobify_term vars l) (grobify_term vars r) with Failure _ -> try let l,r = ring_dest_div tm in grob_div (grobify_term vars l) (grobify_term vars r) with Failure _ -> try let l,r = ring_dest_pow tm in grob_pow vars (grobify_term vars l) (dest_small_numeral r) with Failure _ -> failwith "grobify_term: unknown or invalid term" in let grobify_equation vars tm = let l,r = dest_eq tm in grob_sub (grobify_term vars l) (grobify_term vars r) in let grobify_equations tm = let cjs = conjuncts tm in let rawvars = itlist (fun eq a -> grobvars (lhand eq) (grobvars (rand eq) a)) cjs [] in let vars = sort (fun x y -> x < y) (setify rawvars) in vars,map (grobify_equation vars) cjs in let holify_polynomial = let holify_varpow (v,n) = if n = 1 then v else ring_mk_pow v (mk_small_numeral n) in let holify_monomial vars (c,m) = let xps = map holify_varpow (filter (fun (_,n) -> n <> 0) (zip vars m)) in end_itlist ring_mk_mul (ring_mk_const c :: xps) in let holify_polynomial vars p = if p = [] then ring_mk_const (num_0) else end_itlist ring_mk_add (map (holify_monomial vars) p) in holify_polynomial in let (pth_idom,pth_ine) = CONJ_PAIR(MATCH_MP pth_step RING_INTEGRAL) in let IDOM_RULE = CONV_RULE(REWR_CONV pth_idom) in let PROVE_NZ n = EQF_ELIM(RING_EQ_CONV (mk_eq(ring_mk_const n,ring_mk_const(num_0)))) in let NOT_EQ_01 = PROVE_NZ (num_1) and INE_RULE n = MATCH_MP(MATCH_MP pth_ine (PROVE_NZ n)) and MK_ADD th1 th2 = MK_COMB(AP_TERM ring_add_tm th1,th2) in let execute_proof vars eths prf = let x,th1 = SPEC_VAR(CONJUNCT1(CONJUNCT2 RING_INTEGRAL)) in let y,th2 = SPEC_VAR th1 in let z,th3 = SPEC_VAR th2 in let SUB_EQ_RULE = GEN_REWRITE_RULE I [SYM(INST [mk_comb(ring_neg_tm,z),x] th3)] in let initpols = map (CONV_RULE(BINOP_CONV RING_NORMALIZE_CONV) o SUB_EQ_RULE) eths in let ADD_RULE th1 th2 = CONV_RULE (BINOP_CONV RING_NORMALIZE_CONV) (MK_COMB(AP_TERM ring_add_tm th1,th2)) and MUL_RULE vars m th = CONV_RULE (BINOP_CONV RING_NORMALIZE_CONV) (AP_TERM (mk_comb(ring_mul_tm,holify_polynomial vars [m])) th) in let execache = ref [] in let memoize prf x = (execache := (prf,x)::(!execache)); x in let rec assoceq a l = match l with [] -> failwith "assoceq" | (x,y)::t -> if x==a then y else assoceq a t in let rec run_proof vars prf = try assoceq prf (!execache) with Failure _ -> (match prf with Start m -> el m initpols | Add(p1,p2) -> memoize prf (ADD_RULE (run_proof vars p1) (run_proof vars p2)) | Mmul(m,p2) -> memoize prf (MUL_RULE vars m (run_proof vars p2))) in let th = run_proof vars prf in execache := []; CONV_RULE RING_EQ_CONV th in let REFUTE tm = if tm = false_tm then ASSUME tm else let nths0,eths0 = partition (is_neg o concl) (CONJUNCTS(ASSUME tm)) in let nths = filter (is_eq o rand o concl) nths0 and eths = filter (is_eq o concl) eths0 in if eths = [] then let th1 = end_itlist (fun th1 th2 -> IDOM_RULE(CONJ th1 th2)) nths in let th2 = CONV_RULE(RAND_CONV(BINOP_CONV RING_NORMALIZE_CONV)) th1 in let l,r = dest_eq(rand(concl th2)) in EQ_MP (EQF_INTRO th2) (REFL l) else if nths = [] && not(is_var ring_neg_tm) then let vars,pols = grobify_equations(list_mk_conj(map concl eths)) in execute_proof vars eths (grobner_refute pols) else let vars,l,cert,noteqth = if nths = [] then let vars,pols = grobify_equations(list_mk_conj(map concl eths)) in let l,cert = grobner_weak vars pols in vars,l,cert,NOT_EQ_01 else let nth = end_itlist (fun th1 th2 -> IDOM_RULE(CONJ th1 th2)) nths in let vars,pol::pols = grobify_equations(list_mk_conj(rand(concl nth)::map concl eths)) in let deg,l,cert = grobner_strong vars pols pol in let th1 = CONV_RULE(RAND_CONV(BINOP_CONV RING_NORMALIZE_CONV)) nth in let th2 = funpow deg (IDOM_RULE o CONJ th1) NOT_EQ_01 in vars,l,cert,th2 in Format.print_string("Translating certificate to HOL inferences"); Format.print_newline(); let cert_pos = map (fun (i,p) -> i,filter (fun (c,m) -> c >/ num_0) p) cert and cert_neg = map (fun (i,p) -> i,map (fun (c,m) -> minus_num c,m) (filter (fun (c,m) -> c </ num_0) p)) cert in let herts_pos = map (fun (i,p) -> i,holify_polynomial vars p) cert_pos and herts_neg = map (fun (i,p) -> i,holify_polynomial vars p) cert_neg in let thm_fn pols = if pols = [] then REFL(ring_mk_const num_0) else end_itlist MK_ADD (map (fun (i,p) -> AP_TERM(mk_comb(ring_mul_tm,p)) (el i eths)) pols) in let th1 = thm_fn herts_pos and th2 = thm_fn herts_neg in let th3 = CONJ(MK_ADD (SYM th1) th2) noteqth in let th4 = CONV_RULE (RAND_CONV(BINOP_CONV RING_NORMALIZE_CONV)) (INE_RULE l th3) in let l,r = dest_eq(rand(concl th4)) in EQ_MP (EQF_INTRO th4) (REFL l) in let ring_ty = snd(dest_fun_ty(snd(dest_fun_ty(type_of ring_add_tm)))) in let RING tm = let avs = filter ((=) ring_ty o type_of) (frees tm) in let tm' = list_mk_forall(avs,tm) in let th1 = INITIAL_CONV(mk_neg tm') in let evs,bod = strip_exists(rand(concl th1)) in if is_forall bod then failwith "RING: non-universal formula" else let th1a = WEAK_DNF_CONV bod in let boda = rand(concl th1a) in let th2a = refute_disj REFUTE boda in let th2b = TRANS th1a (EQF_INTRO(NOT_INTRO(DISCH boda th2a))) in let th2 = UNDISCH(NOT_ELIM(EQF_ELIM th2b)) in let finbod,th3 = let rec CHOOSES evs (etm,th) = match evs with [] -> (etm,th) | ev::oevs -> let etm',th' = CHOOSES oevs (etm,th) in mk_exists(ev,etm'),CHOOSE (ev,ASSUME (mk_exists(ev,etm'))) th' in CHOOSES evs (bod,th2) in SPECL avs (MATCH_MP (FINAL_RULE (DISCH finbod th3)) th1) and ideal tms tm = let rawvars = itlist grobvars (tm::tms) [] in let vars = sort (fun x y -> x < y) (setify rawvars) in let pols = map (grobify_term vars) tms and pol = grobify_term vars tm in let cert = grobner_ideal vars pols pol in map (fun n -> let p = assocd n cert [] in holify_polynomial vars p) (0--(length pols-1)) in RING,ideal;; let RING parms = fst(RING_AND_IDEAL_CONV parms);; let ideal_cofactors parms = snd(RING_AND_IDEAL_CONV parms);; Simplify a natural number assertion to eliminate conditionals , DIV , MOD , PRE , cutoff subtraction , EVEN and ODD . Try to do it in a way that makes make this quantifier selection work there too ; better to do NNF first if you care . This also applies to EVEN and ODD . let NUM_SIMPLIFY_CONV = let pre_tm = `PRE` and div_tm = `(DIV):num->num->num` and mod_tm = `(MOD):num->num->num` and p_tm = `P:num->bool` and n_tm = `n:num` and m_tm = `m:num` and q_tm = `P:num->num->bool` and a_tm = `a:num` and b_tm = `b:num` in let is_pre tm = is_comb tm && rator tm = pre_tm and is_sub = is_binop `(-):num->num->num` and is_divmod = let is_div = is_binop div_tm and is_mod = is_binop mod_tm in fun tm -> is_div tm || is_mod tm and contains_quantifier = can (find_term (fun t -> is_forall t || is_exists t || is_uexists t)) and BETA2_CONV = RATOR_CONV BETA_CONV THENC BETA_CONV * * and PRE_ELIM_THM '' = CONV_RULE ( RAND_CONV NNF_CONV ) PRE_ELIM_THM and SUB_ELIM_THM '' = CONV_RULE ( RAND_CONV NNF_CONV ) SUB_ELIM_THM and DIVMOD_ELIM_THM '' = CONV_RULE ( RAND_CONV NNF_CONV ) DIVMOD_ELIM_THM * * and PRE_ELIM_THM'' = CONV_RULE (RAND_CONV NNF_CONV) PRE_ELIM_THM and SUB_ELIM_THM'' = CONV_RULE (RAND_CONV NNF_CONV) SUB_ELIM_THM and DIVMOD_ELIM_THM'' = CONV_RULE (RAND_CONV NNF_CONV) DIVMOD_ELIM_THM ***) and pth_evenodd = prove (`(EVEN(x) <=> (!y. ~(x = SUC(2 * y)))) /\ (ODD(x) <=> (!y. ~(x = 2 * y))) /\ (~EVEN(x) <=> (!y. ~(x = 2 * y))) /\ (~ODD(x) <=> (!y. ~(x = SUC(2 * y))))`, REWRITE_TAC[GSYM NOT_EXISTS_THM; GSYM EVEN_EXISTS; GSYM ODD_EXISTS] THEN REWRITE_TAC[NOT_EVEN; NOT_ODD]) in let rec NUM_MULTIPLY_CONV pos tm = if is_forall tm || is_exists tm || is_uexists tm then BINDER_CONV (NUM_MULTIPLY_CONV pos) tm else if is_imp tm && contains_quantifier tm then COMB2_CONV (RAND_CONV(NUM_MULTIPLY_CONV(not pos))) (NUM_MULTIPLY_CONV pos) tm else if (is_conj tm || is_disj tm || is_iff tm) && contains_quantifier tm then BINOP_CONV (NUM_MULTIPLY_CONV pos) tm else if is_neg tm && not pos && contains_quantifier tm then RAND_CONV (NUM_MULTIPLY_CONV (not pos)) tm else * * try let t = find_term ( fun t - > is_pre t & & free_in t tm ) tm in let ty = type_of t in let v = in let p = mk_abs(v , subst [ v , t ] tm ) in let = if pos then PRE_ELIM_THM '' else PRE_ELIM_THM ' in let th1 = INST [ p , p_tm ; rand t , n_tm ] in let th2 = CONV_RULE(COMB2_CONV ( RAND_CONV BETA_CONV ) ( BINDER_CONV(RAND_CONV BETA_CONV ) ) ) th1 in CONV_RULE(RAND_CONV ( NUM_MULTIPLY_CONV pos ) ) th2 with Failure _ - > try let t = find_term ( fun t - > is_sub t & & free_in t tm ) tm in let ty = type_of t in let v = in let p = mk_abs(v , subst [ v , t ] tm ) in let = if pos then SUB_ELIM_THM '' else SUB_ELIM_THM ' in let th1 = INST [ p , p_tm ; lhand t , a_tm ; rand t , b_tm ] in let th2 = CONV_RULE(COMB2_CONV ( RAND_CONV BETA_CONV ) ( BINDER_CONV(RAND_CONV BETA_CONV ) ) ) th1 in CONV_RULE(RAND_CONV ( NUM_MULTIPLY_CONV pos ) ) th2 with Failure _ - > try let t = find_term ( fun t - > is_divmod t & & free_in t tm ) tm in let x = lhand t and y = rand t in let dtm = mk_comb(mk_comb(div_tm , x),y ) and mtm = mk_comb(mk_comb(mod_tm , x),y ) in let vd = genvar(type_of dtm ) and vm = genvar(type_of mtm ) in let p = list_mk_abs([vd;vm],subst[vd , dtm ; vm , mtm ] tm ) in let = if pos then DIVMOD_ELIM_THM '' else DIVMOD_ELIM_THM ' in let th1 = INST [ p , q_tm ; x , m_tm ; y , n_tm ] in let th2 = CONV_RULE(COMB2_CONV(RAND_CONV BETA2_CONV ) ( funpow 2 BINDER_CONV(RAND_CONV BETA2_CONV ) ) ) th1 in CONV_RULE(RAND_CONV ( NUM_MULTIPLY_CONV pos ) ) th2 with Failure _ - > * * try let t = find_term (fun t -> is_pre t && free_in t tm) tm in let ty = type_of t in let v = genvar ty in let p = mk_abs(v,subst [v,t] tm) in let th0 = if pos then PRE_ELIM_THM'' else PRE_ELIM_THM' in let th1 = INST [p,p_tm; rand t,n_tm] th0 in let th2 = CONV_RULE(COMB2_CONV (RAND_CONV BETA_CONV) (BINDER_CONV(RAND_CONV BETA_CONV))) th1 in CONV_RULE(RAND_CONV (NUM_MULTIPLY_CONV pos)) th2 with Failure _ -> try let t = find_term (fun t -> is_sub t && free_in t tm) tm in let ty = type_of t in let v = genvar ty in let p = mk_abs(v,subst [v,t] tm) in let th0 = if pos then SUB_ELIM_THM'' else SUB_ELIM_THM' in let th1 = INST [p,p_tm; lhand t,a_tm; rand t,b_tm] th0 in let th2 = CONV_RULE(COMB2_CONV (RAND_CONV BETA_CONV) (BINDER_CONV(RAND_CONV BETA_CONV))) th1 in CONV_RULE(RAND_CONV (NUM_MULTIPLY_CONV pos)) th2 with Failure _ -> try let t = find_term (fun t -> is_divmod t && free_in t tm) tm in let x = lhand t and y = rand t in let dtm = mk_comb(mk_comb(div_tm,x),y) and mtm = mk_comb(mk_comb(mod_tm,x),y) in let vd = genvar(type_of dtm) and vm = genvar(type_of mtm) in let p = list_mk_abs([vd;vm],subst[vd,dtm; vm,mtm] tm) in let th0 = if pos then DIVMOD_ELIM_THM'' else DIVMOD_ELIM_THM' in let th1 = INST [p,q_tm; x,m_tm; y,n_tm] th0 in let th2 = CONV_RULE(COMB2_CONV(RAND_CONV BETA2_CONV) (funpow 2 BINDER_CONV(RAND_CONV BETA2_CONV))) th1 in CONV_RULE(RAND_CONV (NUM_MULTIPLY_CONV pos)) th2 with Failure _ -> ***) REFL tm in NUM_REDUCE_CONV THENC CONDS_CELIM_CONV THENC NNF_CONV THENC NUM_MULTIPLY_CONV true THENC NUM_REDUCE_CONV THENC GEN_REWRITE_CONV ONCE_DEPTH_CONV [pth_evenodd];; let NUM_RING = let NUM_INTEGRAL_LEMMA = prove (`((w : num) = x + d) /\ (y = z + e) ==> ((w * y + x * z = w * z + x * y) <=> (w = x) \/ (y = z))`, DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a : num) + b + c + d + e = a + c + e + b + d`] THEN REWRITE_TAC[EQ_ADD_LCANCEL; EQ_ADD_LCANCEL_0; MULT_EQ_0]) in let NUM_INTEGRAL = prove (`(!x : num. 0 * x = 0) /\ (!x y z : num. (x + y = x + z) <=> (y = z)) /\ (!w x y z : num. (w * y + x * z = w * z + x * y) <=> (w = x) \/ (y = z))`, REWRITE_TAC[MULT_CLAUSES; EQ_ADD_LCANCEL] THEN REPEAT GEN_TAC THEN DISJ_CASES_TAC (SPECL [`w:num`; `x:num`] LE_CASES) THEN DISJ_CASES_TAC (SPECL [`y:num`; `z:num`] LE_CASES) THEN REPEAT(FIRST_X_ASSUM (CHOOSE_THEN SUBST1_TAC o REWRITE_RULE[LE_EXISTS])) THEN ASM_MESON_TAC[NUM_INTEGRAL_LEMMA; ADD_SYM; MULT_SYM]) in let rawring = RING(dest_numeral,mk_numeral,NUM_EQ_CONV, genvar bool_ty,`(+):num->num->num`,genvar bool_ty, genvar bool_ty,`( * ):num->num->num`,genvar bool_ty, `(EXP):num->num->num`, NUM_INTEGRAL,TRUTH,NUM_NORMALIZE_CONV) in let initconv = NUM_SIMPLIFY_CONV THENC GEN_REWRITE_CONV DEPTH_CONV [ADD1] and t_tm = `T` in fun tm -> let th = initconv tm in if rand(concl th) = t_tm then th else EQ_MP (SYM th) (rawring(rand(concl th)));;
3c532751cfc78c355d15bffc4d58df4099efddb1fbdac04913efb4388248982a
bobzhang/fan
fan_args.ml
* TODO : add an unit test for import DDSL (* %import{ *) (* Prelude: *) (* parse_file *) (* parse_interf *) (* parse_implem *) (* ; *) (* Format: *) (* printf *) (* ; *) (* };; *) let parse_file = Prelude.parse_file let eprintf = Format.eprintf let fprintf = Format.fprintf let printf = Format.printf open Util let just_print_filters () = let pp = eprintf in let p_tbl f tbl = Hashtbl.iter (fun k _v -> fprintf f "%s@;" k) tbl in begin pp "@[for interface:@[<hv2>%a@]@]@." p_tbl Ast_filters.interf_filters ; pp "@[for phrase:@[<hv2>%a@]@]@." p_tbl Ast_filters.implem_filters ; pp "@[for top_phrase:@[<hv2>%a@]@]@." p_tbl Ast_filters.topphrase_filters end let just_print_parsers () = let pp = eprintf in let p_tbl f tbl = Hashtbl.iter (fun k _v -> fprintf f "%s@;" k) tbl in begin pp "@[Loaded Parsers:@;@[<hv2>%a@]@]@." p_tbl Ast_parsers.registered_parsers end let just_print_applied_parsers () = let pp = eprintf in pp "@[Applied Parsers:@;@[<hv2>%a@]@]@." (fun f q -> Queue.iter (fun (k,_) -> fprintf f "%s@;" k) q ) Ast_parsers.applied_parsers type file_kind = | Intf of string | Impl of string | Str of string | ModuleImpl of string | IncludeDir of string let print_loaded_modules = ref false let output_file = ref None (** parse the file, apply the filter and pipe it to the backend *) let process_intf name = let v = Option.map Ast_filters.apply_interf_filters @@ parse_file name Prelude.parse_interf in Prelude.CurrentPrinter.print_interf ?input_file:(Some name) ?output_file:(!output_file) v let process_impl name = let v = Option.map Ast_filters.apply_implem_filters @@ parse_file name Prelude.parse_implem in Prelude.CurrentPrinter.print_implem ~input_file:name ?output_file:(!output_file) v let input_file x = match x with | Intf file_name -> begin if file_name <> "-" then Configf.compilation_unit := Some (String.capitalize (Filename.(chop_extension (basename file_name)))); Configf.current_input_file := file_name; process_intf file_name end | Impl file_name -> begin if file_name <> "-" then Configf.compilation_unit := Some (String.capitalize (Filename.(chop_extension (basename file_name)))); Configf.current_input_file := file_name; process_impl file_name; end | Str s -> let (f, o) = Filename.open_temp_file "from_string" ".ml" in (output_string o s; close_out o; Configf.current_input_file := f; process_impl f; at_exit (fun () -> Sys.remove f)) | ModuleImpl file_name -> Control_require.add file_name | IncludeDir dir -> Ref.modify Configf.dynload_dirs (cons dir) (* local variables: *) compile - command : " cd .. & & pmake main_annot / fan_args.cmo " (* end: *)
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/cold/fan_args.ml
ocaml
%import{ Prelude: parse_file parse_interf parse_implem ; Format: printf ; };; * parse the file, apply the filter and pipe it to the backend local variables: end:
* TODO : add an unit test for import DDSL let parse_file = Prelude.parse_file let eprintf = Format.eprintf let fprintf = Format.fprintf let printf = Format.printf open Util let just_print_filters () = let pp = eprintf in let p_tbl f tbl = Hashtbl.iter (fun k _v -> fprintf f "%s@;" k) tbl in begin pp "@[for interface:@[<hv2>%a@]@]@." p_tbl Ast_filters.interf_filters ; pp "@[for phrase:@[<hv2>%a@]@]@." p_tbl Ast_filters.implem_filters ; pp "@[for top_phrase:@[<hv2>%a@]@]@." p_tbl Ast_filters.topphrase_filters end let just_print_parsers () = let pp = eprintf in let p_tbl f tbl = Hashtbl.iter (fun k _v -> fprintf f "%s@;" k) tbl in begin pp "@[Loaded Parsers:@;@[<hv2>%a@]@]@." p_tbl Ast_parsers.registered_parsers end let just_print_applied_parsers () = let pp = eprintf in pp "@[Applied Parsers:@;@[<hv2>%a@]@]@." (fun f q -> Queue.iter (fun (k,_) -> fprintf f "%s@;" k) q ) Ast_parsers.applied_parsers type file_kind = | Intf of string | Impl of string | Str of string | ModuleImpl of string | IncludeDir of string let print_loaded_modules = ref false let output_file = ref None let process_intf name = let v = Option.map Ast_filters.apply_interf_filters @@ parse_file name Prelude.parse_interf in Prelude.CurrentPrinter.print_interf ?input_file:(Some name) ?output_file:(!output_file) v let process_impl name = let v = Option.map Ast_filters.apply_implem_filters @@ parse_file name Prelude.parse_implem in Prelude.CurrentPrinter.print_implem ~input_file:name ?output_file:(!output_file) v let input_file x = match x with | Intf file_name -> begin if file_name <> "-" then Configf.compilation_unit := Some (String.capitalize (Filename.(chop_extension (basename file_name)))); Configf.current_input_file := file_name; process_intf file_name end | Impl file_name -> begin if file_name <> "-" then Configf.compilation_unit := Some (String.capitalize (Filename.(chop_extension (basename file_name)))); Configf.current_input_file := file_name; process_impl file_name; end | Str s -> let (f, o) = Filename.open_temp_file "from_string" ".ml" in (output_string o s; close_out o; Configf.current_input_file := f; process_impl f; at_exit (fun () -> Sys.remove f)) | ModuleImpl file_name -> Control_require.add file_name | IncludeDir dir -> Ref.modify Configf.dynload_dirs (cons dir) compile - command : " cd .. & & pmake main_annot / fan_args.cmo "
5cc87328efb92d565ab0ec5d4ee8f3b3ec66c021fec76930db8bd06514bf1db4
a-nikolaev/wanderers
item.ml
Wanderers - open world adventure game . Copyright ( C ) 2013 - 2014 . This program is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . Copyright (C) 2013-2014 Alexey Nikolaev. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) open Base type mat = Leather | Wood | Steel | DmSteel | RustySteel | Gold type eff = [ `Heal ] (* unified quality measure *) type qm = float let qm_min = 0.0 (* extremely bad, poor quality *) let qm_max = 1.0 (* perfect, flawless *) module Ranged = struct type t = {force: float; projmass: float; dmgmult: float} end module Melee = struct type t = {attrate: float; duration: float;} let join_simple {attrate=ar1; duration=d1} {attrate=ar2; duration=d2} = {attrate=ar1 +. ar2; duration = max d1 d2} let join_max {attrate=ar1; duration=d1} {attrate=ar2; duration=d2} = {attrate = max ar1 ar2; duration = max d1 d2} end type prop = [ `Melee of Melee.t | `Defense of float | `Weight of float | `Material of mat | `Consumable of eff | `Wearable | `Headgear | `Wieldable | `Quality of qm | `Ranged of Ranged.t | `Money] let upgrade_prop (m0,m1) prop = match m1 with | DmSteel -> ( let c = 1.4 in match prop with | `Weight x -> `Weight (x *. 0.90) | `Defense x -> `Defense (x *. c) | `Melee {Melee.attrate=att; Melee.duration=dur} -> `Melee Melee.({attrate = att *. c; duration = dur}) | `Ranged {Ranged.force=frc; Ranged.projmass=m; Ranged.dmgmult=dmg} -> `Ranged Ranged.({force = frc; projmass = m; dmgmult = dmg *. c}) | `Material _ -> `Material m1 | x -> x ) | RustySteel -> ( let c = 0.65 in match prop with | `Weight x -> `Weight (x *. 1.0) | `Defense x -> `Defense (x *. c) | `Melee {Melee.attrate=att; Melee.duration=dur} -> `Melee Melee.({attrate = att *. c; duration = dur}) | `Ranged {Ranged.force=frc; Ranged.projmass=m; Ranged.dmgmult=dmg} -> `Ranged Ranged.({force = frc; projmass = m; dmgmult = dmg *. c}) | `Material _ -> `Material m1 | x -> x ) | _ -> prop module PS = Set.Make(struct type t = prop let compare = compare end) (* kind size mat variant *) type barcode = {bc_kind: int; bc_size: int; bc_mat: mat; bc_var: int} type t = { name: string; prop: PS.t; imgindex:int; price: int; stackable: int option; barcode:barcode; } (* the parameter 'stackable' tells you the max size of the stack of such objects *) type item_type = t let upgrade_item (m0,m1) item = let prop_u = PS.fold (fun p acc -> PS.add (upgrade_prop (m0,m1) p) acc) item.prop PS.empty in let price_u = match m1 with | DmSteel -> 50 + item.price * 4 | RustySteel -> (item.price+1) / 2 | x -> item.price in {item with prop = prop_u; price = price_u; barcode = {item.barcode with bc_mat = m1}} item obj has property p let is p obj = PS.mem p obj.prop let get_melee obj = PS.fold (fun prop acc -> match prop with `Melee x -> Some x | _ -> acc ) obj.prop None let get_defense obj = PS.fold (fun prop acc -> match prop with `Defense x -> acc +. x | _ -> acc ) obj.prop 0.0 let get_ranged obj = PS.fold (fun prop acc -> match prop with `Ranged x -> Some x | _ -> acc ) obj.prop None let get_mat obj = PS.fold (fun prop acc -> match prop with `Material x -> Some x | _ -> acc ) obj.prop None let get_mass obj = PS.fold (fun prop acc -> match prop with `Weight x -> acc +. x | _ -> acc ) obj.prop 0.0 let is_wearable obj = PS.mem `Wearable obj.prop let is_a_headgear obj = PS.mem `Headgear obj.prop let is_wieldable obj = PS.mem `Wieldable obj.prop let string_of_item i = Printf.sprintf "[%i,%i] p=%i (%s)" i.barcode.bc_kind i.barcode.bc_size i.price i.name (* integer map *) module M = Map.Make(struct type t = int let compare = compare end) let map_of_list ls = List.fold_left (fun acc (key,obj) -> M.add key obj acc) M.empty ls (* container *) module Cnt = struct type slot_type = General | Hand | Head | Body | Purse let does_fit slt obj = match slt with | General -> true | Hand -> is `Wieldable obj | Head -> is `Headgear obj | Body -> is `Wearable obj | Purse -> is `Money obj type bunch = {item: item_type; amount: int} type t = {bunch: bunch M.t; slot: slot_type M.t; caplim: int option;} let make slot caplim = {bunch = M.empty; slot; caplim} let default_coins_slot = 4 let empty_nat_human = let ls = [(0,Hand); (1,Body); (2,Hand); (3, Head); (4,Purse)] in let len = List.length ls in make (map_of_list ls) (Some len) let empty_only_money = let ls = [(0,Purse)] in let len = List.length ls in make (map_of_list ls) (Some len) let empty_only_money_plus = let ls = [(0,Purse); (1,General)] in let len = List.length ls in make (map_of_list ls) (Some len) let empty_unlimited = make M.empty None let empty_limited n = let ls = fold_lim (fun acc i -> (i, General)::acc) [] 0 (n-1) |> List.rev in make (map_of_list ls) (Some n) let find_empty_slot pred c = let rec search i = let enough_space = match c.caplim with | Some lim -> i < lim | None -> true in if enough_space then ( if not (M.mem i c.bunch) && (not (M.mem i c.slot) || pred (M.find i c.slot)) then Some i else search (i+1) ) else None in search 0 let find_matching_half_full_slot obj c = match obj.stackable with | Some max_amount -> M.fold (fun i b acc -> match acc, b with | None, {item; amount} when item = obj && amount < max_amount -> Some i | _ -> acc ) c.bunch None | None -> None let put obj c = let opt_i = match find_matching_half_full_slot obj c with | Some i -> Some i | None -> find_empty_slot (fun slt -> does_fit slt obj) c in match opt_i with | Some i -> let {item; amount} = try M.find i c.bunch with Not_found -> {item=obj; amount=0} in Some {c with bunch = M.add i {item; amount = amount+1} c.bunch} | None -> None get only one object let get i c = try let {item; amount} = M.find i c.bunch in if amount > 1 then Some (item, {c with bunch = M.add i {item; amount=amount-1} c.bunch}) else Some (item, {c with bunch = M.remove i c.bunch}) with | Not_found -> None type 'a move_bunch_result = | MoveBunchFailure | MoveBunchPartial of (bunch * 'a) | MoveBunchSuccess of 'a (* put the whole bunch *) let put_bunch bunch c = let max_amount = match bunch.item.stackable with Some x -> x | _ -> 1 in let rec repeat some_success bunch c = let {item; amount} = bunch in let opt_i = match find_matching_half_full_slot item c with | Some i -> Some i | None -> find_empty_slot (fun slt -> does_fit slt item) c in match opt_i with | Some i -> let amount_already_there = try (M.find i c.bunch).amount with Not_found -> 0 in let amount_to_add = (min (amount+amount_already_there) max_amount) - amount_already_there in let amount_remains = amount - amount_to_add in let uc = {c with bunch = M.add i {item; amount = amount_already_there + amount_to_add} c.bunch} in if amount_remains > 0 then repeat true {item; amount = amount_remains} uc else MoveBunchSuccess uc | None -> if some_success then MoveBunchPartial (bunch, c) else MoveBunchFailure in if bunch.amount > 0 then repeat false bunch c else MoveBunchSuccess c (* get the whole bunch *) let get_bunch i c = try let bunch = M.find i c.bunch in Some (bunch, {c with bunch = M.remove i c.bunch}) with | Not_found -> None (* move everything (as much as possible) from csrc to cdst *) let put_all csrc cdst = let rec next leftovers cs cd = if M.is_empty cs.bunch then (leftovers, cd) else ( let i, bunch = M.choose cs.bunch in let cs1 = { cs with bunch = M.remove i cs.bunch } in match put_bunch bunch cd with MoveBunchSuccess cd1 -> next leftovers cs1 cd1 | MoveBunchFailure -> ( match put_bunch bunch leftovers with | MoveBunchSuccess lo -> next lo cs1 cd | _ -> failwith "Cnt.put_all : cannot fit an object into the leftovers container" ) | MoveBunchPartial (b, cd1) -> ( match put_bunch b leftovers with | MoveBunchSuccess lo -> next lo cs1 cd1 | _ -> failwith "Cnt.put_all : cannot fit an object into the leftovers container" ) ) in let leftovers = {bunch = M.empty; slot = csrc.slot; caplim = csrc.caplim} in next leftovers csrc cdst let examine i c = try Some (M.find i c.bunch) with | Not_found -> None let fold f acc c = M.fold (fun si bunch acc -> f acc si bunch) c.bunch acc let remove_everything c = {c with bunch = M.empty} exception Compacting_failure (* move the items to the beginning of the list when possible *) let compact c = try M.fold (fun si bunch acc -> match put_bunch bunch acc with | MoveBunchSuccess acc_upd -> acc_upd | _ -> raise Compacting_failure ) c.bunch (remove_everything c) with Compacting_failure -> c let is_empty c = M.cardinal c.bunch > 0 end (* Collection of objects *) module Coll = struct let upgrade_mat = function | Steel -> DmSteel | x -> x let downgrade_mat = function | Steel -> RustySteel | x -> x let rec prob_change_mat p change mat = let mat_upd = change mat in if Random.float 1.0 < p then (if mat_upd <> mat then prob_change_mat p change mat_upd else mat_upd) else mat let index kind size = let y = match kind with | 0 -> 0 | 1 -> 1 | 2 -> 2 | 3 -> 3 | 4 -> 4 | 5 -> 5 | 6 -> 7 | 7 -> 8 | 8 -> 9 | 9 -> 11 | _ -> 16 in y * 8 + size let stdprice size = max 1 (int_of_float (2.0 *. (4.0 ** float size))) let cheap_price = 6 let sw_weight_0 = 0.5 let sw_weight_4 = 1.6 let sw_weight_power = 1.9 let sw_weight_a, sw_weight_b = sw_weight_0, (sw_weight_4 -. sw_weight_0) /. (4.0**sw_weight_power) let coin_barcode = {bc_kind=10; bc_size=0; bc_mat=Gold; bc_var=0;} let simple_random opt_kind = let kind = match opt_kind with | None -> any_from_rate_ls [(0, 8.0); (1, 8.0); (2, 2.0); (3, 8.0); (4, 7.0); (5, 1.0); (6, 9.0) (* armor *); (7, 6.0) (* helmets *); (8, 8.0); (9, 12.0); (* ranged *) (10, 5.0) (* money *) ] | Some x -> x in let melee x d = `Melee Melee.({attrate=1.0 *. (x+.1.0); duration = (2.0 -. 1.0/.(x+.1.0) +. 0.1 *. x) *. d;}) in let sword_weight s = sw_weight_a +. sw_weight_b *. (s**sw_weight_power) in match kind with 0 -> (* sword *) knife , dagger , short sword , arming sword , long sword ( first two - handed ) , great sword , x , y let size = Random.int 8 in let price = stdprice size in let s = float size in 2 kg for a long ( two - handed sword ) let weight = 0.5 + . 1.5 * . 0.25 * . 0.25 * . ( s*.s ) in let weight = sword_weight s in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee s 1.0) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Sword-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } | 1 -> (* rogue / backsword *) let size = Random.int 8 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.10 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s *. 1.1) 1.0) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Backsword-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } | 2 -> (* sabre *) let size = 2 + Random.int 2 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.10 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s *. 1.05) 1.0) |> PS.add (`Defense (0.05 +. 0.01 *. float (size-2))) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Sabre-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } | 3 -> (* blunt weapons *) let size = Random.int 8 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.2 in let mat = if size < 2 then Wood else Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s*.1.1) 1.2) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Mace-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } | 4 -> (* axe *) let size = 1 + Random.int 7 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.3 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s*.1.2) 1.3) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Axe-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } | 5 -> (* polearm *) let size = 4 + Random.int 3 in let price = stdprice (size-1) in let s = float size in let weight = (sword_weight s) *. 1.1 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s*.1.05) 1.05) |> PS.add (`Defense (0.08 +. 0.02 *. float (size-4))) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Axe-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } | 6 -> (* armor *) let size = 1 + Random.int 5 in let price = stdprice size * 2 in let s = float size in let weight = (sword_weight s) *. 6.0 in let mat = if size < 2 then Leather else Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (`Defense (0.05 +. 0.13 *. float size)) |> PS.add (`Weight (weight)) |> PS.add `Wearable |> PS.add (`Material mat) in let name = match size with 0 -> "Leather Armor" | 1 -> "Chain mail" | 2 -> "Plated mail" | 3 -> "Laminar armor" | _ -> "Plate armor" in {name; prop; imgindex = index kind size; price; stackable = None; barcode } | 7 -> (* headgear *) let size = Random.int 6 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 2.0 in let mat = if size < 1 then Leather else Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (`Defense (0.07 +. 0.06 *. float size)) |> PS.add (`Weight (weight)) |> PS.add `Headgear |> PS.add (`Material mat) in let name = match size with 0 -> "Leather Cap" | _ -> "Helmet" in {name; prop; imgindex = index kind size; price; stackable = None; barcode } | 8 -> (* shield *) let size = 0 + Random.int 8 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.1 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let dd = if size > 1 then 0.05 else 0.0 in let prop = PS.empty |> PS.add (`Defense (0.08 +. 0.06 *. float size +. dd)) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in let prop = match size with | 0 -> PS.add (melee (s*.0.5) 1.5) prop | 1 -> PS.add (melee (s*.0.25) 1.5) prop | _ -> prop in {name = "Shield-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } | 9 -> (* ranged *) let size = Random.int 5 in let x = float size in let price = stdprice size in let s = float size in let weight = (sword_weight s) in let mat = if size < 1 then Leather else Wood in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (`Ranged Ranged.( {force = 0.85 *. (2.0 +. 0.9 *. x); projmass = 0.13 *. (5.0 +. 2.2 *. x); dmgmult = 1.5 *. ( 2.5 +. 0.2 *. x )})) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Ranged-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } | _ -> (* coin *) let size = 0 in let price = 1 in let weight = 0.0 in let mat = Gold in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in assert (barcode = coin_barcode); let prop = PS.empty |> PS.add (`Money) |> PS.add (`Weight weight) |> PS.add (`Material mat) in {name = "Coin"; prop; imgindex = index kind size; price; stackable = Some 999999; barcode } let random opt_kind = let item = simple_random opt_kind in match get_mat item with Some mat -> let mat_u = mat |> prob_change_mat 0.1 upgrade_mat |> prob_change_mat 0.4 downgrade_mat in if mat_u <> mat then upgrade_item (mat,mat_u) item else item | None -> item let coin = let coin = random (Some 10) in assert (coin.barcode = coin_barcode); coin end let decompose obj = Resource.make (obj.price) let decompose_bunch bunch = Resource.make (bunch.Cnt.item.price * bunch.Cnt.amount)
null
https://raw.githubusercontent.com/a-nikolaev/wanderers/054c1cdc6dd833d8938357e6d898def510531d67/src/item.ml
ocaml
unified quality measure extremely bad, poor quality perfect, flawless kind size mat variant the parameter 'stackable' tells you the max size of the stack of such objects integer map container put the whole bunch get the whole bunch move everything (as much as possible) from csrc to cdst move the items to the beginning of the list when possible Collection of objects armor helmets ranged money sword rogue / backsword sabre blunt weapons axe polearm armor headgear shield ranged coin
Wanderers - open world adventure game . Copyright ( C ) 2013 - 2014 . This program is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . Copyright (C) 2013-2014 Alexey Nikolaev. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) open Base type mat = Leather | Wood | Steel | DmSteel | RustySteel | Gold type eff = [ `Heal ] type qm = float module Ranged = struct type t = {force: float; projmass: float; dmgmult: float} end module Melee = struct type t = {attrate: float; duration: float;} let join_simple {attrate=ar1; duration=d1} {attrate=ar2; duration=d2} = {attrate=ar1 +. ar2; duration = max d1 d2} let join_max {attrate=ar1; duration=d1} {attrate=ar2; duration=d2} = {attrate = max ar1 ar2; duration = max d1 d2} end type prop = [ `Melee of Melee.t | `Defense of float | `Weight of float | `Material of mat | `Consumable of eff | `Wearable | `Headgear | `Wieldable | `Quality of qm | `Ranged of Ranged.t | `Money] let upgrade_prop (m0,m1) prop = match m1 with | DmSteel -> ( let c = 1.4 in match prop with | `Weight x -> `Weight (x *. 0.90) | `Defense x -> `Defense (x *. c) | `Melee {Melee.attrate=att; Melee.duration=dur} -> `Melee Melee.({attrate = att *. c; duration = dur}) | `Ranged {Ranged.force=frc; Ranged.projmass=m; Ranged.dmgmult=dmg} -> `Ranged Ranged.({force = frc; projmass = m; dmgmult = dmg *. c}) | `Material _ -> `Material m1 | x -> x ) | RustySteel -> ( let c = 0.65 in match prop with | `Weight x -> `Weight (x *. 1.0) | `Defense x -> `Defense (x *. c) | `Melee {Melee.attrate=att; Melee.duration=dur} -> `Melee Melee.({attrate = att *. c; duration = dur}) | `Ranged {Ranged.force=frc; Ranged.projmass=m; Ranged.dmgmult=dmg} -> `Ranged Ranged.({force = frc; projmass = m; dmgmult = dmg *. c}) | `Material _ -> `Material m1 | x -> x ) | _ -> prop module PS = Set.Make(struct type t = prop let compare = compare end) type barcode = {bc_kind: int; bc_size: int; bc_mat: mat; bc_var: int} type t = { name: string; prop: PS.t; imgindex:int; price: int; stackable: int option; barcode:barcode; } type item_type = t let upgrade_item (m0,m1) item = let prop_u = PS.fold (fun p acc -> PS.add (upgrade_prop (m0,m1) p) acc) item.prop PS.empty in let price_u = match m1 with | DmSteel -> 50 + item.price * 4 | RustySteel -> (item.price+1) / 2 | x -> item.price in {item with prop = prop_u; price = price_u; barcode = {item.barcode with bc_mat = m1}} item obj has property p let is p obj = PS.mem p obj.prop let get_melee obj = PS.fold (fun prop acc -> match prop with `Melee x -> Some x | _ -> acc ) obj.prop None let get_defense obj = PS.fold (fun prop acc -> match prop with `Defense x -> acc +. x | _ -> acc ) obj.prop 0.0 let get_ranged obj = PS.fold (fun prop acc -> match prop with `Ranged x -> Some x | _ -> acc ) obj.prop None let get_mat obj = PS.fold (fun prop acc -> match prop with `Material x -> Some x | _ -> acc ) obj.prop None let get_mass obj = PS.fold (fun prop acc -> match prop with `Weight x -> acc +. x | _ -> acc ) obj.prop 0.0 let is_wearable obj = PS.mem `Wearable obj.prop let is_a_headgear obj = PS.mem `Headgear obj.prop let is_wieldable obj = PS.mem `Wieldable obj.prop let string_of_item i = Printf.sprintf "[%i,%i] p=%i (%s)" i.barcode.bc_kind i.barcode.bc_size i.price i.name module M = Map.Make(struct type t = int let compare = compare end) let map_of_list ls = List.fold_left (fun acc (key,obj) -> M.add key obj acc) M.empty ls module Cnt = struct type slot_type = General | Hand | Head | Body | Purse let does_fit slt obj = match slt with | General -> true | Hand -> is `Wieldable obj | Head -> is `Headgear obj | Body -> is `Wearable obj | Purse -> is `Money obj type bunch = {item: item_type; amount: int} type t = {bunch: bunch M.t; slot: slot_type M.t; caplim: int option;} let make slot caplim = {bunch = M.empty; slot; caplim} let default_coins_slot = 4 let empty_nat_human = let ls = [(0,Hand); (1,Body); (2,Hand); (3, Head); (4,Purse)] in let len = List.length ls in make (map_of_list ls) (Some len) let empty_only_money = let ls = [(0,Purse)] in let len = List.length ls in make (map_of_list ls) (Some len) let empty_only_money_plus = let ls = [(0,Purse); (1,General)] in let len = List.length ls in make (map_of_list ls) (Some len) let empty_unlimited = make M.empty None let empty_limited n = let ls = fold_lim (fun acc i -> (i, General)::acc) [] 0 (n-1) |> List.rev in make (map_of_list ls) (Some n) let find_empty_slot pred c = let rec search i = let enough_space = match c.caplim with | Some lim -> i < lim | None -> true in if enough_space then ( if not (M.mem i c.bunch) && (not (M.mem i c.slot) || pred (M.find i c.slot)) then Some i else search (i+1) ) else None in search 0 let find_matching_half_full_slot obj c = match obj.stackable with | Some max_amount -> M.fold (fun i b acc -> match acc, b with | None, {item; amount} when item = obj && amount < max_amount -> Some i | _ -> acc ) c.bunch None | None -> None let put obj c = let opt_i = match find_matching_half_full_slot obj c with | Some i -> Some i | None -> find_empty_slot (fun slt -> does_fit slt obj) c in match opt_i with | Some i -> let {item; amount} = try M.find i c.bunch with Not_found -> {item=obj; amount=0} in Some {c with bunch = M.add i {item; amount = amount+1} c.bunch} | None -> None get only one object let get i c = try let {item; amount} = M.find i c.bunch in if amount > 1 then Some (item, {c with bunch = M.add i {item; amount=amount-1} c.bunch}) else Some (item, {c with bunch = M.remove i c.bunch}) with | Not_found -> None type 'a move_bunch_result = | MoveBunchFailure | MoveBunchPartial of (bunch * 'a) | MoveBunchSuccess of 'a let put_bunch bunch c = let max_amount = match bunch.item.stackable with Some x -> x | _ -> 1 in let rec repeat some_success bunch c = let {item; amount} = bunch in let opt_i = match find_matching_half_full_slot item c with | Some i -> Some i | None -> find_empty_slot (fun slt -> does_fit slt item) c in match opt_i with | Some i -> let amount_already_there = try (M.find i c.bunch).amount with Not_found -> 0 in let amount_to_add = (min (amount+amount_already_there) max_amount) - amount_already_there in let amount_remains = amount - amount_to_add in let uc = {c with bunch = M.add i {item; amount = amount_already_there + amount_to_add} c.bunch} in if amount_remains > 0 then repeat true {item; amount = amount_remains} uc else MoveBunchSuccess uc | None -> if some_success then MoveBunchPartial (bunch, c) else MoveBunchFailure in if bunch.amount > 0 then repeat false bunch c else MoveBunchSuccess c let get_bunch i c = try let bunch = M.find i c.bunch in Some (bunch, {c with bunch = M.remove i c.bunch}) with | Not_found -> None let put_all csrc cdst = let rec next leftovers cs cd = if M.is_empty cs.bunch then (leftovers, cd) else ( let i, bunch = M.choose cs.bunch in let cs1 = { cs with bunch = M.remove i cs.bunch } in match put_bunch bunch cd with MoveBunchSuccess cd1 -> next leftovers cs1 cd1 | MoveBunchFailure -> ( match put_bunch bunch leftovers with | MoveBunchSuccess lo -> next lo cs1 cd | _ -> failwith "Cnt.put_all : cannot fit an object into the leftovers container" ) | MoveBunchPartial (b, cd1) -> ( match put_bunch b leftovers with | MoveBunchSuccess lo -> next lo cs1 cd1 | _ -> failwith "Cnt.put_all : cannot fit an object into the leftovers container" ) ) in let leftovers = {bunch = M.empty; slot = csrc.slot; caplim = csrc.caplim} in next leftovers csrc cdst let examine i c = try Some (M.find i c.bunch) with | Not_found -> None let fold f acc c = M.fold (fun si bunch acc -> f acc si bunch) c.bunch acc let remove_everything c = {c with bunch = M.empty} exception Compacting_failure let compact c = try M.fold (fun si bunch acc -> match put_bunch bunch acc with | MoveBunchSuccess acc_upd -> acc_upd | _ -> raise Compacting_failure ) c.bunch (remove_everything c) with Compacting_failure -> c let is_empty c = M.cardinal c.bunch > 0 end module Coll = struct let upgrade_mat = function | Steel -> DmSteel | x -> x let downgrade_mat = function | Steel -> RustySteel | x -> x let rec prob_change_mat p change mat = let mat_upd = change mat in if Random.float 1.0 < p then (if mat_upd <> mat then prob_change_mat p change mat_upd else mat_upd) else mat let index kind size = let y = match kind with | 0 -> 0 | 1 -> 1 | 2 -> 2 | 3 -> 3 | 4 -> 4 | 5 -> 5 | 6 -> 7 | 7 -> 8 | 8 -> 9 | 9 -> 11 | _ -> 16 in y * 8 + size let stdprice size = max 1 (int_of_float (2.0 *. (4.0 ** float size))) let cheap_price = 6 let sw_weight_0 = 0.5 let sw_weight_4 = 1.6 let sw_weight_power = 1.9 let sw_weight_a, sw_weight_b = sw_weight_0, (sw_weight_4 -. sw_weight_0) /. (4.0**sw_weight_power) let coin_barcode = {bc_kind=10; bc_size=0; bc_mat=Gold; bc_var=0;} let simple_random opt_kind = let kind = match opt_kind with | None -> any_from_rate_ls [(0, 8.0); (1, 8.0); (2, 2.0); (3, 8.0); (4, 7.0); (5, 1.0); (8, 8.0); ] | Some x -> x in let melee x d = `Melee Melee.({attrate=1.0 *. (x+.1.0); duration = (2.0 -. 1.0/.(x+.1.0) +. 0.1 *. x) *. d;}) in let sword_weight s = sw_weight_a +. sw_weight_b *. (s**sw_weight_power) in match kind with knife , dagger , short sword , arming sword , long sword ( first two - handed ) , great sword , x , y let size = Random.int 8 in let price = stdprice size in let s = float size in 2 kg for a long ( two - handed sword ) let weight = 0.5 + . 1.5 * . 0.25 * . 0.25 * . ( s*.s ) in let weight = sword_weight s in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee s 1.0) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Sword-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } let size = Random.int 8 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.10 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s *. 1.1) 1.0) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Backsword-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } let size = 2 + Random.int 2 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.10 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s *. 1.05) 1.0) |> PS.add (`Defense (0.05 +. 0.01 *. float (size-2))) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Sabre-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } let size = Random.int 8 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.2 in let mat = if size < 2 then Wood else Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s*.1.1) 1.2) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Mace-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } let size = 1 + Random.int 7 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.3 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s*.1.2) 1.3) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Axe-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } let size = 4 + Random.int 3 in let price = stdprice (size-1) in let s = float size in let weight = (sword_weight s) *. 1.1 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (melee (s*.1.05) 1.05) |> PS.add (`Defense (0.08 +. 0.02 *. float (size-4))) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Axe-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } let size = 1 + Random.int 5 in let price = stdprice size * 2 in let s = float size in let weight = (sword_weight s) *. 6.0 in let mat = if size < 2 then Leather else Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (`Defense (0.05 +. 0.13 *. float size)) |> PS.add (`Weight (weight)) |> PS.add `Wearable |> PS.add (`Material mat) in let name = match size with 0 -> "Leather Armor" | 1 -> "Chain mail" | 2 -> "Plated mail" | 3 -> "Laminar armor" | _ -> "Plate armor" in {name; prop; imgindex = index kind size; price; stackable = None; barcode } let size = Random.int 6 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 2.0 in let mat = if size < 1 then Leather else Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (`Defense (0.07 +. 0.06 *. float size)) |> PS.add (`Weight (weight)) |> PS.add `Headgear |> PS.add (`Material mat) in let name = match size with 0 -> "Leather Cap" | _ -> "Helmet" in {name; prop; imgindex = index kind size; price; stackable = None; barcode } let size = 0 + Random.int 8 in let price = stdprice size in let s = float size in let weight = (sword_weight s) *. 1.1 in let mat = Steel in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let dd = if size > 1 then 0.05 else 0.0 in let prop = PS.empty |> PS.add (`Defense (0.08 +. 0.06 *. float size +. dd)) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in let prop = match size with | 0 -> PS.add (melee (s*.0.5) 1.5) prop | 1 -> PS.add (melee (s*.0.25) 1.5) prop | _ -> prop in {name = "Shield-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } let size = Random.int 5 in let x = float size in let price = stdprice size in let s = float size in let weight = (sword_weight s) in let mat = if size < 1 then Leather else Wood in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in let prop = PS.empty |> PS.add (`Ranged Ranged.( {force = 0.85 *. (2.0 +. 0.9 *. x); projmass = 0.13 *. (5.0 +. 2.2 *. x); dmgmult = 1.5 *. ( 2.5 +. 0.2 *. x )})) |> PS.add (`Weight (weight)) |> PS.add `Wieldable |> PS.add (`Material mat) in {name = "Ranged-"^(string_of_int size); prop; imgindex = index kind size; price; stackable = None; barcode } let size = 0 in let price = 1 in let weight = 0.0 in let mat = Gold in let barcode = {bc_kind=kind; bc_size=size; bc_mat=mat; bc_var=0;} in assert (barcode = coin_barcode); let prop = PS.empty |> PS.add (`Money) |> PS.add (`Weight weight) |> PS.add (`Material mat) in {name = "Coin"; prop; imgindex = index kind size; price; stackable = Some 999999; barcode } let random opt_kind = let item = simple_random opt_kind in match get_mat item with Some mat -> let mat_u = mat |> prob_change_mat 0.1 upgrade_mat |> prob_change_mat 0.4 downgrade_mat in if mat_u <> mat then upgrade_item (mat,mat_u) item else item | None -> item let coin = let coin = random (Some 10) in assert (coin.barcode = coin_barcode); coin end let decompose obj = Resource.make (obj.price) let decompose_bunch bunch = Resource.make (bunch.Cnt.item.price * bunch.Cnt.amount)
be1b91df262681b19d2ea54c7b7939bd541f5f99765c5de7cc0d47c61feebaf2
mainland/dph
Pretty.hs
module DPH.Core.Pretty ( module DPH.Base.Pretty , pprModGuts , pprTopBinds) where import DPH.Base.Pretty import HscTypes import Avail import CoreSyn import Type import Coercion import Var import Name import OccName import DataCon import Literal import Id import Unique import qualified UniqFM as UFM -- Guts ----------------------------------------------------------------------- pprModGuts :: ModGuts -> Doc pprModGuts guts = vcat [ text "Exports:" <+> ppr (mg_exports guts) , empty , text "VectInfo:" <+> ppr (mg_vect_info guts) , empty , pprTopBinds $ mg_binds guts] -- | An AvailInfo carries an exported name. instance Pretty AvailInfo where ppr aa = case aa of Avail n -> ppr n AvailTC n _ -> ppr n | The VectInfo maps names to their vectorised versions . instance Pretty VectInfo where ppr vi = ppr $ UFM.eltsUFM (vectInfoVar vi) -- Top Binds ------------------------------------------------------------------ pprTopBinds :: Pretty a => [Bind a] -> Doc pprTopBinds binds = vcat $ map pprTopBind binds pprTopBind :: Pretty a => Bind a -> Doc pprTopBind (NonRec binder expr) = pprBinding (binder, expr) <$$> empty pprTopBind (Rec []) = text "Rec { }" pprTopBind (Rec bb@(b:bs)) = vcat [ text "Rec {" , vcat [empty <$$> pprBinding b | b <- bb] , text "end Rec }" , empty ] -- Binding -------------------------------------------------------------------- pprBinding :: Pretty a => (a, Expr a) -> Doc pprBinding (binder, x) = ppr binder <+> breakWhen (not $ isSimpleX x) <+> equals <+> align (ppr x) -- Expr ----------------------------------------------------------------------- instance Pretty a => Pretty (Expr a) where pprPrec d xx = case xx of Var ident -> pprBound ident -- Discard types and coersions Type _ -> empty Coercion _ -> empty -- Literals. Lit ll -> ppr ll -- Suppress Casts completely. Cast x _co -> pprPrec d x -- Abstractions. Lam{} -> pprParen' (d > 2) $ let (bndrs, body) = collectBinders xx in text "\\" <> sep (map ppr bndrs) <> text "." <> (nest 2 $ (breakWhen $ not $ isSimpleX body) <> ppr body) -- Applications. App x1 x2 | isTypeArg x2 -> pprPrec d x1 | otherwise -> pprParen' (d > 10) $ ppr x1 <> nest 2 (breakWhen (not $ isSimpleX x2) <> pprPrec 11 x2) -- Destructors. Case x1 var ty [(con, binds, x2)] -> pprParen' (d > 2) $ text "let" <+> (fill 12 (ppr con <+> hsep (map ppr binds))) -- <> breakWhen (not $ isSimpleX x1) <+> text "<-" <+> ppr x1 <+> text "in" <$$> ppr x2 Case x1 var ty alts -> pprParen' (d > 2) $ (nest 2 $ text "case" <+> ppr x1 <+> text "of" <+> ppr var <+> lbrace <> line <> vcat (punctuate semi $ map pprAlt alts)) <> line <> rbrace -- Binding. Let (NonRec b x1) x2 -> pprParen' (d > 2) $ text "let" <+> fill 12 (ppr b) <+> equals <+> ppr x1 <+> text "in" <$$> ppr x2 Let (Rec bxs) x2 -> pprParen' (d > 2) $ text "letrec {" <+> vcat [ fill 12 (ppr b) <+> equals <+> ppr x | (b, x) <- bxs] <+> text "} in" <$$> ppr x2 _ -> text "DUNNO" -- Alt ------------------------------------------------------------------------ pprAlt :: Pretty a => (AltCon, [a], Expr a) -> Doc pprAlt (con, binds, x) = ppr con <+> (hsep $ map ppr binds) <+> nest 1 (line <> nest 3 (text "->" <+> ppr x)) instance Pretty AltCon where ppr con = case con of DataAlt con -> ppr con LitAlt lit -> ppr lit DEFAULT -> text "_" -- | Pretty print bound occurrences of an identifier pprBound :: Id -> Doc pprBound i Suppress uniqueids from primops , dictionary functions and data constructors -- These are unlikely to have conflicting base names. | isPrimOpId i || isDFunId i || isDataConWorkId i = ppr (idName i) | otherwise = ppr (idName i) <> text "_" <> text (show $ idUnique i) -- Literal -------------------------------------------------------------------- instance Pretty Literal where ppr _ = text "<LITERAL>" -- Type ----------------------------------------------------------------------- instance Pretty Type where ppr _ = empty -- Coercion ------------------------------------------------------------------- instance Pretty Coercion where ppr _ = empty -- Names ---------------------------------------------------------------------- instance Pretty CoreBndr where ppr bndr = ppr (idName bndr) <> text "_" <> text (show $ idUnique bndr) instance Pretty DataCon where ppr con = ppr (dataConName con) instance Pretty Name where ppr name = ppr (nameOccName name) instance Pretty OccName where ppr occName = text (occNameString occName) -- Utils ---------------------------------------------------------------------- breakWhen :: Bool -> Doc breakWhen True = line breakWhen False = space isSimpleX :: Expr a -> Bool isSimpleX xx = case xx of Var{} -> True Lit{} -> True App x1 x2 -> isSimpleX x1 && isAtomX x2 Cast x1 _ -> isSimpleX x1 _ -> False isAtomX :: Expr a -> Bool isAtomX xx = case xx of Var{} -> True Lit{} -> True _ -> False parens' :: Doc -> Doc parens' d = lparen <> nest 1 d <> rparen | Wrap a ` Doc ` in parens if the predicate is true . pprParen' :: Bool -> Doc -> Doc pprParen' b c = if b then parens' c else c
null
https://raw.githubusercontent.com/mainland/dph/742078c9e18b7dcf6526348e08d2dd16e2334739/dph-plugin/DPH/Core/Pretty.hs
haskell
Guts ----------------------------------------------------------------------- | An AvailInfo carries an exported name. Top Binds ------------------------------------------------------------------ Binding -------------------------------------------------------------------- Expr ----------------------------------------------------------------------- Discard types and coersions Literals. Suppress Casts completely. Abstractions. Applications. Destructors. <> breakWhen (not $ isSimpleX x1) Binding. Alt ------------------------------------------------------------------------ | Pretty print bound occurrences of an identifier These are unlikely to have conflicting base names. Literal -------------------------------------------------------------------- Type ----------------------------------------------------------------------- Coercion ------------------------------------------------------------------- Names ---------------------------------------------------------------------- Utils ----------------------------------------------------------------------
module DPH.Core.Pretty ( module DPH.Base.Pretty , pprModGuts , pprTopBinds) where import DPH.Base.Pretty import HscTypes import Avail import CoreSyn import Type import Coercion import Var import Name import OccName import DataCon import Literal import Id import Unique import qualified UniqFM as UFM pprModGuts :: ModGuts -> Doc pprModGuts guts = vcat [ text "Exports:" <+> ppr (mg_exports guts) , empty , text "VectInfo:" <+> ppr (mg_vect_info guts) , empty , pprTopBinds $ mg_binds guts] instance Pretty AvailInfo where ppr aa = case aa of Avail n -> ppr n AvailTC n _ -> ppr n | The VectInfo maps names to their vectorised versions . instance Pretty VectInfo where ppr vi = ppr $ UFM.eltsUFM (vectInfoVar vi) pprTopBinds :: Pretty a => [Bind a] -> Doc pprTopBinds binds = vcat $ map pprTopBind binds pprTopBind :: Pretty a => Bind a -> Doc pprTopBind (NonRec binder expr) = pprBinding (binder, expr) <$$> empty pprTopBind (Rec []) = text "Rec { }" pprTopBind (Rec bb@(b:bs)) = vcat [ text "Rec {" , vcat [empty <$$> pprBinding b | b <- bb] , text "end Rec }" , empty ] pprBinding :: Pretty a => (a, Expr a) -> Doc pprBinding (binder, x) = ppr binder <+> breakWhen (not $ isSimpleX x) <+> equals <+> align (ppr x) instance Pretty a => Pretty (Expr a) where pprPrec d xx = case xx of Var ident -> pprBound ident Type _ -> empty Coercion _ -> empty Lit ll -> ppr ll Cast x _co -> pprPrec d x Lam{} -> pprParen' (d > 2) $ let (bndrs, body) = collectBinders xx in text "\\" <> sep (map ppr bndrs) <> text "." <> (nest 2 $ (breakWhen $ not $ isSimpleX body) <> ppr body) App x1 x2 | isTypeArg x2 -> pprPrec d x1 | otherwise -> pprParen' (d > 10) $ ppr x1 <> nest 2 (breakWhen (not $ isSimpleX x2) <> pprPrec 11 x2) Case x1 var ty [(con, binds, x2)] -> pprParen' (d > 2) $ text "let" <+> (fill 12 (ppr con <+> hsep (map ppr binds))) <+> text "<-" <+> ppr x1 <+> text "in" <$$> ppr x2 Case x1 var ty alts -> pprParen' (d > 2) $ (nest 2 $ text "case" <+> ppr x1 <+> text "of" <+> ppr var <+> lbrace <> line <> vcat (punctuate semi $ map pprAlt alts)) <> line <> rbrace Let (NonRec b x1) x2 -> pprParen' (d > 2) $ text "let" <+> fill 12 (ppr b) <+> equals <+> ppr x1 <+> text "in" <$$> ppr x2 Let (Rec bxs) x2 -> pprParen' (d > 2) $ text "letrec {" <+> vcat [ fill 12 (ppr b) <+> equals <+> ppr x | (b, x) <- bxs] <+> text "} in" <$$> ppr x2 _ -> text "DUNNO" pprAlt :: Pretty a => (AltCon, [a], Expr a) -> Doc pprAlt (con, binds, x) = ppr con <+> (hsep $ map ppr binds) <+> nest 1 (line <> nest 3 (text "->" <+> ppr x)) instance Pretty AltCon where ppr con = case con of DataAlt con -> ppr con LitAlt lit -> ppr lit DEFAULT -> text "_" pprBound :: Id -> Doc pprBound i Suppress uniqueids from primops , dictionary functions and data constructors | isPrimOpId i || isDFunId i || isDataConWorkId i = ppr (idName i) | otherwise = ppr (idName i) <> text "_" <> text (show $ idUnique i) instance Pretty Literal where ppr _ = text "<LITERAL>" instance Pretty Type where ppr _ = empty instance Pretty Coercion where ppr _ = empty instance Pretty CoreBndr where ppr bndr = ppr (idName bndr) <> text "_" <> text (show $ idUnique bndr) instance Pretty DataCon where ppr con = ppr (dataConName con) instance Pretty Name where ppr name = ppr (nameOccName name) instance Pretty OccName where ppr occName = text (occNameString occName) breakWhen :: Bool -> Doc breakWhen True = line breakWhen False = space isSimpleX :: Expr a -> Bool isSimpleX xx = case xx of Var{} -> True Lit{} -> True App x1 x2 -> isSimpleX x1 && isAtomX x2 Cast x1 _ -> isSimpleX x1 _ -> False isAtomX :: Expr a -> Bool isAtomX xx = case xx of Var{} -> True Lit{} -> True _ -> False parens' :: Doc -> Doc parens' d = lparen <> nest 1 d <> rparen | Wrap a ` Doc ` in parens if the predicate is true . pprParen' :: Bool -> Doc -> Doc pprParen' b c = if b then parens' c else c
daea19c9c9cb9b01a09f2d627239d733b6d30369ed09f25102fd48d9802cd963
bobzhang/fan
pr4329.ml
open Camlp4.PreCast ; module G = Camlp4.PreCast.Gram; value ab_eoi = G.Entry.mk "ab_eoi" ; value a_or_ab = G.Entry.mk "a_or_ab" ; value a_or_ab_eoi = G.Entry.mk "a_or_ab_eoi" ; value c_a_or_ab_eoi = G.Entry.mk "c_a_or_ab_eoi" ; EXTEND G ab_eoi: [[ "a"; "b"; `EOI -> () ]]; a_or_ab: [[ "a" -> () | "a"; "b" -> () ]]; a_or_ab_eoi: [[ a_or_ab; `EOI -> () ]]; c_a_or_ab_eoi: [[ "c"; a_or_ab; `EOI -> () ]]; END ; value parse_string entry s = try G.parse_string entry (Loc.mk "<string>") s with [ Loc.Exc_located loc exn -> begin print_endline (Loc.to_string loc); print_endline (Printexc.to_string exn); failwith " Syntax Error " end ] ; (* Consider the following syntax errors: *) parse_string ab_eoi "a c" ; File " < string > " , line 1 , characters 2 - 3 Stream . Error("illegal begin of ab_eoi " ) Exception : Failure " Syntax Error " . -- > " Illegal begin " : at least the first symbol was correct -- > nevertheless , the reported position is correct -- > The message used to be : " b " then EOI expected after " a " in [ ab_eoi ] Stream.Error("illegal begin of ab_eoi") Exception: Failure "Syntax Error". --> "Illegal begin": at least the first symbol was correct --> nevertheless, the reported position is correct --> The message used to be: "b" then EOI expected after "a" in [ab_eoi] *) parse_string a_or_ab_eoi "a c" ; File " < string > " , line 1 , characters 0 - 1 Stream . Error("illegal begin of a_or_ab_eoi " ) Exception : Failure " Syntax Error " . -- > " Illegal begin " : at least the first non - terminal was correct -- > the reported position is weird -- > I think the message used to be either : " b " expected after " a " in [ a_or_ab ] or : EOI expected after [ a_or_ab ] in [ a_or_ab_eoi ] Stream.Error("illegal begin of a_or_ab_eoi") Exception: Failure "Syntax Error". --> "Illegal begin": at least the first non-terminal was correct --> the reported position is weird --> I think the message used to be either: "b" expected after "a" in [a_or_ab] or: EOI expected after [a_or_ab] in [a_or_ab_eoi] *) parse_string c_a_or_ab_eoi "c a c" ; File " < string > " , line 1 , characters 2 - 3 Stream . Error("[a_or_ab ] expected after \"c\ " ( in [ c_a_or_ab_eoi ] ) " ) Exception : Failure " Syntax Error " . -- > " [ a_or_ab ] expected " : this is very confusing : there is a valid a_or_ab there , namely " a " Stream.Error("[a_or_ab] expected after \"c\" (in [c_a_or_ab_eoi])") Exception: Failure "Syntax Error". --> "[a_or_ab] expected": this is very confusing: there is a valid a_or_ab there, namely "a" *)
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/fixtures/pr4329.ml
ocaml
Consider the following syntax errors:
open Camlp4.PreCast ; module G = Camlp4.PreCast.Gram; value ab_eoi = G.Entry.mk "ab_eoi" ; value a_or_ab = G.Entry.mk "a_or_ab" ; value a_or_ab_eoi = G.Entry.mk "a_or_ab_eoi" ; value c_a_or_ab_eoi = G.Entry.mk "c_a_or_ab_eoi" ; EXTEND G ab_eoi: [[ "a"; "b"; `EOI -> () ]]; a_or_ab: [[ "a" -> () | "a"; "b" -> () ]]; a_or_ab_eoi: [[ a_or_ab; `EOI -> () ]]; c_a_or_ab_eoi: [[ "c"; a_or_ab; `EOI -> () ]]; END ; value parse_string entry s = try G.parse_string entry (Loc.mk "<string>") s with [ Loc.Exc_located loc exn -> begin print_endline (Loc.to_string loc); print_endline (Printexc.to_string exn); failwith " Syntax Error " end ] ; parse_string ab_eoi "a c" ; File " < string > " , line 1 , characters 2 - 3 Stream . Error("illegal begin of ab_eoi " ) Exception : Failure " Syntax Error " . -- > " Illegal begin " : at least the first symbol was correct -- > nevertheless , the reported position is correct -- > The message used to be : " b " then EOI expected after " a " in [ ab_eoi ] Stream.Error("illegal begin of ab_eoi") Exception: Failure "Syntax Error". --> "Illegal begin": at least the first symbol was correct --> nevertheless, the reported position is correct --> The message used to be: "b" then EOI expected after "a" in [ab_eoi] *) parse_string a_or_ab_eoi "a c" ; File " < string > " , line 1 , characters 0 - 1 Stream . Error("illegal begin of a_or_ab_eoi " ) Exception : Failure " Syntax Error " . -- > " Illegal begin " : at least the first non - terminal was correct -- > the reported position is weird -- > I think the message used to be either : " b " expected after " a " in [ a_or_ab ] or : EOI expected after [ a_or_ab ] in [ a_or_ab_eoi ] Stream.Error("illegal begin of a_or_ab_eoi") Exception: Failure "Syntax Error". --> "Illegal begin": at least the first non-terminal was correct --> the reported position is weird --> I think the message used to be either: "b" expected after "a" in [a_or_ab] or: EOI expected after [a_or_ab] in [a_or_ab_eoi] *) parse_string c_a_or_ab_eoi "c a c" ; File " < string > " , line 1 , characters 2 - 3 Stream . Error("[a_or_ab ] expected after \"c\ " ( in [ c_a_or_ab_eoi ] ) " ) Exception : Failure " Syntax Error " . -- > " [ a_or_ab ] expected " : this is very confusing : there is a valid a_or_ab there , namely " a " Stream.Error("[a_or_ab] expected after \"c\" (in [c_a_or_ab_eoi])") Exception: Failure "Syntax Error". --> "[a_or_ab] expected": this is very confusing: there is a valid a_or_ab there, namely "a" *)
32415ff1dd3f00881e42123462f8ea8860fdba46c19c7e090561668ef06f9b11
ocaml/dune
wrap.ml
let t = Shared.t ^ "melange"
null
https://raw.githubusercontent.com/ocaml/dune/445005f3da4c27dea34b130f7ceaf62ec7b86765/test/blackbox-tests/test-cases/melange/virtual_lib.t/impl_melange/wrap.ml
ocaml
let t = Shared.t ^ "melange"
ec75140a24528dee3c74109c70745f0c15ba60872b00c2c327994bff8b107ef0
tomcobley/haskell-final-exams
Tries.hs
module Tries where import Data.List hiding (insert) import Data.Bits import Types import HashFunctions import Examples -------------------------------------------------------------------- -- Part I Use this if you 're counting the number of 1s in every four - bit block ... bitTable :: [Int] bitTable = [0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4] countOnes :: Int -> Int countOnes n | n == 0 = 0 | otherwise = (bitTable !! ((bit 4 - 1) .&. n)) + countOnes (shiftR n 4) countOnesFrom :: Int -> Int -> Int countOnesFrom i = popCount . (.&.) (pred (bit i)) getIndex :: Int -> Int -> Int -> Int getIndex n blockIndex blockSize = (bit blockSize - 1) .&. (shiftR n (blockIndex * blockSize)) -- Pre: the index is less than the length of the list replace :: Int -> [a] -> a -> [a] replace i (a:as) a' | i == 0 = a' : as | otherwise = a : replace (i - 1) as a' -- Pre: the index is less than or equal to the length of the list insertAt :: Int -> a -> [a] -> [a] insertAt 0 a' [] = [a'] insertAt i a' (a:as) | i == 0 = a' : (a : as) | otherwise = a : insertAt (i - 1) a' as -------------------------------------------------------------------- -- Part II sumTrie :: (Int -> Int) -> ([Int] -> Int) -> Trie -> Int sumTrie f g t | Leaf vs <- t = g vs | Node _ subNodes <- t = sum (map sumSubNode subNodes) where sumSubNode :: SubNode -> Int sumSubNode s | Term n <- s = f n | SubTrie t <- s = sumTrie f g t -- -- Predefined functions using sumTrie: -- trieSize :: Trie -> Int trieSize t = sumTrie (const 1) length t binCount :: Trie -> Int binCount t = sumTrie (const 1) (const 1) t meanBinSize :: Trie -> Double meanBinSize t = fromIntegral (trieSize t) / fromIntegral (binCount t) member :: Int -> Hash -> Trie -> Int -> Bool member v hash trie blockSize = member' 0 trie where member' :: Int -> Trie -> Bool member' currentLevel (Leaf vs) = elem v vs member' currentLevel (Node bitVector subNodes) | isBitSet, Term v' <- subNode = v == v' | isBitSet, SubTrie t <- subNode = member' (currentLevel + 1) t | otherwise = False where i = getIndex hash currentLevel blockSize isBitSet = testBit bitVector i subNode = subNodes !! (countOnesFrom i bitVector) -------------------------------------------------------------------- -- Part III insert :: HashFun -> Int -> Int -> Int -> Trie -> Trie insert hashFn maxDepth blockSize v t = insert' v (hashFn v) 0 t where insert' :: Int -> Int -> Int -> Trie -> Trie insert' v hash currentLevel t | (Leaf vs) <- t = Leaf (nub (v : vs)) | currentLevel == maxDepth - 1 = Leaf [v] insert' v hash currentLevel (Node bitVector subNodes) | bitNotSet = Node (setBit bitVector i) (insertAt n (Term v) subNodes) | SubTrie t' <- s = Node bitVector (replace' t') | Term v' <- s, v == v' = t | Term v' <- s = Node bitVector (replace' (insert' v' (hashFn v') (nextLev) empty)) where i = getIndex hash currentLevel blockSize bitNotSet = not (testBit bitVector i) n = countOnesFrom i bitVector s = subNodes !! n nextLev = currentLevel + 1 replace' x = replace n subNodes (SubTrie (insert' v hash (nextLev) x)) buildTrie :: HashFun -> Int -> Int -> [Int] -> Trie buildTrie hashFn maxDepth blockSize vs = foldl (flip (insert hashFn maxDepth blockSize)) empty vs
null
https://raw.githubusercontent.com/tomcobley/haskell-final-exams/49807e0da0ee7121d19eacff3ccc5ff5d0e4d4a2/2020-hash-array-mapped-tries/Tries.hs
haskell
------------------------------------------------------------------ Part I Pre: the index is less than the length of the list Pre: the index is less than or equal to the length of the list ------------------------------------------------------------------ Part II Predefined functions using sumTrie: ------------------------------------------------------------------ Part III
module Tries where import Data.List hiding (insert) import Data.Bits import Types import HashFunctions import Examples Use this if you 're counting the number of 1s in every four - bit block ... bitTable :: [Int] bitTable = [0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4] countOnes :: Int -> Int countOnes n | n == 0 = 0 | otherwise = (bitTable !! ((bit 4 - 1) .&. n)) + countOnes (shiftR n 4) countOnesFrom :: Int -> Int -> Int countOnesFrom i = popCount . (.&.) (pred (bit i)) getIndex :: Int -> Int -> Int -> Int getIndex n blockIndex blockSize = (bit blockSize - 1) .&. (shiftR n (blockIndex * blockSize)) replace :: Int -> [a] -> a -> [a] replace i (a:as) a' | i == 0 = a' : as | otherwise = a : replace (i - 1) as a' insertAt :: Int -> a -> [a] -> [a] insertAt 0 a' [] = [a'] insertAt i a' (a:as) | i == 0 = a' : (a : as) | otherwise = a : insertAt (i - 1) a' as sumTrie :: (Int -> Int) -> ([Int] -> Int) -> Trie -> Int sumTrie f g t | Leaf vs <- t = g vs | Node _ subNodes <- t = sum (map sumSubNode subNodes) where sumSubNode :: SubNode -> Int sumSubNode s | Term n <- s = f n | SubTrie t <- s = sumTrie f g t trieSize :: Trie -> Int trieSize t = sumTrie (const 1) length t binCount :: Trie -> Int binCount t = sumTrie (const 1) (const 1) t meanBinSize :: Trie -> Double meanBinSize t = fromIntegral (trieSize t) / fromIntegral (binCount t) member :: Int -> Hash -> Trie -> Int -> Bool member v hash trie blockSize = member' 0 trie where member' :: Int -> Trie -> Bool member' currentLevel (Leaf vs) = elem v vs member' currentLevel (Node bitVector subNodes) | isBitSet, Term v' <- subNode = v == v' | isBitSet, SubTrie t <- subNode = member' (currentLevel + 1) t | otherwise = False where i = getIndex hash currentLevel blockSize isBitSet = testBit bitVector i subNode = subNodes !! (countOnesFrom i bitVector) insert :: HashFun -> Int -> Int -> Int -> Trie -> Trie insert hashFn maxDepth blockSize v t = insert' v (hashFn v) 0 t where insert' :: Int -> Int -> Int -> Trie -> Trie insert' v hash currentLevel t | (Leaf vs) <- t = Leaf (nub (v : vs)) | currentLevel == maxDepth - 1 = Leaf [v] insert' v hash currentLevel (Node bitVector subNodes) | bitNotSet = Node (setBit bitVector i) (insertAt n (Term v) subNodes) | SubTrie t' <- s = Node bitVector (replace' t') | Term v' <- s, v == v' = t | Term v' <- s = Node bitVector (replace' (insert' v' (hashFn v') (nextLev) empty)) where i = getIndex hash currentLevel blockSize bitNotSet = not (testBit bitVector i) n = countOnesFrom i bitVector s = subNodes !! n nextLev = currentLevel + 1 replace' x = replace n subNodes (SubTrie (insert' v hash (nextLev) x)) buildTrie :: HashFun -> Int -> Int -> [Int] -> Trie buildTrie hashFn maxDepth blockSize vs = foldl (flip (insert hashFn maxDepth blockSize)) empty vs
5acf7e6ef59cb5ab0efa54883cb1213d181555a66f910c41c83024ab0c1eddb6
aeternity/enoise
enoise_tests.erl
%%%------------------------------------------------------------------- ( C ) 2018 , Aeternity Anstalt %%%------------------------------------------------------------------- -module(enoise_tests). -include_lib("eunit/include/eunit.hrl"). noise_interactive_test_() -> Test vectors from -c/master/tests/vector/noise-c-basic.txt {setup, fun() -> test_utils:noise_test_vectors() end, fun(_X) -> ok end, fun(Tests) -> [ {maps:get(protocol_name, T), fun() -> noise_interactive(T) end} || T <- test_utils:noise_test_filter(Tests) ] end }. noise_interactive(V = #{ protocol_name := Name }) -> Protocol = enoise_protocol:from_name(Name), FixK = fun(undefined) -> undefined; (Bin) -> test_utils:hex_str_to_bin("0x" ++ binary_to_list(Bin)) end, Init = #{ prologue => FixK(maps:get(init_prologue, V, <<>>)) , e => FixK(maps:get(init_ephemeral, V, undefined)) , s => FixK(maps:get(init_static, V, undefined)) , rs => FixK(maps:get(init_remote_static, V, undefined)) }, Resp = #{ prologue => FixK(maps:get(resp_prologue, V, <<>>)) , e => FixK(maps:get(resp_ephemeral, V, undefined)) , s => FixK(maps:get(resp_static, V, undefined)) , rs => FixK(maps:get(resp_remote_static, V, undefined)) }, Messages = maps:get(messages, V), HandshakeHash = maps:get(handshake_hash, V), noise_interactive(Name, Protocol, Init, Resp, Messages, FixK(HandshakeHash)), ok. noise_interactive(_Name, Protocol, Init, Resp, Messages, HSHash) -> DH = enoise_protocol:dh(Protocol), SecK = fun(undefined) -> undefined; (Sec) -> enoise_keypair:new(DH, Sec, undefined) end, PubK = fun(undefined) -> undefined; (Pub) -> enoise_keypair:new(DH, Pub) end, HSInit = fun(#{ e := E, s := S, rs := RS, prologue := PL }, R) -> Opts = [{noise, Protocol}, {s, SecK(S)}, {e, SecK(E)}, {rs, PubK(RS)}, {prologue, PL}], enoise:handshake(Opts, R) end, {ok, InitHS} = HSInit(Init, initiator), {ok, RespHS} = HSInit(Resp, responder), noise_interactive(Messages, InitHS, RespHS, HSHash). noise_interactive([#{ payload := PL0, ciphertext := CT0 } | Msgs], SendHS, RecvHS, HSHash) -> PL = test_utils:hex_str_to_bin("0x" ++ binary_to_list(PL0)), CT = test_utils:hex_str_to_bin("0x" ++ binary_to_list(CT0)), case enoise_hs_state:next_message(SendHS) of out -> {ok, send, Message, SendHS1} = enoise:step_handshake(SendHS, {send, PL}), ?assertEqual(CT, Message), {ok, rcvd, PL1, RecvHS1} = enoise:step_handshake(RecvHS, {rcvd, Message}), ?assertEqual(PL, PL1), noise_interactive(Msgs, RecvHS1, SendHS1, HSHash); done -> {ok, done, #{ rx := RX1, tx := TX1, hs_hash := HSHash1 }} = enoise:step_handshake(SendHS, done), {ok, done, #{ rx := RX2, tx := TX2, hs_hash := HSHash2 }} = enoise:step_handshake(RecvHS, done), ?assertEqual(RX1, TX2), ?assertEqual(RX2, TX1), ?assertEqual(HSHash, HSHash1), ?assertEqual(HSHash, HSHash2) end. noise_dh25519_test_() -> Test vectors from -c/master/tests/vector/noise-c-basic.txt {setup, fun() -> setup_dh25519() end, fun(_X) -> ok end, fun({Tests, SKP, CKP}) -> [ {T, fun() -> noise_test(T, SKP, CKP) end} || T <- Tests ] end }. noise_monitor_test_() -> {setup, fun() -> setup_dh25519() end, fun(_X) -> ok end, fun({Tests, SKP, CKP}) -> [ {T, fun() -> noise_monitor_test(T, SKP, CKP) end} || T <- Tests ] end }. setup_dh25519() -> %% Generate a static key-pair for Client and Server SrvKeyPair = enoise_keypair:new(dh25519), CliKeyPair = enoise_keypair:new(dh25519), #{ hs_pattern := Ps, hash := Hs, cipher := Cs } = enoise_protocol:supported(), Configurations = [ enoise_protocol:to_name(P, dh25519, C, H) || P <- Ps, C <- Cs, H <- Hs ], Configurations = [ enoise_protocol : to_name(xk , dh25519 , ' ' , blake2b ) ] , {Configurations, SrvKeyPair, CliKeyPair}. noise_test(Conf, SKP, CKP) -> #{econn := EConn, echo_srv := EchoSrv} = noise_test_run(Conf, SKP, CKP), enoise:close(EConn), enoise_utils:echo_srv_stop(EchoSrv), ok. noise_test_run(Conf, SKP, CKP) -> {Pid, MRef} = spawn_monitor_proxy( fun() -> noise_test_run_(Conf, SKP, CKP) end), receive {Pid, #{} = Info} -> Info#{proxy => Pid, proxy_mref => MRef} after 5000 -> erlang:error(timeout) end. spawn_monitor_proxy(F) -> Me = self(), spawn_monitor(fun() -> MRef = erlang:monitor(process, Me), Res = F(), Me ! {self(), Res}, proxy_loop(Me, MRef) end). proxy_loop(Parent, MRef) -> receive {Parent, Ref, F} when is_function(F, 0) -> Parent ! {Ref, F()}, proxy_loop(Parent, MRef); {'DOWN', MRef, process, Parent, _} -> done end. proxy_exec(P, F) when is_function(F, 0) -> R = erlang:monitor(process, P), P ! {self(), R, F}, receive {R, Res} -> Res; {'DOWN', R, _, _, Reason} -> erlang:error(Reason) after 5000 -> erlang:error(timeout) end. noise_test_run_(Conf, SKP, CKP) -> Protocol = enoise_protocol:from_name(Conf), Port = 4556, SrvOpts = [{echos, 2}, {cpub, CKP}], EchoSrv = enoise_utils:echo_srv_start(Port, Protocol, SKP, SrvOpts), {ok, TcpSock} = gen_tcp:connect("localhost", Port, [{active, once}, binary, {reuseaddr, true}], 100), Opts = [{noise, Protocol}, {s, CKP}] ++ [{rs, SKP} || enoise_utils:need_rs(initiator, Conf) ], {ok, EConn, _} = enoise:connect(TcpSock, Opts), ok = enoise:send(EConn, <<"Hello World!">>), receive {noise, _, <<"Hello World!">>} -> ok after 100 -> error(timeout) end, enoise:set_active(EConn, once), ok = enoise:send(EConn, <<"Goodbye!">>), receive {noise, _, <<"Goodbye!">>} -> ok after 100 -> error(timeout) end, #{ econn => EConn , tcp_sock => TcpSock , echo_srv => EchoSrv }. noise_monitor_test(Conf, SKP, CKP) -> #{ econn := {enoise, EConnPid} , proxy := Proxy , tcp_sock := _TcpSock } = noise_test_run(Conf, SKP, CKP), try proxy_exec(Proxy, fun() -> exit(normal) end) catch error:normal -> receive after 100 -> false = is_process_alive(EConnPid) end end. %% Talks to local echo-server (noise-c) %% client_test() -> %% TestProtocol = enoise_protocol:from_name("Noise_XK_25519_ChaChaPoly_BLAKE2b"), = < < 64,168,119,119,151,194,94,141,86,245,144,220,78,53,243,231,168,216,66,199,49,148,202,117,98,40,61,109,170,37,133,122 > > , ClientPubKey = < < 115,39,86,77,44,85,192,176,202,11,4,6,194,144,127,123 , 34,67,62,180,190,232,251,5,216,168,192,190,134,65,13,64 > > , ServerPubKey = < < 112,91,141,253,183,66,217,102,211,40,13,249,238,51,77,114,163,159,32,1,162,219,76,106,89,164,34,71,149,2,103,59 > > , { ok , TcpSock } = gen_tcp : connect("localhost " , 7890 , [ { active , once } , binary , { reuseaddr , true } ] , 1000 ) , gen_tcp : send(TcpSock , < < 0,8,0,0,3 > > ) , % % " Noise_XK_25519_ChaChaPoly_Blake2b " %% Opts = [ {noise, TestProtocol} , { s , enoise_keypair : new(dh25519 , , ClientPubKey ) } , { rs , enoise_keypair : new(dh25519 , ServerPubKey ) } , { prologue , < < 0,8,0,0,3 > > } ] , { ok , } = enoise : connect(TcpSock , Opts ) , %% ok = enoise:send(EConn, <<"ok\n">>), %% receive { noise , EConn , < < " ok\n " > > } - > ok %% after 1000 -> error(timeout) end, % % { ok , < < " ok\n " > > } = enoise : recv(EConn , 3 , 1000 ) , %% enoise:close(EConn). %% Expects a call-in from a local echo-client (noise-c) %% server_test_() -> { timeout , 20 , fun ( ) - > %% TestProtocol = enoise_protocol:from_name("Noise_XK_25519_ChaChaPoly_Blake2b"), %% ServerPrivKey = <<200,81,196,192,228,196,182,200,181,83,169,255,242,54,99,113,8,49,129,92,225,220,99,50,93,96,253,250,116,196,137,103>>, ServerPubKey = < < 112,91,141,253,183,66,217,102,211,40,13,249,238,51,77,114,163,159,32,1,162,219,76,106,89,164,34,71,149,2,103,59 > > , %% Opts = [ {noise, TestProtocol} , { s , enoise_keypair : new(dh25519 , ServerPrivKey , ServerPubKey ) } , { prologue , < < 0,8,0,0,3 > > } ] , { ok , LSock } = gen_tcp : listen(7891 , [ { reuseaddr , true } , binary ] ) , { ok , TcpSock } = gen_tcp : accept(LSock , 10000 ) , receive { tcp , TcpSock , < < 0,8,0,0,3 > > } - > ok %% after 1000 -> error(timeout) end, { ok , } = enoise : accept(TcpSock , ) , { EConn1 , Msg } = enoise : recv(EConn ) , %% EConn2 = enoise:send(EConn1, Msg), %% enoise:close(EConn2) %% end}.
null
https://raw.githubusercontent.com/aeternity/enoise/991d7390ea49216f0b170d7b9662b3ff0a925aaa/test/enoise_tests.erl
erlang
------------------------------------------------------------------- ------------------------------------------------------------------- Generate a static key-pair for Client and Server Talks to local echo-server (noise-c) client_test() -> TestProtocol = enoise_protocol:from_name("Noise_XK_25519_ChaChaPoly_BLAKE2b"), % " Noise_XK_25519_ChaChaPoly_Blake2b " Opts = [ {noise, TestProtocol} ok = enoise:send(EConn, <<"ok\n">>), receive after 1000 -> error(timeout) end, % { ok , < < " ok\n " > > } = enoise : recv(EConn , 3 , 1000 ) , enoise:close(EConn). Expects a call-in from a local echo-client (noise-c) server_test_() -> TestProtocol = enoise_protocol:from_name("Noise_XK_25519_ChaChaPoly_Blake2b"), ServerPrivKey = <<200,81,196,192,228,196,182,200,181,83,169,255,242,54,99,113,8,49,129,92,225,220,99,50,93,96,253,250,116,196,137,103>>, Opts = [ {noise, TestProtocol} after 1000 -> error(timeout) end, EConn2 = enoise:send(EConn1, Msg), enoise:close(EConn2) end}.
( C ) 2018 , Aeternity Anstalt -module(enoise_tests). -include_lib("eunit/include/eunit.hrl"). noise_interactive_test_() -> Test vectors from -c/master/tests/vector/noise-c-basic.txt {setup, fun() -> test_utils:noise_test_vectors() end, fun(_X) -> ok end, fun(Tests) -> [ {maps:get(protocol_name, T), fun() -> noise_interactive(T) end} || T <- test_utils:noise_test_filter(Tests) ] end }. noise_interactive(V = #{ protocol_name := Name }) -> Protocol = enoise_protocol:from_name(Name), FixK = fun(undefined) -> undefined; (Bin) -> test_utils:hex_str_to_bin("0x" ++ binary_to_list(Bin)) end, Init = #{ prologue => FixK(maps:get(init_prologue, V, <<>>)) , e => FixK(maps:get(init_ephemeral, V, undefined)) , s => FixK(maps:get(init_static, V, undefined)) , rs => FixK(maps:get(init_remote_static, V, undefined)) }, Resp = #{ prologue => FixK(maps:get(resp_prologue, V, <<>>)) , e => FixK(maps:get(resp_ephemeral, V, undefined)) , s => FixK(maps:get(resp_static, V, undefined)) , rs => FixK(maps:get(resp_remote_static, V, undefined)) }, Messages = maps:get(messages, V), HandshakeHash = maps:get(handshake_hash, V), noise_interactive(Name, Protocol, Init, Resp, Messages, FixK(HandshakeHash)), ok. noise_interactive(_Name, Protocol, Init, Resp, Messages, HSHash) -> DH = enoise_protocol:dh(Protocol), SecK = fun(undefined) -> undefined; (Sec) -> enoise_keypair:new(DH, Sec, undefined) end, PubK = fun(undefined) -> undefined; (Pub) -> enoise_keypair:new(DH, Pub) end, HSInit = fun(#{ e := E, s := S, rs := RS, prologue := PL }, R) -> Opts = [{noise, Protocol}, {s, SecK(S)}, {e, SecK(E)}, {rs, PubK(RS)}, {prologue, PL}], enoise:handshake(Opts, R) end, {ok, InitHS} = HSInit(Init, initiator), {ok, RespHS} = HSInit(Resp, responder), noise_interactive(Messages, InitHS, RespHS, HSHash). noise_interactive([#{ payload := PL0, ciphertext := CT0 } | Msgs], SendHS, RecvHS, HSHash) -> PL = test_utils:hex_str_to_bin("0x" ++ binary_to_list(PL0)), CT = test_utils:hex_str_to_bin("0x" ++ binary_to_list(CT0)), case enoise_hs_state:next_message(SendHS) of out -> {ok, send, Message, SendHS1} = enoise:step_handshake(SendHS, {send, PL}), ?assertEqual(CT, Message), {ok, rcvd, PL1, RecvHS1} = enoise:step_handshake(RecvHS, {rcvd, Message}), ?assertEqual(PL, PL1), noise_interactive(Msgs, RecvHS1, SendHS1, HSHash); done -> {ok, done, #{ rx := RX1, tx := TX1, hs_hash := HSHash1 }} = enoise:step_handshake(SendHS, done), {ok, done, #{ rx := RX2, tx := TX2, hs_hash := HSHash2 }} = enoise:step_handshake(RecvHS, done), ?assertEqual(RX1, TX2), ?assertEqual(RX2, TX1), ?assertEqual(HSHash, HSHash1), ?assertEqual(HSHash, HSHash2) end. noise_dh25519_test_() -> Test vectors from -c/master/tests/vector/noise-c-basic.txt {setup, fun() -> setup_dh25519() end, fun(_X) -> ok end, fun({Tests, SKP, CKP}) -> [ {T, fun() -> noise_test(T, SKP, CKP) end} || T <- Tests ] end }. noise_monitor_test_() -> {setup, fun() -> setup_dh25519() end, fun(_X) -> ok end, fun({Tests, SKP, CKP}) -> [ {T, fun() -> noise_monitor_test(T, SKP, CKP) end} || T <- Tests ] end }. setup_dh25519() -> SrvKeyPair = enoise_keypair:new(dh25519), CliKeyPair = enoise_keypair:new(dh25519), #{ hs_pattern := Ps, hash := Hs, cipher := Cs } = enoise_protocol:supported(), Configurations = [ enoise_protocol:to_name(P, dh25519, C, H) || P <- Ps, C <- Cs, H <- Hs ], Configurations = [ enoise_protocol : to_name(xk , dh25519 , ' ' , blake2b ) ] , {Configurations, SrvKeyPair, CliKeyPair}. noise_test(Conf, SKP, CKP) -> #{econn := EConn, echo_srv := EchoSrv} = noise_test_run(Conf, SKP, CKP), enoise:close(EConn), enoise_utils:echo_srv_stop(EchoSrv), ok. noise_test_run(Conf, SKP, CKP) -> {Pid, MRef} = spawn_monitor_proxy( fun() -> noise_test_run_(Conf, SKP, CKP) end), receive {Pid, #{} = Info} -> Info#{proxy => Pid, proxy_mref => MRef} after 5000 -> erlang:error(timeout) end. spawn_monitor_proxy(F) -> Me = self(), spawn_monitor(fun() -> MRef = erlang:monitor(process, Me), Res = F(), Me ! {self(), Res}, proxy_loop(Me, MRef) end). proxy_loop(Parent, MRef) -> receive {Parent, Ref, F} when is_function(F, 0) -> Parent ! {Ref, F()}, proxy_loop(Parent, MRef); {'DOWN', MRef, process, Parent, _} -> done end. proxy_exec(P, F) when is_function(F, 0) -> R = erlang:monitor(process, P), P ! {self(), R, F}, receive {R, Res} -> Res; {'DOWN', R, _, _, Reason} -> erlang:error(Reason) after 5000 -> erlang:error(timeout) end. noise_test_run_(Conf, SKP, CKP) -> Protocol = enoise_protocol:from_name(Conf), Port = 4556, SrvOpts = [{echos, 2}, {cpub, CKP}], EchoSrv = enoise_utils:echo_srv_start(Port, Protocol, SKP, SrvOpts), {ok, TcpSock} = gen_tcp:connect("localhost", Port, [{active, once}, binary, {reuseaddr, true}], 100), Opts = [{noise, Protocol}, {s, CKP}] ++ [{rs, SKP} || enoise_utils:need_rs(initiator, Conf) ], {ok, EConn, _} = enoise:connect(TcpSock, Opts), ok = enoise:send(EConn, <<"Hello World!">>), receive {noise, _, <<"Hello World!">>} -> ok after 100 -> error(timeout) end, enoise:set_active(EConn, once), ok = enoise:send(EConn, <<"Goodbye!">>), receive {noise, _, <<"Goodbye!">>} -> ok after 100 -> error(timeout) end, #{ econn => EConn , tcp_sock => TcpSock , echo_srv => EchoSrv }. noise_monitor_test(Conf, SKP, CKP) -> #{ econn := {enoise, EConnPid} , proxy := Proxy , tcp_sock := _TcpSock } = noise_test_run(Conf, SKP, CKP), try proxy_exec(Proxy, fun() -> exit(normal) end) catch error:normal -> receive after 100 -> false = is_process_alive(EConnPid) end end. = < < 64,168,119,119,151,194,94,141,86,245,144,220,78,53,243,231,168,216,66,199,49,148,202,117,98,40,61,109,170,37,133,122 > > , ClientPubKey = < < 115,39,86,77,44,85,192,176,202,11,4,6,194,144,127,123 , 34,67,62,180,190,232,251,5,216,168,192,190,134,65,13,64 > > , ServerPubKey = < < 112,91,141,253,183,66,217,102,211,40,13,249,238,51,77,114,163,159,32,1,162,219,76,106,89,164,34,71,149,2,103,59 > > , { ok , TcpSock } = gen_tcp : connect("localhost " , 7890 , [ { active , once } , binary , { reuseaddr , true } ] , 1000 ) , , { s , enoise_keypair : new(dh25519 , , ClientPubKey ) } , { rs , enoise_keypair : new(dh25519 , ServerPubKey ) } , { prologue , < < 0,8,0,0,3 > > } ] , { ok , } = enoise : connect(TcpSock , Opts ) , { noise , EConn , < < " ok\n " > > } - > ok { timeout , 20 , fun ( ) - > ServerPubKey = < < 112,91,141,253,183,66,217,102,211,40,13,249,238,51,77,114,163,159,32,1,162,219,76,106,89,164,34,71,149,2,103,59 > > , , { s , enoise_keypair : new(dh25519 , ServerPrivKey , ServerPubKey ) } , { prologue , < < 0,8,0,0,3 > > } ] , { ok , LSock } = gen_tcp : listen(7891 , [ { reuseaddr , true } , binary ] ) , { ok , TcpSock } = gen_tcp : accept(LSock , 10000 ) , receive { tcp , TcpSock , < < 0,8,0,0,3 > > } - > ok { ok , } = enoise : accept(TcpSock , ) , { EConn1 , Msg } = enoise : recv(EConn ) ,
e03a0902d5bfa0de95b4785ae648007d66160e969b41a51c6932f287986e9df9
static-analysis-engineering/codehawk
bCHMIPSAssemblyInstructions.mli
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2019 Kestrel Technology LLC Copyright ( c ) 2020 ( c ) 2021 - 2023 Aarno Labs LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2019 Kestrel Technology LLC Copyright (c) 2020 Henny Sipma Copyright (c) 2021-2023 Aarno Labs LLC 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. ============================================================================= *) (* bchlib *) open BCHLibTypes (* bchlibmips32 *) open BCHMIPSTypes open BCHMIPSAssemblyInstruction * Holds an array of all of the assembly instructions , made available through a class instance reference . This is the backing store of all assembly instructions . There is one array element for each word address ( i.e. , elements are at 4 - byte boundaries ) . a class instance reference. This is the backing store of all assembly instructions. There is one array element for each word address (i.e., elements are at 4-byte boundaries). *) (** Return a reference to the class wrapper of the array of assembly instructions.*) val mips_assembly_instructions: mips_assembly_instructions_int ref (** Create an array of the given size to hold the assembly instructions.*) val initialize_mips_instructions: int -> unit (** Initialize the instruction array with instructions *) val initialize_mips_assembly_instructions: int (* length in bytes of the combined executable sections *) -> doubleword_int (* address of code base *) -> unit (** [set_mips_assembly_instruction instr] enters [instr] at the address obtained from [instr#get_address] in the mips_assembly_instructions store. If the obtained address is out-of-range and the instruction is further ignored.*) val set_mips_assembly_instruction: mips_assembly_instruction_int -> unit (** [get_mips_assembly_instruction va] returns the assembly instruction at virtual address [va]. If [va] is out-of-range or if there is no instruction at [va] an Error result is returned.*) val get_mips_assembly_instruction: doubleword_int -> mips_assembly_instruction_result
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/dd2c3b9f84b4b5f3c88898505ee912e1e461e809/CodeHawk/CHB/bchlibmips32/bCHMIPSAssemblyInstructions.mli
ocaml
bchlib bchlibmips32 * Return a reference to the class wrapper of the array of assembly instructions. * Create an array of the given size to hold the assembly instructions. * Initialize the instruction array with instructions length in bytes of the combined executable sections address of code base * [set_mips_assembly_instruction instr] enters [instr] at the address obtained from [instr#get_address] in the mips_assembly_instructions store. If the obtained address is out-of-range and the instruction is further ignored. * [get_mips_assembly_instruction va] returns the assembly instruction at virtual address [va]. If [va] is out-of-range or if there is no instruction at [va] an Error result is returned.
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2019 Kestrel Technology LLC Copyright ( c ) 2020 ( c ) 2021 - 2023 Aarno Labs LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2019 Kestrel Technology LLC Copyright (c) 2020 Henny Sipma Copyright (c) 2021-2023 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) open BCHLibTypes open BCHMIPSTypes open BCHMIPSAssemblyInstruction * Holds an array of all of the assembly instructions , made available through a class instance reference . This is the backing store of all assembly instructions . There is one array element for each word address ( i.e. , elements are at 4 - byte boundaries ) . a class instance reference. This is the backing store of all assembly instructions. There is one array element for each word address (i.e., elements are at 4-byte boundaries). *) val mips_assembly_instructions: mips_assembly_instructions_int ref val initialize_mips_instructions: int -> unit val initialize_mips_assembly_instructions: -> unit val set_mips_assembly_instruction: mips_assembly_instruction_int -> unit val get_mips_assembly_instruction: doubleword_int -> mips_assembly_instruction_result