| {"text": "module Unlambda\n\nimport Control.Monad.Trans\nimport src.ContT\n\n-- Based on http://www.madore.org/~david/programs/unlambda/\n\ndata Rec : (r : Type) -> (m : Type -> Type) -> Type where\n RecK : (Rec r m -> ContT r m (Rec r m)) -> Rec r m\n\n\ndata Expr : Type where\n S : Expr\n K : Expr\n I : Expr\n R : Expr\n C : Expr\n Dot : Char -> Expr\n Backtick : Expr -> Expr -> Expr\n\napply : ContT r m (Rec r m) -> ContT r m (Rec r m) -> ContT r m (Rec r m)\napply first second = do (RecK k) <- first\n b <- second\n k b\n\neval : Monad m => Expr -> (Char -> m ()) -> ContT r m (Rec r m)\neval S put = pure $ RecK (\\rec =>\n pure $ RecK (\\rec' =>\n pure $ RecK (\\rec'' => apply (apply (pure rec) (pure rec'')) (apply (pure rec') (pure rec'')))))\neval K put = pure $ RecK (\\rec => pure $ RecK (\\_ => pure rec))\neval I put = pure $ RecK (\\rec => pure rec)\neval R put = pure $ RecK (\\rec => do lift $ put '\\n'; pure rec)\neval C put = pure $ RecK (\\(RecK k) => callCC (\\k' => k $ RecK k'))\neval (Dot char) put = pure $ RecK (\\rec => do lift $ put char; pure rec)\neval (Backtick expr expr') put = apply (eval expr put) (eval expr' put)\n\n\nparse : List Char -> Maybe (Expr, List Char)\nparse ('s' :: xs) = Just (S, xs)\nparse ('k' :: xs) = Just (K, xs)\nparse ('i' :: xs) = Just (I, xs)\nparse ('r' :: xs) = Just (R, xs)\nparse ('c' :: xs) = Just (C, xs)\nparse ('.' :: c :: xs) = Just (Dot c, xs)\nparse ('`' :: xs) = do (expr, xs') <- parse xs\n (expr', xs'') <- parse xs'\n Just (Backtick expr expr', xs'')\nparse (x :: xs) = Nothing\nparse [] = Nothing\n\ncallCCTest : String\ncallCCTest = \"``cir\"\n\nhelloWorldTest : String\nhelloWorldTest = \"```si`k``s.H``s.e``s.l``s.l``s.o``s. ``s.w``s.o``s.r``s.l``s.d``s.!``sri``si``si``si``si``si``si``si``si`ki\"\n\nexample : IO ()\nexample = case parse (unpack helloWorldTest) of\n Just (expr, _) => run (\\_ => pure ()) $ eval expr putChar\n Nothing => putStrLn \"Parse error\"\n", "meta": {"hexsha": "9f8c190cedd26040d0b06adb26f0c3a090e8f036", "size": 2007, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Unlambda.idr", "max_stars_repo_name": "STELIORD/idris-snippets", "max_stars_repo_head_hexsha": "f5ca6fa86370d24587040af9871ae850bbc630c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-11-21T22:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T18:25:18.000Z", "max_issues_repo_path": "src/Unlambda.idr", "max_issues_repo_name": "stjordanis/idris-snippets", "max_issues_repo_head_hexsha": "d92734b8624ae27be21a63fcb041077b38eaaecb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Unlambda.idr", "max_forks_repo_name": "stjordanis/idris-snippets", "max_forks_repo_head_hexsha": "d92734b8624ae27be21a63fcb041077b38eaaecb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-06T13:39:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T15:39:16.000Z", "avg_line_length": 32.9016393443, "max_line_length": 126, "alphanum_fraction": 0.5296462382, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4493926344647596, "lm_q1q2_score": 0.24917494298146659}} |
| {"text": "module Extra.C.CPtr\n\nimport Data.Nat\nimport Data.Vect\nimport Extra.String\nimport Extra.Proof\nimport Extra.C.Ptr\nimport Extra.C.Storable\nimport public Control.Linear.LIO\nimport public Extra.C.Types\n\npublic export\ndata Content : Type where\n NullTerminated : (can_free : Bool) -> Content\n Bytes : (can_free, can_read, can_write : Bool) -> Nat -> Content\n Opaque : (can_free : Bool) -> (ty : Type) -> Content\n\npublic export\nisFreeable : Content -> Bool\nisFreeable (NullTerminated can_free) = can_free\nisFreeable (Bytes can_free _ _ _) = can_free\nisFreeable (Opaque can_free _) = can_free\n\npublic export\ntypeOf : Content -> Type\ntypeOf (NullTerminated _) = CChar\ntypeOf (Bytes _ _ _ _) = CUInt8\ntypeOf (Opaque _ ty) = ty\n\npublic export\ndata CPtr : Content -> Type where\n MkCPtr : Ptr (typeOf content) -> CPtr content\n\nexport\nmalloc\n : LinearIO io\n => (length : Nat)\n -> {default True can_free : Bool}\n -> {default True can_read : Bool}\n -> {default True can_write : Bool}\n -> L io {use=1} (CPtr (Bytes can_free can_read can_write length))\nmalloc length = do\n ptr <- primIO $ prim__malloc $ cast $ natToInteger length\n pure1 $ MkCPtr (castPtr ptr)\n\nexport\ncalloc\n : LinearIO io\n => (length : Nat)\n -> {default True can_free : Bool}\n -> {default True can_read : Bool}\n -> {default True can_write : Bool}\n -> L io {use=1} (CPtr (Bytes can_free can_read can_write length))\ncalloc length = do\n ptr <- primIO $ prim__calloc $ cast $ natToInteger length\n pure1 $ MkCPtr (castPtr ptr)\n\nexport\nfree\n : LinearIO io\n => (1 _ : CPtr content)\n -> {auto okay : isFreeable content = True}\n -> L io ()\nfree (MkCPtr ptr) = primIO $ prim__free (forgetPtr ptr)\n\nexport\npokeByte\n : LinearIO io\n => (1 _ : CPtr (Bytes can_free can_read True length))\n -> (index : Nat)\n -> {auto 0 okay : LT index length}\n -> (byte : CUInt8)\n -> L io {use=1} (CPtr (Bytes can_free can_read True length))\npokeByte (MkCPtr ptr) index byte = do\n poke (plusPtr ptr (cast $ natToInteger index)) byte\n pure1 $ MkCPtr ptr\n\nexport\npeekByte\n : LinearIO io\n => (1 _ : CPtr (Bytes can_free True can_write length))\n -> (index : Nat)\n -> {auto 0 okay : LT index length}\n -> L io {use=1} (Res CUInt8 (\\_ => CPtr (Bytes can_free True can_write length)))\npeekByte (MkCPtr ptr) index = do\n byte <- peek (plusPtr ptr (cast $ natToInteger index))\n pure1 $ (byte # MkCPtr ptr)\n\nexport\npeekBytes\n : LinearIO io \n => (1 _ : CPtr (Bytes can_free True can_write length))\n -> (offset : Nat)\n -> (count : Nat)\n -> {auto okay : LTE (offset + count) length}\n -> L io {use=1} (Res (Vect count CUInt8) (\\_ => CPtr (Bytes can_free True can_write length)))\npeekBytes cptr ofs Z = pure1 $ Nil # cptr\npeekBytes cptr ofs (S cnt) = do\n let m = lteAddRight (S ofs) {m = cnt}\n let m = replace {p = LTE (S ofs)} (plusSuccRightSucc ofs cnt) m\n byte # cptr <- peekByte {okay = lteTransitive m okay} cptr ofs\n let n = okay\n let n = replace {p = \\a => LTE a length} (sym $ plusSuccRightSucc ofs cnt) n\n bytes # cptr <- peekBytes cptr (S ofs) cnt {okay = n}\n pure1 $ (byte :: bytes) # cptr\n\nexport\npokeBytes\n : LinearIO io \n => (1 _ : CPtr (Bytes can_free can_read True length))\n -> (offset : Nat)\n -> {count : Nat}\n -> (bytes : Vect count CUInt8)\n -> {auto okay : LTE (offset + count) length}\n -> L io {use=1} (CPtr (Bytes can_free can_read True length))\npokeBytes {count = Z} cptr ofs Nil = pure1 $ cptr\npokeBytes {count = S cnt} cptr ofs (byte :: bytes) = do\n let m = lteAddRight (S ofs) {m = cnt}\n let m = replace {p = LTE (S ofs)} (plusSuccRightSucc ofs cnt) m\n cptr <- pokeByte {okay = lteTransitive m okay} cptr ofs byte\n let n = okay\n let n = replace {p = \\a => LTE a length} (sym $ plusSuccRightSucc ofs cnt) n\n pokeBytes {okay = n} cptr (S ofs) bytes\n\nexport\nunsafeToNullTerminated\n : LinearIO io\n => (1 _ : CPtr (Bytes can_free can_read can_write length))\n -> L io {use=1} (CPtr (NullTerminated can_free))\nunsafeToNullTerminated (MkCPtr ptr) = pure1 $ MkCPtr ptr\n\nexport\nunsafeToBytes\n : LinearIO io\n => (1 _ : CPtr (NullTerminated can_free))\n -> (0 length : Nat)\n -> {default True can_read : Bool}\n -> {default True can_write : Bool}\n -> L io {use=1} (CPtr (Bytes can_free can_read can_write length))\nunsafeToBytes (MkCPtr ptr) _ = pure1 $ MkCPtr ptr\n\n-- TODO: behavior of length on strings containing '\\0' is weird (?\nexport\npackString\n : LinearIO io\n => String\n -> {default True can_free : Bool}\n -> L io {use=1} (CPtr (NullTerminated can_free))\npackString str = do\n cptr <- malloc (S (length str))\n cptr <- pokeBytes {okay = believe_me ()} cptr 0 ((map (cast . ord) $ unpackVect str) `snoc` 0)\n let (MkCPtr ptr) = cptr\n pure1 $ MkCPtr ptr\n\nexport\npackBytes\n : LinearIO io\n => {length : Nat}\n -> Vect length CUInt8\n -> {default True can_read : Bool}\n -> {default True can_write : Bool}\n -> L io {use=1} (CPtr (Bytes True can_read can_write length))\npackBytes bytes = do\n cptr <- malloc length\n cptr <- pokeBytes {okay = lteRefl} cptr 0 bytes\n let (MkCPtr ptr) = cptr\n pure1 $ MkCPtr ptr\n\nexport\nunpackBytes\n : LinearIO io\n => {length : Nat}\n -> (1 _ : CPtr (Bytes can_free True can_write length))\n -> L io {use=1} (Res (Vect length CUInt8) (\\_ => CPtr (Bytes can_free True can_write length)))\nunpackBytes cptr = do\n bytes # cptr <- peekBytes {okay = lteRefl} cptr 0 length\n pure1 $ bytes # cptr\n", "meta": {"hexsha": "f6e0b82ec8622af8eca81c6eebba65cb82c7592b", "size": 5333, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Extra/C/CPtr.idr", "max_stars_repo_name": "tensorknower69/idris2-extra", "max_stars_repo_head_hexsha": "b856915276987758da8c38865b4b336079bc1e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Extra/C/CPtr.idr", "max_issues_repo_name": "tensorknower69/idris2-extra", "max_issues_repo_head_hexsha": "b856915276987758da8c38865b4b336079bc1e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Extra/C/CPtr.idr", "max_forks_repo_name": "tensorknower69/idris2-extra", "max_forks_repo_head_hexsha": "b856915276987758da8c38865b4b336079bc1e9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9606741573, "max_line_length": 96, "alphanum_fraction": 0.6654790924, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.24896579559260795}} |
| {"text": "module Control.JS.Async\n\nexport\ndata Async : Type -> Type where\n Pure : a -> Async a\n LiftIO : PrimIO a -> Async a\n Asyn : ((a -> PrimIO ()) -> PrimIO ()) -> Async a\n Par : Async (a -> b) -> Async a -> Async b\n Bind : Async a -> (a -> Async b) -> Async b\n\nexport\nFunctor Async where\n map f (Pure x) = Pure $ f x\n map f (LiftIO g) = LiftIO $ \\w => let MkIORes x w' = g w in MkIORes (f x) w'\n map f (Asyn g) = Asyn $ \\k, w => g (\\x, w' => k (f x) w') w\n map f (Par mf mx) = Par (map (f .) mf) mx\n map f (Bind mx g) = Bind mx $ \\x => map f $ g x\n\nexport\nApplicative Async where\n pure = Pure\n mf <*> mx = Bind mf $ \\f => map f mx\n\nexport\n[Parallel] Applicative Async where\n pure = Pure\n (<*>) = Par\n\nexport\nMonad Async where\n (>>=) = Bind\n\nexport\nHasIO Async where\n liftIO act = LiftIO (toPrim act)\n\nexport %inline\nparallel : Traversable t => t (Async a) -> Async (t a)\nparallel = sequence @{Parallel}\n\nexport %inline\nparallelMap : Traversable t => (a -> Async b) -> t a -> Async (t b)\nparallelMap = traverse @{%search} @{Parallel}\n\nexport %inline\nprim__async : ((a -> PrimIO ()) -> PrimIO ()) -> Async a\nprim__async = Asyn\n\nexport %inline\nasync : ((a -> IO ()) -> IO ()) -> Async a\nasync f = prim__async (\\k, w => toPrim (f (\\x => fromPrim (k x))) w)\n\ndata Promise : Type -> Type where [external]\n\n%foreign \"javascript:support:pure,async\"\npromise__pure : {0 a : _} -> a -> PrimIO (Promise a)\n\n%foreign \"javascript:support:liftIO,async\"\npromise__liftIO : {0 a : _} -> PrimIO a -> PrimIO (Promise a)\n\n%foreign \"javascript:support:async,async\"\npromise__async : {0 a : _} -> ((a -> PrimIO ()) -> PrimIO ()) -> PrimIO (Promise a)\n\n%foreign \"javascript:support:par_app,async\"\npromise__par_app : {0 a, b : _} -> Promise (a -> b) -> Promise a -> PrimIO (Promise b)\n\n%foreign \"javascript:support:bind,async\"\npromise__bind :{0 a, b : _} -> Promise a -> (a -> PrimIO (Promise b)) -> PrimIO (Promise b)\n\nexport\ntoPromise : Async a -> IO (Promise a)\ntoPromise (Pure x) = fromPrim $ promise__pure x\ntoPromise (LiftIO f) = fromPrim $ promise__liftIO f\ntoPromise (Asyn f) = fromPrim $ promise__async f\ntoPromise (Par x y) = fromPrim $ promise__par_app !(toPromise x) !(toPromise y)\ntoPromise (Bind x f) = fromPrim $ promise__bind !(toPromise x) (\\x => toPrim $ toPromise (f x))\n\nexport\nlaunch : Async a -> IO ()\nlaunch = ignore . toPromise\n", "meta": {"hexsha": "809cbc15e308b8a9dd72a0ce8cc3609b6176d843", "size": 2369, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "Control/JS/Async.idr", "max_stars_repo_name": "Z-snails/idris2-async", "max_stars_repo_head_hexsha": "c2e5c80e038f0fbe5faf9be4d7e320a8ae15446d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-11-15T12:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T23:51:09.000Z", "max_issues_repo_path": "Control/JS/Async.idr", "max_issues_repo_name": "Z-snails/idris2-async", "max_issues_repo_head_hexsha": "c2e5c80e038f0fbe5faf9be4d7e320a8ae15446d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Control/JS/Async.idr", "max_forks_repo_name": "Z-snails/idris2-async", "max_forks_repo_head_hexsha": "c2e5c80e038f0fbe5faf9be4d7e320a8ae15446d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-16T16:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T16:45:20.000Z", "avg_line_length": 29.2469135802, "max_line_length": 95, "alphanum_fraction": 0.6209371043, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2465660590056481}} |
| {"text": "module Dimp\n\nimport Data.Vect\n\nimport Assn\nimport Expr\nimport Hoare\nimport Imp\nimport Maps\n\n-- %hide Assn.(->>)\n\n%access public export\n\n%default total\n\ndata DCom : Type where\n DCSkip : Assertion -> DCom\n DCSeq : DCom -> DCom -> DCom\n DCAss : Id -> AExp -> Assertion -> DCom\n DCIf : BExp -> Assertion -> DCom -> Assertion -> DCom -> Assertion -> DCom\n DCWhile : BExp -> Assertion -> DCom -> Assertion -> DCom\n DCPre : Assertion -> DCom -> DCom\n DCPost : DCom -> Assertion -> DCom\n\ndata Decorated : Type where\n Decorate : Assertion -> DCom -> Decorated\n\nSKIP : Vect 1 Assertion -> DCom\nSKIP [p] = DCSkip p\n\nsyntax [x] \"::=\" [a] \"[\" [p] \"]\" = DCAss x a p\n\nsyntax IF [b] THEN \"[\" [pThen] \"]\" [dt] ELSE \"[\" [pElse] \"]\" [df] END \"[\" [pIf] \"]\" = DCIf b pThen dt pElse df pIf\n\nsyntax WHILE [b] DO \"[\" [pBody] \"]\" [d] END \"[\" [pPost] \"]\" = DCWhile b pBody d pPost\n\nsyntax \"->>\" \"[\" [p] \"]\" [d] = DCPre p d\n\n(->>) : DCom -> Vect 1 Assertion -> DCom\nd ->> [p] = DCPost d p\n\n(>>=) : DCom -> (() -> DCom) -> DCom\n(>>=) c f = DCSeq c (f ())\n\nsyntax \"[\" [p] \"]\" [d] = Decorate p d\n\ndec0 : DCom\ndec0 = SKIP [const ()]\n\ndec1 : DCom\ndec1 = WHILE BTrue DO [const ()] SKIP [const ()] END [const ()]\n\ndec_while : Decorated\ndec_while =\n ([const ()]\n WHILE not (X == 0) DO\n [\\st => ((), Not (st X = 0))]\n DCAss X (X - 1)\n (const ())\n END\n [\\st => ((), st X = 0)] ->>\n [\\st => st X = 0])\n\nextract : DCom -> Com\nextract (DCSkip _) = CSkip\nextract (DCSeq d1 d2) = CSeq (extract d1) (extract d2)\nextract (DCAss x e _) = CAss x e\nextract (DCIf b _ dt _ df _) = CIf b (extract dt) (extract df)\nextract (DCWhile b _ d _) = CWhile b (extract d)\nextract (DCPre _ d) = extract d\nextract (DCPost d _) = extract d\n\nextract_dec : Decorated -> Com\nextract_dec (Decorate _ d) = extract d\n\npost : DCom -> Assertion\npost (DCSkip p) = p\npost (DCSeq _ d2) = post d2\npost (DCAss _ _ p) = p\npost (DCIf _ _ _ _ _ p) = p\npost (DCWhile _ _ _ p) = p\npost (DCPre _ d) = post d\npost (DCPost _ p) = p\n\npre_dec : Decorated -> Assertion\npre_dec (Decorate p _) = p\n\npost_dec : Decorated -> Assertion\npost_dec (Decorate _ d) = post d\n\nDecCorrect : (dec : Decorated) -> Type\nDecCorrect dec = HoareTriple (pre_dec dec) (extract_dec dec) (post_dec dec)\n\nVerificationConditions : (p : Assertion) -> (d : DCom) -> Type\nVerificationConditions p (DCSkip q) = p ->> q\nVerificationConditions p (DCSeq d1 d2) =\n ( VerificationConditions p d1\n , VerificationConditions (post d1) d2 )\nVerificationConditions p (DCAss x a q) = p ->> AssignSub x a q\nVerificationConditions p (DCIf b pt dt pf df q) =\n ( (\\st => (p st, BAssn b st)) ->> pt\n , (\\st => (p st, Not (BAssn b st))) ->> pf\n , post dt ->> q, post df ->> q\n , VerificationConditions pt dt\n , VerificationConditions pf df )\nVerificationConditions p (DCWhile b pBody d q) =\n ( p ->> post d\n , (\\st => (post d st, BAssn b st)) ->> pBody\n , (\\st => (post d st, Not (BAssn b st))) ->> q\n , VerificationConditions pBody d )\nVerificationConditions p (DCPre p' d) = (p ->> p', VerificationConditions p' d)\nVerificationConditions p (DCPost d q) =\n (VerificationConditions p d, post d ->> q)\n\nverification_correct : (d : DCom) -> (p : Assertion) ->\n VerificationConditions p d ->\n HoareTriple p (extract d) (post d)\nverification_correct (DCSkip q) p vc st _ E_Skip p_st = vc st p_st\nverification_correct (DCSeq d1 d2) p (vc1, vc2) st st' (E_Seq {st2} c1 c2) p_st =\n let post_d1_st2 = verification_correct d1 p vc1 st st2 c1 p_st\n in verification_correct d2 (post d1) vc2 st2 st' c2 post_d1_st2\nverification_correct (DCAss x e q) p vc st _ (E_Ass prf) p_st =\n rewrite sym prf in vc st p_st\nverification_correct (DCIf b pt dt pf df q) p\n (p_pt_imp, p_pf_imp, pt_q_imp, pf_q_imp, vc_pt_dt, vc_pf_df)\n st st' (E_IfTrue prf ct) p_st =\n let pt_st = p_pt_imp st (p_st, prf)\n post_dt_st' = verification_correct dt pt vc_pt_dt st st' ct pt_st\n in pt_q_imp st' post_dt_st'\nverification_correct (DCIf b pt dt pf df q) p\n (p_pt_imp, p_pf_imp, pt_q_imp, pf_q_imp, vc_pt_dt, vc_pf_df)\n st st' (E_IfFalse prf cf) p_st =\n let pf_st = p_pf_imp st (p_st, bexp_eval_false prf)\n post_df_st' = verification_correct df pf vc_pf_df st st' cf pf_st\n in pf_q_imp st' post_df_st'\nverification_correct (DCWhile b pd d q) p (p_d_imp, d_pd_imp, d_q_imp, vc_pd_d)\n st _ (E_WhileEnd prf) p_st =\n d_q_imp st (p_d_imp st p_st, bexp_eval_false prf)\nverification_correct w@(DCWhile b pd d q) p (p_d_imp, d_pd_imp, d_q_imp, vc_pd_d)\n st st' (E_WhileLoop {st1} prf cbody cnext) p_st =\n let pd_st = d_pd_imp st (p_d_imp st p_st, prf)\n d_st1 = verification_correct d pd vc_pd_d st st1 cbody pd_st\n in verification_correct\n w\n (post d)\n (\\_, d_st2 => d_st2, d_pd_imp, d_q_imp, vc_pd_d)\n st1\n st'\n cnext\n d_st1\nverification_correct (DCPre p' d) p (imp, vc) st st' rel p_st =\n verification_correct d p' vc st st' rel (imp st p_st)\nverification_correct (DCPost d q) p (vc, imp) st st' rel p_st =\n imp st' (verification_correct d p vc st st' rel p_st)\n\nVerificationConditionsDec : Decorated -> Type\nVerificationConditionsDec (Decorate p d) = VerificationConditions p d\n\nverification_correct_dec : (dec : Decorated) -> VerificationConditionsDec dec ->\n DecCorrect dec\nverification_correct_dec (Decorate p d) vc = verification_correct d p vc\n", "meta": {"hexsha": "06132819803c2303d4a5c47dbe125ca7436b7f6f", "size": 5474, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "Dimp.idr", "max_stars_repo_name": "minhnhdo/programming-language-foundations-in-idris", "max_stars_repo_head_hexsha": "0881c34307afa8c90cda2290bf72910be4a1ea57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dimp.idr", "max_issues_repo_name": "minhnhdo/programming-language-foundations-in-idris", "max_issues_repo_head_hexsha": "0881c34307afa8c90cda2290bf72910be4a1ea57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dimp.idr", "max_forks_repo_name": "minhnhdo/programming-language-foundations-in-idris", "max_forks_repo_head_hexsha": "0881c34307afa8c90cda2290bf72910be4a1ea57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5828220859, "max_line_length": 114, "alphanum_fraction": 0.6324442821, "num_tokens": 1809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24604901585646127}} |
| {"text": "module ZiriaCont\n\n\ndata FreerCont : (f : Type -> Type) -> Type -> Type where\n Cont : ({r : Type} -> (a -> r) -> ({x : Type} -> f x -> (x -> r) -> r) -> r) -> FreerCont f a\n\nreturn : a -> FreerCont f a\nreturn x = Cont (\\k, _ => k x)\n\n(>>=) : FreerCont f a -> (a -> FreerCont f b) -> FreerCont f b\n(>>=) (Cont g) f = Cont (\\k, imp => g (\\x => let (Cont g') = f x in g' k imp) imp)\n\ndata Zir : (i : Type) -> (o : Type) -> (v : Type) -> Type where\n Yield : o -> Zir i o ()\n NeedInput : Zir i o i\n\nemit : o -> FreerCont (Zir i o) ()\nemit o = Cont (\\k, imp => imp (Yield o) k)\n\ntake : FreerCont (Zir i o) i\ntake = Cont (\\k, imp => imp NeedInput k)\n\ndata Rec : (x : Type) -> (r : Type) -> Type where\n K : ((x -> Rec x r -> r) -> r) -> Rec x r\n\ngImp : ({y : Type} -> Zir i o y -> (y -> r) -> r) -> Zir m o x -> (x -> Rec m r -> r) -> Rec m r -> r\ngImp imp (Yield ot) k rec = imp (Yield ot) (\\() => k () rec)\ngImp imp NeedInput k (K k') = k' k\n\nfImp : ({y : Type} -> Zir i o y -> (y -> r) -> r) -> Zir i m x -> (x -> (m -> Rec m r -> r) -> r) -> (m -> Rec m r -> r) -> r\nfImp imp (Yield ot) k k' = k' ot (K (k ()))\nfImp imp NeedInput k k' = imp NeedInput (\\i => k i k')\n\ninfixl 9 >>>\n(>>>) : FreerCont (Zir i m) v -> FreerCont (Zir m o) v -> FreerCont (Zir i o) v\n(>>>) (Cont f) (Cont g) = Cont (\\k, imp => let g' = g (\\x, _ => k x) (gImp imp) in\n let f' = f (\\x, _ => k x) (fImp imp) in\n g' (K f'))\n\n\nimp : Zir i o x -> (x -> Stream i -> (v, List o)) -> Stream i -> (v, List o)\nimp (Yield x) k xs = let (v, xs') = k () xs in (v, x :: xs')\nimp NeedInput k (x :: xs) = k x xs\n\nrun : FreerCont (Zir i o) v -> Stream i -> (v, List o)\nrun (Cont f) = f k imp\n where\n k : v -> Stream i -> (v, List o)\n k x _ = (x, [])\n\n\nexample : FreerCont (Zir Int Int) Int\nexample = do x <- take\n emit (x + 1)\n y <- take\n emit (y + 2)\n return (x + y)\n\ntest : (Int, List Int)\ntest = run example [1..]\n\nstream1 : FreerCont (Zir Int Int) Int\nstream1 = do emit 1\n emit 2\n return 41\n\nstream2 : FreerCont (Zir Int Int) Int\nstream2 = do x <- take\n y <- take\n emit (x + y)\n return 42\n\ntest' : (Int, List Int)\ntest' = run (stream1 >>> stream2) [1..]\n", "meta": {"hexsha": "5166665976dcdfe61c938b0f659e819edaf5eb43", "size": 2313, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/ZiriaCont.idr", "max_stars_repo_name": "STELIORD/idris-snippets", "max_stars_repo_head_hexsha": "f5ca6fa86370d24587040af9871ae850bbc630c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-11-21T22:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T18:25:18.000Z", "max_issues_repo_path": "src/ZiriaCont.idr", "max_issues_repo_name": "stjordanis/idris-snippets", "max_issues_repo_head_hexsha": "d92734b8624ae27be21a63fcb041077b38eaaecb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ZiriaCont.idr", "max_forks_repo_name": "stjordanis/idris-snippets", "max_forks_repo_head_hexsha": "d92734b8624ae27be21a63fcb041077b38eaaecb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-06T13:39:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T15:39:16.000Z", "avg_line_length": 30.84, "max_line_length": 126, "alphanum_fraction": 0.4595763078, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2453118435562797}} |
| {"text": "||| This module contains an adaptation of the session description language as presented in:\n|||\n||| <https://dblp.uni-trier.de/rec/html/journals/corr/abs-1904-01288>\n|||\n||| This implementation differs from the original in that recursive\n||| calls and calling of subprograms are achieved using standard idris\n||| constructs. To support his natively in resources, one will need to\n||| introduce new primitives. As described in the `Resources` paper,\n||| however, this requires that now means to reason about the\n||| interaction between the type-level state of the caller and callee\n||| programs. It would not be correct to assume anything about said\n||| interaction with the framework in its current form.\n|||\n||| Furthermore, as described in the `Resources` paper, there is no\n||| handler program to provide projection capabilities.\nmodule Example.Sessions\n\nimport Data.List\n\nimport Resources\n\n%access public export\n%default total\n\n{- [ Actors]\n\nHere we define actors/roles in a session description, ensuring that we have a means to compare them.\n\n-}\ndata Actor = MkActor String\n\nEq Actor where\n (==) (MkActor a) (MkActor b) = a == b\n\nactorNotEqual : ((x = y) -> Void) -> (MkActor x = MkActor y) -> Void\nactorNotEqual f Refl = f Refl\n\nactorDecEq : (x,y : Actor) -> Dec (x = y)\nactorDecEq (MkActor x) (MkActor y) with (decEq x y)\n actorDecEq (MkActor y) (MkActor y) | (Yes Refl) = Yes Refl\n actorDecEq (MkActor x) (MkActor y) | (No contra) = No (actorNotEqual contra)\n\nDecEq Actor where\n decEq = actorDecEq\n\nOrd Actor where\n compare (MkActor a) (MkActor b) = compare a b\n\n-- Here we describe our type-level states.\nnamespace TypeLevel\n\n ||| Channels are born free until they are bound.\n data Usage = Free | Bound\n\n ||| Variables in Sessions are either paired actors, or data types.\n data Ty = CHAN (Actor, Actor) | DATA Type\n\n namespace State\n\n ||| A channel's state is it's usage.\n record ChanState where\n constructor MkChanState\n usage : Usage\n\n ||| A data types state is the type of message and who has seen the message.\n record DataState where\n constructor MkDataState\n knownBy : List Actor\n type : Type\n\n ||| A mapping between variable types and their abstract state.\n CalcStateType : Ty -> Type\n CalcStateType (CHAN _) = ChanState\n CalcStateType (DATA _) = DataState\n\n\nnamespace Predicates\n\n ||| A predicate to state that all the listed actors are aware of the data item.\n |||\n ||| @actors The actors who know about the item.\n ||| @var The item the actors know about.\n ||| @item The abstract state associated with the item.\n data AllKnow : (actors : List Actor)\n -> (var : Var Ty (DATA type))\n -> (item : StateItem Ty CalcStateType (DATA type))\n -> Type\n where\n NilKnows : (prf : Elem x actors)\n -> AllKnow [x] msg (MkStateItem (DATA type) msg (MkDataState actors type))\n ConsKnows : (prf : Elem x actors)\n -> (later : AllKnow xs msg (MkStateItem (DATA type) msg (MkDataState actors type)))\n -> AllKnow (x::xs) msg (MkStateItem (DATA type) msg (MkDataState actors type))\n\n ||| A predicate to state that the given actor knows about the provided data item.\n |||\n ||| @actor The actor who knows about the item.\n ||| @var The item the actors know about.\n ||| @item The abstract state associated with the item.\n data KnowsData : (actor : Actor)\n -> (var : Var Ty (DATA type))\n -> (item : StateItem Ty CalcStateType (DATA type))\n -> Type\n where\n DoesKnow : (prf : x = y)\n -> (prfE : Elem x actors)\n -> KnowsData y var (MkStateItem (DATA type) var (MkDataState actors type))\n\n ||| A type-level function to record that a particular message has been used by an actor.\n ExpandWhoKnows : (newActor : Actor)\n -> (oldState : StateItem Ty CalcStateType (DATA type))\n -> (prfState : KnowsData sender label oldState)\n -> StateItem Ty CalcStateType (DATA type)\n ExpandWhoKnows newActor (MkStateItem (DATA type) label (MkDataState actors type)) (DoesKnow Refl prfE) =\n MkStateItem (DATA type) label (MkDataState (newActor::actors) type)\n\n ||| Proof that the given sender and receiver are valid participants in the protocol.\n data AllowedToConnect : (sender, receiver : Actor)\n -> (actors : List Actor)\n -> Type where\n CanConnect : (prfSender : Elem sender actors)\n -> (prfReceiver : Elem receiver actors)\n -> AllowedToConnect sender receiver actors\n\n ||| An assertion that the given channel has the given state.\n data ChannelHasState : (assumedState : Usage)\n -> (chan : Var Ty (CHAN (s,r)))\n -> (actual : StateItem Ty CalcStateType (CHAN (s,r)))\n -> Type\n where\n YesChanHasState : ChannelHasState state chan (MkStateItem (CHAN (s,r)) chan (MkChanState state))\n\n ||| A type-level function to set a channel's state.\n SetChannelState : (newState : Usage)\n -> (oldState : StateItem Ty CalcStateType (CHAN (s,r)))\n -> (prfState : ChannelHasState oldState' var oldState)\n -> StateItem Ty CalcStateType (CHAN (s,r))\n SetChannelState newState (MkStateItem (CHAN (s,r)) var (MkChanState oldState')) YesChanHasState = MkStateItem (CHAN (s,r)) var (MkChanState newState)\n\n ||| A predicate to describe valid end states for data and connections.\n data EndState : (ty : Ty) -> StateItem Ty CalcStateType ty -> Type where\n ||| We do not care.\n EndData : EndState (DATA type) state\n ||| Connections must be free.\n EndConn : EndState (CHAN (s,r)) (MkStateItem (CHAN (s,r)) lbl (MkChanState Free))\n\n\n||| Our algebraic definition of a Session description language.\ndata Sessions : (participants : List Actor) -> Lang Ty CalcStateType where\n\n ||| Describe that the given actor `a` creates a message of type `type`.\n |||\n ||| We also need proof that the actor is allowed to participate in the description.\n NewData : (a : Actor)\n -> (type : Type)\n -> (prf : Elem a ps)\n -> Sessions ps (Var Ty (DATA type)) old (\\lbl => MkStateItem (DATA type) lbl (MkDataState [a] type) :: old)\n\n ||| Describe that the given actor `a` creates a message that depends on an earlier message that `a` has seen.\n |||\n ||| The resulting message type will be a dependent pair.\n NewDataDep : (a : Actor)\n -> (dep : Var Ty (DATA type))\n -> (prfKnows : InContext (DATA type) (KnowsData a dep) old)\n -> (msgType : (msg : type) -> Type)\n -> Sessions ps (Var Ty (DATA (x ** msgType x)))\n old\n (\\lbl => MkStateItem (DATA (x ** msgType x))\n lbl\n (MkDataState [a] (x ** msgType x)) :: old)\n\n ||| Specify a new connection between two valid participants in the session.\n NewConnection : (a,b : Actor)\n -> (prf : AllowedToConnect a b ps)\n -> Sessions ps (Var Ty (CHAN (a,b))) old (\\lbl => MkStateItem (CHAN (a,b)) lbl (MkChanState Bound) :: old)\n\n ||| Close an existing connection.\n EndConnection : (chan : Var Ty (CHAN (a,b)))\n -> (prf : InContext (CHAN (a,b)) (ChannelHasState Bound chan) old)\n -> Sessions ps () old (const $ update old prf (SetChannelState Free))\n\n ||| Send a message that the channel sender knows about (either created or received) to the receiver on the given active channel.\n SendLeft : (chan : Var Ty (CHAN (s,r)))\n -> (msg : Var Ty (DATA type))\n -> (prfActive : InContext (CHAN (s,r)) (ChannelHasState Bound chan) old)\n -> (prfKnows : InContext (DATA type) (KnowsData s msg) old)\n -> Sessions ps () old (const $ update old prfKnows (ExpandWhoKnows r))\n\n ||| Send a message that the receiver on the channel knows about (either created or received) to the sending end on the given active channel.\n SendRight : (chan : Var Ty (CHAN (s,r)))\n -> (msg : Var Ty (DATA type))\n -> (prfActive : InContext (CHAN (s,r)) (ChannelHasState Bound chan) old)\n -> (prfKnows : InContext (DATA type) (KnowsData r msg) old)\n -> Sessions ps () old (const $ update old prfKnows (ExpandWhoKnows s))\n\n ||| If all actors in the session have seen the data then we can access the message's value and depend on it.\n ReadMsg : (msg : Var Ty (DATA type))\n -> (prf : InContext (DATA type) (AllKnow ps msg) old)\n -> Sessions ps type old (const old)\n\n ||| End the session description if all the variables are in the correct end state.\n |||\n ||| This is our check that all channels have been closed.\n StopSession : AllContext EndState old -> Sessions ps () old (const Nil)\n\n{- [ NOTE ]\n\nHere we define the language and high-level friendly API.\n\n-}\n||| Define the `SESSIONS` language.\nSESSIONS : (ps : List Actor) -> LANG Ty CalcStateType\nSESSIONS ps = MkLang Ty CalcStateType (Sessions ps)\n\n||| Define a closed session.\nSession : (m : Type -> Type) -> List Actor -> Type\nSession m ps = LangM m () (SESSIONS ps) Nil (const Nil)\n\n||| Describe that the given actor `a` creates a message of type `type`.\n|||\n||| We also need proof that the actor is allowed to participate in the description.\nmsg : (creator : Actor)\n -> (type : Type)\n -> {auto prf : Elem creator actors}\n -> LangM m (Var Ty (DATA type)) (SESSIONS actors) old (\\lbl => MkStateItem (DATA type) lbl (MkDataState ([creator]) type) :: old)\nmsg creator type {prf} = Expr $ NewData creator type prf\n\n||| Describe that the given actor `a` creates a message that depends on an earlier message that `a` has seen.\n|||\n||| The resulting message type will be a dependent pair.\nmsgDep : (creator : Actor)\n -> (dep : Var Ty (DATA type))\n -> {auto prfKnows : InContext (DATA type) (KnowsData creator dep) old}\n -> (msgType : (msg : type) -> Type)\n -> LangM m\n (Var Ty (DATA (x ** msgType x)))\n (SESSIONS actors)\n old\n (\\lbl => MkStateItem (DATA (x ** msgType x))\n lbl\n (MkDataState [creator] (x ** msgType x)) :: old)\nmsgDep creator dep {prfKnows} msgType = Expr (NewDataDep creator dep prfKnows msgType)\n\n||| If all actors in the session have seen the data then we can access the message's value and depend on it.\nread : (msg : Var Ty (DATA type))\n -> {auto prf : InContext (DATA type) (AllKnow actors msg) old}\n -> LangM m type (SESSIONS actors) old (const old)\nread msg {prf} = Expr $ ReadMsg msg prf\n\n||| End the session description if all the variables are in the correct end state.\n|||\n||| This is our check that all channels have been closed.\nend : {auto prf : AllContext EndState old} -> LangM m () (SESSIONS actors) old (const Nil)\nend {prf} = Expr $ StopSession prf\n\n||| Specify a new connection between two valid participants in the session.\nsetup : (a, b : Actor)\n -> {auto prf : AllowedToConnect a b actors}\n -> LangM m (Var Ty (CHAN (a,b))) (SESSIONS actors) old (\\lbl => MkStateItem (CHAN (a,b)) lbl (MkChanState Bound) :: old)\nsetup sender receiver {prf} = Expr $ NewConnection sender receiver prf\n\n||| Close an existing connection.\ndestroy : (chan : Var Ty (CHAN (a,b)))\n -> {auto prf : InContext (CHAN (a,b)) (ChannelHasState Bound chan) old}\n -> LangM m () (SESSIONS actors) old (const $ update old prf (SetChannelState Free))\ndestroy chan {prf} = Expr $ EndConnection chan prf\n\n||| Send a message that the channel sender knows about (either created or received) to the receiver on the given active channel.\nsendLeft : (chan : Var Ty (CHAN (s,r)))\n -> (msg : Var Ty (DATA type))\n -> {auto prfActive : InContext (CHAN (s,r)) (ChannelHasState Bound chan) old}\n -> {auto prfKnows : InContext (DATA type) (KnowsData s msg) old}\n -> LangM m () (SESSIONS actors) old (const $ update old prfKnows (ExpandWhoKnows r))\nsendLeft chan msg {prfActive} {prfKnows} = Expr (SendLeft chan msg prfActive prfKnows)\n\n||| Send a message that the receiver on the channel knows about (either created or received) to the sending end on the given active channel.\nsendRight : (chan : Var Ty (CHAN (s,r)))\n -> (msg : Var Ty (DATA type))\n -> {auto prfActive : InContext (CHAN (s,r)) (ChannelHasState Bound chan) old}\n -> {auto prfKnows : InContext (DATA type) (KnowsData r msg) old}\n -> LangM m () (SESSIONS actors) old (const $ update old prfKnows (ExpandWhoKnows s))\nsendRight chan msg {prfActive} {prfKnows} = Expr (SendRight chan msg prfActive prfKnows)\n\n{- [ NOTE ]\n\nLet's define some actors.\n\n-}\n\nAlice : Actor\nAlice = MkActor \"A\"\n\nBob : Actor\nBob = MkActor \"B\"\n\nCharlie : Actor\nCharlie = MkActor \"C\"\n\n{- [ NOTE ]\n\nHere we define a value dependent version of the well known TCP Handshake.\n\nDependent pairs are used to ensure that the sequence numbers sent are the ones previously seen.\n\nThere are better ways to encode this, see the PLACES paper linked in the module's documentation.\n\n-}\n\ndata Packet\n\nTCPHandshake : Session m [Alice, Bob]\nTCPHandshake = do\n chan <- setup Alice Bob\n\n m1 <- msg Alice (Packet, Nat)\n sendLeft chan m1\n\n (p,x) <- read m1\n m2 <- msg Bob (Packet, (x' ** x' = x), Nat)\n\n sendRight chan m2\n\n (p,xplus,y) <- read m2\n\n m3 <- msg Alice (Packet, (x' ** x' = x), (y' ** y' = y))\n sendLeft chan m3\n destroy chan\n end\n\n\n{- [ NOTE ]\n\nHere we define a PingPong protocol. In which Alice sends a Ping to Bob who responds with a Pong, and proof that they send a pong, and calls the session description again. If alice sent a Pong then the session ends.\n\nThis is *a* encoding, there are probably better ways to encode this.\n\n-}\ndata PingPong = Ping | Pong\n\npingNotPong : (Ping = Pong) -> Void\npingNotPong Refl impossible\n\nDecEq PingPong where\n decEq Ping Ping = Yes Refl\n decEq Pong Pong = Yes Refl\n decEq Ping Pong = No pingNotPong\n decEq Pong Ping = No (negEqSym pingNotPong)\n\nRfcPingPong : Session m [Alice, Bob]\nRfcPingPong = do chan <- setup Alice Bob\n val <- msg Alice PingPong\n sendLeft chan val\n res <- read val\n case res of\n Pong => do destroy chan\n end\n Ping => do val' <- msg Bob (x : PingPong ** x = Pong)\n sendRight chan val'\n destroy chan\n end\n assert_total $ RfcPingPong\n\n{- [ NOTE ]\n\nHere we define a simple varient of the Echo protocol that uses an optional type to act as a quit message in the Empty case.\n\n-}\nEcho : Session m [Alice, Bob]\nEcho {m} = do chan <- setup Alice Bob\n val <- msg Alice (Maybe String)\n sendLeft chan val\n res <- read val\n case res of\n Nothing => do destroy chan\n end\n Just _ => do sendRight chan val\n destroy chan\n end\n assert_total $ Echo {m=m}\n\n{- [ NOTE ]\n\nHere we define a simple Higher-Order-Protocol that emulates an authentication step using a Boolean.\n\n-}\n\nhoppy : Session m [Alice, Bob]\n -> Session m [Alice, Bob]\nhoppy p = do chan <- setup Alice Bob\n val <- msg Alice String\n sendLeft chan val\n resp <- msg Bob Bool\n sendRight chan resp\n res <- read resp\n case res of\n False => do destroy chan\n end\n True => do destroy chan\n end\n p\n\n-- --------------------------------------------------------------------- [ EOF ]\n", "meta": {"hexsha": "647431a8c063df1f21babc8f083394831d92a3c6", "size": 16003, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "Example/Sessions.idr", "max_stars_repo_name": "border-patrol/resources", "max_stars_repo_head_hexsha": "930a1c4be75ca800340a7dc7c6b4e6a095d95e8d", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-13T05:32:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T07:10:09.000Z", "max_issues_repo_path": "Example/Sessions.idr", "max_issues_repo_name": "border-patrol/resources", "max_issues_repo_head_hexsha": "930a1c4be75ca800340a7dc7c6b4e6a095d95e8d", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Example/Sessions.idr", "max_forks_repo_name": "border-patrol/resources", "max_forks_repo_head_hexsha": "930a1c4be75ca800340a7dc7c6b4e6a095d95e8d", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7096774194, "max_line_length": 214, "alphanum_fraction": 0.6141348497, "num_tokens": 4154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24512061337500554}} |
| {"text": "module Circuits.NetList.Linear.Interp\n\nimport Decidable.Equality\n\nimport Data.Nat\nimport Data.Fin\nimport Data.List.Elem\nimport Data.List.Quantifiers\n\nimport Toolkit.Decidable.Informative\n\nimport Toolkit.Data.Graph.EdgeBounded\nimport Toolkit.Data.Graph.EdgeBounded.HasExactDegree.All\n\nimport Toolkit.Data.Whole\nimport Toolkit.Data.List.DeBruijn\n\nimport Circuits.NetList.Types\n\nimport Circuits.NetList.Linear.Usage\nimport Circuits.NetList.Linear.Terms\n\n%default total\n\npublic export\nInterpTy : Ty -> Type\nInterpTy TyUnit\n = Unit\n\nInterpTy (TyPort x)\n = Vertex String\n\nInterpTy (TyChan x)\n = Pair (Vertex String) (Vertex String)\n\nInterpTy TyGate\n = Graph String\n\n\nselect : Project dir -> Vertex a -> Vertex a -> Vertex a\nselect WRITE y z = y\nselect READ y z = z\n\nnamespace Environments\n\n public export\n data Env : List Item -> Type where\n Empty : Env Nil\n Extend : (term : InterpTy type)\n -> (env : Env rest)\n -> Env (I type usage :: rest)\n\n\n namespace Port\n\n export\n lookup : (env : Env this)\n -> (prf : IsFreePort (I (TyPort (flow,type)) u) this)\n -> (use : UsePort this prf that)\n -> (Env that, InterpTy (TyPort (flow,type)))\n lookup (Extend term rest) (FreePortHere pf) (UsePortHere use)\n = (Extend term rest, term)\n\n lookup (Extend not_term env) (FreePortThere rest) (UsePortThere later) with (lookup env rest later)\n lookup (Extend not_term env) (FreePortThere rest) (UsePortThere later) | (new, term)\n = (Extend not_term new, term)\n\n namespace Project\n\n export\n lookup : (env : Env this)\n -> (prf : IsFreeChannel how (I (TyChan type) (TyChan ein eout)) this)\n -> (use : ProjectChannel how this prf that)\n -> (Env that, InterpTy (TyChan type))\n lookup (Extend term env) (FreeChannelHere prf) (ProjectHere use)\n = (Extend term env, term)\n\n lookup (Extend not_term env) (FreeChannelThere rest) (ProjectThere later) with (lookup env rest later)\n lookup (Extend not_term env) (FreeChannelThere rest) (ProjectThere later) | (new, term)\n = (Extend not_term new, term)\n\n namespace Index\n\n export\n lookup : (env : Env this)\n -> (prf : CanIndexPort idx (I (TyPort (flow, BVECT (W (S n) ItIsSucc) type)) u) this)\n -> (use : IndexPort idx this prf that)\n -> (Env that, InterpTy (TyPort (flow, type)))\n lookup (Extend term env) (CanIndexHere prf) (IndexHere use)\n = (Extend term env, term)\n\n lookup (Extend not_term env) (CanIndexThere rest) (IndexThere later) with (lookup env rest later)\n lookup (Extend not_term env) (CanIndexThere rest) (IndexThere later) | (new, term)\n = (Extend not_term new, term)\n\nnamespace Result\n\n public export\n data Result : (context : List Item)\n -> (type : Ty)\n -> Type\n where\n R : (counter : Nat)\n -> (env : Env new)\n -> (graph : Graph String)\n -> (result : InterpTy type)\n -> Result new type\n\n public export\n getResult : Result ctxt type -> InterpTy type\n getResult (R counter env g result) = result\n\n public export\n data GetGraph : (res : Result.Result ctxt type) -> Graph String -> Type\n where\n G : (g : Graph String) -> GetGraph (R c e g r) g\n\n public export\n getGraph : (r : Result.Result ctxt type) -> DPair (Graph String) (GetGraph r)\n getGraph (R counter env graph result) = MkDPair graph (G graph)\n\n\ninterp : (env : Env this)\n -> (counter : Nat)\n -> (graph : Graph String)\n -> (term : Term this type that)\n -> Result that type\n\n-- [ NOTE ]\n--\n-- As normal\ninterp e c g (VarPort prf use)\n\n = let (new, ret) = lookup e prf use\n in R c new g ret\n\n-- [ NOTE ]\n--\n-- Ports are leaf nodes in the graph.\ninterp e c g (Port flow dtype (FP u prf) body)\n = let c1 = S c\n in let v = vertexFromFlow flow c1 (size dtype)\n\n in let R e1 c2 g1 MkUnit = interp (Extend v e)\n c1\n (insertNode v g)\n body\n in R e1 c2 g1 MkUnit\n\n where\n vertexFromFlow : Direction -> Nat -> Nat -> Vertex String\n vertexFromFlow INPUT = driver (\"INPUT : \" <+> show dtype )\n vertexFromFlow OUTPUT = catcher (\"OUTPUT : \" <+> show dtype )\n vertexFromFlow INOUT = gateway (\"INOUT : \" <+> show dtype )\n\n\ninterp e c g (Wire dtype (FC u prf) body)\n = let c1 = S c\n in let c2 = S c1\n\n in let s = size dtype\n\n in let chanIN = node (\"CHAN_IN : \" <+> show dtype) c1 s 1\n in let chanOUT = node (\"CHAN_OUT : \" <+> show dtype) c2 1 s\n\n in let R e1 c3 g2 MkUnit = interp (Extend (chanIN, chanOUT) e)\n c2\n (updateWith g [chanIN, chanOUT]\n [MkPair (ident chanIN) (ident chanOUT)])\n body\n in R e1 c3 g2 MkUnit\n\n\ninterp e c g (Gate gate body)\n = let R c1 e1 g1 res = interp e c g gate\n in interp (Extend res e1) c1 (merge g res) body\n\ninterp e c g (Stop prf)\n = R c Empty g MkUnit\n\n\ninterp e c g (Mux o s l r)\n\n = let c1 = S c\n\n in let mux = node \"MUX\" c1 3 1\n\n in let R c2 e1 g1 vo = interp e c1 g o\n in let R c3 e2 g2 vc = interp e1 c2 g1 s\n in let R c4 e3 g3 vl = interp e2 c2 g2 l\n in let R c5 e4 g4 vr = interp e3 c3 g3 r\n\n in let mg = fromLists [mux]\n [ (ident vl, ident mux)\n , (ident vr, ident mux)\n , (ident vc, ident mux)\n , (ident mux, ident vo)\n ]\n in R c5 e4 g4 mg\n\ninterp e c g (GateU kind o i)\n = let c1 = S c\n\n in let ugate = node (show kind) c1 1 1\n\n in let R c2 e1 g1 vo = interp e c1 g o\n in let R c3 e2 g2 vi = interp e1 c2 g1 i\n\n in R c3 e2 g2\n (fromLists [ugate] [ MkPair (ident vi) (ident ugate)\n , MkPair (ident ugate) (ident vo)\n ])\n\ninterp e c g (GateB kind o l r)\n\n = let c1 = S c\n\n in let bgate = node (show kind) c1 2 1\n\n in let R c2 e1 g1 vo = interp e c1 g o\n in let R c3 e2 g2 vl = interp e1 c2 g1 l\n in let R c4 e3 g3 vr = interp e2 c3 g2 r\n\n in let bg = fromLists [bgate]\n [ MkPair (ident bgate) (ident vo)\n , MkPair (ident vl) (ident bgate)\n , MkPair (ident vr) (ident bgate)\n ]\n\n in R c4 e3 g3 bg\n\ninterp e c g (Split a b i)\n\n = let c1 = S c\n in let s = size LOGIC\n\n in let sVertex = both \"SPLIT\" c1 s\n\n in let R c2 e1 g1 av = interp e c1 g a\n in let R c3 e2 g2 bv = interp e1 c2 g1 b\n in let R c4 e3 g3 iv = interp e2 c3 g2 i\n\n in let esIS = replicate s (MkPair (ident iv) (ident sVertex))\n in let esSA = replicate s (MkPair (ident sVertex) (ident av))\n in let esSB = replicate s (MkPair (ident sVertex) (ident bv))\n\n in R c4 e3\n g3\n (fromLists [av,bv,iv,sVertex]\n (esIS ++ esSA ++ esSB))\n\ninterp e c g (Collect {type} o a b)\n\n = let c1 = S c\n in let s = size type\n\n in let sVertex = both \"COLLECT\" c1 s\n\n in let R c2 e1 g1 ov = interp e c1 g o\n in let R c3 e2 g2 av = interp e1 c2 g1 a\n in let R c4 e3 g3 bv = interp e2 c3 g2 b\n\n in let esAC = replicate s (MkPair (ident av) (ident sVertex))\n in let esBC = replicate s (MkPair (ident bv) (ident sVertex))\n in let esSO = replicate s (MkPair (ident sVertex) (ident ov))\n\n in R c4 e3\n g3\n (fromLists [ov,av,bv,sVertex]\n (esAC ++ esBC ++ esSO))\n\ninterp e c g (Cast cast port)\n = let c1 = S c\n\n in let cVertex = both \"CAST\" c1 1\n\n in let R c2 e1 g1 what = interp e c1 g port\n\n in R c2 e1\n (updateWith g1 [cVertex] [buildEdge cast cVertex what])\n cVertex\n\n where buildEdge : Cast INOUT r -> (a,b : Vertex String) -> Edge\n buildEdge BI a b = MkPair (ident b) (ident a)\n buildEdge BO a b = MkPair (ident a) (ident b)\n\n\ninterp e c g (Project how prf use)\n\n = let (new, (i,o)) = lookup e prf use\n\n in R c new g (selectNode how i o)\n\n where selectNode : Project dir -> Vertex String -> Vertex String -> Vertex String\n selectNode WRITE i _ = i\n selectNode READ _ o = o\n\ninterp e c g (Index dir idx prf use)\n = let c1 = S c\n\n in let idxVertex = both (\"IDX [\" <+> show (finToNat idx) <+> \"](\" <+> show dir <+>\")\" ) c1 1\n\n in let (new,p) = lookup e prf use\n\n in R c1 new (updateWith g [idxVertex]\n (buildEdge dir p idxVertex))\n idxVertex\n where buildEdge : Index direc -> (a,b : Vertex String) -> Edges\n buildEdge (UP x) a b = [MkPair (ident b) (ident a)]\n buildEdge (DOWN x) a b = [MkPair (ident a) (ident b)]\n\npublic export\ndata ValidGraph : Graph type -> Type where\n IsValid : HasExactDegrees vs es\n -> ValidGraph (MkGraph vs es)\n\nexport\nvalidGraph : {type : Type}\n -> (g : Graph type)\n -> DecInfo (HasExactDegree.Error type)\n (ValidGraph g)\nvalidGraph (MkGraph nodes edges) with (hasExactDegrees nodes edges)\n validGraph (MkGraph nodes edges) | (Yes prf)\n = Yes (IsValid prf)\n validGraph (MkGraph nodes edges) | (No msg contra)\n = No msg (\\(IsValid prf) => contra prf)\n\n\npublic export\ndata Valid : (res : Result ctxt TyUnit)\n -> Type\n where\n D : {res : Result ctxt TyUnit}\n -> (g : Graph String)\n -> GetGraph res g\n -> ValidGraph g\n -> Valid res\n\nisValid : (r : Result ctxt TyUnit)\n -> DecInfo (Graph String, HasExactDegree.Error String)\n (Valid r)\nisValid r with (getGraph r)\n isValid (R c e g r) | (MkDPair g (G g)) with (validGraph g)\n isValid (R c e g r) | (MkDPair g (G g)) | (Yes prf)\n = Yes (D g (G g) prf)\n isValid (R c e g r) | (MkDPair g (G g)) | (No msg contra)\n = No (g,msg) (\\(D graph (G graph) prf) => contra prf)\n\npublic export\ndata Run : (term : Term Nil TyUnit Nil) -> Type where\n R : (prf : Valid (interp Empty Z (MkGraph Nil Nil) term))\n -> Run term\n\npublic export\ngetGraph : Run term -> DPair (Graph String) ValidGraph\ngetGraph (R (D g x y)) = MkDPair g y\n\nexport\nrun : (term : Term Nil TyUnit Nil)\n -> DecInfo (Graph String, HasExactDegree.Error String) (Run term)\nrun term with (isValid (interp Empty Z empty term))\n run term | (Yes prf) = Yes (R prf)\n run term | (No msg contra) = No msg (\\(R prf) => contra prf)\n\nexport\nrunIO : (term : Term Nil TyUnit Nil)\n -> IO (Either (Graph String, HasExactDegree.Error String)\n (Run term))\nrunIO term = pure $ (asEither (run term))\n\n-- [ EOF ]\n", "meta": {"hexsha": "12b77da8ca228375e424cecf8485c7e9fe060227", "size": 10925, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Circuits/NetList/Linear/Interp.idr", "max_stars_repo_name": "gallais/linear-circuits", "max_stars_repo_head_hexsha": "5d13d955eafc2d92beae363e96d3cec8695830f2", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Circuits/NetList/Linear/Interp.idr", "max_issues_repo_name": "gallais/linear-circuits", "max_issues_repo_head_hexsha": "5d13d955eafc2d92beae363e96d3cec8695830f2", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Circuits/NetList/Linear/Interp.idr", "max_forks_repo_name": "gallais/linear-circuits", "max_forks_repo_head_hexsha": "5d13d955eafc2d92beae363e96d3cec8695830f2", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3682795699, "max_line_length": 106, "alphanum_fraction": 0.5642105263, "num_tokens": 3260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24395876097908092}} |
| {"text": "module Core.Abstraction\n\nimport General\nimport Core.Variable\nimport Core.Term\nimport Core.ConSig\n\n%access export\n\n-- o8o 8888. oYYYo YY8YY 8YYYo o8o oYYo YY8YY Y8Y _YYY_ 8o 0 oYYYo\n-- 8 8 8___Y %___ 0 8___P 8 8 0 \" 0 0 0 0 8Yo 8 %___\n-- 8YYY8 8\"\"\"o `\"\"\"p 0 8\"\"Yo 8YYY8 0 , 0 0 0 0 8 Yo8 `\"\"\"p\n-- 0 0 8ooo\" YoooY 0 0 0 0 0 YooY 0 o8o \"ooo\" 0 8 YoooY\n\nimplementation Abstract a b c => Abstract a b (Plict,c) where\n\tabstr (plic,x) = MkPair plic <$> abstr x\n\nimplementation (Abstract a b Pattern, Abstract a b Term) => Abstract a b Clause where\n\tabstr (NewClause psc sc) = NewClause <$> abstractScope psc <*> abstractScope sc\n\nimplementation Abstract a b Term => Abstract a b CaseMotive where\n\tabstr (CaseMotiveNil a) = CaseMotiveNil <$> abstr a\n\tabstr (CaseMotiveCons a sc) = CaseMotiveCons <$> abstr a <*> abstractScope sc\n\nimplementation Abstract a b Term => Abstract a b Telescope where\n\tabstr TelescopeNil = pure TelescopeNil\n\tabstr (TelescopeCons t sc) = TelescopeCons <$> abstr t <*> abstractScope sc\n\nmutual\n\timplementation Abstract String Term Term where\n\t\tabstr (Meta i) = pure $ Meta i\n\t\tabstr (Var (Name x)) = asks $ \\e => case SortedMap.lookup x e of\n\t\t\tNothing => Var (Name x)\n\t\t\tJust m => m\n\t\tabstr (Var (Generated x i)) = pure $ Var (Generated x i)\n\t\tabstr (DottedVar m var) = pure $ DottedVar m var\n\t\tabstr (AbsoluteDottedVar m var) = pure $ AbsoluteDottedVar m var\n\t\tabstr (Ann m ty) = Ann <$> abstr m <*> pure ty\n\t\tabstr Star = pure Star\n\t\tabstr (Pi plic a sc) = Pi plic <$> abstr a <*> abstractScope sc\n\t\tabstr (Lam plic sc) = Lam plic <$> abstractScope sc\n\t\tabstr (App plic f a) = App plic <$> abstr f <*> abstr a\n\t\tabstr (Con c as) = Con c <$> Traversable.for as (\\(plic, a) => do a' <- abstr a ; pure (plic,a'))\n\t\tabstr (Case as t cs) = Case <$> traverse abstr as <*> abstr t <*> traverse abstr cs\n\t\tabstr (RecordType tele) = RecordType <$> abstr tele\n\t\tabstr (RecordCon fields) = RecordCon <$> (sequence [ MkPair x <$> abstr m | (x,m) <- fields ])\n\t\tabstr (Project m x) = Project <$> abstr m <*> pure x\n\n\timplementation Abstract String Term Pattern where\n\t\tabstr (VarPat x) = pure $ VarPat x\n\t\tabstr (ConPat c ps) = ConPat c <$> traverse abstr ps\n\t\tabstr (AssertionPat m) = AssertionPat <$> abstr m\n\t\tabstr MakeMeta = pure MakeMeta\n\nmutual\n\timplementation Abstract Int Term Term where\n\t\tabstr (Meta i) = pure $ Meta i\n\t\tabstr (Var (Name x)) = pure $ Var (Name x)\n\t\tabstr (Var (Generated x i)) = asks $ \\e => case SortedMap.lookup i e of\n\t\t\tNothing => Var (Generated x i)\n\t\t\tJust m => m\n\t\tabstr (DottedVar m var) = pure $ DottedVar m var\n\t\tabstr (AbsoluteDottedVar m var) = pure $ AbsoluteDottedVar m var\n\t\tabstr (Ann m ty) = Ann <$> abstr m <*> pure ty\n\t\tabstr Star = pure Star\n\t\tabstr (Pi plic a sc) = Pi plic <$> abstr a <*> abstractScope sc\n\t\tabstr (Lam plic sc) = Lam plic <$> abstractScope sc\n\t\tabstr (App plic f a) = App plic <$> abstr f <*> abstr a\n\t\tabstr (Con c as) = Con c <$> Traversable.for as (\\(plic,a) => do a' <- abstr a ; pure (plic,a'))\n\t\tabstr (Case as t cs) = Case <$> traverse abstr as <*> abstr t <*> traverse abstr cs\n\t\tabstr (RecordType tele) = RecordType <$> abstr tele\n\t\tabstr (RecordCon fields) = RecordCon <$> (sequence [ MkPair x <$> abstr m | (x,m) <- fields ])\n\t\tabstr (Project m x) = Project <$> abstr m <*> pure x\n\n\timplementation Abstract Int Term Pattern where\n\t\tabstr (VarPat x) = pure $ VarPat x\n\t\tabstr (ConPat c ps) = ConPat c <$> traverse abstr ps\n\t\tabstr (AssertionPat m) = AssertionPat <$> abstr m\n\t\tabstr MakeMeta = pure MakeMeta\n\nmutual\n\timplementation Abstract String Variable Term where\n\t\tabstr (Meta i) = pure $ Meta i\n\t\tabstr (Var (Name x)) = asks $ \\e => case SortedMap.lookup x e of\n\t\t\tNothing => Var (Name x)\n\t\t\tJust y => Var y\n\t\tabstr (Var (Generated x i)) = pure $ Var (Generated x i)\n\t\tabstr (DottedVar m var) = pure $ DottedVar m var\n\t\tabstr (AbsoluteDottedVar m var) = pure $ AbsoluteDottedVar m var\n\t\tabstr (Ann m ty) = Ann <$> abstr m <*> pure ty\n\t\tabstr Star = pure Star\n\t\tabstr (Pi plic a sc) = Pi plic <$> abstr a <*> abstractScope sc\n\t\tabstr (Lam plic sc) = Lam plic <$> abstractScope sc\n\t\tabstr (App plic f a) = App plic <$> abstr f <*> abstr a\n\t\tabstr (Con c as) = Con c <$> Traversable.for as (\\(plic,a) => do a' <- abstr a ; pure (plic,a'))\n\t\tabstr (Case as t cs) = Case <$> traverse abstr as <*> abstr t <*> traverse abstr cs\n\t\tabstr (RecordType tele) = RecordType <$> abstr tele\n\t\tabstr (RecordCon fields) = RecordCon <$> (sequence [ MkPair x <$> abstr m | (x,m) <- fields ])\n\t\tabstr (Project m x) = Project <$> abstr m <*> pure x\n\n\timplementation Abstract String Variable Pattern where\n\t\tabstr (VarPat (Name x)) = asks $ \\e => case SortedMap.lookup x e of\n\t\t\tNothing => VarPat (Name x)\n\t\t\tJust y => VarPat y\n\t\tabstr (VarPat (Generated x i)) = pure $ VarPat (Generated x i)\n\t\tabstr (ConPat c ps) = ConPat c <$> traverse abstr ps\n\t\tabstr (AssertionPat m) = AssertionPat <$> abstr m\n\t\tabstr MakeMeta = pure MakeMeta\n\nmutual\n\timplementation Abstract Int Variable Term where\n\t\tabstr (Meta i) = pure $ Meta i\n\t\tabstr (Var (Name x)) = pure $ Var (Name x)\n\t\tabstr (Var (Generated x i)) = asks $ \\e => case SortedMap.lookup i e of\n\t\t\tNothing => Var (Generated x i)\n\t\t\tJust y => Var y\n\t\tabstr (DottedVar m var) = pure $ DottedVar m var\n\t\tabstr (AbsoluteDottedVar m var) = pure $ AbsoluteDottedVar m var\n\t\tabstr (Ann m ty) = Ann <$> abstr m <*> pure ty\n\t\tabstr Star = pure Star\n\t\tabstr (Pi plic a sc) = Pi plic <$> abstr a <*> abstractScope sc\n\t\tabstr (Lam plic sc) = Lam plic <$> abstractScope sc\n\t\tabstr (App plic f a) = App plic <$> abstr f <*> abstr a\n\t\tabstr (Con c as) = Con c <$> Traversable.for as (\\(plic,a) => do a' <- abstr a ; pure (plic,a'))\n\t\tabstr (Case as t cs) = Case <$> traverse abstr as <*> abstr t <*> traverse abstr cs\n\t\tabstr (RecordType tele) = RecordType <$> abstr tele\n\t\tabstr (RecordCon fields) = RecordCon <$> (sequence [ MkPair x <$> abstr m | (x,m) <- fields ])\n\t\tabstr (Project m x) = Project <$> abstr m <*> pure x\n\n\timplementation Abstract Int Variable Pattern where\n\t\tabstr (VarPat (Name x)) = pure $ VarPat (Name x)\n\t\tabstr (VarPat (Generated x i)) = asks $ \\e => case SortedMap.lookup i e of\n\t\t\tNothing => VarPat (Generated x i)\n\t\t\tJust y => VarPat y\n\t\tabstr (ConPat c ps) = ConPat c <$> traverse abstr ps\n\t\tabstr (AssertionPat m) = AssertionPat <$> abstr m\n\t\tabstr MakeMeta = pure MakeMeta\n\n-- 0 0 8YYYY 0 8YYYo 8YYYY 8YYYo oYYYo\n-- 8___8 8___ 0 8___P 8___ 8___P %___\n-- 8\"\"\"8 8\"\"\" 0 8\"\"\" 8\"\"\" 8\"\"Yo `\"\"\"p\n-- 0 0 8oooo 8ooo 0 8oooo 0 0 YoooY\n\npiHelper : Plict -> String -> Term -> Term -> Term\npiHelper plic x a b = Pi plic a (scope [x] b)\n\nlamHelper : Plict -> String -> Term -> Term\nlamHelper plic x b = Lam plic (scope [x] b)\n\nclauseHelper : List Pattern -> List String -> Term -> Clause\nclauseHelper ps xs b = do\n\tlet cleanedXs = fst $ runState (traverse cleanXs xs) 0\n\tlet cleanedPs = fst $ runState (traverse cleanPs ps) 0\n\tNewClause (scope2 xs cleanedXs cleanedPs) (scope (filter isVar xs) b)\nwhere\n\tcleanXs : String -> State Integer String\n\tcleanXs \"_\" = do\n\t\ti <- get\n\t\tput (i + 1)\n\t\tpure $ \"$\" ++ show i\n\tcleanXs x = pure x\n\n\tcleanPs : Pattern -> State Integer Pattern\n\tcleanPs (VarPat (Name \"_\")) = do\n\t\ti <- get\n\t\tput (i + 1)\n\t\tpure $ VarPat (Name (\"$\" ++ show i))\n\tcleanPs (VarPat (Name n)) = pure $ VarPat (Name n)\n\tcleanPs (VarPat (Generated n i)) = pure $ VarPat (Generated n i)\n\tcleanPs (ConPat c ps') = ConPat c <$> traverse (\\(plic,p) => do { p' <- cleanPs p ; pure (plic,p') }) ps'\n\tcleanPs (AssertionPat m) = pure $ AssertionPat m\n\tcleanPs MakeMeta = pure MakeMeta\n\nconsMotiveHelper : String -> Term -> CaseMotive -> CaseMotive\nconsMotiveHelper x a b = CaseMotiveCons a (scope [x] b)\n\ntelescopeHelper : List (String, Term) -> Telescope\ntelescopeHelper [] = TelescopeNil\ntelescopeHelper ((x,t)::xts) = let tele = telescopeHelper xts in TelescopeCons t (scope [x] tele)\n\nimplementation Abstract a Term Term => Abstract a Term (ConSig Term) where\n\tabstr (ConSigNil a) = ConSigNil <$> abstr a\n\tabstr (ConSigCons plic a sc) = ConSigCons plic <$> abstr a <*> abstractScope sc\n\nconSigHelper : List DeclArg -> Term -> ConSig Term\nconSigHelper [] b = ConSigNil b\nconSigHelper (NewDeclArg plic x a :: as) b = ConSigCons plic a (scope [x] (conSigHelper as b))\n", "meta": {"hexsha": "b86ebb9a1d311870927c38446fe709e5bb407da1", "size": 8271, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Core/Abstraction.idr", "max_stars_repo_name": "totalscript/totalscript", "max_stars_repo_head_hexsha": "8923f52bb46173f0ad7b03ac0bdb69ee0c9fd13b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-03-08T10:55:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-06T05:05:33.000Z", "max_issues_repo_path": "src/Core/Abstraction.idr", "max_issues_repo_name": "totalscript/totalscript", "max_issues_repo_head_hexsha": "8923f52bb46173f0ad7b03ac0bdb69ee0c9fd13b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-03-08T10:26:46.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-04T20:56:57.000Z", "max_forks_repo_path": "src/Core/Abstraction.idr", "max_forks_repo_name": "totalscript/totalscript", "max_forks_repo_head_hexsha": "8923f52bb46173f0ad7b03ac0bdb69ee0c9fd13b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-04-01T15:18:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-30T08:15:47.000Z", "avg_line_length": 43.9946808511, "max_line_length": 106, "alphanum_fraction": 0.6519163342, "num_tokens": 2883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4726834766204329, "lm_q1q2_score": 0.24372501437868963}} |
| {"text": "module FoldFusion\n\nArray : Type -> Type\nVar : Type -> Type -> Type\n\ninterface Symantics (rep : Type -> Type) where\n int : Int -> rep Int\n bool : Bool -> rep Bool\n (==) : rep Int -> rep Int -> rep Bool\n (>) : rep Int -> rep Int -> rep Bool\n (<) : rep Int -> rep Int -> rep Bool\n (&&) : rep Bool -> rep Bool -> rep Bool\n (||) : rep Bool -> rep Bool -> rep Bool\n (+) : rep Int -> rep Int -> rep Int\n (*) : rep Int -> rep Int -> rep Int\n ite : rep Bool -> rep a -> rep a -> rep a\n deref : rep (Var s a) -> rep a\n assign : rep a -> rep (Var s a) -> rep ()\n newVar : rep a -> ({s : Type} -> rep (Var s a) -> rep b) -> rep b\n foreach : rep (Array a) -> (rep a -> rep ()) -> rep ()\n seq : rep a -> rep b -> rep b\n lam : (rep a -> rep b) -> rep (a -> b)\n app : rep (a -> b) -> rep a -> rep b\n\ndata Code : Type -> Type where\n C : (Int -> String) -> Code a\n\n\nSymantics Code where\n int x = C (\\_ => show x)\n bool x = C (\\_ => if x then \"true\" else \"false\")\n (==) (C l) (C r) = C (\\v => \"( \" ++ l v ++ \" = \" ++ r v ++ \" )\")\n (>) (C l) (C r) = C (\\v => \"( \" ++ l v ++ \" > \" ++ r v ++ \" )\")\n (<) (C l) (C r) = C (\\v => \"( \" ++ l v ++ \" < \" ++ r v ++ \" )\")\n (&&) (C l) (C r) = C (\\v => \"( \" ++ l v ++ \" && \" ++ r v ++ \" )\")\n (||) (C l) (C r) = C (\\v => \"( \" ++ l v ++ \" || \" ++ r v ++ \" )\")\n (+) (C l) (C r) = C (\\v => \"( \" ++ l v ++ \" + \" ++ r v ++ \" )\")\n (*) (C l) (C r) = C (\\v => \"( \" ++ l v ++ \" * \" ++ r v ++ \" )\")\n ite (C b) (C l) (C r) = C (\\v => \"(if \" ++ b v ++ \" then \" ++ l v ++ \" else \" ++ r v ++ \")\")\n deref (C x) = C (\\v => \"!\" ++ x v)\n assign (C val) (C var) = C (\\v => var v ++ \" := \" ++ val v)\n newVar {a} (C s) f = C (\\v => let x = \"x\" ++ show v in\n let (C c) = f $ the (Code (Var () a)) (C (\\_ => x)) in\n \"let \" ++ x ++ \" = ref \" ++ s v ++ \" in \" ++ c (v + 1))\n foreach (C arr) f = C (\\v => let x = \"x\" ++ show v in\n let (C c) = f (C (\\_ => x)) in\n \"(for \" ++ x ++ \" in \" ++ arr v ++ \" do \" ++ c (v + 1) ++ \")\")\n seq (C fs) (C sn) = C (\\v => \"(\" ++ fs v ++ \"; \" ++ sn v ++ \")\")\n lam f = C (\\v => let x = \"x\" ++ show v in\n let (C g) = f (C (\\_ => x)) in\n \"(fun \" ++ x ++ \" -> \" ++ g (v + 1) ++ \")\" )\n app (C f) (C g) = C (\\v => \"(\" ++ f v ++ \" \" ++ g v ++ \")\" )\n\n\ndata Fold : (rep : Type -> Type) -> (a : Type) -> Type where\n FC : ({r : Type} -> (rep a -> rep r -> rep r) -> rep r -> rep r) -> Fold rep a\n\n\nofArray : Symantics rep => rep (Array a) -> Fold rep a\nofArray arr = FC (\\f, seed => newVar seed (\\v => seq (foreach arr (\\x => assign (f x (deref v)) v)) (deref v)))\n\nfold : (rep a -> rep r -> rep r) -> rep r -> Fold rep a -> rep r\nfold f seed (FC g) = g f seed\n\nmap : (rep a -> rep b) -> Fold rep a -> Fold rep b\nmap f (FC g) = FC (\\h => g (\\x, r => h (f x) r))\n\nflatMap : (rep a -> Fold rep b) -> Fold rep a -> Fold rep b\nflatMap f (FC g) = FC (\\h => g (\\x, r => fold h r (f x)))\n\nfilter : Symantics rep => (rep a -> rep Bool) -> Fold rep a -> Fold rep a\nfilter f (FC g) = FC (\\h => g (\\x, r => ite (f x) (h x r) r))\n\ncount : Symantics rep => Fold rep a -> rep Int\ncount = fold (\\x, acc => acc + (int 1)) (int 0)\n\nsum : Symantics rep => Fold rep Int -> rep Int\nsum = fold (\\x, acc => x + acc) (int 0)\n\nexample : Symantics rep => rep (Array Int) -> rep Int\nexample = sum . map (\\x => x * (int 2)) . filter (\\x => x < (int 5)) . ofArray\n\ntest : Code (Array Int -> Int)\ntest = lam example\n\ncode : String\ncode = let (C c) = test in c 0\n", "meta": {"hexsha": "a1c673f5c083b42500493ef0d2d4b0f3371ee76b", "size": 3543, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/FoldFusion.idr", "max_stars_repo_name": "STELIORD/idris-snippets", "max_stars_repo_head_hexsha": "f5ca6fa86370d24587040af9871ae850bbc630c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2017-11-21T22:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-05T18:25:18.000Z", "max_issues_repo_path": "src/FoldFusion.idr", "max_issues_repo_name": "stjordanis/idris-snippets", "max_issues_repo_head_hexsha": "d92734b8624ae27be21a63fcb041077b38eaaecb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FoldFusion.idr", "max_forks_repo_name": "stjordanis/idris-snippets", "max_forks_repo_head_hexsha": "d92734b8624ae27be21a63fcb041077b38eaaecb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-05-06T13:39:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T15:39:16.000Z", "avg_line_length": 40.2613636364, "max_line_length": 111, "alphanum_fraction": 0.4053062377, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24354672606361613}} |
| {"text": "||| Spec: https://webassembly.github.io/spec/core/syntax/types.html#external-types\nmodule WebAssembly.Structure.Types.ExternalTypes\n\nimport WebAssembly.Structure.Types.ValueTypes\nimport WebAssembly.Structure.Types.FunctionTypes\nimport WebAssembly.Structure.Types.TableTypes\nimport WebAssembly.Structure.Types.Limits\nimport WebAssembly.Structure.Types.MemoryTypes\nimport WebAssembly.Structure.Types.GlobalTypes\n\nimport Decidable.Equality\n\n-- Definition\n\npublic export\ndata ExternType : Type where\n Func : FuncType -> ExternType\n Table : TableType -> ExternType\n Mem : MemType -> ExternType\n Global : GlobalType -> ExternType\n\n-- Equality\n\ntotal public export\nlemma_externtype__func_injective : ((x = y) -> Void) -> (Func x = Func y) -> Void\nlemma_externtype__func_injective func_types_neq Refl = func_types_neq Refl\n\ntotal public export\nlemma_externtype__table_injective : ((x = y) -> Void) -> (Table x = Table y) -> Void\nlemma_externtype__table_injective table_tables_neq Refl = table_tables_neq Refl\n\ntotal public export\nlemma_externtype__mem_injective : ((x = y) -> Void) -> (Mem x = Mem y) -> Void\nlemma_externtype__mem_injective mem_types_neq Refl = mem_types_neq Refl\n\ntotal public export\nlemma_externtype__global_injective : ((x = y) -> Void) -> (Global x = Global y) -> Void\nlemma_externtype__global_injective global_types_neq Refl = global_types_neq Refl\n\ntotal public export\nlemma_func_not_table : (Func x = Table y) -> Void\nlemma_func_not_table Refl impossible\n\ntotal public export\nlemma_func_not_mem : (Func x = Mem y) -> Void\nlemma_func_not_mem Refl impossible\n\ntotal public export\nlemma_func_not_global : (Func x = Global y) -> Void\nlemma_func_not_global Refl impossible\n\ntotal public export\nlemma_table_not_func : (Table x = Func y) -> Void\nlemma_table_not_func Refl impossible\n\ntotal public export\nlemma_table_not_mem : (Table x = Mem y) -> Void\nlemma_table_not_mem Refl impossible\n\ntotal public export\nlemma_table_not_global : (Table x = Global y) -> Void\nlemma_table_not_global Refl impossible\n\ntotal public export\nlemma_mem_not_func : (Mem x = Func y) -> Void\nlemma_mem_not_func Refl impossible\n\ntotal public export\nlemma_mem_not_table : (Mem x = Table y) -> Void\nlemma_mem_not_table Refl impossible\n\ntotal public export\nlemma_mem_not_global : (Mem x = Global y) -> Void\nlemma_mem_not_global Refl impossible\n\ntotal public export\nlemma_global_not_func : (Global x = Func y) -> Void\nlemma_global_not_func Refl impossible\n\ntotal public export\nlemma_global_not_table : (Global x = Table y) -> Void\nlemma_global_not_table Refl impossible\n\ntotal public export\nlemma_global_not_mem : (Global x = Mem y) -> Void\nlemma_global_not_mem Refl impossible\n\n-- Decidable Equality\n\npublic export\nimplementation DecEq ExternType where\n decEq (Func x) (Func y) = case decEq x y of\n No func_types_neq => No (lemma_externtype__func_injective func_types_neq)\n Yes Refl => Yes Refl\n decEq (Table x) (Table y) = case decEq x y of\n No table_tables_neq => No (lemma_externtype__table_injective table_tables_neq)\n Yes Refl => Yes Refl\n decEq (Mem x) (Mem y) = case decEq x y of\n No mem_types_neq => No (lemma_externtype__mem_injective mem_types_neq)\n Yes Refl => Yes Refl\n decEq (Global x) (Global y) = case decEq x y of\n No global_types_neq => No (lemma_externtype__global_injective global_types_neq)\n Yes Refl => Yes Refl\n decEq (Func x) (Table y) = No lemma_func_not_table\n decEq (Func x) (Mem y) = No lemma_func_not_mem\n decEq (Func x) (Global y) = No lemma_func_not_global\n decEq (Table x) (Func y) = No lemma_table_not_func\n decEq (Table x) (Mem y) = No lemma_table_not_mem\n decEq (Table x) (Global y) = No lemma_table_not_global\n decEq (Mem x) (Func y) = No lemma_mem_not_func\n decEq (Mem x) (Table y) = No lemma_mem_not_table\n decEq (Mem x) (Global y) = No lemma_mem_not_global\n decEq (Global x) (Func y) = No lemma_global_not_func\n decEq (Global x) (Table y) = No lemma_global_not_table\n decEq (Global x) (Mem y) = No lemma_global_not_mem\n", "meta": {"hexsha": "89fb015da6dc2225974610494a7ebcb56c5c92f2", "size": 4086, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "WebAssembly/Structure/Types/ExternalTypes.idr", "max_stars_repo_name": "RaoulSchaffranek/idris-webassembly", "max_stars_repo_head_hexsha": "ce77f5a5b612aad85eefe2374d22456d7d1edbb5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-07T16:03:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T16:03:42.000Z", "max_issues_repo_path": "WebAssembly/Structure/Types/ExternalTypes.idr", "max_issues_repo_name": "RaoulSchaffranek/idris-webassembly", "max_issues_repo_head_hexsha": "ce77f5a5b612aad85eefe2374d22456d7d1edbb5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WebAssembly/Structure/Types/ExternalTypes.idr", "max_forks_repo_name": "RaoulSchaffranek/idris-webassembly", "max_forks_repo_head_hexsha": "ce77f5a5b612aad85eefe2374d22456d7d1edbb5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.224137931, "max_line_length": 87, "alphanum_fraction": 0.751835536, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.24105574422662424}} |
| {"text": "module Compiler.LLVM.Rapid.Integer\n\nimport Data.Bits\nimport Data.Vect\n\nimport Compiler.LLVM.IR\nimport Compiler.LLVM.Instruction\nimport Compiler.LLVM.Rapid.Object\nimport Control.Codegen\n\nGMP_LIMB_SIZE : Integer\nGMP_LIMB_SIZE = 8\n\nGMP_LIMB_BITS : Integer\nGMP_LIMB_BITS = 8 * GMP_LIMB_SIZE\n\nGMP_LIMB_BOUND : Integer\nGMP_LIMB_BOUND = (1 `prim__shl_Integer` (GMP_LIMB_BITS))\n\n-- To estimate required count of limbs (upper bound):\n-- x = the number (result)\n-- length of string == number of digits <= log10(x) + 1\n-- required limbs: log10(x) / log10(2^LIMB_BITS)\n-- LIMB_BITS=32 -> required limbs <= number of digits / 9\n-- LIMB_BITS=64 -> required limbs <= number of digits / 19\nGMP_ESTIMATE_DIGITS_PER_LIMB : Integer\nGMP_ESTIMATE_DIGITS_PER_LIMB = 19\n\nTARGET_SIZE_T : IRType\nTARGET_SIZE_T = I64\n\nMP_LIMB_T : IRType\nMP_LIMB_T = I64\n\ntwosComplement : Num a => Bits a => a -> a\ntwosComplement x = 1 + (complement x)\n\nexport\ncgMkConstInteger : Integer -> Codegen (IRValue IRObjPtr)\ncgMkConstInteger val =\n do\n let absVal = abs val\n let (len ** limbs) = getLimbs absVal\n let len32 = cast {to=Bits32} $ cast {to=Int} len\n let lenForHeader = if (val >= 0) then len32 else (twosComplement len32)\n let newHeader = constHeader OBJECT_TYPE_ID_BIGINT lenForHeader\n let typeSignature = \"{i64, [\" ++ show len ++ \" x %LimbT]}\"\n cName <- addConstant $ \"private unnamed_addr addrspace(1) constant \" ++ typeSignature ++ \" {\" ++ toIR newHeader ++ \", [\" ++ show len ++ \" x %LimbT] [\" ++ (getLimbsIR limbs) ++ \"]}, align 8\"\n pure $ SSA IRObjPtr $ \"bitcast (\" ++ typeSignature ++ \" addrspace(1)* \" ++ cName ++ \" to %ObjPtr)\"\n where\n getLimbs : Integer -> (n:Nat ** Vect n Integer)\n getLimbs 0 = (0 ** [])\n getLimbs x = let (n ** v) = (getLimbs (x `div` GMP_LIMB_BOUND))\n limb = (x `mod` GMP_LIMB_BOUND) in\n ((S n) ** (limb::v))\n getLimbsIR : Vect n Integer -> String\n getLimbsIR [] = \"\"\n getLimbsIR (limb::[]) = \"%LimbT \" ++ show limb\n getLimbsIR (limb::rest) = \"%LimbT \" ++ show limb ++ \", \" ++ (getLimbsIR rest)\n\nexport\ninteger0 : Codegen (IRValue IRObjPtr)\ninteger0 = do\n newObj <- dynamicAllocate (Const I64 0)\n putObjectHeader newObj (constHeader OBJECT_TYPE_ID_BIGINT 0)\n pure newObj\n\nexport\ncgMkIntegerSigned : IRValue I64 -> Codegen (IRValue IRObjPtr)\ncgMkIntegerSigned val = do\n isNegative <- icmp \"slt\" val (Const I64 0)\n isZero <- icmp \"eq\" val (Const I64 0)\n newSize1 <- mkSelect isNegative (Const I32 (-1)) (Const I32 1)\n newSize <- mkSelect isZero (Const I32 0) newSize1\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT newSize\n newSizeAbs <- mkAbs newSize\n allocSize <- mkMul !(mkZext newSizeAbs) (Const I64 GMP_LIMB_SIZE)\n newObj <- dynamicAllocate allocSize\n ignore $ mkIf (pure isZero) (pure (Const I1 0)) (do\n absVal <- mkAbs64 val\n putObjectSlot newObj (Const I64 0) absVal\n pure $ Const I1 0)\n putObjectHeader newObj newHeader\n pure newObj\n\nexport\ncgMkIntegerUnsigned : IRValue I64 -> Codegen (IRValue IRObjPtr)\ncgMkIntegerUnsigned ival = do\n isZero <- icmp \"eq\" (Const I64 0) ival\n newObj <- mkIf (pure isZero) integer0 (do\n newInteger <- dynamicAllocate (Const I64 GMP_LIMB_SIZE)\n putObjectHeader newInteger !(mkHeader OBJECT_TYPE_ID_BIGINT (Const I32 1))\n putObjectSlot newInteger (Const I64 0) ival\n pure newInteger\n )\n pure newObj\n\nexport\nunboxIntegerUnsigned : IRValue IRObjPtr -> Codegen (IRValue I64)\nunboxIntegerUnsigned integerObj = do\n isZero <- icmp \"eq\" (Const I32 0) !(getObjectSize integerObj)\n -- get first limb (LSB)\n mkIf (pure isZero) (pure $ Const I64 0) (getObjectSlot {t=I64} integerObj 0)\n\nexport\nunboxIntegerSigned : IRValue IRObjPtr -> Codegen (IRValue I64)\nunboxIntegerSigned integerObj = do\n size <- getObjectSize integerObj\n isZero <- icmp \"eq\" (Const I32 0) size\n let isNegative = icmp \"sgt\" (Const I32 0) size\n -- get first limb (LSB)\n firstLimb <- getObjectSlot {t=I64} integerObj 0\n -- TODO: this is probably wrong for 64bit\n mkIf (pure isZero) (pure $ Const I64 0) (mkIf isNegative (mkSub (Const I64 0) firstLimb) (pure firstLimb))\n\n||| compare two BigInts `a` and `b`, return -1 if a<b, +1 if a>b, 0 otherwise\nexport\ncompareInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue I64)\ncompareInteger obj1 obj2 = do\n size1 <- getObjectSize obj1\n size2 <- getObjectSize obj2\n cmpResult <- mkIf (icmp \"slt\" size1 size2) (pure (Const I64 (-1))) (\n mkIf (icmp \"sgt\" size1 size2) (pure (Const I64 1)) (do\n limbs1 <- getObjectPayloadAddr {t=I64} obj1\n limbs2 <- getObjectPayloadAddr {t=I64} obj2\n absSize <- mkZext {to=I64} !(mkAbs size1)\n mpnResult <- call {t=I32} \"ccc\" \"@__gmpn_cmp\" [toIR limbs1, toIR limbs2, toIR absSize]\n sizeIsNegative <- icmp \"slt\" size1 (Const I32 0)\n mkSext !(mkSelect sizeIsNegative !(mkSub (Const I32 0) mpnResult) mpnResult)\n )\n )\n\n pure cmpResult\n\nnormaliseIntegerSize : IRValue IRObjPtr -> IRValue I32 -> IRValue I1 -> Codegen ()\nnormaliseIntegerSize integerObj maxSizeSigned invert = do\n maxSizeAbs <- mkAbs maxSizeSigned\n absRealNewSize <- mkTrunc {to=I32} !(call {t=I64} \"ccc\" \"@rapid_bigint_real_size\" [\n toIR !(getObjectPayloadAddr {t=I64} integerObj),\n toIR !(mkZext {to=I64} maxSizeAbs)\n ])\n isNegative <- icmp \"slt\" maxSizeSigned (Const I32 0)\n invertResult <- mkXOr isNegative invert\n signedNewSize <- mkSelect invertResult !(mkSub (Const I32 0) absRealNewSize) absRealNewSize\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT signedNewSize\n putObjectHeader integerObj newHeader\n\nexport\naddInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\naddInteger i1 i2 = do\n s1 <- getObjectSize i1\n s2 <- getObjectSize i2\n i1Negative <- icmp \"slt\" s1 (Const I32 0)\n s1a <- mkAbs s1\n s2a <- mkAbs s2\n i1longer <- icmp \"ugt\" s1a s2a\n -- \"big\" and \"small\" refer just to the respective limb counts\n -- it doesn't matter which number is actually bigger\n big <- mkSelect i1longer i1 i2\n small <- mkSelect i1longer i2 i1\n size1 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s1a s2a)\n size2 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s2a s1a)\n newLength <- mkAdd size1 (Const I64 1)\n newSize <- mkMul (Const I64 GMP_LIMB_SIZE) newLength\n newObj <- dynamicAllocate newSize\n carry <- call {t=I64} \"ccc\" \"@__gmpn_add\" [\n toIR !(getObjectPayloadAddr {t=I64} newObj),\n toIR !(getObjectPayloadAddr {t=I64} big),\n toIR size1,\n toIR !(getObjectPayloadAddr {t=I64} small),\n toIR size2\n ]\n putObjectSlot newObj size1 carry\n absRealNewSize <- mkAdd size1 carry\n signedNewSize <- mkSelect i1Negative !(mkSub (Const I64 0) absRealNewSize) absRealNewSize\n signedNewSize32 <- mkTrunc {to=I32} signedNewSize\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT signedNewSize32\n putObjectHeader newObj newHeader\n pure newObj\n\nexport\nsubInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\nsubInteger i1 i2 = do\n -- Subtract the smaller (by abs. value) from the larger (by abs. value)\n -- and use the sign of the larger (by abs. value) number as sign for the\n -- returned result.\n s1 <- getObjectSize i1\n s2 <- getObjectSize i2\n i1Negative <- icmp \"slt\" s1 (Const I32 0)\n s1a <- mkAbs s1\n s2a <- mkAbs s2\n i1longer <- icmp \"ugt\" s1a s2a\n i2longer <- icmp \"ugt\" s2a s1a\n i1bigger <- mkIf (pure i1longer) (pure $ Const I1 1) (mkIf (pure i2longer) (pure $ Const I1 0) (icmp \"sgt\" !(call \"ccc\" \"@__gmpn_cmp\" [\n toIR !(getObjectPayloadAddr {t=I64} i1),\n toIR !(getObjectPayloadAddr {t=I64} i2),\n toIR !(mkZext {to=I64} s1a)\n ]) (Const I32 0))\n )\n big <- mkSelect i1bigger i1 i2\n small <- mkSelect i1bigger i2 i1\n swapped <- mkSelect i1bigger (Const I1 0) (Const I1 1)\n bigSize <- getObjectSize big\n bigSizeAbs <- mkAbs bigSize\n smallSizeAbs <- mkAbs !(getObjectSize small)\n newSize <- mkMul (Const I64 GMP_LIMB_SIZE) !(mkZext {to=I64} bigSizeAbs)\n newObj <- dynamicAllocate newSize\n absDiff <- call {t=I64} \"ccc\" \"@__gmpn_sub\" [\n toIR !(getObjectPayloadAddr {t=I64} newObj),\n toIR !(getObjectPayloadAddr {t=I64} big),\n toIR !(mkZext {to=I64} bigSizeAbs),\n toIR !(getObjectPayloadAddr {t=I64} small),\n toIR !(mkZext {to=I64} smallSizeAbs)\n ]\n absRealNewSize <- call {t=I64} \"ccc\" \"@rapid_bigint_real_size\" [\n toIR !(getObjectPayloadAddr {t=I64} newObj),\n toIR !(mkZext {to=I64} bigSizeAbs)\n ]\n resultIsNegative <- mkXOr swapped i1Negative\n signedNewSize <- mkSelect resultIsNegative !(mkSub (Const I64 0) absRealNewSize) absRealNewSize\n signedNewSize32 <- mkTrunc {to=I32} signedNewSize\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT signedNewSize32\n putObjectHeader newObj newHeader\n pure newObj\n\nexport\nandInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\nandInteger i1 i2 = do\n -- TODO: what to do with negative numbers?\n s1 <- getObjectSize i1\n s2 <- getObjectSize i2\n zero1 <- icmp \"eq\" s1 (Const I32 0)\n zero2 <- icmp \"eq\" s2 (Const I32 0)\n resultIsZero <- mkOr zero1 zero2\n\n mkIf (pure resultIsZero) (mkSelect zero1 i1 i2) (do\n s1a <- mkAbs s1\n s2a <- mkAbs s2\n i1longer <- icmp \"ugt\" s1a s2a\n -- \"long\" and \"short\" refer just to the respective limb counts\n -- it doesn't matter which number is actually bigger\n long <- mkSelect i1longer i1 i2\n short <- mkSelect i1longer i2 i1\n size1 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s1a s2a)\n size2 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s2a s1a)\n -- result can not be longer than shortest number\n let newLength = size2\n newSize <- mkMul (Const I64 GMP_LIMB_SIZE) newLength\n newObj <- dynamicAllocate newSize\n putObjectHeader newObj !(mkHeader OBJECT_TYPE_ID_BIGINT !(mkTrunc newLength))\n\n newLimbs <- getObjectPayloadAddr {t=I64} newObj\n shortLimbs <- getObjectPayloadAddr {t=I64} short\n longLimbs <- getObjectPayloadAddr {t=I64} long\n voidCall \"ccc\" \"@__gmpn_and_n\" [toIR newLimbs, toIR shortLimbs, toIR longLimbs, toIR newLength]\n\n normaliseIntegerSize newObj !(mkTrunc newLength) (Const I1 0)\n\n pure newObj\n )\n\nexport\norInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\norInteger i1 i2 = do\n -- TODO: what to do with negative numbers?\n s1 <- getObjectSize i1\n s2 <- getObjectSize i2\n zero1 <- icmp \"eq\" s1 (Const I32 0)\n zero2 <- icmp \"eq\" s2 (Const I32 0)\n resultIsZero <- mkAnd zero1 zero2\n\n mkIf (pure resultIsZero) (pure i1) (do\n s1a <- mkAbs s1\n s2a <- mkAbs s2\n i1longer <- icmp \"ugt\" s1a s2a\n -- \"big\" and \"small\" refer just to the respective limb counts\n -- it doesn't matter which number is actually bigger\n big <- mkSelect i1longer i1 i2\n small <- mkSelect i1longer i2 i1\n size1 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s1a s2a)\n size2 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s2a s1a)\n mkIf (icmp \"eq\" (Const I64 0) size2) (pure big) (do\n let newLength = size1\n newSize <- mkMul (Const I64 GMP_LIMB_SIZE) newLength\n newObj <- dynamicAllocate newSize\n putObjectHeader newObj !(mkHeader OBJECT_TYPE_ID_BIGINT !(mkTrunc newLength))\n\n newPayload <- getObjectPayloadAddr {t=I8} newObj\n bigPayload <- getObjectPayloadAddr {t=I8} big\n appendCode $ \" call void @llvm.memcpy.p1i8.p1i8.i64(\" ++ toIR newPayload ++ \", \" ++ toIR bigPayload ++ \", \" ++ toIR newSize++ \", i1 false)\"\n\n newLimbs <- getObjectPayloadAddr {t=I64} newObj\n smallLimbs <- getObjectPayloadAddr {t=I64} small\n voidCall \"ccc\" \"@__gmpn_ior_n\" [toIR newLimbs, toIR newLimbs, toIR smallLimbs, toIR size2]\n pure newObj\n )\n )\n\nexport\nxorInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\nxorInteger i1 i2 = do\n -- TODO: what to do with negative numbers?\n s1 <- getObjectSize i1\n s2 <- getObjectSize i2\n zero1 <- icmp \"eq\" s1 (Const I32 0)\n zero2 <- icmp \"eq\" s2 (Const I32 0)\n resultIsUnchanged <- mkOr zero1 zero2\n\n mkIf (pure resultIsUnchanged) (mkSelect zero1 i2 i1) (do\n s1a <- mkAbs s1\n s2a <- mkAbs s2\n i1longer <- icmp \"ugt\" s1a s2a\n -- \"long\" and \"short\" refer just to the respective limb counts\n -- it doesn't matter which number is actually bigger\n long <- mkSelect i1longer i1 i2\n short <- mkSelect i1longer i2 i1\n size1 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s1a s2a)\n size2 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s2a s1a)\n -- result can not be longer than longest number\n let newLength = size1\n newSize <- mkMul (Const I64 GMP_LIMB_SIZE) newLength\n newObj <- dynamicAllocate newSize\n putObjectHeader newObj !(mkHeader OBJECT_TYPE_ID_BIGINT !(mkTrunc newLength))\n\n newPayload <- getObjectPayloadAddr {t=I8} newObj\n longPayload <- getObjectPayloadAddr {t=I8} long\n appendCode $ \" call void @llvm.memcpy.p1i8.p1i8.i64(\" ++ toIR newPayload ++ \", \" ++ toIR longPayload ++ \", \" ++ toIR newSize ++ \", i1 false)\"\n\n newLimbs <- getObjectPayloadAddr {t=I64} newObj\n shortLimbs <- getObjectPayloadAddr {t=I64} short\n voidCall \"ccc\" \"@__gmpn_xor_n\" [toIR newLimbs, toIR newLimbs, toIR shortLimbs, toIR size2]\n\n normaliseIntegerSize newObj !(mkTrunc newLength) (Const I1 0)\n\n pure newObj\n )\n\nexport\nmulInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\nmulInteger i1 i2 = do\n s1 <- getObjectSize i1\n s2 <- getObjectSize i2\n zero1 <- icmp \"eq\" s1 (Const I32 0)\n zero2 <- icmp \"eq\" s2 (Const I32 0)\n resultIsZero <- mkOr zero1 zero2\n mkIf (pure resultIsZero) {- then -} integer0 {- else -} (do\n sx <- mkXOr s1 s2\n signsMatch <- icmp \"sge\" sx (Const I32 0)\n s1a <- mkAbs s1\n s2a <- mkAbs s2\n i1longer <- icmp \"ugt\" s1a s2a\n -- \"big\" and \"small\" refer just to the respective limb counts\n -- it doesn't matter which number is actually bigger\n big <- mkSelect i1longer i1 i2\n small <- mkSelect i1longer i2 i1\n size1 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s1a s2a)\n size2 <- mkZext {to=I64} !(mkSelect {t=I32} i1longer s2a s1a)\n newLength <- mkAdd size1 size2\n newSize <- mkMul (Const I64 GMP_LIMB_SIZE) newLength\n newObj <- dynamicAllocate newSize\n ignore $ call {t=I64} \"ccc\" \"@__gmpn_mul\" [\n toIR !(getObjectPayloadAddr {t=I64} newObj),\n toIR !(getObjectPayloadAddr {t=I64} big),\n toIR size1,\n toIR !(getObjectPayloadAddr {t=I64} small),\n toIR size2\n ]\n absRealNewSize <- call {t=I64} \"ccc\" \"@rapid_bigint_real_size\" [\n toIR !(getObjectPayloadAddr {t=I64} newObj),\n toIR newLength\n ]\n signedNewSize <- mkSelect signsMatch absRealNewSize !(mkSub (Const I64 0) absRealNewSize)\n signedNewSize32 <- mkTrunc {to=I32} signedNewSize\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT signedNewSize32\n putObjectHeader newObj newHeader\n pure newObj)\n\n||| divide i1 by i2, return (quotient, remainder)\ndivInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr, IRValue IRObjPtr)\ndivInteger i1 i2 = do\n s1 <- getObjectSize i1\n s2 <- getObjectSize i2\n s1a <- mkZext !(mkAbs s1)\n s2a <- mkZext !(mkAbs s2)\n zero1 <- icmp \"eq\" s1 (Const I32 0)\n zero2 <- icmp \"eq\" s2 (Const I32 0)\n ignore $ mkIf (pure zero2) (do\n mkRuntimeCrash \"division by 0\"\n pure (Const I1 0)\n ) (pure (Const I1 0))\n\n retZeroLbl <- genLabel \"ret0\"\n checkDividendLbl <- genLabel \"div_chk\"\n dividendLargerLbl <- genLabel \"div_lg\"\n divLbl <- genLabel \"div\"\n endLbl <- genLabel \"div_end\"\n\n branch zero1 retZeroLbl checkDividendLbl\n\n beginLabel retZeroLbl\n zeroInteger <- integer0\n jump endLbl\n\n beginLabel checkDividendLbl\n dividendLarger <- icmp \"ugt\" s2a s1a\n branch dividendLarger dividendLargerLbl divLbl\n\n beginLabel dividendLargerLbl\n zeroQuotient <- integer0\n jump endLbl\n\n beginLabel divLbl\n -- i1, i2 /= 0\n sx <- mkXOr s1 s2\n signsMatch <- icmp \"sge\" sx (Const I32 0)\n\n -- remainder can not be bigger than divisor\n let maxLimbsRemainder = s2a\n remainder <- dynamicAllocate !(mkMul (Const I64 GMP_LIMB_SIZE) maxLimbsRemainder)\n -- object must have a valid header, because the next allocation might trigger a GC\n tempHeader <- mkHeader OBJECT_TYPE_ID_BIGINT !(mkTrunc maxLimbsRemainder)\n putObjectHeader remainder tempHeader\n\n maxLimbsQuotient <- mkMax (Const I64 1) !(mkAdd (Const I64 1) !(mkSub s1a s2a))\n quotient <- dynamicAllocate !(mkMul (Const I64 GMP_LIMB_SIZE) maxLimbsQuotient)\n\n voidCall \"ccc\" \"@__gmpn_tdiv_qr\" [\n toIR !(getObjectPayloadAddr {t=I64} quotient),\n toIR !(getObjectPayloadAddr {t=I64} remainder),\n toIR (Const I64 0),\n toIR !(getObjectPayloadAddr {t=I64} i1),\n toIR s1a,\n toIR !(getObjectPayloadAddr {t=I64} i2),\n toIR s2a\n ]\n qRealNewSize <- call {t=I64} \"ccc\" \"@rapid_bigint_real_size\" [\n toIR !(getObjectPayloadAddr {t=I64} quotient),\n toIR maxLimbsQuotient\n ]\n signedNewSize <- mkSelect signsMatch qRealNewSize !(mkSub (Const I64 0) qRealNewSize)\n signedNewSize32 <- mkTrunc {to=I32} signedNewSize\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT signedNewSize32\n putObjectHeader quotient newHeader\n\n i1negative <- icmp \"slt\" s1 (Const I32 0)\n rRealNewSize <- call {t=I64} \"ccc\" \"@rapid_bigint_real_size\" [\n toIR !(getObjectPayloadAddr {t=I64} remainder),\n toIR maxLimbsRemainder\n ]\n signedNewSize <- mkSelect i1negative !(mkSub (Const I64 0) rRealNewSize) rRealNewSize\n signedNewSize32 <- mkTrunc {to=I32} signedNewSize\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT signedNewSize32\n putObjectHeader remainder newHeader\n\n jump endLbl\n\n beginLabel endLbl\n quotient <- phi [(zeroInteger, retZeroLbl), (zeroQuotient, dividendLargerLbl), (quotient, divLbl)]\n remainder <- phi [(zeroInteger, retZeroLbl), (i1, dividendLargerLbl), (remainder, divLbl)]\n pure (quotient, remainder)\n\nexport\ndivIntegerQuotient : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\ndivIntegerQuotient a b = fst <$> divInteger a b\n\nexport\ndivIntegerRemainder : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\ndivIntegerRemainder a b = snd <$> divInteger a b\n\nexport\nshiftLeftInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\nshiftLeftInteger integerObj bitCountObj = do\n bitCount <- mkTrunc {to=I32} !(unboxIntegerUnsigned bitCountObj)\n\n size <- getObjectSize integerObj\n unchanged <- mkOr !(icmp \"eq\" size (Const I32 0)) !(icmp \"eq\" bitCount (Const I32 0))\n mkIf (pure unchanged) (do\n pure integerObj\n ) (do\n sizeAbs <- mkAbs size\n fullLimbs <- mkUDiv bitCount (Const I32 GMP_LIMB_BITS)\n maxLimbsCount <- mkAdd !(mkAdd fullLimbs sizeAbs) (Const I32 1)\n\n newObj <- dynamicAllocate !(mkZext !(mkMul maxLimbsCount (Const I32 GMP_LIMB_SIZE)))\n lowerLimbsAddr <- getObjectPayloadAddr {t=I8} newObj\n appendCode $ \" call void @llvm.memset.p1i8.i64(\" ++ toIR lowerLimbsAddr ++ \", i8 0, \" ++ toIR !(mkMul !(mkZext fullLimbs) (Const I64 8)) ++ \", i1 false)\"\n\n restBits <- mkURem bitCount (Const I32 GMP_LIMB_BITS)\n mkIf_ (icmp \"ne\" (Const I32 0) restBits) (do\n srcLimbs <- getObjectPayloadAddr {t=I64} integerObj\n higherLimbsAddr <- getObjectSlotAddrVar {t=I64} newObj !(mkZext {to=I64} fullLimbs)\n msbLimb <- call {t=I64} \"ccc\" \"@__gmpn_lshift\" [\n toIR higherLimbsAddr,\n toIR srcLimbs,\n toIR !(mkZext {to=I64} sizeAbs),\n toIR restBits\n ]\n msbLimbAddr <- getObjectSlotAddrVar {t=I64} newObj !(mkZext !(mkSub maxLimbsCount (Const I32 1)))\n store msbLimb msbLimbAddr\n ) (do\n srcLimbs <- getObjectPayloadAddr {t=I8} integerObj\n higherLimbsAddr <- getObjectSlotAddrVar {t=I8} newObj !(mkZext {to=I64} fullLimbs)\n voidCall \"ccc\" \"@llvm.memcpy.p1i8.p1i8.i64\" [\n toIR higherLimbsAddr,\n toIR srcLimbs,\n toIR !(mkMul !(mkZext size) (Const I64 GMP_LIMB_SIZE)),\n \"i1 false\"\n ]\n )\n\n isNegative <- icmp \"slt\" size (Const I32 0)\n normaliseIntegerSize newObj maxLimbsCount isNegative\n pure newObj\n )\n\nexport\nshiftRightInteger : IRValue IRObjPtr -> IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\nshiftRightInteger integerObj bitCountObj = do\n bitCount <- mkTrunc {to=I32} !(unboxIntegerUnsigned bitCountObj)\n\n size <- getObjectSize integerObj\n unchanged <- mkOr !(icmp \"eq\" size (Const I32 0)) !(icmp \"eq\" bitCount (Const I32 0))\n mkIf (pure unchanged) (pure integerObj) (do\n sizeAbs <- mkAbs size\n fullLimbs <- mkUDiv bitCount (Const I32 GMP_LIMB_BITS)\n maxLimbsCount <- mkSub sizeAbs fullLimbs\n\n mkIf (icmp \"sle\" maxLimbsCount (Const I32 0)) integer0 (do\n newObj <- dynamicAllocate !(mkZext !(mkMul maxLimbsCount (Const I32 GMP_LIMB_SIZE)))\n\n restBits <- mkURem bitCount (Const I32 GMP_LIMB_BITS)\n mkIf_ (icmp \"ne\" (Const I32 0) restBits) (do\n srcHigherLimbs <- getObjectSlotAddrVar {t=I64} integerObj !(mkZext {to=I64} fullLimbs)\n dstLimbsAddr <- getObjectPayloadAddr {t=I64} newObj\n ignore $ call {t=I64} \"ccc\" \"@__gmpn_rshift\" [\n toIR dstLimbsAddr,\n toIR srcHigherLimbs,\n toIR !(mkZext {to=I64} maxLimbsCount),\n toIR restBits\n ]\n ) (do\n srcHigherLimbs <- getObjectSlotAddrVar {t=I8} integerObj !(mkZext {to=I64} fullLimbs)\n dstLimbsAddr <- getObjectPayloadAddr {t=I8} newObj\n voidCall \"ccc\" \"@llvm.memcpy.p1i8.p1i8.i64\" [\n toIR dstLimbsAddr,\n toIR srcHigherLimbs,\n toIR !(mkMul !(mkZext maxLimbsCount) (Const I64 GMP_LIMB_SIZE)),\n \"i1 false\"\n ]\n )\n\n isNegative <- icmp \"slt\" size (Const I32 0)\n normaliseIntegerSize newObj maxLimbsCount isNegative\n pure newObj\n )\n\n )\n\nIEEE_DOUBLE_MASK_EXP : Bits64\nIEEE_DOUBLE_MASK_EXP = 0x7ff0000000000000\nIEEE_DOUBLE_MASK_FRAC : Bits64\nIEEE_DOUBLE_MASK_FRAC = 0x000fffffffffffff\nIEEE_DOUBLE_MASK_SIGN : Bits64\nIEEE_DOUBLE_MASK_SIGN = 0x8000000000000000\nIEEE_DOUBLE_INF_POS : Bits64\nIEEE_DOUBLE_INF_POS = 0x7ff0000000000000\nIEEE_DOUBLE_INF_NEG : Bits64\nIEEE_DOUBLE_INF_NEG = 0xfff0000000000000\n\nexport\ncastDoubleToInteger : IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\ncastDoubleToInteger floatObj = do\n floatBitsAsI64 <- getObjectSlot {t=I64} floatObj 0\n exponent <- mkShiftR !(mkAnd (Const I64 $ cast IEEE_DOUBLE_MASK_EXP) floatBitsAsI64) (Const I64 52)\n -- NaN and infinity will be returned as \"0\"\n isInfOrNaN <- icmp \"eq\" exponent (Const I64 0x7ff)\n -- absolute values < 1.0 will be returned as \"0\"\n isSmallerThanOne <- icmp \"ult\" exponent (Const I64 1023)\n returnZero <- mkOr isInfOrNaN isSmallerThanOne\n\n mkIf (pure returnZero) {- then -} integer0 {- else -} (do\n fraction <- mkAnd (Const I64 $ cast IEEE_DOUBLE_MASK_FRAC) floatBitsAsI64\n -- highest bit is sign bit in both, Double and I64, so we can just use that one\n isNegative <- icmp \"slt\" floatBitsAsI64 (Const I64 0)\n initial <- mkOr fraction (Const I64 0x10000000000000)\n toShift <- mkSub exponent (Const I64 1075)\n shiftLeft <- icmp \"sgt\" toShift (Const I64 0)\n mkIf (pure shiftLeft) (do\n let maxLimbCount = Const I64 17\n payloadSize <- mkMul maxLimbCount (Const I64 GMP_LIMB_SIZE)\n -- requiredBits <- (exponent - 1022)\n -- requiredLimbs <- (requiredBits+63) / 64\n -- newObj <- allocObject (requiredLimbs * 8)\n newObj <- dynamicAllocate payloadSize\n payloadAddr <- getObjectPayloadAddr {t=I8} newObj\n appendCode $ \" call void @llvm.memset.p1i8.i64(\" ++ toIR payloadAddr ++ \", i8 0, \" ++ toIR payloadSize ++ \", i1 false)\"\n putObjectSlot newObj (Const I64 0) initial\n absRealNewSize <- call {t=I64} \"ccc\" \"@rapid_bigint_lshift_inplace\" [\n toIR !(getObjectPayloadAddr {t=I64} newObj),\n toIR maxLimbCount,\n toIR !(mkTrunc {to=I32} toShift)\n ]\n signedNewSize <- mkSelect isNegative !(mkSub (Const I64 0) absRealNewSize) absRealNewSize\n size32 <- mkTrunc {to=I32} signedNewSize\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT size32\n putObjectHeader newObj newHeader\n pure newObj\n ) (do\n newObj <- dynamicAllocate (Const I64 8)\n toShiftRight <- mkSub (Const I64 0) toShift\n shifted <- mkShiftR initial toShiftRight\n putObjectSlot newObj (Const I64 0) shifted\n signedNewSize32 <- mkSelect isNegative (Const I32 (-1)) (Const I32 1)\n newHeader <- mkHeader OBJECT_TYPE_ID_BIGINT signedNewSize32\n putObjectHeader newObj newHeader\n pure newObj\n )\n )\n\nexport\ncastIntegerToDouble : IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\ncastIntegerToDouble intObj = do\n size <- getObjectSize intObj\n isZero <- icmp \"eq\" (Const I32 0) size\n\n mkIf (pure isZero) (cgMkConstDouble 0.0) (do\n sizeAbs <- mkAbs size\n highestLimbIndex <- mkZext {to=I64} !(mkSub sizeAbs (Const I32 1))\n msbLimbAddr <- getObjectSlotAddrVar {t=I64} intObj highestLimbIndex\n msbLimb <- load msbLimbAddr\n countLeadingZeros <- SSA I64 <$> assignSSA (\" call ccc i64 @llvm.ctlz.i64(\" ++ toIR msbLimb ++ \", i1 1)\")\n exponentOffset <- mkAdd (Const I64 (1023 + 63)) !(mkMul highestLimbIndex (Const I64 64))\n exponent <- mkSub exponentOffset countLeadingZeros\n\n isInfinity <- icmp \"ugt\" exponent (Const I64 2046)\n doubleAsBits <- mkIf (pure isInfinity) (do\n pure (Const I64 $ cast IEEE_DOUBLE_INF_POS)\n ) (do\n fracShiftLeft <- icmp \"uge\" countLeadingZeros (Const I64 12)\n shiftedFraction <- mkIf (pure fracShiftLeft) (do\n mkShiftL msbLimb !(mkSub countLeadingZeros (Const I64 11))\n ) (do\n mkShiftR msbLimb !(mkSub (Const I64 11) countLeadingZeros)\n )\n fraction <- mkIf (icmp \"eq\" sizeAbs (Const I32 1)) (do\n pure shiftedFraction\n ) (do\n mkIf (pure fracShiftLeft) (do\n secondMsbLimbAddr <- getObjectSlotAddrVar {t=I64} intObj !(mkSub highestLimbIndex (Const I64 1))\n secondMsbLimb <- load secondMsbLimbAddr\n fractionLowerPart <- mkShiftR secondMsbLimb !(mkSub (Const I64 (64 + 11)) countLeadingZeros)\n mkOr shiftedFraction fractionLowerPart\n ) (do\n pure shiftedFraction\n )\n )\n shiftedExponent <- mkShiftL exponent (Const I64 52)\n maskedFraction <- mkAnd (Const I64 $ cast IEEE_DOUBLE_MASK_FRAC) fraction\n mkOr shiftedExponent maskedFraction\n )\n isNegative <- icmp \"slt\" size (Const I32 0)\n sign <- mkSelect isNegative (Const I64 $ cast IEEE_DOUBLE_MASK_SIGN) (Const I64 0)\n signedDoubleAsBits <- mkOr sign doubleAsBits\n cgMkDoubleFromBits signedDoubleAsBits\n )\n\nexport\ncastStringToInteger : IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\ncastStringToInteger strObj = do\n strLength <- getObjectSize strObj\n maxLimbsCount <- mkUDiv strLength (Const I32 GMP_ESTIMATE_DIGITS_PER_LIMB)\n -- GMP requires 1 limb scratch space\n maxLimbsCountPlus1 <- mkAdd maxLimbsCount (Const I32 1)\n\n newObj <- dynamicAllocate !(mkZext !(mkMul maxLimbsCountPlus1 (Const I32 GMP_LIMB_SIZE)))\n putObjectHeader newObj !(mkHeader OBJECT_TYPE_ID_BIGINT maxLimbsCountPlus1)\n ignore $ call {t=I32} \"ccc\" \"@rapid_bigint_set_str\" [\n toIR newObj,\n toIR strObj\n ]\n pure newObj\n\nexport\ncastIntegerToString : IRValue IRObjPtr -> Codegen (IRValue IRObjPtr)\ncastIntegerToString i1 = do\n s1 <- getObjectSize i1\n u1 <- mkZext {to=I64} !(mkAbs s1)\n\n isZero <- icmp \"eq\" s1 (Const I32 0)\n\n mkIf (pure isZero) (mkStr \"0\") (do\n maxDigits <- call {t=TARGET_SIZE_T} \"ccc\" \"@__gmpn_sizeinbase\" [toIR !(getObjectPayloadAddr {t=MP_LIMB_T} i1), toIR u1, \"i32 10\"]\n isNegative <- icmp \"slt\" s1 (Const I32 0)\n\n -- we need to add one extra byte of \"scratch space\" for mpn_get_str\n -- if the number is negative we need one character more for the leading minus\n needsSign <- mkSelect isNegative (Const I64 2) (Const I64 1)\n maxDigitsWithSign <- mkAdd maxDigits needsSign\n\n newStr <- dynamicAllocate maxDigitsWithSign\n newHeader <- mkHeader OBJECT_TYPE_ID_STR !(mkTrunc maxDigitsWithSign)\n putObjectHeader newStr newHeader\n\n actualDigits <- call {t=I64} \"ccc\" \"@rapid_bigint_get_str\" [toIR newStr, toIR i1, \"i32 10\"]\n actualLengthHeader <- mkHeader OBJECT_TYPE_ID_STR !(mkTrunc actualDigits)\n putObjectHeader newStr actualLengthHeader\n\n pure newStr\n )\n", "meta": {"hexsha": "f8fe00e3a8961f143000e993583d678dd33651f1", "size": 28869, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Compiler/LLVM/Rapid/Integer.idr", "max_stars_repo_name": "a8e5/idris2-llvm", "max_stars_repo_head_hexsha": "61aec3ca4e09d39e3a83bc4487c4fcddba786444", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Compiler/LLVM/Rapid/Integer.idr", "max_issues_repo_name": "a8e5/idris2-llvm", "max_issues_repo_head_hexsha": "61aec3ca4e09d39e3a83bc4487c4fcddba786444", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Compiler/LLVM/Rapid/Integer.idr", "max_forks_repo_name": "a8e5/idris2-llvm", "max_forks_repo_head_hexsha": "61aec3ca4e09d39e3a83bc4487c4fcddba786444", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6605633803, "max_line_length": 195, "alphanum_fraction": 0.6756035886, "num_tokens": 9316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24046929253846613}} |
| {"text": "module Flexidisc.Record.Update\n\nimport Flexidisc.RecordContent\nimport public Flexidisc.Record.Type\n\n%default total\n%access export\n\n\n||| Replace a row, can change its type\n|||\n||| Complexity is _O(n)_\n|||\n||| @ xs the record\n||| @ loc the proof that the row is in it\n||| @ new the new value for the row\nsetByLabel : (xs : RecordM m k header) -> (loc : Label query header) ->\n (new : m ty) ->\n RecordM m k (changeType header loc ty)\nsetByLabel (Rec xs nub) (L loc) new =\n Rec (set xs loc new) (changeValuePreservesNub nub)\n\n||| Update a row, the update can change the row type.\n|||\n||| Complexity is _O(n)_\n|||\n||| @ key the row name\n||| @ xs the record\n||| @ loc the proof that the row is in it\n||| @ new the new value for the row\nset : (key : k) -> (new : m ty) -> (xs : RecordM m k header) ->\n {auto loc : Label key header} ->\n RecordM m k (changeType header loc ty)\nset _ new xs {loc} = setByLabel xs loc new\n\n||| Update a row, the update can change the row type.\n|||\n||| Complexity is _O(n)_\n|||\n||| @ query the row name\n||| @ xs the record\n||| @ loc the proof that the row is in it\n||| @ new the new value for the row\nsetA : Applicative m =>\n (query : k) -> (new : ty) -> (xs : RecordM m k header) ->\n {auto loc : Label query header} ->\n RecordM m k (changeType header loc ty)\nsetA loc = set loc . pure\n\n||| Update a row at a given `Label`, can change its type.\n|||\n||| Complexity is _O(n)_\n|||\n||| @ xs the record\n||| @ loc the proof that the row is in it\n||| @ f the update function\nupdateByLabel : (xs : RecordM m k header) -> (loc : Row query a header) ->\n (f : m a -> m b) ->\n RecordM m k (changeType header loc b)\nupdateByLabel (Rec xs nub) (R loc) f =\n Rec (update xs loc f) (changeValuePreservesNub nub)\n\n||| Update a row at the given key, can change its type.\n|||\n||| Complexity is _O(n)_\n|||\n||| @ query the row name\n||| @ xs the record\n||| @ loc the proof that the row is in it\n||| @ f the update function\nupdate : (query : k) -> (f : m a -> m b) -> (xs : RecordM m k header) ->\n {auto loc : Row query a header} ->\n RecordM m k (changeType header loc b)\nupdate _ f xs {loc} = updateByLabel xs loc f\n\n||| Map at a given `Row`, can change its type.\n|||\n||| Complexity is _O(n)_\n|||\n||| @ query the row name\n||| @ xs the record\n||| @ loc the proof that the row is in it\n||| @ f the update function\nmapRow : Functor m =>\n (query : k) -> (f : a -> b) -> (xs : RecordM m k header) ->\n {auto loc : Row query a header} ->\n RecordM m k (changeType header loc b)\nmapRow _ f xs {loc} = updateByLabel xs loc (map f)\n", "meta": {"hexsha": "df9b5ea54b957d1592799e6d1fdb3bb0837ad354", "size": 2703, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Flexidisc/Record/Update.idr", "max_stars_repo_name": "berewt/flexidisc", "max_stars_repo_head_hexsha": "8a0c367244229be5d417c04588d8d41b6030dba2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-04-02T09:51:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-03T05:15:49.000Z", "max_issues_repo_path": "src/Flexidisc/Record/Update.idr", "max_issues_repo_name": "LIST-LUXEMBOURG/flexidisc", "max_issues_repo_head_hexsha": "f5a9cdc81554359e324b64400d8479494cd45a8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Flexidisc/Record/Update.idr", "max_forks_repo_name": "LIST-LUXEMBOURG/flexidisc", "max_forks_repo_head_hexsha": "f5a9cdc81554359e324b64400d8479494cd45a8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3707865169, "max_line_length": 74, "alphanum_fraction": 0.5882352941, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.23570879540448897}} |
| {"text": "module Data.SortedMap.Dependent\n\nimport Data.DPair\n\nimport Decidable.Equality\n\n-- TODO: write split\n\n-------------------------------\n--- Internal representation ---\n-------------------------------\n\nprivate\ndata Tree : Nat -> (k : Type) -> (v : k -> Type) -> Ord k -> Type where\n Leaf : (x : k) -> v x -> Tree Z k v o\n Branch2 : Tree n k v o -> k -> Tree n k v o -> Tree (S n) k v o\n Branch3 : Tree n k v o -> k -> Tree n k v o -> k -> Tree n k v o -> Tree (S n) k v o\n\nbranch4 :\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o ->\n Tree (S (S n)) k v o\nbranch4 a b c d e f g =\n Branch2 (Branch2 a b c) d (Branch2 e f g)\n\nbranch5 :\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o ->\n Tree (S (S n)) k v o\nbranch5 a b c d e f g h i =\n Branch2 (Branch2 a b c) d (Branch3 e f g h i)\n\nbranch6 :\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o ->\n Tree (S (S n)) k v o\nbranch6 a b c d e f g h i j k =\n Branch3 (Branch2 a b c) d (Branch2 e f g) h (Branch2 i j k)\n\nbranch7 :\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o -> k ->\n Tree n k v o ->\n Tree (S (S n)) k v o\nbranch7 a b c d e f g h i j k l m =\n Branch3 (Branch3 a b c d e) f (Branch2 g h i) j (Branch2 k l m)\n\nmerge1 : Tree n k v o -> k -> Tree (S n) k v o -> k -> Tree (S n) k v o -> Tree (S (S n)) k v o\nmerge1 a b (Branch2 c d e) f (Branch2 g h i) = branch5 a b c d e f g h i\nmerge1 a b (Branch2 c d e) f (Branch3 g h i j k) = branch6 a b c d e f g h i j k\nmerge1 a b (Branch3 c d e f g) h (Branch2 i j k) = branch6 a b c d e f g h i j k\nmerge1 a b (Branch3 c d e f g) h (Branch3 i j k l m) = branch7 a b c d e f g h i j k l m\n\nmerge2 : Tree (S n) k v o -> k -> Tree n k v o -> k -> Tree (S n) k v o -> Tree (S (S n)) k v o\nmerge2 (Branch2 a b c) d e f (Branch2 g h i) = branch5 a b c d e f g h i\nmerge2 (Branch2 a b c) d e f (Branch3 g h i j k) = branch6 a b c d e f g h i j k\nmerge2 (Branch3 a b c d e) f g h (Branch2 i j k) = branch6 a b c d e f g h i j k\nmerge2 (Branch3 a b c d e) f g h (Branch3 i j k l m) = branch7 a b c d e f g h i j k l m\n\nmerge3 : Tree (S n) k v o -> k -> Tree (S n) k v o -> k -> Tree n k v o -> Tree (S (S n)) k v o\nmerge3 (Branch2 a b c) d (Branch2 e f g) h i = branch5 a b c d e f g h i\nmerge3 (Branch2 a b c) d (Branch3 e f g h i) j k = branch6 a b c d e f g h i j k\nmerge3 (Branch3 a b c d e) f (Branch2 g h i) j k = branch6 a b c d e f g h i j k\nmerge3 (Branch3 a b c d e) f (Branch3 g h i j k) l m = branch7 a b c d e f g h i j k l m\n\ntreeLookup : Ord k => (x : k) -> Tree n k v o -> Maybe (y : k ** v y) -- may also return an erased `So (x == y)`\ntreeLookup k (Leaf k' v) =\n if k == k' then\n Just (k' ** v)\n else\n Nothing\ntreeLookup k (Branch2 t1 k' t2) =\n if k <= k' then\n treeLookup k t1\n else\n treeLookup k t2\ntreeLookup k (Branch3 t1 k1 t2 k2 t3) =\n if k <= k1 then\n treeLookup k t1\n else if k <= k2 then\n treeLookup k t2\n else\n treeLookup k t3\n\ntreeInsert' : Ord k => (x : k) -> v x -> Tree n k v o -> Either (Tree n k v o) (Tree n k v o, k, Tree n k v o)\ntreeInsert' k v (Leaf k' v') =\n case compare k k' of\n LT => Right (Leaf k v, k, Leaf k' v')\n EQ => Left (Leaf k v)\n GT => Right (Leaf k' v', k', Leaf k v)\ntreeInsert' k v (Branch2 t1 k' t2) =\n if k <= k' then\n case treeInsert' k v t1 of\n Left t1' => Left (Branch2 t1' k' t2)\n Right (a, b, c) => Left (Branch3 a b c k' t2)\n else\n case treeInsert' k v t2 of\n Left t2' => Left (Branch2 t1 k' t2')\n Right (a, b, c) => Left (Branch3 t1 k' a b c)\ntreeInsert' k v (Branch3 t1 k1 t2 k2 t3) =\n if k <= k1 then\n case treeInsert' k v t1 of\n Left t1' => Left (Branch3 t1' k1 t2 k2 t3)\n Right (a, b, c) => Right (Branch2 a b c, k1, Branch2 t2 k2 t3)\n else\n if k <= k2 then\n case treeInsert' k v t2 of\n Left t2' => Left (Branch3 t1 k1 t2' k2 t3)\n Right (a, b, c) => Right (Branch2 t1 k1 a, b, Branch2 c k2 t3)\n else\n case treeInsert' k v t3 of\n Left t3' => Left (Branch3 t1 k1 t2 k2 t3')\n Right (a, b, c) => Right (Branch2 t1 k1 t2, k2, Branch2 a b c)\n\ntreeInsert : Ord k => (x : k) -> v x -> Tree n k v o -> Either (Tree n k v o) (Tree (S n) k v o)\ntreeInsert k v t =\n case treeInsert' k v t of\n Left t' => Left t'\n Right (a, b, c) => Right (Branch2 a b c)\n\ndelType : Nat -> (k : Type) -> (v : k -> Type) -> Ord k -> Type\ndelType Z k v o = ()\ndelType (S n) k v o = Tree n k v o\n\ntreeDelete : Ord k => (n : Nat) -> k -> Tree n k v o -> Either (Tree n k v o) (delType n k v o)\ntreeDelete _ k (Leaf k' v) =\n if k == k' then\n Right ()\n else\n Left (Leaf k' v)\ntreeDelete (S Z) k (Branch2 t1 k' t2) =\n if k <= k' then\n case treeDelete Z k t1 of\n Left t1' => Left (Branch2 t1' k' t2)\n Right () => Right t2\n else\n case treeDelete Z k t2 of\n Left t2' => Left (Branch2 t1 k' t2')\n Right () => Right t1\ntreeDelete (S Z) k (Branch3 t1 k1 t2 k2 t3) =\n if k <= k1 then\n case treeDelete Z k t1 of\n Left t1' => Left (Branch3 t1' k1 t2 k2 t3)\n Right () => Left (Branch2 t2 k2 t3)\n else if k <= k2 then\n case treeDelete Z k t2 of\n Left t2' => Left (Branch3 t1 k1 t2' k2 t3)\n Right () => Left (Branch2 t1 k1 t3)\n else\n case treeDelete Z k t3 of\n Left t3' => Left (Branch3 t1 k1 t2 k2 t3')\n Right () => Left (Branch2 t1 k1 t2)\ntreeDelete (S (S n)) k (Branch2 t1 k' t2) =\n if k <= k' then\n case treeDelete (S n) k t1 of\n Left t1' => Left (Branch2 t1' k' t2)\n Right t1' =>\n case t2 of\n Branch2 a b c => Right (Branch3 t1' k' a b c)\n Branch3 a b c d e => Left (branch4 t1' k' a b c d e)\n else\n case treeDelete (S n) k t2 of\n Left t2' => Left (Branch2 t1 k' t2')\n Right t2' =>\n case t1 of\n Branch2 a b c => Right (Branch3 a b c k' t2')\n Branch3 a b c d e => Left (branch4 a b c d e k' t2')\ntreeDelete (S (S n)) k (Branch3 t1 k1 t2 k2 t3) =\n if k <= k1 then\n case treeDelete (S n) k t1 of\n Left t1' => Left (Branch3 t1' k1 t2 k2 t3)\n Right t1' => Left (merge1 t1' k1 t2 k2 t3)\n else if k <= k2 then\n case treeDelete (S n) k t2 of\n Left t2' => Left (Branch3 t1 k1 t2' k2 t3)\n Right t2' => Left (merge2 t1 k1 t2' k2 t3)\n else\n case treeDelete (S n) k t3 of\n Left t3' => Left (Branch3 t1 k1 t2 k2 t3')\n Right t3' => Left (merge3 t1 k1 t2 k2 t3')\n\ntreeToList : Tree n k v o -> List (x : k ** v x)\ntreeToList = treeToList' (:: [])\n where\n -- explicit quantification to avoid conflation with {n} from treeToList\n treeToList' : {0 n : Nat} -> ((x : k ** v x) -> List (x : k ** v x)) -> Tree n k v o -> List (x : k ** v x)\n treeToList' cont (Leaf k v) = cont (k ** v)\n treeToList' cont (Branch2 t1 _ t2) = treeToList' (:: treeToList' cont t2) t1\n treeToList' cont (Branch3 t1 _ t2 _ t3) = treeToList' (:: treeToList' (:: treeToList' cont t3) t2) t1\n\n----------------------\n--- User interface ---\n----------------------\n\nexport\ndata SortedDMap : (k : Type) -> (v : k -> Type) -> Type where\n Empty : Ord k => SortedDMap k v\n M : (o : Ord k) => (n : Nat) -> Tree n k v o -> SortedDMap k v\n\nexport\nempty : Ord k => SortedDMap k v\nempty = Empty\n\nexport\nlookup : (x : k) -> SortedDMap k v -> Maybe (y : k ** v y) -- could return also `So (x == y)`\nlookup _ Empty = Nothing\nlookup k (M _ t) = treeLookup k t\n\nexport\nlookupPrecise : DecEq k => (x : k) -> SortedDMap k v -> Maybe (v x)\nlookupPrecise x = lookup x >=> \\(y ** v) =>\n case decEq x y of\n Yes Refl => Just v\n No _ => Nothing\n\nexport\ninsert : (x : k) -> v x -> SortedDMap k v -> SortedDMap k v\ninsert k v Empty = M Z (Leaf k v)\ninsert k v (M _ t) =\n case treeInsert k v t of\n Left t' => (M _ t')\n Right t' => (M _ t')\n\nexport\nsingleton : Ord k => (x : k) -> v x -> SortedDMap k v\nsingleton k v = insert k v empty\n\nexport\ninsertFrom : Foldable f => f (x : k ** v x) -> SortedDMap k v -> SortedDMap k v\ninsertFrom = flip $ foldl $ flip $ uncurry insert\n\nexport\ndelete : k -> SortedDMap k v -> SortedDMap k v\ndelete _ Empty = Empty\ndelete k (M Z t) =\n case treeDelete Z k t of\n Left t' => (M _ t')\n Right () => Empty\ndelete k (M (S n) t) =\n case treeDelete (S n) k t of\n Left t' => (M _ t')\n Right t' => (M _ t')\n\nexport\nfromList : Ord k => List (x : k ** v x) -> SortedDMap k v\nfromList = foldl (flip (uncurry insert)) empty\n\nexport\ntoList : SortedDMap k v -> List (x : k ** v x)\ntoList Empty = []\ntoList (M _ t) = treeToList t\n\n||| Gets the keys of the map.\nexport\nkeys : SortedDMap k v -> List k\nkeys = map fst . toList\n\nexport\nvalues : SortedDMap k v -> List (x : k ** v x)\nvalues = toList\n\ntreeMap : ({x : k} -> a x -> b x) -> Tree n k a o -> Tree n k b o\ntreeMap f (Leaf k v) = Leaf k (f v)\ntreeMap f (Branch2 t1 k t2) = Branch2 (treeMap f t1) k (treeMap f t2)\ntreeMap f (Branch3 t1 k1 t2 k2 t3)\n = Branch3 (treeMap f t1) k1 (treeMap f t2) k2 (treeMap f t3)\n\ntreeTraverse : Applicative f => ({x : k} -> a x -> f (b x)) -> Tree n k a o -> f (Tree n k b o)\ntreeTraverse f (Leaf k v) = Leaf k <$> f v\ntreeTraverse f (Branch2 t1 k t2) =\n Branch2\n <$> treeTraverse f t1\n <*> pure k\n <*> treeTraverse f t2\ntreeTraverse f (Branch3 t1 k1 t2 k2 t3) =\n Branch3\n <$> treeTraverse f t1\n <*> pure k1\n <*> treeTraverse f t2\n <*> pure k2\n <*> treeTraverse f t3\n\nexport\nmap : ({x : k} -> v x -> w x) -> SortedDMap k v -> SortedDMap k w\nmap _ Empty = Empty\nmap f (M _ t) = M _ $ treeMap f t\n\nexport\nfoldl : (acc -> (x : k ** v x) -> acc) -> acc -> SortedDMap k v -> acc\nfoldl f i = foldl f i . values\n\nexport\nfoldr : ((x : k ** v x) -> acc -> acc) -> acc -> SortedDMap k v -> acc\nfoldr f i = foldr f i . values\n\nexport\nfoldlM : Monad m => (acc -> (x : k ** v x) -> m acc) -> acc -> SortedDMap k v -> m acc\nfoldlM f i = foldl (\\ma, b => ma >>= flip f b) (pure i)\n\nexport\nfoldMap : Monoid m => (f : (x : k) -> v x -> m) -> SortedDMap k v -> m\nfoldMap f = foldr ((<+>) . uncurry f) neutral\n\nexport\nnull : SortedDMap k v -> Bool\nnull Empty = True\nnull (M _ _) = False\n\nexport\ntraverse : Applicative f => ({x : k} -> v x -> f (w x)) -> SortedDMap k v -> f (SortedDMap k w)\ntraverse _ Empty = pure Empty\ntraverse f (M _ t) = M _ <$> treeTraverse f t\n\n||| Merge two maps. When encountering duplicate keys, using a function to combine the values.\n||| Uses the ordering of the first map given.\nexport\nmergeWith : DecEq k => ({x : k} -> v x -> v x -> v x) -> SortedDMap k v -> SortedDMap k v -> SortedDMap k v\nmergeWith f x y = insertFrom inserted x where\n inserted : List (x : k ** v x)\n inserted = do\n (k ** v) <- toList y\n let v' = (maybe id f $ lookupPrecise k x) v\n pure (k ** v')\n\n||| Merge two maps using the Semigroup (and by extension, Monoid) operation.\n||| Uses mergeWith internally, so the ordering of the left map is kept.\nexport\nmerge : DecEq k => ({x : k} -> Semigroup (v x)) => SortedDMap k v -> SortedDMap k v -> SortedDMap k v\nmerge = mergeWith (<+>)\n\n||| Left-biased merge, also keeps the ordering specified by the left map.\nexport\nmergeLeft : DecEq k => SortedDMap k v -> SortedDMap k v -> SortedDMap k v\nmergeLeft = mergeWith const\n\ntreeLeftMost : Tree n k v o -> (x : k ** v x)\ntreeLeftMost (Leaf x y) = (x ** y)\ntreeLeftMost (Branch2 x _ _) = treeLeftMost x\ntreeLeftMost (Branch3 x _ _ _ _) = treeLeftMost x\n\ntreeRightMost : Tree n k v o -> (x : k ** v x)\ntreeRightMost (Leaf x y) = (x ** y)\ntreeRightMost (Branch2 _ _ x) = treeRightMost x\ntreeRightMost (Branch3 _ _ _ _ x) = treeRightMost x\n\ntreeLookupBetween : Ord k => k -> Tree n k v o -> (Maybe (x : k ** v x), Maybe (x : k ** v x))\ntreeLookupBetween k (Leaf k' v) with (k < k')\n treeLookupBetween k (Leaf k' v) | True = (Nothing, Just (k' ** v))\n treeLookupBetween k (Leaf k' v) | False = (Just (k' ** v), Nothing)\ntreeLookupBetween k (Branch2 t1 k' t2) with (k < k')\n treeLookupBetween k (Branch2 t1 k' t2) | True = -- k < k'\n let (lower, upper) = treeLookupBetween k t1 in\n (lower, upper <|> pure (treeLeftMost t2))\n treeLookupBetween k (Branch2 t1 k' t2) | False = -- k >= k'\n let (lower, upper) = treeLookupBetween k t2 in\n (lower <|> pure (treeRightMost t1), upper)\ntreeLookupBetween k (Branch3 t1 k1 t2 k2 t3) with (k < k1)\n treeLookupBetween k (Branch3 t1 k1 t2 k2 t3) | True = treeLookupBetween k (Branch2 t1 k1 t2)\n treeLookupBetween k (Branch3 t1 k1 t2 k2 t3) | False with (k < k2)\n treeLookupBetween k (Branch3 t1 k1 t2 k2 t3) | False | False = treeLookupBetween k (Branch2 t2 k2 t3)\n treeLookupBetween k (Branch3 t1 k1 t2 k2 t3) | False | True = --k1 <= k < k2\n let (lower, upper) = treeLookupBetween k (Branch2 t1 k1 t2) in\n (lower, upper <|> pure (treeLeftMost t3))\n\n||| looks up a key in map, returning the left and right closest values, so that\n||| k1 <= k < k2. If at the end of the beginning and/or end of the sorted map, returns\n||| nothing appropriately\nexport\nlookupBetween : k -> SortedDMap k v -> (Maybe (x : k ** v x), Maybe (x : k ** v x))\nlookupBetween k Empty = (Nothing, Nothing)\nlookupBetween k (M _ t) = treeLookupBetween k t\n\n\n||| Returns the leftmost (least) key and value\nexport\nleftMost : SortedDMap k v -> Maybe (x : k ** v x)\nleftMost Empty = Nothing\nleftMost (M _ t) = Just $ treeLeftMost t\n\n\n||| Returns the rightmost (greatest) key and value\nexport\nrightMost : SortedDMap k v -> Maybe (x : k ** v x)\nrightMost Empty = Nothing\nrightMost (M _ t) = Just $ treeRightMost t\n\nexport\n(Show k, {x : k} -> Show (v x)) => Show (SortedDMap k v) where\n show m = \"fromList \" ++ (show $ toList m)\n\nexport\n(DecEq k, {x : k} -> Eq (v x)) => Eq (SortedDMap k v) where\n (==) = (==) `on` toList\n\nexport\nstrictSubmap : DecEq k => ({x : k} -> Eq (v x)) => (sub : SortedDMap k v) -> (sup : SortedDMap k v) -> Bool\nstrictSubmap sub sup = all (\\(k ** v) => Just v == lookupPrecise k sup) $ toList sub\n\n-- TODO: is this the right variant of merge to use for this? I think it is, but\n-- I could also see the advantages of using `mergeLeft`. The current approach is\n-- strictly more powerful I believe, because `mergeLeft` can be emulated with\n-- the `First` monoid. However, this does require more code to do the same\n-- thing.\nexport\nDecEq k => ({x : k} -> Semigroup (v x)) => Semigroup (SortedDMap k v) where\n (<+>) = merge\n\n||| For `neutral <+> y`, y is rebuilt in `Ord k`, so this is not a \"strict\" Monoid.\n||| However, semantically, it should be equal.\nexport\nDecEq k => Ord k => ({x : k} -> Semigroup (v x)) => Monoid (SortedDMap k v) where\n neutral = empty\n", "meta": {"hexsha": "5dd83a51ab118d5adc3ecdd9d30cab8bb5f9ecc4", "size": 14624, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "libs/contrib/Data/SortedMap/Dependent.idr", "max_stars_repo_name": "ska80/idris-jvm", "max_stars_repo_head_hexsha": "66223d026d034578876b325e9fcd95874faa6052", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 128, "max_stars_repo_stars_event_min_datetime": "2020-06-09T21:25:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:50:24.000Z", "max_issues_repo_path": "libs/contrib/Data/SortedMap/Dependent.idr", "max_issues_repo_name": "ska80/idris-jvm", "max_issues_repo_head_hexsha": "66223d026d034578876b325e9fcd95874faa6052", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2020-08-26T03:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-23T21:32:49.000Z", "max_forks_repo_path": "libs/contrib/Data/SortedMap/Dependent.idr", "max_forks_repo_name": "ska80/idris-jvm", "max_forks_repo_head_hexsha": "66223d026d034578876b325e9fcd95874faa6052", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2020-08-28T04:16:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T12:47:16.000Z", "avg_line_length": 34.3286384977, "max_line_length": 112, "alphanum_fraction": 0.579868709, "num_tokens": 5397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23390872761876408}} |
| {"text": "module Circuits.NetList.Check\n\nimport Decidable.Equality\n\nimport Data.Nat\nimport Data.String\nimport Data.List.Elem\nimport Data.List.Quantifiers\nimport Data.Fin\n\nimport Toolkit.Decidable.Informative\n\nimport Toolkit.Data.Location\nimport Toolkit.Data.Whole\nimport Toolkit.Data.List.DeBruijn\n\nimport Ref\n\nimport Circuits.NetList.Types\nimport Circuits.NetList.Terms\nimport Circuits.NetList.AST\n\n%default total\n\ndata Entry : (String,Ty) -> Type where\n MkEntry : (name : String)\n -> (type : Ty)\n -> Entry (MkPair name type)\n\nEnv : List (String,Ty) -> Type\nEnv = Env (String,Ty) Entry\n\n\nexport\ndata Error = Mismatch Ty Ty\n | MismatchD DType DType\n | NotBound String\n | VectorExpected\n | PortChanExpected\n | PortExpected\n | OOB Nat Nat\n | ErrI String\n | Err FileContext Error\nexport\nShow Error where\n show (Mismatch x y)\n = \"Type Mismatch:\\n\\n\"\n <+>\n unlines [unwords [\"\\tExpected:\",show x], unwords [\"\\tGiven:\", show y]]\n\n show (MismatchD x y)\n = \"Type Mismatch:\\n\\n\"\n <+>\n unlines [unwords [\"\\tExpected:\",show x], unwords [\"\\tGiven:\", show y]]\n\n\n show (NotBound x)\n = unwords [\"Undeclared variable:\", x]\n\n show (VectorExpected)\n = \"Vector Expected\"\n\n show (PortChanExpected)\n = \"Port or Wire Expected\"\n\n show (PortExpected)\n = \"Port Expected\"\n\n show (ErrI msg)\n = \"Internal Err: \" <+> msg\n show (OOB x y)\n = unwords [\"Out of Bounds:\" , show x, \"is not within\", show y]\n\n show (Err x y) = unwords [show x, show y]\n\nstrip : {ctxt : List (String, Ty)}\n -> Elem (s,type) ctxt -> Elem type (map Builtin.snd ctxt)\nstrip Here = Here\nstrip (There x) = There (strip x)\n\npublic export\nTyCheck : Type -> Type\nTyCheck = Either Error\n\nlift : Dec a -> Error -> TyCheck a\nlift (Yes prf) _ = Right prf\nlift (No contra) e = Left e\n\nnamespace Elab\n\n export\n getDataType : FileContext\n -> (term : (type ** Term ctxt type))\n -> TyCheck DType\n getDataType fc (MkDPair (TyPort (d,x)) snd) = pure x\n getDataType fc (MkDPair (TyChan x) snd) = pure x\n getDataType fc (MkDPair type snd)\n = Left (Err fc PortChanExpected)\n\n ||| Need to make sure that the indices are in the correct direction.\n rewriteTerm : Cast flow expected\n -> Index INOUT\n -> Term ctxt (TyPort (flow,type))\n -> Term ctxt (TyPort (flow,type))\n rewriteTerm c d (Var prf) = Var prf\n\n rewriteTerm BI (UP UB) (Index idir what idx)\n = Index (UP UB) (rewriteTerm BI (UP UB) what) idx\n\n rewriteTerm BI (DOWN DB) (Index idir what idx)\n = Index (DOWN DB) (rewriteTerm BI (DOWN DB) what) idx\n\n rewriteTerm BO (UP UB) (Index idir what idx)\n = Index (UP UB) (rewriteTerm BI (UP UB) what) idx\n\n rewriteTerm BO (DOWN DB) (Index idir what idx)\n = Index (DOWN DB) (rewriteTerm BI (DOWN DB) what) idx\n\n rewriteTerm BI _ (Project WRITE _) impossible\n rewriteTerm BO _ (Project WRITE _) impossible\n rewriteTerm BI _ (Project READ _) impossible\n rewriteTerm BO _ (Project READ _) impossible\n\n rewriteTerm BI _ (Cast BI _) impossible\n rewriteTerm BO _ (Cast BI _) impossible\n rewriteTerm BI _ (Cast BO _) impossible\n rewriteTerm BO _ (Cast BO _) impossible\n\n ||| When casting we finally know which direction indexing should go, so lets fix that.\n shouldCast : {type : DType}\n -> (flow,expected : Direction)\n -> (term : Term ctxt (TyPort (flow,type)))\n -> Dec ( Cast flow expected\n , Term ctxt (TyPort (expected,type))\n )\n shouldCast flow expected term with (Cast.cast flow expected)\n shouldCast INOUT INPUT term | (Yes BI) with (dirFromCast BI)\n shouldCast INOUT INPUT term | (Yes BI) | idir\n = Yes $ MkPair BI (Cast BI (rewriteTerm BI idir term))\n\n\n shouldCast INOUT OUTPUT term | (Yes BO) with (dirFromCast BO)\n shouldCast INOUT OUTPUT term | (Yes BO) | idir\n = Yes $ MkPair BO (Cast BO (rewriteTerm BO idir term))\n\n shouldCast flow expected term | (No contra)\n = No (\\(prf,t) => contra prf)\n\n portCast : {type : DType}\n -> {flow : Direction}\n -> FileContext\n -> (expected : Direction)\n -> (term : Term ctxt (TyPort (flow,type)))\n -> TyCheck (Term ctxt (TyPort (expected,type)))\n\n portCast {type} {flow = flow} fc exp term with (shouldCast flow exp term)\n portCast {type} {flow = flow} fc exp term | Yes (p,e)\n = Right e\n portCast {type} {flow = flow} fc exp term | No contra with (decEq flow exp)\n portCast {type} {flow = exp} fc exp term | No contra | (Yes Refl)\n = Right term\n portCast {type} {flow = flow} fc exp term | No contra | (No f)\n = Left (Err fc (Mismatch (TyPort (exp,type)) (TyPort (flow,type))))\n\n export\n checkPort : (fc : FileContext)\n -> (exdir : Direction)\n -> (expty : DType)\n -> (term : (type ** Term ctxt type))\n -> TyCheck (Term ctxt (TyPort (exdir,expty)))\n\n -- [ NOTE ]\n --\n checkPort fc exdir exty (MkDPair (TyPort (given,x)) term)\n = do Refl <- lift (decEq exty x)\n (Err fc (MismatchD exty x))\n\n portCast fc exdir term\n\n -- [ NOTE ]\n --\n -- READ implies INPUT\n checkPort fc INPUT exty (MkDPair (TyChan x) term)\n = do Refl <- lift (decEq exty x)\n (Err fc (MismatchD exty x))\n\n pure (Project READ term)\n\n -- [ NOTE ]\n --\n -- WRITE implies OUTPUT\n checkPort fc OUTPUT exty (MkDPair (TyChan x) term)\n = do Refl <- lift (decEq exty x)\n (Err fc (MismatchD exty x))\n\n Right (Project WRITE term)\n\n -- [ NOTE ]\n --\n -- INOUT Chan's impossible.\n checkPort fc INOUT exty (MkDPair (TyChan x) term)\n = Left (Err fc (ErrI \"INOUT CHAN not expected\"))\n\n\n -- [ NOTE ]\n --\n -- Gates/TyUnit not expected\n checkPort fc exdir exty (MkDPair type term)\n = Left (Err fc (Mismatch (TyPort (exdir,exty)) type))\n\n export\n indexDir : {flow : Direction}\n -> (fc : FileContext)\n -> (term : Term ctxt (TyPort (flow,BVECT (W (S n) ItIsSucc) type)))\n -> TyCheck (Index flow)\n indexDir {flow} fc term with (flow)\n indexDir {flow = flow} fc term | INPUT\n = pure (DOWN DI)\n indexDir {flow = flow} fc term | OUTPUT\n = pure (UP UO)\n indexDir {flow = flow} fc (Var prf) | INOUT\n = pure (UP UB)\n indexDir {flow = flow} fc (Index idir what idx) | INOUT\n = pure idir\n indexDir {flow = flow} fc (Project how what) | INOUT\n = Left (Err fc (ErrI \"Shouldn't happen impossible indexing a projection with inout\"))\n indexDir {flow = flow} fc (Cast x what) | INOUT\n = Left (Err fc (ErrI \"Shouldn't happen impossible indexing a cast with inout\"))\n\nnamespace TypeCheck\n export\n typeCheck : {ctxt : List (String,Ty)}\n -> (curr : Env ctxt)\n -> (ast : AST)\n -> TyCheck (DPair Ty (Term (map Builtin.snd ctxt)))\n\n\n typeCheck {ctxt} curr (Var x)\n = do (ty ** prf) <- lift (isIndex (get x) ctxt)\n (Err (span x) (NotBound (get x)))\n\n pure (ty ** Var (strip prf))\n\n typeCheck curr (Port fc flow ty n body)\n = do (TyUnit ** term) <- typeCheck (MkEntry (get n) (TyPort (flow,ty))::curr) body\n | (type ** _) => Left (Err fc (Mismatch TyUnit type))\n\n pure (_ ** Port flow ty term)\n\n typeCheck curr (Wire fc ty n body)\n = do (TyUnit ** term) <- typeCheck (MkEntry (get n) (TyChan ty)::curr) body\n | (type ** _) => Left (Err fc (Mismatch TyUnit type))\n\n pure (_ ** Wire ty term)\n\n typeCheck curr (GateDecl fc n g body)\n = do (TyGate ** gate) <- typeCheck curr g\n | (type ** _) => Left (Err fc (Mismatch TyGate type))\n\n (TyUnit ** term) <- typeCheck (MkEntry (get n) (TyGate)::curr) body\n | (type ** _) => Left (Err fc (Mismatch TyUnit type))\n\n pure (_ ** GateDecl gate term)\n\n typeCheck curr (Assign fc i o rest)\n = do termI <- typeCheck curr i\n\n ity <- getDataType fc termI\n\n termO <- typeCheck curr o\n oty <- getDataType fc termO\n\n Refl <- lift (decEq ity oty)\n (Err fc (MismatchD ity oty))\n\n i' <- checkPort fc INPUT ity termI\n o' <- checkPort fc OUTPUT ity termO\n\n\n (TyUnit ** r') <- typeCheck curr rest\n | (type ** _) => Left (Err fc (Mismatch TyUnit type))\n\n pure (_ ** Assign i' o' r')\n\n\n typeCheck curr (Mux fc o c l r)\n = do termO <- typeCheck curr o\n termC <- typeCheck curr c\n termL <- typeCheck curr l\n termR <- typeCheck curr r\n\n o' <- checkPort fc OUTPUT LOGIC termO\n c' <- checkPort fc INPUT LOGIC termC\n l' <- checkPort fc INPUT LOGIC termL\n r' <- checkPort fc INPUT LOGIC termR\n\n pure (_ ** Mux o' c' l' r')\n\n typeCheck curr (GateU fc k o i)\n = do termO <- typeCheck curr o\n termI <- typeCheck curr i\n\n o' <- checkPort fc OUTPUT LOGIC termO\n i' <- checkPort fc INPUT LOGIC termI\n\n pure (_ ** GateU k o' i')\n\n typeCheck curr (GateB fc k o l r)\n\n = do termO <- typeCheck curr o\n termL <- typeCheck curr l\n termR <- typeCheck curr r\n\n o' <- checkPort fc OUTPUT LOGIC termO\n l' <- checkPort fc INPUT LOGIC termL\n r' <- checkPort fc INPUT LOGIC termR\n\n pure (_ ** GateB k o' l' r')\n\n typeCheck curr (Index fc idx t)\n\n = do (TyPort (flow,BVECT (W (S n) ItIsSucc) type) ** term) <- typeCheck curr t\n | (type ** term)\n => Left (Err fc VectorExpected)\n\n case natToFin idx (S n) of\n Nothing => Left (OOB idx (S n))\n Just idx' => do idir <- indexDir fc term\n pure (_ ** Index idir term idx')\n\n typeCheck curr (Split fc a b i)\n\n = do termA <- typeCheck curr a\n termB <- typeCheck curr b\n termI <- typeCheck curr i\n\n a' <- checkPort fc OUTPUT LOGIC termA\n b' <- checkPort fc OUTPUT LOGIC termB\n i' <- checkPort fc INPUT LOGIC termI\n\n pure (_ ** Split a' b' i')\n\n typeCheck curr (Collect fc o l r)\n = do (TyPort (OUTPUT,BVECT (W (S (S Z)) ItIsSucc) type) ** o') <- typeCheck curr o\n | (TyPort (flow,BVECT (W (S (S n)) ItIsSucc) type) ** term)\n => Left (Err fc (Mismatch (TyPort (OUTPUT, BVECT (W (S (S Z)) ItIsSucc) type))\n (TyPort (flow, BVECT (W (S (S n)) ItIsSucc) type))\n ))\n | (type ** term)\n => Left (Err fc VectorExpected)\n\n termL <- typeCheck curr l\n termR <- typeCheck curr r\n\n l' <- checkPort fc INPUT type termL\n r' <- checkPort fc INPUT type termR\n\n pure (_ ** Collect o' l' r')\n\n typeCheck curr (Shim fc dir thing)\n\n = do t <- typeCheck curr thing\n\n dtype <- getDataType fc t\n\n term <- checkPort fc dir dtype t\n\n pure (_ ** term)\n\n typeCheck curr (Stop x)\n = pure (_ ** Stop)\n\nnamespace Design\n export\n typeCheck : (ast : AST) -> TyCheck (Term Nil TyUnit)\n typeCheck ast with (typeCheck Nil ast)\n typeCheck ast | (Left x) = Left x\n typeCheck ast | (Right (MkDPair TyUnit term)) = Right term\n typeCheck ast | (Right (MkDPair ty snd)) = Left (Mismatch TyUnit ty)\n\n export\n typeCheckIO : (ast : AST) -> IO (TyCheck (Term Nil TyUnit))\n typeCheckIO ast = pure (typeCheck ast)\n\n-- [ EOF ]\n", "meta": {"hexsha": "2ba4e99bd6ee46adf158b432d7d9184c40ee1c71", "size": 11518, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Circuits/NetList/Check.idr", "max_stars_repo_name": "gallais/linear-circuits", "max_stars_repo_head_hexsha": "5d13d955eafc2d92beae363e96d3cec8695830f2", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Circuits/NetList/Check.idr", "max_issues_repo_name": "gallais/linear-circuits", "max_issues_repo_head_hexsha": "5d13d955eafc2d92beae363e96d3cec8695830f2", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Circuits/NetList/Check.idr", "max_forks_repo_name": "gallais/linear-circuits", "max_forks_repo_head_hexsha": "5d13d955eafc2d92beae363e96d3cec8695830f2", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8393782383, "max_line_length": 93, "alphanum_fraction": 0.5762285119, "num_tokens": 3300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23164922552692596}} |
| {"text": "module Circuits.Idealised.Check\n\nimport Decidable.Equality\n\nimport Data.Nat\nimport Data.String\nimport Data.List.Elem\nimport Data.List.Quantifiers\nimport Data.DPair\n\nimport Toolkit.Decidable.Informative\nimport Toolkit.Decidable.Equality.Views\n\nimport Toolkit.Data.Graph.EdgeBounded\nimport Toolkit.Data.Whole\nimport Toolkit.Data.Location\nimport Toolkit.Data.DList\n\nimport Toolkit.Data.List.AtIndex\nimport Toolkit.DeBruijn.Context.Item\nimport Toolkit.DeBruijn.Context\nimport Toolkit.DeBruijn.Renaming\n\n\nimport Circuits.Split\nimport Circuits.Idealised.Core\nimport Circuits.Idealised.Types\nimport Circuits.Idealised.Terms\nimport Circuits.Idealised.AST\n\n\n%default total\n\npublic export\nContext : List (Ty, Usage) -> Type\nContext = Context (Ty,Usage)\n\nnamespace FreeVar\n\n public export\n data IsFree : (item : (Ty, Usage)) -> Type\n where\n FVar : (prf : u = FREE)\n -> IsFree (type, u)\n\n\n Uninhabited (IsFree (ty,USED)) where\n uninhabited (FVar Refl) impossible\n\n isFree : (item : (Ty, Usage))\n -> DecInfo ()\n (IsFree item)\n isFree (ty, USED)\n = No () absurd\n\n isFree (ty, FREE)\n = Yes (FVar Refl)\n\n public export\n FreeVar : {types : List (Ty, Usage)}\n -> (key : String)\n -> (ctxt : Context types)\n -> Type\n FreeVar str ctxt\n = Exists (Ty,Usage)\n IsFree\n str\n ctxt\n\n export\n lookup : {types : List (Ty, Usage)}\n -> (str : String)\n -> (ctxt : Context types)\n -> DecInfo (Exists.Error ())\n (FreeVar str ctxt)\n lookup = exists isFree\n\n\nuse : (ctxt : Context curr)\n -> (use : Use curr prf next)\n -> Context next\nuse (I k (ty,FREE) :: rest) H\n = I k (ty, USED) :: rest\n\nuse (head :: tail) (T later)\n = head :: use tail later\n\n\nisUsed : (ctxt : Context types)\n -> Dec (All Used types)\nisUsed []\n = Yes []\n\nisUsed ((I name x) :: tail) with (used x)\n isUsed ((I name x) :: tail) | (Yes pH) with (isUsed tail)\n isUsed ((I name x) :: tail) | (Yes pH) | (Yes pT)\n = Yes (pH :: pT)\n\n isUsed ((I name x) :: tail) | (Yes pH) | (No contra)\n = No (\\(a::as) => contra as)\n\n isUsed ((I name x) :: tail) | (No contra)\n = No (\\(a::as) => contra a)\n\nwithLocThrow : FileContext -> Check.Error -> Idealised a\nwithLocThrow fc e = throw (TyCheck $ Err fc e)\n\nthrow : Check.Error -> Idealised a\nthrow = (throw . TyCheck)\n\npublic export\nallEqual : FileContext\n -> (a,b,c : DType)\n -> Idealised (AllEqual a b c)\nallEqual fc a b c with (Views.allEqual a b c)\n allEqual fc c c c | (Yes AE)\n = pure AE\n allEqual fc a b c | (No AB prfWhyNot)\n = withLocThrow fc (MismatchGate a b)\n allEqual fc a b c | (No AC prfWhyNot)\n = withLocThrow fc (MismatchGate a c)\n\n\ndata Result : (curr : List (Ty,Usage))\n -> Type\n where\n R : {cout : _}\n -> (type : Ty)\n -> (new : Context cout)\n -> (term : Term cin type cout)\n -> Result cin\n\ncheck : {cin : List (Ty,Usage)}\n -> (curr : Context cin)\n -> (ast : AST)\n -> Idealised (Result cin)\n\ncheck curr (Var x) with (FreeVar.lookup (get x) curr)\n check curr (Var x) | (Yes (E type item prf locC locN)) with (prf)\n check curr (Var x) | (Yes (E (type, u) item prf locC locN)) | (FVar prf1) with (prf1)\n check curr (Var x) | (Yes (E (type, FREE) item prf locC locN)) | (FVar prf1) | Refl with (use (V _ locN))\n check curr (Var x) | (Yes (E (type, FREE) item prf locC locN)) | (FVar prf1) | Refl | (MkDPair next pU) with (use curr pU)\n check curr (Var x) | (Yes (E (type, FREE) item prf locC locN)) | (FVar prf1) | Refl | (MkDPair next pU) | new\n = pure (R type new (Var (V _ locN) pU))\n\n check curr (Var x) | (No msg _)\n = withLocThrow (span x) (ElemFail (get x) msg)\n\ncheck curr (Input fc x y name body)\n\n = do R TyUnit Nil body <- check (I (get name) ((TyPort (MkPair x y)),FREE) :: curr)\n body\n | R ty Nil _ => throw (Mismatch TyUnit ty)\n | R _ xs _ => withLocThrow fc (LinearityError xs)\n\n pure (R TyUnit Nil (NewSignal x y body))\n\ncheck curr (Wire fc type a b body)\n\n = do R TyUnit Nil term <- check (I (get a) ((TyPort (MkPair OUTPUT type)), FREE) ::\n I (get b) ((TyPort (MkPair INPUT type)), FREE) :: curr)\n body\n | R ty Nil _ => throw (Mismatch TyUnit ty)\n | R ty xs _ => withLocThrow fc (LinearityError xs)\n\n pure (R TyUnit Nil (Wire type term))\n\ncheck curr (Seq x y)\n = do R TyGate ex x <- check curr x\n | R ty _ _ => throw (Mismatch TyGate ty)\n\n R TyUnit Nil y <- check ex y\n | R ty Nil _ => throw (Mismatch TyUnit ty)\n | R ty xs _ => throw (LinearityError xs)\n\n pure (R TyUnit Nil (Seq x y))\n\ncheck curr (Mux fc o c a b)\n = do R (TyPort (OUTPUT,dtypeA)) cO o <- check curr o\n | _ => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT,LOGIC)) cC c <- check cO c\n | R ty _ _ => withLocThrow fc (Mismatch (TyPort (INPUT,LOGIC)) ty)\n\n R (TyPort (INPUT,dtypeB)) cA a <- check cC a\n | _ => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT,dtypeC)) cB b <- check cA b\n | _ => withLocThrow fc (PortExpected OUTPUT)\n\n\n AE <- allEqual fc dtypeA dtypeB dtypeC\n\n pure (R TyGate cB (Mux o c a b))\n\ncheck curr (Dup fc a b i)\n = do R (TyPort (OUTPUT,dtypeA)) cA a <- check curr a\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (OUTPUT,dtypeB)) cB b <- check cA b\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT,dtypeC)) cI i <- check cB i\n | ty => withLocThrow fc (PortExpected INPUT)\n\n AE <- allEqual fc dtypeA dtypeB dtypeC\n\n pure (R TyGate cI (Dup a b i))\n\ncheck curr (Not fc a b)\n = do R (TyPort (OUTPUT,LOGIC)) cA a <- check curr a\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT,LOGIC)) cB b <- check cA b\n | ty => withLocThrow fc (PortExpected INPUT)\n\n pure (R TyGate cB (Not a b))\n\ncheck curr (Gate fc k a b c)\n = do R (TyPort (OUTPUT,LOGIC)) cA a <- check curr a\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT,LOGIC)) cB b <- check cA b\n | ty => withLocThrow fc (PortExpected INPUT)\n\n R (TyPort (INPUT,LOGIC)) cC c <- check cB c\n | ty => withLocThrow fc (PortExpected INPUT)\n\n\n pure (R TyGate cC (Gate k a b c))\n\n\ncheck curr (IndexS fc o i)\n = do R (TyPort (OUTPUT,dtypeO)) cO termO <- check curr o\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT,BVECT (W (S Z) ItIsSucc) dtypeI)) cI termI <- check cO i\n | R (TyPort (INPUT, BVECT s type)) _ _\n => withLocThrow fc (Mismatch (TyPort (INPUT, BVECT (W (S Z) ItIsSucc) type))\n (TyPort (INPUT, BVECT s type)))\n | ty => withLocThrow fc (PortExpected INPUT)\n\n Refl <- embed (TyCheck $ Err fc (MismatchGate dtypeO dtypeI))\n (decEq dtypeO dtypeI)\n\n\n pure (R TyGate cI (IndexSingleton termO termI))\n\ncheck curr (IndexE fc k a b i)\n\n = do R (TyPort (OUTPUT,dtypeA)) cA termA <- check curr a\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (OUTPUT,BVECT free dtypeB)) cB termB <- check cA b\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT,BVECT size dtypeC)) cI termI <- check cB i\n | ty => withLocThrow fc (PortExpected INPUT)\n\n AE <- allEqual fc dtypeA dtypeB dtypeC\n\n let p = case k of { F => minus (toNat size) 1; L => 0}\n\n (s ** prf) <- embed (const $ TyCheck $ Err fc (NotEdgeCase (InvalidEdge (toNat size) (S Z) (toNat free))))\n (EdgeCase.index size p)\n\n\n Refl <- embed (TyCheck $ Err fc (NotEdgeCase (InvalidEdge (toNat size) (S Z) (toNat free))))\n (decEq free s)\n\n\n pure (R TyGate cI (IndexEdge p prf termA termB termI))\n\ncheck curr (IndexP fc p a b c i)\n = do R (TyPort (OUTPUT,dtypeA)) cA termA <- check curr a\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (OUTPUT,BVECT freeB dtypeB)) cB termB <- check cA b\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (OUTPUT,BVECT freeC dtypeC)) cC termC <- check cB c\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT,BVECT size dtypeD)) cI termI <- check cC i\n | ty => withLocThrow fc (PortExpected INPUT)\n\n Refl <- embed (TyCheck $ Err fc (MismatchGate dtypeA (BVECT freeB dtypeB)))\n (decEq dtypeA dtypeB)\n\n Refl <- embed (TyCheck $ Err fc (MismatchGate (BVECT freeB dtypeB) (BVECT freeC dtypeC)))\n (decEq dtypeB dtypeC)\n\n\n Refl <- embed (TyCheck $ Err fc (MismatchGate (BVECT freeC dtypeC) (BVECT size dtypeD)))\n (decEq dtypeC dtypeD)\n\n\n (a ** b ** prf) <- embed (const $ TyCheck $ Err fc (NotEdgeCase (InvalidSplit p (toNat size) (toNat freeB) (toNat freeC))))\n (Pivot.index p size)\n\n\n Refl <- embed (TyCheck $ Err fc (MismatchGate (BVECT a dtypeB)\n (BVECT freeB dtypeB)))\n (decEq freeB a)\n\n Refl <- embed (TyCheck $ Err fc (MismatchGate (BVECT b dtypeB)\n (BVECT freeC dtypeB)))\n (decEq freeC b)\n\n pure (R TyGate cI (IndexSplit p prf termA termB termC termI))\n\ncheck curr (MergeS fc o i)\n\n = do R (TyPort (OUTPUT,BVECT (W (S Z) ItIsSucc) dtypeO)) cO termO <- check curr o\n | R (TyPort (INPUT, BVECT s type)) _ _\n => withLocThrow fc (Mismatch (TyPort (OUTPUT, BVECT (W (S Z) ItIsSucc) type))\n (TyPort (INPUT, BVECT s type)))\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT, dtypeI)) cI termI <- check cO i\n | ty => withLocThrow fc (PortExpected INPUT)\n\n Refl <- embed (TyCheck $ Err fc (MismatchGate dtypeO dtypeI))\n (decEq dtypeO dtypeI)\n\n\n pure (R TyGate cI (MergeSingleton termO termI))\n\n\ncheck curr (MergeV fc o a b)\n\n = do R (TyPort (OUTPUT, dtypeO)) cO termO <- check curr o\n | ty => withLocThrow fc (PortExpected OUTPUT)\n\n R (TyPort (INPUT, dtypeA)) cA termA <- check cO a\n | ty => withLocThrow fc (PortExpected INPUT)\n\n R (TyPort (INPUT, dtypeB)) cB termB <- check cA b\n | ty => withLocThrow fc (PortExpected INPUT)\n\n case Views.allEqual LOGIC dtypeA dtypeB of\n Yes AE\n => do Refl <- embed (TyCheck (Err fc (MismatchGate (BVECT (W (S (S Z)) ItIsSucc) LOGIC)\n dtypeO)))\n (decEq dtypeO (BVECT (W (S (S Z)) ItIsSucc) LOGIC))\n\n pure (R TyGate cB (Merge2L2V termO termA termB))\n No msg prf\n => case dtypeO of\n LOGIC => withLocThrow fc VectorExpected\n BVECT sO tO\n => case dtypeA of\n LOGIC => withLocThrow fc VectorExpected\n BVECT sA tA\n => case dtypeB of\n LOGIC => withLocThrow fc VectorExpected\n BVECT sB tB\n => do prfS <- embed (TyCheck (Err fc (VectorSizeMismatch sO sA sB)))\n (isPlus sA sB sO)\n\n AE <- allEqual fc tO tA tB\n\n pure (R TyGate cB (Merge2V2V prfS termO termA termB))\n\n\ncheck curr (Stop fc)\n = do prf <- embed (TyCheck (Err fc (LinearityError curr)))\n (isUsed curr)\n\n pure (R TyUnit Nil (Stop prf))\n\nnamespace Design\n\n export\n check : (ast : AST)\n -> Idealised (Term Nil TyUnit Nil)\n check ast\n = do R TyUnit Nil term <- check Nil ast\n | R ty _ _ => throw (TyCheck (Mismatch TyUnit ty))\n pure term\n\n-- [ EOF ]\n", "meta": {"hexsha": "14b2f5fab326c462c722905d802e0dc76f57c4bc", "size": 12335, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Circuits/Idealised/Check.idr", "max_stars_repo_name": "border-patrol/linear-circuits", "max_stars_repo_head_hexsha": "e6eb41dc07830d2e337acfad5b087fcc81479aa9", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-11-29T17:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T21:41:44.000Z", "max_issues_repo_path": "src/Circuits/Idealised/Check.idr", "max_issues_repo_name": "border-patrol/linear-circuits", "max_issues_repo_head_hexsha": "e6eb41dc07830d2e337acfad5b087fcc81479aa9", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Circuits/Idealised/Check.idr", "max_forks_repo_name": "border-patrol/linear-circuits", "max_forks_repo_head_hexsha": "e6eb41dc07830d2e337acfad5b087fcc81479aa9", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-09T19:49:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T19:49:11.000Z", "avg_line_length": 32.2062663185, "max_line_length": 130, "alphanum_fraction": 0.5502229428, "num_tokens": 3581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23053760221808195}} |
| {"text": "module Data.Bytes.Strict.API\n\nimport public Data.Bytes.Strict.Internal\nimport public Data.Bytes.Prim\nimport Data.Bytes.Util\n\nimport Data.Word.Word8\n\nimport Data.List -- List.drop\n\nmoduleName : String\nmoduleName = \"Data.Bytes.Strict.API\"\n\n%hide Prelude.empty\n\n%default total\n\n---------------------------------------------------------------------\n-- Documentation\n---------------------------------------------------------------------\n{-\n\nPretty standard (strict) ByteString kind of stuff. Some operations have `'`\n(prime) versions with slightly different behavior for convenience. In\nparticular operations which require `NonEmpty` proof have their `'` versions\ngive runtime errors on bad inputs instead. And things like replicate' use Int\ninstead of Nat.\n\nThis is to support what I consider the Idris community spirit: be provably safe\nwhen it can be made convenient, but don't force anyone to jump through hoops.\nI'm sure there's better wording for that though.\n\nIncluded are some intended complexity values. They might be a lie since I don't\nunderstand complexity very well. Hopefully they're in the ballpark, which is\nall big-o is anyway.\n\nOpen Design Questions:\n\nIs there a reason to allow negative position values in a Bytes? If we were\nusing pointers there might be some cute things we could do with that but\noverall it doesn't really seem useful.\nIf we can get Nat or Fin to compile to Int, instead of the Integer that Nat\ncompiles to, then Nat for both fields of Bytes makes sense.\n\nhttps://hackage.haskell.org/package/bytestring-0.10.10.0/docs/src/Data.ByteString.Internal.html#concat\nShould helpers take all their arguments explicitly to avoid capturing as much\nin closures? Does this even happen in idris?\n\nShould things like replicate and unfoldrN simply cast their Nat and then call\nto replicate'/unfoldrN' ? If that's the case is there any advantage to\nproviding them, aside from reducing cast noise for users?\n\nShould functions that return List return lazy Lists?\n\n\n\nIf you feel something is missing from the API it might not be! Internal modules\nimplement common interfaces, be sure to check there first. e.g. <+>\n-}\n\n\n-- All of this will get fancier as Idris2 gains support for documentation\n-- generation.\n\n---------------------------------------------------------------------\n-- API\n---------------------------------------------------------------------\n\n\n\n-------------------------------------------------\n-- Barebones basic Bytes\n-------------------------------------------------\n\n\n-- Intended complexity: O(1)\nexport\nempty : Bytes\nempty = neutral\n\n-- Intended complexity: O(1)\n-- Provides NonEmpty\nexport\nsingleton : Word8 -> Bytes\nsingleton w = unsafeCreateBytes 1 $ \\p => setByte p 0 w\n\nprivate\npackLenBytes : Int -> List Word8 -> Bytes\npackLenBytes len xs0\n = unsafeCreateBytes len $ \\b => go 0 b xs0\n where\n go : Int -> MutBlock -> List Word8 -> IO ()\n go p buf [] = pure ()\n go p buf (x::xs) = setByte buf p x *> go (p+1) buf xs\n\n-- Intended complexity: O(n)\nexport\npack : List Word8 -> Bytes\npack xs = packLenBytes (cast (length xs)) xs\n\n-- Intended complexity: O(n)\nexport\nunpack : Bytes -> List Word8\nunpack (MkB fp pos len) =\n take (intToNat len) . drop (intToNat pos)\n . unsafePerformIO . blockData $ fp\n\n-------------------------------------------------\n-- Basic interface\n-------------------------------------------------\n\n-- Intended complexity: O(1)\ntotal\nlength : Bytes -> Int\nlength (MkB _ _ len) = len\n\n-- Intended complexity: O(1)\nexport\ntotal\nnull : Bytes -> Bool\nnull buf = 0 >= length buf\n\n-- Intended complexity: O(1)\nexport\ncons : Word8 -> Bytes -> Bytes\ncons x (MkB p0 pos len)\n = do unsafeCreateBytes (1 + len) $ \\p => do\n setByte p 0 x\n copyBlock p0 pos len p 1\n\n-- Intended complexity: O(1)\nexport\nsnoc : Bytes -> Word8 -> Bytes\nsnoc (MkB p0 pos len) x\n = unsafeCreateBytes (1 + len) $ \\p => do\n copyBlock p0 pos len p 0\n setByte p len x\n\n-- Intended complexity: O(1)\nexport\nhead : (b : Bytes) -> NonEmpty b => Word8\nhead (MkB b pos _) = unsafePerformIO (getByte b pos)\n\nexport\npartial\nhead' : (b : Bytes) -> Word8\nhead' (MkB b pos len) = if 0 >= len\n then errorCall moduleName \"head'\" \"block empty\"\n else unsafePerformIO (getByte b pos)\n\n-- Intended complexity: O(1)\nexport\ntail : (b : Bytes) -> NonEmpty b => Bytes\ntail (MkB p pos len) = MkB p (1 + pos) (len - 1)\n\nexport\npartial\ntail' : Bytes -> Bytes\ntail' (MkB p pos len) = if len > 0\n then MkB p (1 + pos) (len - 1)\n else errorCall moduleName \"tail'\" \"block empty\"\n\n-- Intended complexity: O(1)\nexport\nuncons : (b : Bytes) -> NonEmpty b => (Word8, Bytes)\nuncons bs = (head bs, tail bs)\n\nexport\nuncons' : Bytes -> Maybe (Word8, Bytes)\nuncons' bs@(MkB _ _ len) = if len > 0\n then Just ( assert_total $ head' bs\n , assert_total $ tail' bs)\n else Nothing\n\nexport\npartial\nuncons'' : Bytes -> (Word8, Bytes)\nuncons'' bs@(MkB _ _ len)\n = if len > 0\n then (head' bs, tail' bs)\n else errorCall moduleName \"uncons''\" \"block empty\"\n\n-- Intended complexity: O(1)\nexport\nlast : (b : Bytes) -> NonEmpty b => Word8\nlast (MkB p pos len) = unsafePerformIO (getByte p (len + pos - 1))\n\nexport\npartial\nlast' : Bytes -> Word8\nlast' (MkB p pos len) = if len > 0\n then unsafePerformIO (getByte p (len + pos - 1))\n else errorCall moduleName \"last'\" \"block empty\"\n\n-- Intended complexity: O(1)\nexport\ninit : (b: Bytes) -> NonEmpty b => Bytes\ninit (MkB p pos len) = MkB p pos (len - 1)\n\nexport\npartial\ninit' : Bytes -> Bytes\ninit' (MkB p pos len) = if len > 0\n then MkB p pos (len - 1)\n else errorCall moduleName \"init'\" \"block empty\"\n\n-- Intended complexity: O(1)\nexport\nunsnoc : (b : Bytes) -> NonEmpty b => (Bytes, Word8)\nunsnoc bs = (init bs, last bs)\n\nexport\nunsnoc' : Bytes -> Maybe (Bytes, Word8)\nunsnoc' bs@(MkB _ _ len) = if len > 0\n then Just ( assert_total $ init' bs\n , assert_total $ last' bs)\n else Nothing\n\nexport\npartial\nunsnoc'' : Bytes -> (Bytes, Word8)\nunsnoc'' bs@(MkB _ _ len) = if len > 0\n then (init' bs, last' bs)\n else errorCall moduleName \"unsnoc''\" \"block empty\"\n\n-------------------------------------------------\n-- Transforms\n-------------------------------------------------\n\n-- Intended complexity: O(n)\nexport\nreverse : Bytes -> Bytes\nreverse b@(MkB buf pos len) = unsafeCreateBytes len $ \\new =>\n rev_ 0 (len - 1) new\n where\n rev_ : Int -> Int -> MutBlock -> IO ()\n rev_ p q new = if 0 > q\n then pure ()\n else do\n x <- getByte buf (pos + p)\n setByte new q x\n assert_total $ rev_ (p+1) (q-1) new\n\nsort : Bytes -> Bytes\n\nintersperse : Word8 -> Bytes -> Bytes\n\nintercalate : Bytes -> List Bytes -> Bytes\n\n\ntranspose : List Bytes -> List Bytes\n\nexport\nstringToBytes : String -> Int -> (Bytes,Int)\nstringToBytes str len = unsafeCreateNBytes' len $ \\b => do\n (_,r) <- fef b (unpack str) 0\n pure (r,r)\n where\n fef : MutBlock -> List Char -> Int -> IO (MutBlock, Int)\n fef bs [] pos = pure (bs,pos)\n fef bs (c :: cs) pos = if len > pos\n then setByte bs pos (cast (cast {to=Int} c)) *> fef bs cs (pos+1)\n else pure (bs, pos)\n\n\n-------------------------------------------------\n-- Folding\n-------------------------------------------------\n\n-- Intended complexity: O(n)\nexport\nfoldl : (a -> Word8 -> a) -> a -> Bytes -> a\nfoldl f v (MkB b pos len)\n = unsafePerformIO $ go v pos (len + pos)\n where\n go : a -> (start : Int) -> (end : Int) -> IO a\n go z p q\n = if p >= q then pure z\n else assert_total $ go (f z !(getByte b p)) (p+1) q\n\n-- TODO: consider foldl', foldl with a lazy accumulator\n\nfoldl1 : (Word8 -> Word8 -> Word8) -> (b : Bytes) -> NonEmpty b => Word8\nfoldl1 f b = foldl f (head b) (tail b)\n\npartial\nfoldl1' : (Word8 -> Word8 -> Word8) -> (b : Bytes) -> Word8\nfoldl1' f b = foldl f (head' b) (tail'\n b)\n\n-- Intended complexity: O(n)\nexport\nfoldr : (Word8 -> a -> a) -> a -> Bytes -> a\nfoldr f v (MkB bs pos len)\n = unsafePerformIO $ go v pos (len + pos - 1)\n where\n go : a -> (start : Int) -> (end : Int) -> IO a\n go z p q\n = if p > q then pure z\n else assert_total $ go (f !(getByte bs q) z) p (q-1)\n\n-- TODO: consider foldr', foldr with a lazy accumulator\n\nfoldr1 : (Word8 -> Word8 -> Word8) -> (b : Bytes) -> NonEmpty b => Word8\nfoldr1 f b = foldr f (last b) (init b)\n\npartial\nfoldr1' : (Word8 -> Word8 -> Word8) -> Bytes -> Word8\nfoldr1' f b = foldr f (last' b) (init' b)\n\nconcat : List Bytes -> Bytes\n\nconcatMap : (Word8 -> Bytes) -> Bytes -> Bytes\n\n-------------------------------------------------\n-- Mapping\n-------------------------------------------------\n\n-- Intended complexity: O(n)\nexport\nmap : (Word8 -> Word8) -> Bytes -> Bytes\nmap f (MkB b0 pos len)\n = unsafeCreateBytes len $ \\new => map_ 0 len new\n where\n map_ : (pos1 : Int) -> (pos2 : Int) -> MutBlock -> IO ()\n map_ p q buf = if p >= q then pure ()\n else do\n x <- getByte b0 (pos + p)\n setByte buf p (f x)\n assert_total $ map_ (p+1) q buf\n\n-- foldl with a state passed along\nmapAccumL : (s -> Word8 -> (s, Word8)) -> s -> Bytes -> (s, Bytes)\n\n-- foldr with a state passed along\nmapAccumR : (s -> Word8 -> (s, Word8)) -> s -> Bytes -> (s, Bytes)\n\n-------------------------------------------------\n-- Scans\n-------------------------------------------------\n\nscanl : (Word8 -> Word8 -> Word8) -> Word8 -> Bytes -> Bytes\nscanl1 : (Word8 -> Word8 -> Word8) -> (b : Bytes) -> NonEmpty b => Bytes\nscanl1' : (Word8 -> Word8 -> Word8) -> Bytes -> Bytes\n\nscanr : (Word8 -> Word8 -> Word8) -> Word8 -> Bytes -> Bytes\nscanr1 : (Word8 -> Word8 -> Word8) -> (b : Bytes) -> NonEmpty b => Bytes\nscanr1' : (Word8 -> Word8 -> Word8) -> Bytes -> Bytes\n\n-------------------------------------------------\n-- Generate Bytes\n-------------------------------------------------\n\n-- This can be written faster with a primitive like memset, should backends be\n-- inclined to provide one?\n-- Like replicate for List and elsewhere negative values are treated as 0.\nreplicate' : Int -> Word8 -> Bytes\nreplicate' n w = if n > 0\n then map (const w) $ unsafeCreateBytes n $ (\\_ => pure ())\n else neutral\n\n-- Why does a Nat version exist you ask? To make safety painless. People are\n-- hopefully going to be using Nat all over their programs for safety reasons\n-- so we want to support that easily. The user littering their code with casts\n-- can get tedious so we'll support that for them here. That being said,\n-- replicate' exists for when you're using Int anyway and especially if that's\n-- due to performance, note that Nat compiles to Integer which (depending on\n-- the backend) can be slower than Int.\n-- TODO: should this case on Nat or is a cast fine? What does casing gain us?\nreplicate : Nat -> Word8 -> Bytes\nreplicate n w = replicate' (cast n) w\n\nunfoldr : (a -> Maybe (Word8, a)) -> a -> Bytes\n\nunfoldrN : Nat -> (a -> Maybe (Word8, a)) -> a -> (Bytes, Maybe a)\n\nunfoldrN' : Int -> (a -> Maybe (Word8, a)) -> a -> (Bytes, Maybe a)\n\n-------------------------------------------------\n-- Splitting Bytes\n-------------------------------------------------\n\ntake' : Int -> Bytes -> Bytes\ntake : Nat -> Bytes -> Bytes\n\ndrop' : Int -> Bytes -> Bytes\ndrop : Nat -> Bytes -> Bytes\n\nsplitAt' : Int -> Bytes -> (Bytes, Bytes)\nsplitAt : Nat -> Bytes -> (Bytes, Bytes)\n\ntakeWhile : (Word8 -> Bool) -> Bytes -> Bytes\ndropWhile : (Word8 -> Bool) -> Bytes -> Bytes\n\nspan : (Word8 -> Bool) -> Bytes -> (Bytes, Bytes)\nspanEnd : (Word8 -> Bool) -> Bytes -> (Bytes, Bytes) -- starts from end\n\n-- Should I really provide break when a person can just write not?\n-- Might as well, for the same reason that we provide Nat and Int versions.\nbreak : (Word8 -> Bool) -> Bytes -> (Bytes, Bytes)\nbreakEnd : (Word8 -> Bool) -> Bytes -> (Bytes, Bytes) -- starts from end\n\n-- potentially faster than groupBy (==), depends how we write this\ngroup : Bytes -> List Bytes\n\ngroupBy : (Word8 -> Word8 -> Bool) -> Bytes -> List Bytes\n\ninits : Bytes -> List Bytes\ntails : Bytes -> List Bytes\n\n-- TODO: Is this really common enough a need to include?\n-- returns 2nd Bytes stripped of 1st Bytes iff 1st is a prefix of 2nd\nstripPrefix : Bytes -> Bytes -> Maybe Bytes\n\n-- Same, but from the other end.\nstripSuffix : Bytes -> Bytes -> Maybe Bytes\n\n-- split on, and consume, each occurence of Word8\nsplit : Word8 -> Bytes -> List Bytes\n\n-- same as above with predicate to determine delimiter\nsplitWith : (Word8 -> Bool) -> Bytes -> List Bytes\n\n-------------------------------------------------\n-- Predicates\n-------------------------------------------------\n\nany : (Word8 -> Bool) -> Bytes -> Bool\nall : (Word8 -> Bool) -> Bytes -> Bool\n\nisPrefixOf : Bytes -> Bytes -> Bool\nisSuffixOf : Bytes -> Bytes -> Bool\nisInfixOf : Bytes -> Bytes -> Bool\n\n\n-------------------------------------------------\n-- Searches\n-------------------------------------------------\n\n-- TODO: needs more fitting name, even though yes we have a string of bytes in\n-- memory.\n-- Like break but we're breaking on a Bytes instead of a Word8. Examples:\n{-\nbreakSubstring [3,4] [1,2,3,4,5] ~ ([1,2],[3,4,5])\nbreakSubstring [3] [1,2,3,4,5] ~ ([1,2],[3,4,5])\nbreakSubstring [3,4,5,6] [1,2,3,4,5] ~ ([1,2,3,4,5],[]) -- NB\nbreakSubstring [6] [1,2,3,4,5] ~ ([1,2,3,4,5],[])\n-}\n-- This is likely to be a big player when you go to write parsers for Bytes\nbreakSubstring : Bytes -> Bytes -> (Bytes, Bytes)\n\n\nelem : Word8 -> Bytes -> Bool\n\n-- notElem is a common enough need to provide it for users so they don't have\n-- to compose `not`\nnotElem : Word8 -> Bytes -> Bool\n\nmaximum : Bytes -> Word8\nminimum : Bytes -> Word8\n\nfind : (Word8 -> Bool) -> Bytes -> Maybe Word8\n\nfilter : (Word8 -> Bool) -> Bytes -> Bytes\n\npartition : (Word8 -> Bool) -> Bytes -> (Bytes, Bytes)\n\n-------------------------------------------------\n-- Indexing\n-------------------------------------------------\n\n-- NB: Best to avoid the Nat returning options until we have a primitive cast\n-- for it to Int.\n\nindex : Bytes -> Nat -> Word8\n\nindex' : Bytes -> Int -> Word8\n\nelemIndex : Word8 -> Bytes -> Maybe Nat\nelemIndex' : Word8 -> Bytes -> Maybe Int\n\nelemIndices : Word8 -> Bytes -> List Nat\nelemIndices' : Word8 -> Bytes -> List Int\n\nelemIndexEnd : Word8 -> Bytes -> Maybe Nat\nelemIndexEnd' : Word8 -> Bytes -> Maybe Int\n\nfindIndex : (Word8 -> Bool) -> Bytes -> Maybe Nat\nfindIndex' : (Word8 -> Bool) -> Bytes -> Maybe Int\n\ncount : Word8 -> Bytes -> Nat\ncount' : Word8 -> Bytes -> Int\n\n-------------------------------------------------\n-- Zips\n-------------------------------------------------\n\n-- analogous to zip for List\nzip : Bytes -> Bytes -> List (Word8, Word8)\n\nzipWith : (Word8 -> Word8 -> a) -> Bytes -> Bytes -> List a\n\nunzip : List (Word8, Word8) -> (Bytes, Bytes)\n\n", "meta": {"hexsha": "dff08256005fc6cbdcc67968910ad12b28624a04", "size": 15230, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Data/Bytes/Strict/API.idr", "max_stars_repo_name": "MarcelineVQ/idris2-bytes", "max_stars_repo_head_hexsha": "c9b18be89fafb077b56ab27d9176e6a78b6b351f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-05-20T09:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T16:06:02.000Z", "max_issues_repo_path": "src/Data/Bytes/Strict/API.idr", "max_issues_repo_name": "MarcelineVQ/idris2-bytes", "max_issues_repo_head_hexsha": "c9b18be89fafb077b56ab27d9176e6a78b6b351f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-27T22:41:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T21:28:06.000Z", "max_forks_repo_path": "src/Data/Bytes/Strict/API.idr", "max_forks_repo_name": "MarcelineVQ/idris2-bytes", "max_forks_repo_head_hexsha": "c9b18be89fafb077b56ab27d9176e6a78b6b351f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-10-26T14:45:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T09:13:23.000Z", "avg_line_length": 30.1584158416, "max_line_length": 102, "alphanum_fraction": 0.5638214051, "num_tokens": 4074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23004915594047903}} |
| {"text": "\n||| SipHash24 copied from C [reference implementation](https://github.com/veorq/SipHash/blob/master/siphash.c)\n||| and rust https://doc.rust-lang.org/src/core/hash/sip.rs.html\nmodule Data.Hashable.SipHashV2\n\nimport Data.Buffer\n\n%default total\n\n%inline\nCROUNDS : Nat\nCROUNDS = 2\n\n%inline\nDROUNDS : Nat\nDROUNDS = 4\n\nrecord HashState where\n constructor MkST\n v0 : Bits64\n v1 : Bits64\n v2 : Bits64\n v3 : Bits64\n\ninitHashState : HashState\ninitHashState = MkST\n { v0 = 0x736f6d6570736575\n , v1 = 0x646f72616e646f6d\n , v2 = 0x6c7967656e657261\n , v3 = 0x7465646279746573\n }\n\nrecord PartialHash where\n constructor MkPartial\n tail : Bits64\n index : Bits64\n length : Bits64\n hst : HashState\n\ninitPartial : PartialHash\ninitPartial = MkPartial 0 0 0 initHashState\n\n%inline\nshl : Bits64 -> Bits64 -> Bits64\nshl = prim__shl_Bits64\n\n%inline\nshr : Bits64 -> Bits64 -> Bits64\nshr = prim__shr_Bits64\n\n%inline\nbor : Bits64 -> Bits64 -> Bits64\nbor = prim__or_Bits64\n\n%inline\nxor : Bits64 -> Bits64 -> Bits64\nxor = prim__xor_Bits64\n\n%inline\nand : Bits64 -> Bits64 -> Bits64\nand = prim__and_Bits64\n\n%inline\nshr16 : Bits16 -> Bits16 -> Bits16\nshr16 = prim__shr_Bits16\n\n%inline\nshr32 : Bits32 -> Bits32 -> Bits32\nshr32 = prim__shr_Bits32\n\n%inline\nandInt : Int -> Int -> Int\nandInt = prim__and_Int\n\n%inline\n%spec b\nrotl : Bits64 -> (b : Bits64) -> Bits64\nrotl x b = (x `shl` b) `bor` (x `shr` (64 - b))\n\n-- Make the length the smallest multiple of 8 tail >= the given number\n%inline\nfullSize : Int -> Int\nfullSize x =\n let left = x `andInt` 7\n in if (x `andInt` 7) == 0\n then x\n else x - left + 8\n\ncompress : HashState -> HashState\ncompress (MkST v0 v1 v2 v3) =\n let v0 = v0 + v1;\n v1 = v1 `rotl` 13;\n v1 = v1 `xor` v0;\n v0 = v0 `rotl` 32;\n v2 = v2 + v3;\n v3 = v3 `rotl` 16;\n v3 = v3 `xor` v2;\n v0 = v0 + v3;\n v3 = v3 `rotl` 21;\n v3 = v3 `xor` v0;\n v2 = v2 + v1;\n v1 = v1 `rotl` 17;\n v1 = v1 `xor` v2;\n v2 = v2 `rotl` 32;\n in MkST v0 v1 v2 v3\n\n%inline\n%spec rounds, f\nrepeat : (rounds : Nat) -> (f : a -> a) -> a -> a\nrepeat Z f x = x\nrepeat (S k) f x = repeat k f (f x)\n\n%inline\nhashBits64 : HashState -> Bits64 -> HashState\nhashBits64 (MkST v0 v1 v2 v3) m =\n let v3 = v3 `xor` m\n MkST v0 v1 v2 v3 = repeat CROUNDS compress $ MkST v0 v1 v2 v3\n v0 = v0 `xor` m\n in MkST v0 v1 v2 v3\n\nexport\nfinish : PartialHash -> Bits64\nfinish (MkPartial tail index length hst) =\n let MkST v0 v1 v2 v3 = hst\n rest = ((length `and` 0xff) `shl` 56) `bor` tail\n v3 = v3 `xor` rest\n MkST v0 v1 v2 v3 = repeat CROUNDS compress $ MkST v0 v1 v2 v3\n v0 = v0 `xor` rest\n v2 = v2 `xor` 0xff\n MkST v0 v1 v2 v3 = repeat DROUNDS compress $ MkST v0 v1 v2 v3\n in (v0 `xor` v1) `xor` (v2 `xor` v3)\n\nexport\naddBits8 : PartialHash -> Bits8 -> PartialHash\naddBits8 (MkPartial tail index len hs) x = case index of\n -- finished a set of tail\n 56 => MkPartial 0 0 (len + 1) $ hashBits64 hs (tail `bor` (cast x `shl` 56))\n -- add byte to partial\n _ => MkPartial (tail `bor` (cast x `shl` index)) (index + 8) (len + 1) hs\n\nexport\naddBits16 : PartialHash -> Bits16 -> PartialHash\naddBits16 ph x = addBits8 (addBits8 ph $ cast x) (cast $ x `shr16` 8)\n\nexport\naddBits32 : PartialHash -> Bits32 -> PartialHash\naddBits32 ph x = addBits16 (addBits16 ph $ cast x) (cast $ x `shr32` 16)\n\nexport\naddBits64 : PartialHash -> Bits64 -> PartialHash\naddBits64 (MkPartial tail index length hst) x = MkPartial tail index (length + 8) $ hashBits64 hst x\n\nhashBuffer' : PartialHash -> Buffer -> Int -> Int -> IO PartialHash\nhashBuffer' ph buf len idx = if idx >= len\n then pure ph\n else do\n word <- getBits64 buf idx\n let ph = addBits64 ph word\n hashBuffer' ph buf len (assert_smaller idx $ idx + 8)\n\nhashBuffer : PartialHash -> Buffer -> IO PartialHash\nhashBuffer ph buf = do\n rawLen <- rawSize buf\n let len = fullSize rawLen\n Just buf' <- resizeBuffer buf len\n | Nothing => hashBuffer' ph buf (rawLen `andInt` (- 7)) 0\n hashBuffer' ph buf' len 0\n", "meta": {"hexsha": "ab534c951059331de4ee8775fd2519b817d9e4e7", "size": 4156, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Data/Hashable/SipHashV2.idr", "max_stars_repo_name": "joelberkeley/Idris2-hashable", "max_stars_repo_head_hexsha": "d97d2c39d9199941e2de1991224f564fc4b956dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-04-09T09:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T14:46:34.000Z", "max_issues_repo_path": "src/Data/Hashable/SipHashV2.idr", "max_issues_repo_name": "joelberkeley/Idris2-hashable", "max_issues_repo_head_hexsha": "d97d2c39d9199941e2de1991224f564fc4b956dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-03-25T17:48:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T11:32:07.000Z", "max_forks_repo_path": "src/Data/Hashable/SipHashV2.idr", "max_forks_repo_name": "joelberkeley/Idris2-hashable", "max_forks_repo_head_hexsha": "d97d2c39d9199941e2de1991224f564fc4b956dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-09T12:09:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T21:36:49.000Z", "avg_line_length": 24.7380952381, "max_line_length": 110, "alphanum_fraction": 0.6270452358, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23004915594047903}} |
| {"text": "module LightClick.Check\n\nimport Decidable.Equality\n\nimport Data.List\nimport Data.Vect\n\nimport Toolkit.Data.DList\nimport Toolkit.Data.DList.DeBruijn\nimport Toolkit.Data.DVect\n\nimport Toolkit.Data.Location\nimport Toolkit.Data.Rig\n\nimport Language.SystemVerilog.Gates\nimport Language.SystemVerilog.Utilities\n\nimport LightClick.Error\n\nimport LightClick.Types\nimport LightClick.Types.Equality\nimport LightClick.Terms\n\nimport LightClick.Connection\n\nimport LightClick.Values\nimport LightClick.Env\n\n%default covering\n\npublic export\nTyCheck : Type -> Type\nTyCheck = Either LightClick.Error\n\nmutual\n namespace Field\n\n hasKey : (fc : FileContext)\n -> (label : String)\n -> (store : List String)\n -> TyCheck (List String)\n hasKey fc label store with (isElem label store)\n hasKey fc label store | Yes prf =\n Left (LabelAlreadyExists fc label store)\n hasKey fc label store | No contra = Right (label :: store)\n\n export\n check : (env : Env ctxt)\n -> (key : String)\n -> (value : Term ctxt DATA)\n -> (store : List String)\n -> TyCheck ( Pair String (Value DATA)\n , Pair String (Ty DATA)\n , List String\n , Env ctxt\n )\n -- References are special\n check env key (Ref {label} fc idx) store\n = do (v,t,env') <- check env (Ref fc idx)\n store' <- hasKey fc key store\n pure ((key, VRef label DATA), (key,t), store, env' )\n\n -- Rest is normal\n check env key term store\n = do (v,t,env') <- check env term\n fc <- getFC term\n store' <- hasKey fc key store\n pure ((key,v), (key,t), store, env')\n\n\n namespace Fields\n export\n check : {n : Nat}\n -> (env : Env ctxt)\n -> (kvs : Vect (S n) (Pair String (Term ctxt DATA)))\n -> (store : List String)\n -> TyCheck\n ( Vect (S n) (Pair String (Value DATA))\n , Vect (S n) (Pair String (Ty DATA))\n )\n check {n = n} env ((k,v) :: xs) store with (check env k v store)\n check {n = n} env ((k,v) :: xs) store | Left err = Left err\n check {n = n} env ((k,v) :: xs) store | Right (kv, kt, store', env') with (xs)\n check {n = Z} env ((k,v) :: Nil) store | Right (kv, kt, store', env') | Nil\n = pure ([kv], [kt])\n check {n = S n} env ((k,v) :: xs) store | Right (kv, kt, store', env') | (y::ys)\n = do (kvs, kts) <- check env' (y::ys) store'\n pure ((kv::kvs), kt::kts)\n\n namespace Modules\n\n export\n check : (env : Env ctxt)\n -> (ports : DVect String\n (\\s => Term ctxt (PORT s))\n (S n)\n names)\n -> TyCheck ( DVect String (Value . PORT) (S n) names\n , DVect String (Ty . PORT) (S n) names\n , Env ctxt)\n check {n = n} env (ex :: rest) with (Check.check env ex)\n check {n = n} env (ex :: rest) | (Left l) = Left l\n check {n = n} env (ex :: rest) | (Right (valueX, typeX, env')) with (rest)\n check {n = Z} env (ex :: Nil) | (Right (valueX, typeX, env')) | Nil\n = Right ([valueX], [typeX], env')\n check {n = S n} env (ex :: xs) | (Right (valueX, typeX, env')) | (y::ys)\n = do (pvs, pts, env'') <- Modules.check env' (y::ys)\n Right (valueX::pvs, typeX::pts, env'')\n\n namespace Port\n export\n use : {s : String} -> FileContext -> Ty (PORT s) -> TyCheck (Ty (PORT s))\n use fc type {s} = do u <- shiftUsage fc s (getUsage type)\n Right (setUsage type u)\n\n where\n shiftUsage : FileContext -> String -> TyRig -> TyCheck TyRig\n shiftUsage fc s None = Left (PortInUse fc s)\n shiftUsage _ _ One = Right None\n shiftUsage _ _ Tonne = Right Tonne\n\n export\n check : (env : Env ctxt)\n -> (term : Term ctxt (PORT s))\n -> TyCheck (Value (PORT s), Ty (PORT s), Env ctxt)\n\n check env (Ref fc idx) with (Check.check env (Ref fc idx))\n check env (Ref fc idx) | Left l = Left l\n check env (Ref fc idx) | Right (v,t,env') with (t)\n check env (Ref fc idx) | Right (v,t,env') | portTy with (use fc portTy)\n check env (Ref fc idx) | Right (v,t,env') | portTy | Left l = Left l\n check env (Ref fc idx) | Right (v,t,env') | portTy | Right portTy'\n = do let env'' = updateWith env' idx (\\(MkEntry value (MkTheType s portTy)) => MkEntry value (MkTheType s portTy'))\n Right (v,portTy', env'')\n\n -- projection is just projection\n check env (Index fc mod idx) = Check.check env (Index fc mod idx)\n\n -- Seqs and Lets are not supposed to be here.\n check env _ = Left (NotSupposedToHappen (Just \"Port.check\"))\n\n namespace Fan\n\n export\n check : (env : Env ctxt)\n -> (ports : DVect String\n (\\s => Term ctxt (PORT s))\n (S (S n))\n names)\n -> TyCheck\n ( DVect String (Value . PORT) (S (S n)) names\n , DVect String (Ty . PORT) (S (S n)) names\n , Env ctxt)\n check {n = n} env (x::y::xs) with (Port.check env x)\n check {n = n} env (x::y::xs) | Left l = Left l\n\n check {n = n} env (x::y::xs) | Right (vx,tx,ex) with (xs)\n check {n = Z} env (x::y::xs) | Right (vx,tx,ex) | Nil with (Port.check ex y)\n check {n = Z} env (x::y::xs) | Right (vx,tx,ex) | Nil | Left l\n = Left l\n check {n = Z} env (x::y::xs) | Right (vx,tx,ex) | Nil | Right (vy,ty,ey)\n = Right ([vx,vy], [tx,ty], ey)\n\n check {n = S n} env (x::y::xs) | Right (vx,tx,ex) | (z::zs) with (Fan.check ex (y::z::zs))\n check {n = S n} env (x::y::xs) | Right (vx,tx,ex) | (z::zs) | Left l = Left l\n check {n = S n} env (x::y::xs) | Right (vx,tx,ex) | (z::zs) | Right (vs, ts, env')\n = Right ((vx::vs), (tx::ts), env')\n\n\n -- [ Top Level Check Definition Begins Here ]\n\n export\n check : (env : Env ctxt)\n -> (term : Term ctxt mty)\n -> TyCheck (Value (interp mty), Ty mty, Env ctxt)\n\n\n\n -- [ Checking References ]\n check env (Ref fc prf) with (read prf env)\n check env (Ref fc prf) | (MkEntry value (MkTheType name type))\n = Right (value, type, env)\n\n -- [ Checking Let Bindings ]\n check env (Let fc label this inThis)\n = do (ev, et, env') <- check env this\n (bv, bt, (u::env'')) <- check (MkEntry ev (MkTheType label et)::env') inThis\n Right (VLet label ev bv, bt, env'')\n\n -- [ Checking Sequencing ]\n check env (Seq x y)\n = do (vX, tX, env') <- check env x\n (vY, tY, env'') <- check env' y\n Right (VSeq vX vY, tY, env'')\n\n -- [ Checking Data Types]\n\n -- Logic\n check env (DataLogic fc) = Right (VDataLogic, TyLogic, env)\n\n -- Arrays\n check env (DataArray fc type size)\n = do (vs, ty', env') <- check env type\n Right (VDataArray vs size, TyArray ty' size, env')\n\n -- Data Strucutres\n\n -- Structs\n\n check env (DataStruct fc kvs)\n = do (kvalues, ktypes) <- check env kvs Nil\n Right (VDataStruct kvalues, TyStruct ktypes, env)\n\n -- Unions\n check env (DataUnion fc kvs)\n = do (kvalues, ktypes) <- check env kvs Nil\n Right (VDataUnion kvalues, TyUnion ktypes, env)\n\n\n -- [ Checking Ports ]\n check env (Port fc l d s w (Ref {label} x y))\n = do (v, t, env') <- check env (Ref x y)\n Right (VPort l d (VRef label DATA), TyPort l d s w t One, env')\n\n check env (Port fc l d s w term)\n = do (v, t, env') <- check env term\n Right (VPort l d v, TyPort l d s w t One, env')\n\n -- [ Checking Modules ]\n\n check env (Module fc ports)\n = do (vs, ts, env') <- check env ports\n Right (VModule vs, TyModule ts, env')\n\n -- [ Checking Module projection ]\n\n check env (Index fc m idx) with (check env m)\n check env (Index fc m idx) | Left l = Left l\n check env (Index fc (Ref fc' {label} midx) idx) | Right (v, t, env') with (t)\n check env (Index fc (Ref fc' {label} midx) idx) | Right (v, t, env') | TyModule names with (index names idx)\n check env (Index fc (Ref fc' {label} midx) idx) | Right (v, t, env') | TyModule names | portTy with (use fc portTy)\n check env (Index fc (Ref fc' {label} midx) idx) | Right (v, t, env') | TyModule names | portTy | Left l = Left l\n check env (Index fc (Ref fc' {label} midx) idx) | Right (v, t, env') | TyModule names | portTy | Right portTy'\n = do let names' = update names idx portTy'\n let env'' = updateWith env' midx (\\(MkEntry value (MkTheType s (TyModule names))) => MkEntry value (MkTheType s (TyModule names')))\n port <- getPortFromModule v idx\n Right (newIDX (recoverRef v label) port, portTy, env'')\n\n check env (Index fc _ idx) | Right (v, t, env') = Left (ConstantsNotAllowed fc)\n\n -- [ Checking Direct Connections ]\n\n check env (Connect fc left right)\n = do (vX, tyX, envx) <- Port.check env left\n (vY, tyY, envy) <- Port.check envx right\n\n case compatible tyX tyY of\n No msg contra => Left (Nest (Mismatch fc tyX tyY)\n (UnSafeDirectConnection fc msg))\n Yes prf => do\n ty <- getData vX\n\n nX <- genNameConn vX\n nY <- genNameConn vY\n let n = newName [nX,nY]\n\n Right (VLet n (VChan ty) (newConn n vX vY), TyConn, envy)\n\n -- [ Checking Fanouts]\n\n check env (FanOut fc i fan)\n = do (vI, tyIN, envi) <- Port.check env i\n (vF, tyFAN, envf) <- Fan.check envi fan\n case Fanout.compatible tyIN tyFAN of\n No (PListError pos ty reason) contra =>\n Left (Nest (Mismatch fc tyIN ty) (UnSafeFan fc FANOUT pos reason))\n\n Yes prf => do\n ty <- getData vI\n\n nI <- genNameConn vI\n nF <- genNameFan vF\n let n = newName [\"fan_out_from\", nI, \"to\", nF]\n Right (VLet n (VChan ty) (newConn n vI vF) , TyConn, envf)\n\n -- [ Checking Multiplexers ]\n\n check env (Mux fc fan ctrl o)\n = do (fs, tf, envf) <- Fan.check env fan\n (vC, tc, envc) <- Port.check envf ctrl\n (vO, to, envo) <- Port.check envc o\n\n case Mux.compatible tf tc to of\n No (CtrlNotSafe c x) contra =>\n Left (Nest (Mismatch fc c tc)\n (UnSafeMuxCtrl !(getFC ctrl) x))\n\n No (MuxNotSafe (PListError pos ty reason)) contra =>\n Left (Nest (Mismatch fc ty to)\n (UnSafeFan fc FANIN pos reason))\n Yes prf => do\n nO <- genNameConn vO\n nC <- genNameConn vC\n nF <- genNameFan fs\n nFS <- getNameFan fs\n\n dC <- getData vC\n dO <- getData vO\n\n let mName = newName [\"mux\", nO, nC, nF]\n\n dualFS <- dualFan' (\"input_\") fs\n dualC <- mkDual \"control_\" vC\n dualO <- mkDual \"output_\" vO\n\n let mRef = (VRef mName (MODULE (nC::nO::nFS)))\n fi <- newConn (newName [mName, \"fanin\"]) dO mRef fs dualFS\n Right (VLet mName\n (VModule (dualC::dualO::dualFS))\n (VLet (newName [mName, \"control\"])\n (VChan dC)\n (VLet (newName [mName, \"output\"])\n (VChan dO)\n (VSeq (Direct.newConn (newName [mName, \"control\"]) vC (newIDX mRef dualC))\n (VSeq (Direct.newConn (newName [mName,\"output\"]) vO (newIDX mRef dualO))\n fi\n )\n )\n\n )\n )\n , TyConn, envo)\n\n -- [ Checking NOT ]\n check env (NOT fc i o)\n = do (vX, tyX, envx) <- Port.check env i\n (vY, tyY, envy) <- Port.check envx o\n\n case compatible tyX tyY of\n No msg contra =>\n Left (Nest (Mismatch fc tyX tyY)\n (UnSafeDirectConnection fc msg))\n Yes prf => do\n\n ty <- getData vX\n\n nX <- genNameConn vX\n nY <- genNameConn vY\n\n let c_in_name = newName [\"not_in\", nX, nY]\n let c_out_name = newName [\"not_out\", nX, nY]\n\n Right (VLet c_in_name\n (VChan ty)\n (VLet c_out_name\n (VChan ty)\n (VSeq (Gate.newConn c_in_name vX)\n (VSeq (Gate.newConn c_out_name vY)\n (VNot (VRef c_out_name CHAN)\n (VRef c_in_name CHAN)\n )\n )\n )\n )\n , TyGate, envy\n )\n\n -- [ Checking the GATE ]\n check env (GATE fc ty is o)\n = do (fs, tf, envf) <- Fan.check env is\n (vO, to, envo) <- Port.check envf o\n\n case Fanin.compatible tf to of\n No (PListError pos ty reason) contra => do\n Left (Nest (Mismatch fc ty to) (UnSafeFan fc FANIN pos reason))\n\n Yes prf => do\n\n tyO <- getData vO\n nO <- genNameConn vO\n\n nF <- genNameFan fs\n\n let c_out_name = newName [Gates.toString ty, nO, nF, \"out\"]\n let c_in_name = newName [toString ty, nO, nF, \"in\"]\n\n (ins', conns) <- Gate.FanIn.newConn c_in_name tyO fs\n\n Right (VLet c_out_name\n (VChan tyO)\n (VSeq conns\n (VSeq (Gate.newConn c_out_name vO)\n (VGate ty (VRef c_out_name CHAN) ins')\n )\n )\n , TyGate, envo)\n\n -- [ Checking the End ]\n check env End with (free env)\n check env End | Nil = Right (VEnd, TyUnit, env)\n check env End | (x::xs) = Left (UnusedPorts (x::xs))\n\nexport\nrunCheck : (term : Term Nil UNIT) -> TyCheck (Value UNIT)\nrunCheck term with (check Nil term)\n runCheck term | (Left l) = Left l\n runCheck term | (Right (value, ty, env)) = Right (value)\n\n\n-- [ EOF ]\n", "meta": {"hexsha": "8e6f1e46bcf8344cb0b93b8587540804eba8765f", "size": 14662, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/LightClick/Check.idr", "max_stars_repo_name": "border-patrol/lightclick", "max_stars_repo_head_hexsha": "1f52fc27674f244c399e5e579403e8075f982a37", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2020-11-03T11:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T17:11:38.000Z", "max_issues_repo_path": "src/LightClick/Check.idr", "max_issues_repo_name": "border-patrol/lightclick", "max_issues_repo_head_hexsha": "1f52fc27674f244c399e5e579403e8075f982a37", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LightClick/Check.idr", "max_forks_repo_name": "border-patrol/lightclick", "max_forks_repo_head_hexsha": "1f52fc27674f244c399e5e579403e8075f982a37", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6739659367, "max_line_length": 149, "alphanum_fraction": 0.4972036557, "num_tokens": 4135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22114752338165658}} |
| {"text": "import Data.Vect\nimport Data.Vect.Elem\nimport Data.List\nimport Data.Strings\n\nimport Decidable.Equality\n\n%default total\n\npublic export\ndata GameState : Type where\n NotRunning : GameState\n Running : (guesses : Nat) -> (letters : Nat) -> GameState\n\nletters : String -> List Char\nletters str = nub (map toUpper (unpack str))\n\ndata GuessResult = Correct | Incorrect\n\nexport\ndata GameCmd : (ty : Type) -> GameState -> (ty -> GameState) -> Type where\n NewGame : (word : String) ->\n GameCmd () NotRunning (const (Running 6 (length (letters word))))\n\n Won : GameCmd () (Running (S guesses) 0) (const NotRunning)\n Lost : GameCmd () (Running 0 (S guesses)) (const NotRunning)\n\n Guess : (c : Char) ->\n GameCmd GuessResult\n (Running (S guesses) (S letters))\n (\\res => case res of\n Correct => Running (S guesses) letters\n Incorrect => Running guesses (S letters))\n\n ShowState : GameCmd () state (const state)\n Message : String -> GameCmd () state (const state)\n ReadGuess : GameCmd Char state (const state)\n\n Pure : (res : ty) -> GameCmd ty (state_fn res) state_fn\n (>>=) : GameCmd a state1 state2_fn ->\n ((res : a) -> GameCmd b (state2_fn res) state3_fn) ->\n GameCmd b state1 state3_fn\n\nnamespace Loop\n public export\n data GameLoop : (ty : Type) -> GameState -> (ty -> GameState) -> Type where\n (>>=) : GameCmd a state1 state2_fn ->\n ((res : a) -> Inf (GameLoop b (state2_fn res) state3_fn)) ->\n GameLoop b state1 state3_fn\n Exit : GameLoop () NotRunning (const NotRunning)\n\ngameLoop : {letters : _} -> {guesses : _} ->\n GameLoop () (Running (S guesses) (S letters)) (const NotRunning)\ngameLoop {guesses} {letters} = do ShowState\n g <- ReadGuess\n ok <- Guess g\n case ok of\n Correct => case letters of\n Z => do Won\n ShowState\n Exit\n S k => do Message \"Correct\"\n gameLoop\n Incorrect => case guesses of\n Z => do Lost\n ShowState\n Exit\n S k => do Message \"Incorrect\"\n gameLoop\n\nhangman : GameLoop () NotRunning (const NotRunning)\nhangman = do NewGame \"testing\"\n gameLoop\n\ndata Game : GameState -> Type where\n GameStart : Game NotRunning\n GameWon : (word : String) -> Game NotRunning\n GameLost : (word : String) -> Game NotRunning\n InProgress : {letters : _} -> (word : String) -> (guesses : Nat) ->\n (missing : Vect letters Char) -> Game (Running guesses letters)\n\nShow (Game g) where\n show GameStart = \"Starting\"\n show (GameWon word) = \"Game won: word was \" ++ word\n show (GameLost word) = \"Game lost: word was \" ++ word\n show (InProgress word guesses missing) = \"\\n\" ++ pack (map hideMissing (unpack word))\n ++ \"\\n\" ++ show guesses ++ \" guesses left \"\n where\n hideMissing : Char -> Char\n hideMissing c = if c `elem` missing then '-' else c\n\ndata Fuel = Dry | More (Lazy Fuel)\n\nremoveElem : {n : _} -> (value : a) -> (xs : Vect (S n) a) -> {auto prf : Elem value xs} -> Vect n a\nremoveElem value (value :: ys) {prf = Here} = ys\nremoveElem {n = Z} value (y :: []) {prf = There later} = absurd later\nremoveElem {n = (S k)} value (y :: ys) {prf = There later} = y :: removeElem value ys\n\ndata GameResult : (ty : Type) -> (ty -> GameState) -> Type where\n OK : (res : ty) -> Game (outState_fn res) -> GameResult ty outState_fn\n OutOfFuel : GameResult ty outState_fn\n\nok : (res : ty) -> Game (outstate_fn res) -> IO (GameResult ty outstate_fn)\nok res st = pure (OK res st)\n\nrunCmd : Fuel -> Game inState -> GameCmd ty inState outState_fn -> IO (GameResult ty outState_fn)\nrunCmd fuel state (NewGame word) = ok () (InProgress (toUpper word) _ (fromList (letters word)))\nrunCmd fuel (InProgress word _ missing) Won = ok () (GameWon word)\nrunCmd fuel (InProgress word _ missing) Lost = ok () (GameLost word)\nrunCmd fuel (InProgress word _ missing) (Guess c) = case isElem c missing of\n Yes prf => ok Correct (InProgress word _ (removeElem c missing))\n No contra => ok Incorrect (InProgress word _ missing)\nrunCmd fuel state ShowState = do printLn state\n ok () state\nrunCmd fuel state (Message str) = do putStrLn str\n ok () state\nrunCmd (More fuel) state ReadGuess = do putStr \"Guess: \"\n input <- getLine\n case unpack input of\n [x] => if isAlpha x\n then ok (toUpper x) state\n else do putStrLn \"Invalid input\"\n runCmd fuel state ReadGuess\n _ => do putStrLn \"Invalid input\"\n runCmd fuel state ReadGuess\nrunCmd fuel state (Pure res) = ok res state\nrunCmd fuel state (cmd >>= next) = do OK cmdRes newSt <- runCmd fuel state cmd\n | OutOfFuel => pure OutOfFuel\n runCmd fuel newSt (next cmdRes)\nrunCmd Dry _ _ = pure OutOfFuel\n\nrun : Fuel -> Game inState -> GameLoop ty inState outState_fn -> IO (GameResult ty outState_fn)\nrun Dry _ _ = pure OutOfFuel\nrun (More fuel) st Exit = ok () st\nrun (More fuel) st (cmd >>= next) = do OK cmdRes newSt <- runCmd fuel st cmd\n | OutOfFuel => pure OutOfFuel\n run fuel newSt (next cmdRes)\n\npartial\nforever : Fuel\nforever = More forever\n\npartial\nmain : IO ()\nmain = do run forever GameStart hangman\n pure ()\n", "meta": {"hexsha": "7359695f3c49273fff3d7807a2fef1f6647ff592", "size": 6620, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "idris2/tests/typedd-book/chapter14/Hangman.idr", "max_stars_repo_name": "Qqwy/Idris2-Erlang", "max_stars_repo_head_hexsha": "945f9c12d315d73bfda2d441bc5f9f20696b5066", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "idris2/tests/typedd-book/chapter14/Hangman.idr", "max_issues_repo_name": "Qqwy/Idris2-Erlang", "max_issues_repo_head_hexsha": "945f9c12d315d73bfda2d441bc5f9f20696b5066", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "idris2/tests/typedd-book/chapter14/Hangman.idr", "max_forks_repo_name": "Qqwy/Idris2-Erlang", "max_forks_repo_head_hexsha": "945f9c12d315d73bfda2d441bc5f9f20696b5066", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0340136054, "max_line_length": 121, "alphanum_fraction": 0.4972809668, "num_tokens": 1443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21482608111446483}} |
| {"text": "total twoPlusTwoNotFive : 2 + 2 = 5 -> Void\ntwoPlusTwoNotFive Refl impossible\n\npartial loop : Void\nloop = loop\n", "meta": {"hexsha": "f1e50ca8668c8a9eb1d23ea7cb1ea6a3769cf606", "size": 111, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "idris/void.idr", "max_stars_repo_name": "ostera/asdf", "max_stars_repo_head_hexsha": "adec59de04ce1c2994db60b92f693e621bf68850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-03-02T22:25:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T18:22:11.000Z", "max_issues_repo_path": "idris/void.idr", "max_issues_repo_name": "ostera/asdf", "max_issues_repo_head_hexsha": "adec59de04ce1c2994db60b92f693e621bf68850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2019-12-05T22:45:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T22:45:58.000Z", "max_forks_repo_path": "idris/void.idr", "max_forks_repo_name": "ostera/asdf", "max_forks_repo_head_hexsha": "adec59de04ce1c2994db60b92f693e621bf68850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5, "max_line_length": 43, "alphanum_fraction": 0.7477477477, "num_tokens": 36, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.388618026705849, "lm_q1q2_score": 0.20945859565121092}} |
| {"text": "module Chapter.Concurrency.ProcessLib\n\nimport System.Concurrency.Channels\n\nexport\ndata MessagePID : (iface : reqType -> Type) -> Type where\n MkMessage : PID -> MessagePID iface\n\n%access public export\n\nNoRecv : Void -> Type\nNoRecv = const Void\n\ndata ProcState = Ready\n | Sent\n | Looping\n\ndata Process : (iface : reqType -> Type) ->\n Type ->\n (in_state : ProcState) ->\n (out_state : ProcState) ->\n Type where\n Request : MessagePID service_iface ->\n (msg : service_reqType) ->\n Process ifae (service_iface msg) st st\n Respond : ((msg : reqType) -> Process iface (iface msg) Ready Ready) ->\n Process iface (Maybe reqType) st Sent\n Spawn : Process service_iface () Ready Looping ->\n Process iface (Maybe (MessagePID service_iface)) st st\n\n Loop : Inf (Process iface a Ready Looping) ->\n Process iface a Sent Looping\n Action : IO a -> Process iface a st st\n Pure : a -> Process iface a st st\n (>>=) : Process iface a st1 st2 ->\n (a -> Process iface b st2 st3) ->\n Process iface b st1 st3\n\ndata Fuel = Dry\n | More (Lazy Fuel)\n\n%access export\n\npartial\nforever : Fuel\nforever = More forever\n\nrun : Fuel -> Process iface t in_state out_state -> IO (Maybe t)\nrun fuel (Request {service_iface} (MkMessage proc) msg) =\n do Just chan <- connect proc\n | Nothing => pure Nothing\n if !(unsafeSend chan msg)\n then do Just x <- unsafeRecv (service_iface msg) chan\n | Nothing => pure Nothing\n pure (Just x)\n else pure Nothing\n-- TODO: encapsulate timeout\nrun fuel (Respond {reqType} calc) =\n do Just sender <- listen 1\n | Nothing => pure (Just Nothing)\n Just msg <- unsafeRecv reqType sender\n | Nothing => pure (Just Nothing)\n Just res <- run fuel (calc msg)\n | Nothing => pure Nothing\n unsafeSend sender res\n pure (Just (Just msg))\nrun fuel (Spawn proc) = do Just pid <- spawn (run fuel proc *> pure ())\n | Nothing => pure (Just Nothing)\n pure (Just (Just (MkMessage pid)))\nrun (More fuel) (Loop proc) = run fuel proc\nrun fuel (Action act) = pure (Just !act)\nrun fuel (Pure val) = pure (Just val)\nrun fuel (act >>= next) = do Just x <- run fuel act\n | Nothing => pure Nothing\n run fuel (next x)\nrun Dry _ = pure Nothing\n\n%access public export\n\nService : (iface : reqType -> Type) -> Type -> Type\nService iface a = Process iface a Ready Looping\n\nClient : Type -> Type\nClient a = Process NoRecv a Ready Ready\n\npartial export\nrunProc : Process iface () in_state out_state -> IO ()\nrunProc proc = run forever proc *> pure ()\n", "meta": {"hexsha": "e510216800a49a4cbebf00f3e12b1cfb487ce4ed", "size": 2933, "ext": "idr", "lang": "Idris", "max_stars_repo_path": "src/Chapter/Concurrency/ProcessLib.idr", "max_stars_repo_name": "yurrriq/tdd-with-idris", "max_stars_repo_head_hexsha": "873c6c719706d06179527c5d93982bb7c184da90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-15T01:29:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-15T01:29:36.000Z", "max_issues_repo_path": "src/Chapter/Concurrency/ProcessLib.idr", "max_issues_repo_name": "yurrriq/tdd-with-idris", "max_issues_repo_head_hexsha": "873c6c719706d06179527c5d93982bb7c184da90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-11-21T23:42:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-01T05:43:10.000Z", "max_forks_repo_path": "src/Chapter/Concurrency/ProcessLib.idr", "max_forks_repo_name": "yurrriq/tdd-with-idris", "max_forks_repo_head_hexsha": "873c6c719706d06179527c5d93982bb7c184da90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9550561798, "max_line_length": 77, "alphanum_fraction": 0.5673371974, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2077106721289736}} |
|
|