smirk-penelope (empty) → 0.1.0.0
raw patch · 6 files changed
+495/−0 lines, 6 filesdep +basedep +hspecdep +penelope-core
Dependencies added: base, hspec, penelope-core, penelope-effects, polytropos-core, polytropos-plugin, smirk, smirk-penelope, text
Files
- CHANGELOG.md +8/−0
- LICENSE +73/−0
- README.md +24/−0
- smirk-penelope.cabal +90/−0
- src/Smirk/Effect/Penelope.hs +224/−0
- test/Spec.hs +76/−0
+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Changelog for `smirk-penelope`++## 0.1.0.0 — Initial Release++* Initial release of Penelope effect system façade for the Smirk PCRE engine.+* First-class algebraic effect `RegexEngine` and smart operations `matchRegex`, `matchRegexFuel`, and `findAllRegex`.+* Zero-cost row-polymorphic handlers `interpretRegexPure` and `interpretRegexWithFuel`.+* Pure execution runners `runRegexEnginePure` and `runRegexEngineWithFuel`.
+ LICENSE view
@@ -0,0 +1,73 @@+Apache License+Version 2.0, January 2004+http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.++"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.++"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.++"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.++"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.++"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.++"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).++"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.++"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."++"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:++ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.++ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work.++To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.++Copyright [yyyy] [name of copyright owner]++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.
+ README.md view
@@ -0,0 +1,24 @@+# smirk-penelope++`smirk-penelope` exposes Smirk's pure, step-bounded PCRE engine as an algebraic+effect for the [`penelope`](https://github.com/NadiaYvette/penelope) effect system.++## Features++- **Zero-Cost Polycategorical Dispatch:** Dispatches regex matching over flat Polytropos row vectors (`SmallArray#`).+- **ReDoS Protection:** Bound execution via `matchRegexFuel` or `runRegexEngineWithFuel`.+- **First-Class Effect:** Embeds into Penelope's `Eff eh ef a` unary monad via `sendEff @"regex"`.++## Quick Start++```haskell+import Data.Text (Text)+import Penelope.Effects (Eff)+import Smirk (re)+import Smirk.Effect.Penelope++searchUser :: (ConstructorIndex "regex" ef) => Text -> Eff eh ef (Maybe Text)+searchUser input = do+ mMatch <- matchRegex [re|user:(\w+)|] input+ pure (fmap matchedSlice mMatch)+```
+ smirk-penelope.cabal view
@@ -0,0 +1,90 @@+cabal-version: 3.0+name: smirk-penelope+version: 0.1.0.0+synopsis: Penelope effect system interface for the Smirk PCRE engine+description:+ Exposes Smirk's pure, step-bounded PCRE engine as an algebraic effect for+ the 'penelope' effect system ('Smirk.Effect.Penelope'), with pure and+ fuel-bounded interpreters over flat Polytropos row representations.+license: Apache-2.0+license-file: LICENSE+author: Nadia Yvette Chambers+maintainer: Nadia Chambers <nadia.yvette.chambers@ik.me>+homepage: https://github.com/NadiaYvette/smirk+bug-reports: https://github.com/NadiaYvette/smirk/issues+category: Text, Regex, Effects+build-type: Simple+extra-doc-files:+ README.md+ , CHANGELOG.md+ , LICENSE++tested-with:+ GHC == 9.12.4+ , GHC == 9.14.1++source-repository head+ type: git+ location: https://github.com/NadiaYvette/smirk.git+ subdir: packages/smirk-penelope++common common-options+ default-language: GHC2021+ default-extensions:+ DataKinds+ DeriveAnyClass+ DeriveGeneric+ DerivingStrategies+ DuplicateRecordFields+ GADTs+ GeneralizedNewtypeDeriving+ LambdaCase+ MultiParamTypeClasses+ OverloadedRecordDot+ OverloadedStrings+ RankNTypes+ RecordWildCards+ ScopedTypeVariables+ TypeApplications+ TypeFamilies+ TypeOperators+ ghc-options:+ -Wall+ -Wcompat+ -Widentities+ -Wincomplete-record-updates+ -Wincomplete-uni-patterns+ -Wpartial-fields+ -Wredundant-constraints++library+ import: common-options+ hs-source-dirs: src+ exposed-modules:+ Smirk.Effect.Penelope+ build-depends:+ base >= 4.16 && < 5,+ penelope-core >= 0.1 && < 0.2,+ penelope-effects >= 0.1 && < 0.2,+ polytropos-core >= 0.1 && < 0.2,+ polytropos-plugin >= 0.1 && < 0.2,+ smirk >= 0.1 && < 0.2,+ text >= 2.0 && < 3++test-suite smirk-penelope-test+ import: common-options+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Spec.hs+ ghc-options:+ -fplugin=Polytropos.Plugin+ build-depends:+ base >= 4.16 && < 5,+ hspec >= 2.10 && < 3,+ penelope-core >= 0.1 && < 0.2,+ penelope-effects >= 0.1 && < 0.2,+ polytropos-core >= 0.1 && < 0.2,+ polytropos-plugin >= 0.1 && < 0.2,+ smirk >= 0.1 && < 0.2,+ smirk-penelope,+ text >= 2.0 && < 3
+ src/Smirk/Effect/Penelope.hs view
@@ -0,0 +1,224 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}++{- |+Module : Smirk.Effect.Penelope+Description : Penelope effect system interface for the Smirk PCRE engine+Copyright : (c) Nadia Yvette Chambers, 2026+License : Apache-2.0+Maintainer : Nadia Chambers <nadia.yvette.chambers@ik.me>+Stability : experimental+Portability : non-portable (GHC extensions)++Exposes Smirk's step-bounded, pure PCRE engine as an algebraic effect ('RegexEngine')+for the @Penelope@ effect system, providing zero-cost polycategorical dispatch over+flat Polytropos row vectors, unlifted pure interpretation, and fuel-bounded execution.++=== Example Usage++@+import Data.Text (Text)+import Penelope.Effects ('t:Eff')+import Smirk (re)+import Smirk.Effect.Penelope++searchUser :: (ConstructorIndex "regex" ef) => Text -> 't:Eff' eh ef (Maybe Text)+searchUser input = do+ mMatch <- matchRegex [re|user:(\\w+)|] input+ pure (fmap matchedSlice mMatch)+@+-}+module Smirk.Effect.Penelope+ ( -- * Effect Definition+ RegexEngine (..)++ -- * Effect Injection Operations+ , matchRegex+ , matchRegexAt+ , matchRegexFuel+ , matchRegexFuelAt+ , findAllRegex+ , findAllRegexAt++ -- * Handlers+ , interpretRegexPure+ , interpretRegexWithFuel++ -- * Pure and Monadic Runners+ , runRegexEnginePure+ , runRegexEngineWithFuel+ , runRegexEngineM+ , runRegexEngineWithFuelM+ ) where++import Data.Functor.Identity (Identity (..))+import Data.Kind (Type)+import Data.Text (Text)+import GHC.TypeLits (Symbol)+import Penelope.Effects+ ( Eff+ , EffHandler+ , UnaryEffect+ , mkEffHandler+ , runEffM+ , send+ )+import Polytropos (Field (..), Pair (..), emptyRecord, insertField)+import Polytropos.Core (ConstructorIndex)+import Smirk.Core.Bytecode (Regex)+import Smirk.Engine.VM+ ( Fuel (..)+ , MatchResult+ , MatchStatus (..)+ , findAllMatches+ , runMatch+ )++-- | First-class algebraic effect representing regular expression operations.+data RegexEngine (a :: Type) where+ -- | Perform an unconstrained search returning the first match if found.+ MatchRegex :: Regex -> Text -> RegexEngine (Maybe (MatchResult Text))+ -- | Perform a step-budgeted search tracking consumed fuel and yielding continuations on exhaustion.+ MatchRegexFuel :: Regex -> Text -> Fuel -> RegexEngine (MatchStatus Text)+ -- | Find all non-overlapping matches across the input text.+ FindAllRegex :: Regex -> Text -> RegexEngine [MatchResult Text]++-- | Perform an unconstrained search at effect label @"regex"@ returning the first match if found.+{-# INLINE matchRegex #-}+matchRegex ::+ forall eh ef.+ ConstructorIndex "regex" ef =>+ Regex+ -> Text+ -> Eff eh ef (Maybe (MatchResult Text))+matchRegex = matchRegexAt @"regex"++-- | Perform an unconstrained search at an explicit effect label returning the first match if found.+{-# INLINE matchRegexAt #-}+matchRegexAt ::+ forall (l :: Symbol) eh ef.+ ConstructorIndex l ef =>+ Regex+ -> Text+ -> Eff eh ef (Maybe (MatchResult Text))+matchRegexAt reg txt = send @l (MatchRegex reg txt)++-- | Perform a step-budgeted search at effect label @"regex"@.+{-# INLINE matchRegexFuel #-}+matchRegexFuel ::+ forall eh ef.+ ConstructorIndex "regex" ef =>+ Regex+ -> Text+ -> Fuel+ -> Eff eh ef (MatchStatus Text)+matchRegexFuel = matchRegexFuelAt @"regex"++-- | Perform a step-budgeted search at an explicit effect label.+{-# INLINE matchRegexFuelAt #-}+matchRegexFuelAt ::+ forall (l :: Symbol) eh ef.+ ConstructorIndex l ef =>+ Regex+ -> Text+ -> Fuel+ -> Eff eh ef (MatchStatus Text)+matchRegexFuelAt reg txt fuel = send @l (MatchRegexFuel reg txt fuel)++-- | Find all non-overlapping matches at effect label @"regex"@ across the input text.+{-# INLINE findAllRegex #-}+findAllRegex ::+ forall eh ef.+ ConstructorIndex "regex" ef =>+ Regex+ -> Text+ -> Eff eh ef [MatchResult Text]+findAllRegex = findAllRegexAt @"regex"++-- | Find all non-overlapping matches at an explicit effect label across the input text.+{-# INLINE findAllRegexAt #-}+findAllRegexAt ::+ forall (l :: Symbol) eh ef.+ ConstructorIndex l ef =>+ Regex+ -> Text+ -> Eff eh ef [MatchResult Text]+findAllRegexAt reg txt = send @l (FindAllRegex reg txt)++-- | Construct an 'EffHandler' interpreting 'RegexEngine' with unlimited execution fuel.+-- Suitable for trusted regular expressions and inputs where ReDoS attacks are not a concern.+{-# INLINE interpretRegexPure #-}+interpretRegexPure ::+ Monad m =>+ EffHandler m RegexEngine+interpretRegexPure = mkEffHandler $ \case+ MatchRegex reg txt -> case runMatch reg txt Unlimited of+ Matched res -> pure (Just res)+ _ -> pure Nothing+ MatchRegexFuel reg txt fuel -> pure (runMatch reg txt fuel)+ FindAllRegex reg txt -> pure (findAllMatches reg txt)++-- | Construct an 'EffHandler' interpreting 'RegexEngine' enforcing a specific default step budget limit.+-- Guarantees ReDoS immunity by bounding execution iterations across untrusted inputs.+{-# INLINE interpretRegexWithFuel #-}+interpretRegexWithFuel ::+ Monad m =>+ Fuel+ -> EffHandler m RegexEngine+interpretRegexWithFuel defaultFuel = mkEffHandler $ \case+ MatchRegex reg txt -> case runMatch reg txt defaultFuel of+ Matched res -> pure (Just res)+ _ -> pure Nothing+ MatchRegexFuel reg txt fuel -> pure (runMatch reg txt fuel)+ FindAllRegex reg txt -> pure (findAllMatches reg txt)++-- | Execute a pure 't:Eff' computation with unlimited fuel using the @"regex"@ label.+{-# INLINE runRegexEnginePure #-}+runRegexEnginePure ::+ Eff '[] '["regex" ':= UnaryEffect RegexEngine] a+ -> a+runRegexEnginePure prog =+ let handlers = insertField (Field @"regex") interpretRegexPure emptyRecord+ Identity res = runEffM handlers prog+ in res++-- | Execute a pure 't:Eff' computation enforcing a step budget using the @"regex"@ label.+{-# INLINE runRegexEngineWithFuel #-}+runRegexEngineWithFuel ::+ Fuel+ -> Eff '[] '["regex" ':= UnaryEffect RegexEngine] a+ -> a+runRegexEngineWithFuel fuel prog =+ let handlers = insertField (Field @"regex") (interpretRegexWithFuel fuel) emptyRecord+ Identity res = runEffM handlers prog+ in res++-- | Execute an effectful 't:Eff' computation under a target 'Monad' using pure unlimited regex matching.+{-# INLINE runRegexEngineM #-}+runRegexEngineM ::+ Monad m =>+ Eff '[] '["regex" ':= UnaryEffect RegexEngine] a+ -> m a+runRegexEngineM prog =+ let handlers = insertField (Field @"regex") interpretRegexPure emptyRecord+ in runEffM handlers prog++-- | Execute an effectful 't:Eff' computation under a target 'Monad' enforcing a step budget.+{-# INLINE runRegexEngineWithFuelM #-}+runRegexEngineWithFuelM ::+ Monad m =>+ Fuel+ -> Eff '[] '["regex" ':= UnaryEffect RegexEngine] a+ -> m a+runRegexEngineWithFuelM fuel prog =+ let handlers = insertField (Field @"regex") (interpretRegexWithFuel fuel) emptyRecord+ in runEffM handlers prog
+ test/Spec.hs view
@@ -0,0 +1,76 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}++module Main (main) where++import Data.Text (Text)+import Test.Hspec++import Smirk+import Smirk.Effect.Penelope++main :: IO ()+main = hspec $ do+ let mReg = compileRegex "(?<key>[a-z]+)=(?<val>\\d+)"+ target = ("config: timeout=500ms max=2000ms" :: Text)+ describe "Smirk.Effect.Penelope (Penelope RegexEngine Interpreter)" $ do+ it "runs pure regex matching in Eff" $ do+ case mReg of+ Right reg -> do+ let mRes = runRegexEnginePure $ do+ matchRegex reg target+ case mRes of+ Just res -> do+ res.matchedSlice `shouldBe` "timeout=500"+ Nothing -> expectationFailure "Expected match in Penelope Eff"+ Left err -> expectationFailure (show err)++ it "runs fuel-bounded matching in Eff" $ do+ case mReg of+ Right reg -> do+ let status = runRegexEnginePure $ do+ matchRegexFuel reg target (StepBudget 1000)+ case status of+ Matched res -> res.matchedSlice `shouldBe` "timeout=500"+ _ -> expectationFailure "Expected Matched status"+ Left err -> expectationFailure (show err)++ it "finds all matches in Eff" $ do+ case mReg of+ Right reg -> do+ let matches = runRegexEnginePure $ do+ findAllRegex reg target+ map (\m -> m.matchedSlice) matches `shouldBe` ["timeout=500", "max=2000"]+ Left err -> expectationFailure (show err)++ it "runs with default fuel runner" $ do+ case mReg of+ Right reg -> do+ let mRes = runRegexEngineWithFuel (StepBudget 5000) $ do+ matchRegex reg target+ case mRes of+ Just res -> res.matchedSlice `shouldBe` "timeout=500"+ Nothing -> expectationFailure "Expected match under fuel budget"+ Left err -> expectationFailure (show err)++ it "runs under IO monad via runRegexEngineM" $ do+ case mReg of+ Right reg -> do+ mRes <- runRegexEngineM $ do+ matchRegex reg target+ case mRes of+ Just res -> res.matchedSlice `shouldBe` "timeout=500"+ Nothing -> expectationFailure "Expected match in IO Eff"+ Left err -> expectationFailure (show err)++ it "runs under IO monad with fuel via runRegexEngineWithFuelM" $ do+ case mReg of+ Right reg -> do+ mRes <- runRegexEngineWithFuelM (StepBudget 2000) $ do+ matchRegex reg target+ case mRes of+ Just res -> res.matchedSlice `shouldBe` "timeout=500"+ Nothing -> expectationFailure "Expected match in IO Eff with fuel"+ Left err -> expectationFailure (show err)