dependent-literals (empty) → 0.1.0.0
raw patch · 6 files changed
+831/−0 lines, 6 filesdep +basedep +fin-intdep +numeric-kinds
Dependencies added: base, fin-int, numeric-kinds, sint, snumber, tagged
Files
- CHANGELOG.md +3/−0
- LICENSE +202/−0
- dependent-literals.cabal +48/−0
- src/DependentLiterals.hs +29/−0
- src/DependentLiterals/Bounds.hs +116/−0
- src/DependentLiterals/Int.hs +433/−0
+ CHANGELOG.md view
@@ -0,0 +1,3 @@+# 0.1.0.0++Initial version.
+ LICENSE view
@@ -0,0 +1,202 @@++ 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.
+ dependent-literals.cabal view
@@ -0,0 +1,48 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.33.0.+--+-- see: https://github.com/sol/hpack+--+-- hash: 30f8fe2e48f6bbcd438d851405bf47990834dff8704739447c29c6398746aa0e++name: dependent-literals+version: 0.1.0.0+synopsis: Provides library support for pseudo-dependently-typed int literals.+description: This is the library counterpart of+ <https://hackage.haskell.org/package/dependent-literals-plugin dependent-literals-plugin>.+ See that package's description for more details.+category: Constraints+homepage: https://github.com/google/hs-dependent-literals#readme+bug-reports: https://github.com/google/hs-dependent-literals/issues+author: Andrew Pritchard <awpr@google.com>+maintainer: Andrew Pritchard <awpr@google.com>+copyright: 2019-2021 Google LLC+license: Apache-2.0+license-file: LICENSE+build-type: Simple+extra-source-files:+ CHANGELOG.md++source-repository head+ type: git+ location: https://github.com/google/hs-dependent-literals+ subdir: dependent-literals++library+ exposed-modules:+ DependentLiterals+ DependentLiterals.Bounds+ DependentLiterals.Int+ other-modules:+ Paths_dependent_literals+ hs-source-dirs:+ src+ build-depends:+ base >=4.12 && <4.16+ , fin-int >=0.1 && <0.2+ , numeric-kinds >=0.1 && <0.2+ , sint >=0.1 && <0.2+ , snumber >=0.1 && <0.2+ , tagged >=0.8 && <0.9+ default-language: Haskell2010
+ src/DependentLiterals.hs view
@@ -0,0 +1,29 @@+-- Copyright 2020-2021 Google LLC+--+-- 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.++-- | Top-level module exporting the key DependentLiterals functionality.++module DependentLiterals+ ( -- * Int Literals+ HasIntLiterals, AllowsIntLiteral, IntLiteral+ , valueOf++ -- ** Basic Literals+ , HasBasicLiterals, StockLit(..)++ -- ** Dependent Literals+ , SNum(..), SNumLit(..)+ ) where++import DependentLiterals.Int
+ src/DependentLiterals/Bounds.hs view
@@ -0,0 +1,116 @@+-- Copyright 2020-2021 Google LLC+--+-- 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.++{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DerivingVia #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE RoleAnnotations #-}+#if !defined(__HLINT__)+{-# LANGUAGE StandaloneDeriving #-}+#endif+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}++module DependentLiterals.Bounds+ ( -- * Bounds Checks++ -- ** Error Messages+ OutOfRangeMsg++ -- ** Error Message Utilities+ , ShowTypedNum, ShowRange++ -- ** Error Constraints+ , OutOfRangeErr++ -- ** Inequality Assertions+ , CheckLessThanMaxBound, CheckAtLeastMinBound, AssertEq, AssertNotApart++ -- * Implementation Details+ , ShowNum, AssertNotApart_, Eql, FailedToProveEq+ ) where++import Data.Kind (Constraint, Type)+import GHC.TypeLits (TypeError, ErrorMessage(..))++import Kinds.Integer (pattern Pos, pattern Neg)+import Kinds.Num (type (-), type (>=?), type (<), type (>=), Cmp)+import qualified Kinds.Integer as K (Integer)++type family ShowNum (n :: K.Integer) where+ ShowNum ('Pos n) = 'ShowType n+ ShowNum ('Neg n) = 'Text "-" ':<>: 'ShowType n++type ShowTypedNum a n = ShowNum n ':<>: 'Text " :: " ':<>: 'ShowType a++type ShowRange min maxp1 =+ 'Text "(" ':<>: ShowNum min ':<>: 'Text ".." ':<>:+ ShowNum (maxp1 - 'Pos 1) ':<>: 'Text ")"++type OutOfRangeMsg min maxp1 a n =+ 'Text "Literal out of range " ':<>: ShowRange min maxp1 ':<>: 'Text ":" ':$$:+ 'Text " " ':<>: ShowTypedNum a n++class OutOfRangeErr (min :: K.Integer) (maxp1 :: K.Integer) (a :: Type) (n :: K.Integer)+instance TypeError (OutOfRangeMsg min maxp1 a n) => OutOfRangeErr min maxp1 a n++type family Eql a b :: Bool where+ Eql a a = 'True+ Eql a b = 'False++class a ~ b => AssertEq (c :: Constraint) a b+instance AssertEq c a a++-- | If you tried to prove a constraint and failed, and want to issue a custom+-- error message for it explicitly, write something like this.+--+-- Given "class _c => FailedToProveC (err :: Constraint) ...",+-- "FailedToProveC (TypeError ...)" is a constraint that pretends to prove @c@+-- but instead throws a type error.+class a ~ b => FailedToProveEq (err :: Constraint) a b++class a ~ b => AssertNotApart_ (msg :: ErrorMessage) eq a b+instance a ~ b => AssertNotApart_ msg 'True a b+instance FailedToProveEq (TypeError msg) a b => AssertNotApart_ msg 'False a b++type AssertNotApart msg a b = AssertNotApart_ msg (Eql a b) a b++class (n < maxp1)+ => CheckLessThanMaxBound+ (msg :: ErrorMessage)+ (maxp1 :: K.Integer)+ (a :: Type)+ (n :: K.Integer)+instance AssertNotApart msg (Cmp n maxp1) 'LT+ => CheckLessThanMaxBound msg maxp1 a n++class (n >= min)+ => CheckAtLeastMinBound+ (msg :: ErrorMessage)+ (min :: K.Integer)+ (a :: Type)+ (n :: K.Integer)+instance AssertNotApart msg (n >=? min) 'True+ => CheckAtLeastMinBound msg min a n
+ src/DependentLiterals/Int.hs view
@@ -0,0 +1,433 @@+-- Copyright 2020-2021 Google LLC+--+-- 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.++{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DerivingVia #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE MagicHash #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE QuantifiedConstraints #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE RoleAnnotations #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE UndecidableSuperClasses #-}++-- We hid all uses of this from HLint+#if !defined(__HLINT__)+{-# LANGUAGE StandaloneDeriving #-}+#endif++-- | The library component of "DependentLiterals.Plugin".+--+-- This provides a class for dependent numeric literal functionality, the entry+-- points used by the plugin for literals and patterns, and a few ways of+-- defining instances with less unsafe-ty.++module DependentLiterals.Int+ ( -- * Dependent Literals+ HasIntLiterals(..), valueOf++ -- ** Convenience Aliases+ , HasBasicLiterals, AllowsIntLiteral, IntLiteral++ -- ** Safer Implementations+ , StockLit(..)+ , SNum(..), Satisfying(..), SNumLit(..)+ , type (-#), CMaybe(..)++ -- ** Plugin Entry Points+ , lit#, match#++ -- * Implementation Details+ , NoAssertion+ ) where++import Data.Functor.Const (Const(..))+import Data.Functor.Identity (Identity(..))+import Data.Int (Int8, Int16, Int32, Int64)+import Data.Kind (Constraint, Type)+import Data.Proxy (Proxy(..))+import Data.Ratio (Ratio)+import Data.Word (Word8, Word16, Word32, Word64)+import Data.Semigroup (Sum(..), Product(..), Min(..), Max(..))+import Data.Type.Equality ((:~:)(..))+import Foreign.C.Types+ ( CChar, CSChar, CUChar, CWchar+ , CShort, CUShort, CInt, CUInt, CLong, CULong, CLLong, CULLong+ , CPtrdiff, CSize, CSigAtomic, CBool+ , CIntPtr, CUIntPtr, CIntMax, CUIntMax+ , CClock, CTime, CUSeconds, CSUSeconds+ )+import GHC.TypeLits (TypeError, ErrorMessage(..))+import GHC.TypeNats (Nat)+import Numeric.Natural (Natural)+import Unsafe.Coerce (unsafeCoerce)++import Data.Tagged (Tagged(..))+import Data.SInt (SInt(SI#, unSInt))+import Data.SNumber (SafeSNumber, SNumber(N#), sameSNumber, unsafeMkSNumber)+import Kinds.Integer (type (-#), KnownInteger(..), pattern Pos)+import Kinds.Num (type (>=), type (<), Cmp, ToInteger)+import qualified Kinds.Integer as K (Integer)+import Data.Fin.Int (Fin, finToInt, unsafeFin)++import DependentLiterals.Bounds+ ( CheckAtLeastMinBound, CheckLessThanMaxBound+ , AssertEq, OutOfRangeMsg, ShowTypedNum+ )+++-- | A GADT containing some @t x@ along with a @c x@ instance.+data Satisfying c t = forall x. c x => Satisfying (t x)++-- | 'Maybe' on 'Constraint's.+data CMaybe c = c => CJust | CNothing++-- | A user-facing dependent numeric typeclass.+--+-- This gives an isomorphism between @a@ and @exists n. SNumber (SNumRepr a) n@+-- given that @SNumConstraint a n@ holds.+--+-- To get instances of 'HasIntLiterals' without interacting with the unsafe+-- parts of the library, implement this class and lift it to 'HasIntLiterals'+-- with @deriving HasIntLiterals via SNumLit MyAssertionClass MyType@.+class SNum a where+ -- | The underlying numerical representation type.+ type SNumRepr a :: Type++ -- | The constraint on literal values to validate/refine @a@.+ type SNumConstraint a :: K.Integer -> Constraint++ -- | Conversion from 'SNumber' with a proof of 'SNumConstraint' into @a@.+ --+ -- Used for interpreting integral literals.+ fromSNum :: Satisfying (SNumConstraint a) (SNumber (SNumRepr a)) -> a++ -- | Conversion from @a@ into 'SNumber' with a proof of 'SNumConstraint.'+ --+ -- Used for providing proofs on successful pattern matches.+ intoSNum :: a -> Satisfying (SNumConstraint a) (SNumber (SNumRepr a))++instance SNum (SInt n) where+ type SNumRepr (SInt n) = Int+#if !defined(__HLINT__)+ type SNumConstraint (SInt n) = (~) ('Pos n)+#endif+ fromSNum (Satisfying (N# x)) = SI# x+ intoSNum x = Satisfying (N# @('Pos n) (unSInt x))++instance SNum (SNumber a n) where+ type SNumRepr (SNumber a n) = a+#if !defined(__HLINT__)+ type SNumConstraint (SNumber a n) = (~) n+#endif+ fromSNum (Satisfying x) = x+ intoSNum = Satisfying++class (Cmp n ('Pos m) ~ 'LT, n >= 'Pos 0)+ => FinInBounds (m :: Nat) (n :: K.Integer)+instance (Cmp n ('Pos m) ~ 'LT, n >= 'Pos 0) => FinInBounds m n++instance SNum (Fin n) where+ type SNumRepr (Fin n) = Int+ type SNumConstraint (Fin n) = FinInBounds n+ fromSNum (Satisfying (N# x)) = unsafeFin x+ intoSNum x = unsafeCoerce (Satisfying @NoConstraint (N# (finToInt x)))++-- | The main class providing dependent-literals functionality.+--+-- Instances of this can have integral literals and numeric patterns with+-- @-fplugin="DependentLiterals.Plugin"@.+--+-- This class exposes the internal unsafe machinery of the library; a safer and+-- less error-prone way to get instances for it is via 'SNum' or 'StockLit'.+class HasIntLiterals a where+ -- | Constraint for representational validity of a literal: this is meant to+ -- prevent overflowed literals from being wrapped incorrectly in 'N#'. This+ -- is required both for expressions and for patterns.+ --+ -- Safety contract: 'unsafeFromInteger' and 'unsafeMatchInteger' must not+ -- construct illegal @SNumber n@ values when called with @Tagged \@n n@; they+ -- may use 'ReprAssertion' to restrict the values they can receive.+ type ReprAssertion a :: Type -> K.Integer -> Constraint++ -- | @LitConstraint a n@ constrains or refines @a@ given the literal value.+ --+ -- This is what's proven about the integer value and type by matching on a+ -- numeric pattern; for example, in the case of @SInt n@, @LitConstraint a m@+ -- is @m ~ n@, so that matching numeric 'SInt' patterns introduces equality+ -- proofs for the type parameter.+ type LitConstraint a :: K.Integer -> Constraint++ -- | Like 'LitConstraint' but with pretty error messages.+ --+ -- This is used on integral literals to provide custom error messages for+ -- failed constraints.+ type LitAssertion a :: Type -> K.Integer -> Constraint++ -- | Runtime conversion from 'Integer' to the appropriate type.+ --+ -- Unsafe in that it trusts that the 'Integer' you give it is the same as the+ -- type-level one.+ unsafeFromInteger+ :: forall n b+ . (LitAssertion a b n, ReprAssertion a b n)+ => Proxy b -> Tagged n Integer -> a++ -- | Runtime pattern match implementation.+ --+ -- Unsafe in that it trusts that the 'Integer' you give it is the same as the+ -- type-level one.+ unsafeMatchInteger+ :: forall n b+ . ReprAssertion a b n+ => Proxy b -> Tagged n Integer -> a -> CMaybe (LitConstraint a n)++-- | A constraint alias that asserts you can use any integral literal.+--+-- This can be useful in polymorphic contexts when you don't want to list out+-- constraints for every literal value you need, and are willing to accept that+-- some types with stronger compile-time validation will be excluded.+type HasBasicLiterals a =+ ( HasIntLiterals a+ , LitAssertion a ~ NoAssertion+ , ReprAssertion a ~ NoAssertion+ )++-- | A constraint alias showing that the particular value @n@ is valid for @a@.+--+-- With this in context along with @'HasIntLiterals' a@, you can use an+-- integral literal value @n@ at type @a@. See also 'IntLiteral'.+type AllowsIntLiteral n a =+ ( LitAssertion a a (ToInteger n)+ , ReprAssertion a a (ToInteger n)+ )++-- | A convenient form of 'IntLiteral' when only one value is needed.+--+-- This is a constraint tuple, so using this multiple times in a signature+-- creates a bit of constraint pollution; for tidier signatures, use one+-- 'HasIntLiterals' and several 'AllowsIntLiteral's.+type IntLiteral n a = (HasIntLiterals a, AllowsIntLiteral n a)++-- | The unsafe entry point used by "DependentLiterals.Plugin" for literals.+--+-- This is unsafe to use explicitly, since it implicitly trusts that the given+-- 'Integer' is equal to the type-level integer. The plugin guarantees this+-- itself when generating calls, so its uses are safe.+lit#+ :: forall n a+ . (HasIntLiterals a, ReprAssertion a a n, LitAssertion a a n)+ => (Num a => a) -> Integer -> a+lit# _ = unsafeFromInteger (Proxy @a) . Tagged @n++-- | The unsafe entry point used by "DependentLiterals.Plugin" for patterns.+--+-- This is unsafe to use explicitly, since it implicitly trusts that the given+-- 'Integer' is equal to the type-level integer. The plugin guarantees this+-- itself when generating calls, so its uses are safe.+match#+ :: forall n a+ . (HasIntLiterals a, ReprAssertion a a n)+ => (Num a => a) -> Integer -> a -> CMaybe (LitConstraint a n)+match# _ = unsafeMatchInteger (Proxy @a) . Tagged @n++-- | 'valueOf' specialized to 'Integer'.+valueOf' :: forall n a. (IntLiteral n a, KnownInteger n) => a+valueOf' = unsafeFromInteger (Proxy @a) (Tagged @n $ toInteger $ integerVal @n)++-- | Get the value of a type-level number at runtime, as if it were a literal.+--+-- That is, when DependentLiterals is enabled, @42@ and @valueOf \@42@ are the+-- same thing. (When it's not enabled, @42@ is just @fromInteger 42@).+valueOf+ :: forall n a+ . (IntLiteral (ToInteger n) a, KnownInteger (ToInteger n))+ => a+valueOf = valueOf' @(ToInteger n)++-- | A newtype carrying a 'HasIntLiterals' instance for use with @DerivingVia@.+newtype SNumLit (c :: Type -> K.Integer -> Constraint) a = SNumLit a++class SNumConstraint a n => SNumLitAssertion c a b n+#if !defined(__HLINT__)+instance (c b n, cc ~ SNumConstraint a, forall m. c b m => cc m)+ => SNumLitAssertion c a b n+#endif++class SafeSNumber repr n => SNumReprAssertion repr b n+instance SafeSNumber repr n => SNumReprAssertion repr b n++instance (Eq (SNumRepr a), Num (SNumRepr a), SNum a)+ => HasIntLiterals (SNumLit c a) where+ type ReprAssertion (SNumLit c a) = SNumReprAssertion (SNumRepr a)+ type LitAssertion (SNumLit c a) = SNumLitAssertion c a+ type LitConstraint (SNumLit c a) = SNumConstraint a++ unsafeFromInteger (_ :: Proxy b) (Tagged n :: Tagged n Integer) =+ SNumLit $ fromSNum $ Satisfying (unsafeMkSNumber @n (fromInteger n))++ unsafeMatchInteger (_ :: Proxy b) (Tagged n :: Tagged n Integer) (SNumLit a) =+ case intoSNum a of+ Satisfying m ->+ case sameSNumber (unsafeMkSNumber @n (fromInteger n)) m of+ Just Refl -> CJust+ Nothing -> CNothing+++-- | A type with a 'HasIntLiterals' instance that just behaves like 'Num'.+--+-- For use with @-XDerivingVia@. This calls through to the 'fromIntegral' of+-- the underlying 'Num' instance for the final conversion. If the type in+-- question has a 'Num' instance and it's acceptable for literals to overflow+-- (or if the type is supported by -Woverflowed-literals), this is a good way+-- to get an instance.+--+-- This is suitable for @DerivingVia@ and tends to work as a deriving clause,+-- so:+--+-- @+-- newtype MyType = MyType Int+-- deriving Num+-- deriving HasIntLiterals via StockLit Int+-- @+--+-- Note in this case you could just as well say @deriving HasIntLiterals@ to+-- get a @GeneralizedNewtypeDeriving@ instance that consumes Int literals and+-- coerces them, but if you wrote a custom Num instance, @via FromIntegral _ _@+-- will respect it.+newtype StockLit a = StockLit a++class NoConstraint (a :: k)+instance NoConstraint a++-- | The "assertion" used by basic integral literals, which is always solvable.+class NoAssertion (a :: Type) (n :: K.Integer)+instance NoAssertion a n++instance (Eq a, Num a) => HasIntLiterals (StockLit a) where+ type ReprAssertion (StockLit a) = NoAssertion+ type LitConstraint (StockLit a) = NoConstraint+ type LitAssertion (StockLit a) = NoAssertion++ unsafeFromInteger _ (Tagged n) = StockLit (fromInteger n)++ unsafeMatchInteger _ (Tagged n) (StockLit a) = if fromInteger n == a+ then CJust+ else CNothing++class n ~ m => SIntLitAssertion (m :: K.Integer) (a :: Type) (n :: K.Integer)+instance AssertEq+ (TypeError+ ('Text "SInt literal value does not match " ':<>:+ 'Text "expected type index:" ':$$:+ 'Text " " ':<>: ShowTypedNum a n))+ n+ m+ => SIntLitAssertion m a n++class (n >= 'Pos 0, n < 'Pos m) => FinLitAssertion m a n+instance ( CheckLessThanMaxBound+ (OutOfRangeMsg ('Pos 0) ('Pos m) a n)+ ('Pos m)+ a+ n+ , CheckAtLeastMinBound+ (OutOfRangeMsg ('Pos 0) ('Pos m) a n)+ ('Pos 0)+ a+ n+ )+ => FinLitAssertion m a n++-- HLint doesn't understand any of these because of DerivingVia :/+#if !defined(__HLINT__)+deriving via SNumLit (SIntLitAssertion ('Pos n)) (SInt n)+ instance HasIntLiterals (SInt n)++deriving via SNumLit (SIntLitAssertion n) (SNumber a n)+ instance (Eq a, Num a) => HasIntLiterals (SNumber a n)++deriving via SNumLit (FinLitAssertion n) (Fin n) instance HasIntLiterals (Fin n)++deriving via StockLit Integer instance HasIntLiterals Integer+deriving via StockLit Natural instance HasIntLiterals Natural+deriving via StockLit (Ratio a) instance Integral a => HasIntLiterals (Ratio a)++deriving via StockLit Int instance HasIntLiterals Int+deriving via StockLit Int8 instance HasIntLiterals Int8+deriving via StockLit Int16 instance HasIntLiterals Int16+deriving via StockLit Int32 instance HasIntLiterals Int32+deriving via StockLit Int64 instance HasIntLiterals Int64++deriving via StockLit Word instance HasIntLiterals Word+deriving via StockLit Word8 instance HasIntLiterals Word8+deriving via StockLit Word16 instance HasIntLiterals Word16+deriving via StockLit Word32 instance HasIntLiterals Word32+deriving via StockLit Word64 instance HasIntLiterals Word64++deriving via StockLit Float instance HasIntLiterals Float+deriving via StockLit Double instance HasIntLiterals Double++deriving via StockLit (Sum a)+ instance (Eq a, Num a) => HasIntLiterals (Sum a)+deriving via StockLit (Product a)+ instance (Eq a, Num a) => HasIntLiterals (Product a)+deriving via StockLit (Min a)+ instance (Eq a, Num a) => HasIntLiterals (Min a)+deriving via StockLit (Max a)+ instance (Eq a, Num a) => HasIntLiterals (Max a)+deriving via StockLit (Const a b)+ instance (Eq a, Num a) => HasIntLiterals (Const a b)+deriving via StockLit (Identity a)+ instance (Eq a, Num a) => HasIntLiterals (Identity a)++deriving via StockLit CChar instance HasIntLiterals CChar+deriving via StockLit CSChar instance HasIntLiterals CSChar+deriving via StockLit CUChar instance HasIntLiterals CUChar+deriving via StockLit CShort instance HasIntLiterals CShort+deriving via StockLit CUShort instance HasIntLiterals CUShort+deriving via StockLit CInt instance HasIntLiterals CInt+deriving via StockLit CUInt instance HasIntLiterals CUInt+deriving via StockLit CLong instance HasIntLiterals CLong+deriving via StockLit CULong instance HasIntLiterals CULong+deriving via StockLit CPtrdiff instance HasIntLiterals CPtrdiff+deriving via StockLit CSize instance HasIntLiterals CSize+deriving via StockLit CWchar instance HasIntLiterals CWchar+deriving via StockLit CSigAtomic instance HasIntLiterals CSigAtomic+deriving via StockLit CLLong instance HasIntLiterals CLLong+deriving via StockLit CULLong instance HasIntLiterals CULLong+deriving via StockLit CBool instance HasIntLiterals CBool+deriving via StockLit CIntPtr instance HasIntLiterals CIntPtr+deriving via StockLit CUIntPtr instance HasIntLiterals CUIntPtr+deriving via StockLit CIntMax instance HasIntLiterals CIntMax+deriving via StockLit CUIntMax instance HasIntLiterals CUIntMax+deriving via StockLit CClock instance HasIntLiterals CClock+deriving via StockLit CTime instance HasIntLiterals CTime+deriving via StockLit CUSeconds instance HasIntLiterals CUSeconds+deriving via StockLit CSUSeconds instance HasIntLiterals CSUSeconds+#endif