packages feed

morley 1.16.2 → 1.16.3

raw patch · 152 files changed

+5526/−2588 lines, 152 filesdep +Diffdep +th-reify-manyPVP: major bump suggested

API removals or changes: PVP suggests a major version bump

Dependencies added: Diff, th-reify-many

API changes (from Hackage documentation)

- Morley.Micheline.Class: instance Data.Singletons.Internal.SingI t => Morley.Micheline.Class.ToExpression (Morley.Michelson.Typed.Annotation.Notes t)
- Morley.Michelson.ErrorPos: unsafeMkPos :: Int -> Pos
- Morley.Michelson.Parser: type Parser = ReaderT LetEnv (Parsec CustomParserException Text)
- Morley.Michelson.Parser.Types: instance Data.Default.Class.Default a => Data.Default.Class.Default (Morley.Michelson.Parser.Types.Parser a)
- Morley.Michelson.Parser.Types: type Parser = ReaderT LetEnv (Parsec CustomParserException Text)
- Morley.Michelson.Text: unsafeMkMText :: HasCallStack => Text -> MText
- Morley.Michelson.TypeCheck.TypeCheck: unsafeMkSomeParamType :: HasCallStack => ParameterType -> SomeParamType
- Morley.Michelson.TypeCheck.Types: NotWellTyped :: T -> BadTypeForScope -> NotWellTyped
- Morley.Michelson.TypeCheck.Types: [nwtBadType] :: NotWellTyped -> T
- Morley.Michelson.TypeCheck.Types: [nwtCause] :: NotWellTyped -> BadTypeForScope
- Morley.Michelson.TypeCheck.Types: data NotWellTyped
- Morley.Michelson.TypeCheck.Types: getWTP :: forall t. SingI t => Either NotWellTyped (Dict (WellTyped t))
- Morley.Michelson.TypeCheck.Types: getWTP' :: Sing t -> Either NotWellTyped (Dict (WellTyped t))
- Morley.Michelson.TypeCheck.Types: instance Formatting.Buildable.Buildable Morley.Michelson.TypeCheck.Types.NotWellTyped
- Morley.Michelson.Typed: SubUnderflow :: MutezArithErrorType
- Morley.Michelson.Typed: [SomeConstant] :: (ConstantScope t, SingI t) => Value t -> SomeConstant
- Morley.Michelson.Typed: [SomeStorage] :: forall st. StorageScope st => Value st -> SomeStorage
- Morley.Michelson.Typed: [SomeValue] :: SingI t => Value t -> SomeValue
- Morley.Michelson.Typed: [ceaApplyEffects] :: CtorEffectsApp x -> forall i o. Semigroup x => x -> x -> Instr i o -> (Instr i o, x)
- Morley.Michelson.Typed: data SomeConstant
- Morley.Michelson.Typed: data SomeStorage
- Morley.Michelson.Typed: data SomeValue
- Morley.Michelson.Typed: mkUType' :: (Sing x, Notes x) -> Ty
- Morley.Michelson.Typed: unsafeMkViewName :: HasCallStack => Text -> ViewName
- Morley.Michelson.Typed: unsafeParseEpAddress :: HasCallStack => Text -> EpAddress
- Morley.Michelson.Typed: unsafeParseEpAddressRaw :: ByteString -> EpAddress
- Morley.Michelson.Typed.AnnotatedValue: instance Data.Singletons.Internal.SingI (Morley.Michelson.Typed.Haskell.Value.ToT v) => Formatting.Buildable.Buildable (Morley.Michelson.Typed.AnnotatedValue.AnnotatedValue v)
- Morley.Michelson.Typed.Arith: SubUnderflow :: MutezArithErrorType
- Morley.Michelson.Typed.Arith: instance (GHC.Show.Show n, GHC.Show.Show m) => Formatting.Buildable.Buildable (Morley.Michelson.Typed.Arith.ArithError n m)
- Morley.Michelson.Typed.Arith: instance Morley.Michelson.Typed.Arith.ArithOp Morley.Michelson.Typed.Arith.Sub 'Morley.Michelson.Typed.T.TMutez 'Morley.Michelson.Typed.T.TMutez
- Morley.Michelson.Typed.Entrypoints: unsafeParseEpAddress :: HasCallStack => Text -> EpAddress
- Morley.Michelson.Typed.Entrypoints: unsafeParseEpAddressRaw :: ByteString -> EpAddress
- Morley.Michelson.Typed.Existential: [SomeConstant] :: (ConstantScope t, SingI t) => Value t -> SomeConstant
- Morley.Michelson.Typed.Existential: [SomeStorage] :: forall st. StorageScope st => Value st -> SomeStorage
- Morley.Michelson.Typed.Existential: [SomeValue] :: SingI t => Value t -> SomeValue
- Morley.Michelson.Typed.Existential: data SomeConstant
- Morley.Michelson.Typed.Existential: data SomeStorage
- Morley.Michelson.Typed.Existential: data SomeValue
- Morley.Michelson.Typed.Existential: instance Formatting.Buildable.Buildable Morley.Michelson.Typed.Existential.SomeConstant
- Morley.Michelson.Typed.Existential: instance GHC.Classes.Eq Morley.Michelson.Typed.Existential.SomeValue
- Morley.Michelson.Typed.Existential: instance GHC.Show.Show Morley.Michelson.Typed.Existential.SomeStorage
- Morley.Michelson.Typed.Existential: instance GHC.Show.Show Morley.Michelson.Typed.Existential.SomeValue
- Morley.Michelson.Typed.Existential: instance Morley.Michelson.Printer.Util.RenderDoc Morley.Michelson.Typed.Existential.SomeConstant
- Morley.Michelson.Typed.Extract: mkUType :: SingI x => Notes x -> Ty
- Morley.Michelson.Typed.Extract: mkUType' :: (Sing x, Notes x) -> Ty
- Morley.Michelson.Typed.Haskell: class (SingI t, WellTypedSuperC t) => WellTyped (t :: T)
- Morley.Michelson.Typed.Haskell.Value: class (SingI t, WellTypedSuperC t) => WellTyped (t :: T)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Haskell.Value.WellTyped t, Morley.Michelson.Typed.Scope.HasNoOp t) => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TContract t)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Haskell.Value.WellTyped t, Morley.Michelson.Typed.Value.Comparable t) => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TTicket t)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Haskell.Value.WellTyped t1, Morley.Michelson.Typed.Haskell.Value.WellTyped t2) => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TLambda t1 t2)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Haskell.Value.WellTyped t1, Morley.Michelson.Typed.Haskell.Value.WellTyped t2) => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TOr t1 t2)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Haskell.Value.WellTyped t1, Morley.Michelson.Typed.Haskell.Value.WellTyped t2) => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TPair t1 t2)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Value.Comparable (Morley.Michelson.Typed.Haskell.Value.ToT a), Morley.Michelson.Typed.Haskell.Value.IsoValue a) => Morley.Michelson.Typed.Haskell.Value.IsoValue (Morley.Michelson.Typed.Haskell.Value.Ticket a)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Value.Comparable (Morley.Michelson.Typed.Haskell.Value.ToT c), GHC.Classes.Ord c, Morley.Michelson.Typed.Haskell.Value.IsoValue c) => Morley.Michelson.Typed.Haskell.Value.IsoValue (Data.Set.Internal.Set c)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Value.Comparable (Morley.Michelson.Typed.Haskell.Value.ToT k), GHC.Classes.Ord k, Morley.Michelson.Typed.Haskell.Value.IsoValue k, Morley.Michelson.Typed.Haskell.Value.IsoValue v) => Morley.Michelson.Typed.Haskell.Value.IsoValue (Data.Map.Internal.Map k v)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Value.Comparable (Morley.Michelson.Typed.Haskell.Value.ToT k), GHC.Classes.Ord k, Morley.Michelson.Typed.Haskell.Value.IsoValue k, Morley.Michelson.Typed.Haskell.Value.IsoValue v, Morley.Michelson.Typed.Haskell.Value.HasNoBigMapToT v, Morley.Michelson.Typed.Haskell.Value.HasNoOpToT v) => Morley.Michelson.Typed.Haskell.Value.IsoValue (Morley.Michelson.Typed.Haskell.Value.BigMap k v)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Value.Comparable k, Morley.Michelson.Typed.Haskell.Value.WellTyped k, Morley.Michelson.Typed.Haskell.Value.WellTyped v) => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TMap k v)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Value.Comparable k, Morley.Michelson.Typed.Haskell.Value.WellTyped k, Morley.Michelson.Typed.Haskell.Value.WellTyped v, Morley.Michelson.Typed.Scope.HasNoBigMap v, Morley.Michelson.Typed.Scope.HasNoOp v) => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TBigMap k v)
- Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Value.Comparable t, Morley.Michelson.Typed.Haskell.Value.WellTyped t) => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TSet t)
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TAddress
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TBls12381Fr
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TBls12381G1
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TBls12381G2
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TBool
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TBytes
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TChainId
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TChest
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TChestKey
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TInt
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TKey
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TKeyHash
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TMutez
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TNat
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TNever
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TOperation
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TSignature
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TString
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TTimestamp
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped 'Morley.Michelson.Typed.T.TUnit
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped t => Morley.Michelson.Typed.Haskell.Value.IsoValue (Morley.Michelson.Typed.Aliases.Value t)
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped t => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TList t)
- Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Haskell.Value.WellTyped t => Morley.Michelson.Typed.Haskell.Value.WellTyped ('Morley.Michelson.Typed.T.TOption t)
- Morley.Michelson.Typed.Scope: instance (Data.Singletons.Internal.SingI t, Morley.Michelson.Typed.Scope.HasNoOp t, Morley.Michelson.Typed.Scope.HasNoBigMap t, Morley.Michelson.Typed.Scope.HasNoContract t, Morley.Michelson.Typed.Scope.HasNoTicket t) => Morley.Michelson.Typed.Scope.ConstantScope t
- Morley.Michelson.Typed.Scope: instance (Data.Singletons.Internal.SingI t, Morley.Michelson.Typed.Scope.HasNoOp t, Morley.Michelson.Typed.Scope.HasNoBigMap t, Morley.Michelson.Typed.Scope.HasNoTicket t) => Morley.Michelson.Typed.Scope.PackedValScope t
- Morley.Michelson.Typed.Scope: instance (Data.Singletons.Internal.SingI t, Morley.Michelson.Typed.Scope.HasNoOp t, Morley.Michelson.Typed.Scope.HasNoNestedBigMaps t) => Morley.Michelson.Typed.Scope.ParameterScope t
- Morley.Michelson.Typed.Scope: instance (Data.Singletons.Internal.SingI t, Morley.Michelson.Typed.Scope.HasNoOp t, Morley.Michelson.Typed.Scope.HasNoNestedBigMaps t, Morley.Michelson.Typed.Scope.HasNoContract t) => Morley.Michelson.Typed.Scope.StorageScope t
- Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.PackedValScope t, Morley.Michelson.Typed.Scope.ConstantScope t) => Morley.Michelson.Typed.Scope.UnpackedValScope t
- Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoOp t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoBigMap t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoContract t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoTicket t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.ConstantScope t a b
- Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoOp t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoBigMap t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoTicket t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.PackedValScope t a b
- Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoOp t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoNestedBigMaps t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.ParameterScope t a b
- Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoOp t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoNestedBigMaps t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoContract t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.StorageScope t a b
- Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.PackedValScope t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.ConstantScope t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.UnpackedValScope t a b
- Morley.Michelson.Typed.Sing: instance Data.Singletons.Decide.SDecide Morley.Michelson.Typed.T.T => Data.Singletons.Decide.SDecide Morley.Michelson.Typed.T.T
- Morley.Michelson.Typed.Sing: instance Data.Singletons.Decide.SDecide Morley.Michelson.Typed.T.T => Data.Type.Coercion.TestCoercion Morley.Michelson.Typed.Sing.SingT
- Morley.Michelson.Typed.Sing: instance Data.Singletons.Decide.SDecide Morley.Michelson.Typed.T.T => Data.Type.Equality.TestEquality Morley.Michelson.Typed.Sing.SingT
- Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TBigMapSym1 a6989586621679396449)
- Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TLambdaSym1 a6989586621679396443)
- Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TMapSym1 a6989586621679396446)
- Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TOrSym1 a6989586621679396440)
- Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TPairSym1 a6989586621679396437)
- Morley.Michelson.Typed.Util: [ceaApplyEffects] :: CtorEffectsApp x -> forall i o. Semigroup x => x -> x -> Instr i o -> (Instr i o, x)
- Morley.Michelson.Typed.Util: instance GHC.Show.Show (Morley.Michelson.Typed.Util.CtorEffectsApp x)
- Morley.Michelson.Typed.Util: instance GHC.Show.Show (Morley.Michelson.Typed.Util.DfsSettings x)
- Morley.Michelson.Typed.Value: class (IsComparable t ~ 'True) => Comparable t
- Morley.Michelson.Typed.Value: comparabilityPresence :: Sing t -> Maybe (Dict $ Comparable t)
- Morley.Michelson.Typed.Value: instance (Morley.Michelson.Typed.Value.Comparable e, Morley.Michelson.Typed.Scope.ForbidNonComparable e) => Morley.Michelson.Typed.Value.Comparable ('Morley.Michelson.Typed.T.TOption e)
- Morley.Michelson.Typed.Value: instance (Morley.Michelson.Typed.Value.Comparable e1, Morley.Michelson.Typed.Value.Comparable e2, Morley.Michelson.Typed.Scope.FailOnNonComparableFound (Morley.Michelson.Typed.Scope.IsComparable e1 Data.Type.Bool.&& Morley.Michelson.Typed.Scope.IsComparable e2)) => Morley.Michelson.Typed.Value.Comparable ('Morley.Michelson.Typed.T.TOr e1 e2)
- Morley.Michelson.Typed.Value: instance (Morley.Michelson.Typed.Value.Comparable e1, Morley.Michelson.Typed.Value.Comparable e2, Morley.Michelson.Typed.Scope.FailOnNonComparableFound (Morley.Michelson.Typed.Scope.IsComparable e1 Data.Type.Bool.&& Morley.Michelson.Typed.Scope.IsComparable e2)) => Morley.Michelson.Typed.Value.Comparable ('Morley.Michelson.Typed.T.TPair e1 e2)
- Morley.Michelson.Typed.Value: instance Data.Singletons.Internal.SingI t => Morley.Michelson.Typed.Scope.CheckScope (Morley.Michelson.Typed.Value.ComparabilityScope t)
- Morley.Michelson.Typed.Value: instance Data.Singletons.Internal.SingI t => Morley.Michelson.Typed.Scope.CheckScope (Morley.Michelson.Typed.Value.Comparable t)
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TAddress
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TBool
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TBytes
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TChainId
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TInt
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TKey
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TKeyHash
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TMutez
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TNat
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TNever
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TSignature
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TString
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TTimestamp
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable 'Morley.Michelson.Typed.T.TUnit
- Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Value.Comparable e => GHC.Classes.Ord (Morley.Michelson.Typed.Value.Value' instr e)
- Morley.Michelson.Typed.Value: type ComparabilityScope t = (SingI t, Comparable t)
- Morley.Michelson.Typed.View: unsafeMkViewName :: HasCallStack => Text -> ViewName
- Morley.Michelson.Untyped.Annotation: instance Morley.Michelson.Untyped.Annotation.KnownAnnTag tag => GHC.Show.Show (Morley.Michelson.Untyped.Annotation.Annotation tag)
- Morley.Michelson.Untyped.Annotation: unsafeMkAnnotation :: HasCallStack => Text -> Annotation a
- Morley.Michelson.Untyped.Entrypoints: unsafeBuildEpName :: HasCallStack => Text -> EpName
- Morley.Michelson.Untyped.Instr: instance Morley.Michelson.Printer.Util.RenderDoc (Morley.Michelson.Untyped.Instr.InstrAbstract op) => GHC.Show.Show (Morley.Michelson.Untyped.Instr.InstrAbstract op)
- Morley.Michelson.Untyped.View: unsafeMkViewName :: HasCallStack => Text -> ViewName
- Morley.Tezos.Address: unsafeParseAddress :: HasCallStack => Text -> Address
- Morley.Tezos.Address: unsafeParseAddressRaw :: ByteString -> Address
- Morley.Tezos.Address: unsafeParseContractHash :: HasCallStack => Text -> ContractHash
- Morley.Tezos.Core: instance Data.Data.Data Morley.Tezos.Core.Mutez
- Morley.Tezos.Core: unsafeMkChainId :: HasCallStack => ByteString -> ChainId
- Morley.Tezos.Core: unsafeMkMutez :: HasCallStack => Word64 -> Mutez
- Morley.Tezos.Crypto: unsafeMkTLTime :: HasCallStack => Word64 -> TLTime
- Morley.Tezos.Crypto: unsafeParseKeyHash :: HasCallStack => Text -> KeyHash
- Morley.Tezos.Crypto.BLS12381: unsafeFromMichelsonBytes :: (CurveObject a, HasCallStack) => ByteString -> a
- Morley.Tezos.Crypto.Timelock: instance GHC.Num.Num Morley.Tezos.Crypto.Timelock.TLTime
- Morley.Tezos.Crypto.Timelock: unsafeMkTLTime :: HasCallStack => Word64 -> TLTime
- Morley.Util.Interpolate: instance GHC.Classes.Eq Morley.Util.Interpolate.Transformation
- Morley.Util.Interpolate: instance GHC.Classes.Ord Morley.Util.Interpolate.Transformation
- Morley.Util.Interpolate: instance GHC.Enum.Bounded Morley.Util.Interpolate.Transformation
- Morley.Util.Interpolate: instance GHC.Enum.Enum Morley.Util.Interpolate.Transformation
- Morley.Util.Named: Name :: Name (name :: Symbol)
- Morley.Util.Peano: S :: !Nat -> Nat
- Morley.Util.Peano: Z :: Nat
- Morley.Util.Peano: data Nat
+ Morley.AsRPC: [IsRPC] :: (SingI (ToT v), IsoValue (AsRPC v), HasRPCRepr v) => AsRPC v -> MaybeRPC v
+ Morley.AsRPC: [NotRPC] :: IsoValue v => v -> MaybeRPC v
+ Morley.AsRPC: class (TAsRPC (ToT t) ~ ToT (AsRPC t)) => HasRPCRepr (t :: Type) where {
+ Morley.AsRPC: data MaybeRPC v
+ Morley.AsRPC: deriveManyRPC :: String -> [String] -> Q [Dec]
+ Morley.AsRPC: deriveManyRPCWithStrategy :: String -> [String] -> GenericStrategy -> Q [Dec]
+ Morley.AsRPC: deriveRPC :: String -> Q [Dec]
+ Morley.AsRPC: deriveRPCWithStrategy :: String -> GenericStrategy -> Q [Dec]
+ Morley.AsRPC: instance (Morley.AsRPC.HasRPCRepr a, Morley.AsRPC.HasRPCRepr b) => Morley.AsRPC.HasRPCRepr (a, b)
+ Morley.AsRPC: instance (Morley.AsRPC.HasRPCRepr l, Morley.AsRPC.HasRPCRepr r) => Morley.AsRPC.HasRPCRepr (Data.Either.Either l r)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr ()
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr (Data.Set.Internal.Set a)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr (Morley.Michelson.Typed.Aliases.Value t)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr (Morley.Michelson.Typed.Haskell.Value.BigMap k v)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr (Morley.Michelson.Typed.Haskell.Value.ContractRef arg)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Data.ByteString.Internal.ByteString
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr GHC.Integer.Type.Integer
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr GHC.Natural.Natural
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr GHC.Types.Bool
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Michelson.Text.MText
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Michelson.Typed.Aliases.Operation
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Michelson.Typed.Entrypoints.EpAddress
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Address.Address
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Core.ChainId
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Core.Mutez
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Core.Timestamp
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Crypto.BLS12381.Bls12381Fr
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Crypto.BLS12381.Bls12381G1
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Crypto.BLS12381.Bls12381G2
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Crypto.KeyHash
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Crypto.PublicKey
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Crypto.Signature
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Crypto.Timelock.Chest
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr Morley.Tezos.Crypto.Timelock.ChestKey
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr a => Morley.AsRPC.HasRPCRepr (Data.Functor.Identity.Identity a)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr a => Morley.AsRPC.HasRPCRepr (GHC.Maybe.Maybe a)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr a => Morley.AsRPC.HasRPCRepr (Named.Internal.NamedF Data.Functor.Identity.Identity a name)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr a => Morley.AsRPC.HasRPCRepr (Named.Internal.NamedF GHC.Maybe.Maybe a name)
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr a => Morley.AsRPC.HasRPCRepr [a]
+ Morley.AsRPC: instance Morley.AsRPC.HasRPCRepr v => Morley.AsRPC.HasRPCRepr (Data.Map.Internal.Map k v)
+ Morley.AsRPC: instance Morley.Michelson.Typed.Scope.HasNoOp (Morley.Michelson.Typed.Haskell.Value.ToT v) => Morley.Micheline.Class.ToExpression (Morley.AsRPC.MaybeRPC v)
+ Morley.AsRPC: instance Universum.TypeOps.Each '[Morley.AsRPC.HasRPCRepr] '[a, b, c, d, e, f, g] => Morley.AsRPC.HasRPCRepr (a, b, c, d, e, f, g)
+ Morley.AsRPC: instance Universum.TypeOps.Each '[Morley.AsRPC.HasRPCRepr] '[a, b, c, d, e, f] => Morley.AsRPC.HasRPCRepr (a, b, c, d, e, f)
+ Morley.AsRPC: instance Universum.TypeOps.Each '[Morley.AsRPC.HasRPCRepr] '[a, b, c, d, e] => Morley.AsRPC.HasRPCRepr (a, b, c, d, e)
+ Morley.AsRPC: instance Universum.TypeOps.Each '[Morley.AsRPC.HasRPCRepr] '[a, b, c, d] => Morley.AsRPC.HasRPCRepr (a, b, c, d)
+ Morley.AsRPC: instance Universum.TypeOps.Each '[Morley.AsRPC.HasRPCRepr] '[a, b, c] => Morley.AsRPC.HasRPCRepr (a, b, c)
+ Morley.AsRPC: notesAsRPC :: Notes t -> Notes (TAsRPC t)
+ Morley.AsRPC: replaceBigMapIds :: forall t m. Monad m => (forall k v. (SingI k, SingI v) => Natural -> m (Value ('TBigMap k v))) -> Sing t -> Value (TAsRPC t) -> m (Value t)
+ Morley.AsRPC: rpcHasNoBigMapEvi :: forall (t :: T). SingI t => Dict (HasNoBigMap (TAsRPC t))
+ Morley.AsRPC: rpcHasNoContractEvi :: forall (t :: T). (SingI t, HasNoContract t) => HasNoContract t :- HasNoContract (TAsRPC t)
+ Morley.AsRPC: rpcHasNoNestedBigMapsEvi :: forall (t :: T). SingI t => Dict (HasNoNestedBigMaps (TAsRPC t))
+ Morley.AsRPC: rpcHasNoOpEvi :: forall (t :: T). (SingI t, HasNoOp t) => HasNoOp t :- HasNoOp (TAsRPC t)
+ Morley.AsRPC: rpcSingIEvi :: forall (t :: T). SingI t :- SingI (TAsRPC t)
+ Morley.AsRPC: rpcStorageScopeEvi :: forall (t :: T). StorageScope t :- StorageScope (TAsRPC t)
+ Morley.AsRPC: type family AsRPC t :: Type;
+ Morley.AsRPC: valueAsRPC :: HasCallStack => Value t -> Value (TAsRPC t)
+ Morley.AsRPC: }
+ Morley.Micheline.Class: instance Morley.Micheline.Class.ToExpression (Morley.Michelson.Typed.Annotation.Notes t)
+ Morley.Michelson.Doc: docBlockToMarkdown :: HeaderLevel -> DocBlock -> Markdown
+ Morley.Michelson.Interpret: [MichelsonUnsupported] :: Text -> MichelsonFailed
+ Morley.Michelson.Parser: DeprecatedException :: CustomParserException
+ Morley.Michelson.Parser: notes :: QuasiQuoter
+ Morley.Michelson.Parser: programExt :: Parsec CustomParserException Text (Contract' ParsedOp)
+ Morley.Michelson.Parser: type Parser a r = HasLetEnv a => Parser' a r
+ Morley.Michelson.Parser.Error: DeprecatedException :: CustomParserException
+ Morley.Michelson.Parser.Helpers: count :: (SingIPeano n, Applicative m) => m a -> m (SizedList n a)
+ Morley.Michelson.Parser.Instr: viewOp :: Parser le ParsedInstr
+ Morley.Michelson.Parser.Lexer: spaces :: Parser le ()
+ Morley.Michelson.Parser.Lexer: symbol1 :: Tokens Text -> Parser le ()
+ Morley.Michelson.Parser.Lexer: symbol1' :: Text -> Parser le ()
+ Morley.Michelson.Parser.Types: assertLetEnv :: forall le. Parser le (le :~: LetEnv)
+ Morley.Michelson.Parser.Types: class HasLetEnv a
+ Morley.Michelson.Parser.Types: instance Data.Default.Class.Default Morley.Michelson.Parser.Types.LetEnv
+ Morley.Michelson.Parser.Types: instance Data.Default.Class.Default a => Data.Default.Class.Default (Morley.Michelson.Parser.Types.Parser' le a)
+ Morley.Michelson.Parser.Types: instance GHC.Classes.Eq Morley.Michelson.Parser.Types.ParserOptions
+ Morley.Michelson.Parser.Types: instance GHC.Show.Show Morley.Michelson.Parser.Types.ParserOptions
+ Morley.Michelson.Parser.Types: instance Morley.Michelson.Parser.Types.HasLetEnv ()
+ Morley.Michelson.Parser.Types: instance Morley.Michelson.Parser.Types.HasLetEnv Morley.Michelson.Parser.Types.LetEnv
+ Morley.Michelson.Parser.Types: isLetEnv :: HasLetEnv a => Maybe (a :~: LetEnv)
+ Morley.Michelson.Parser.Types: type Parser' a = ReaderT a (Parsec CustomParserException Text)
+ Morley.Michelson.Parser.Types: withLetEnv :: forall le a. Parser' LetEnv a -> Parser le a
+ Morley.Michelson.Printer.Util: instance GHC.Base.Functor Morley.Michelson.Printer.Util.Prettier
+ Morley.Michelson.Runtime: ExecutorLog :: [GStateUpdate] -> [(Address, InterpretResult)] -> ExecutorLog
+ Morley.Michelson.Runtime: ExecutorState :: GState -> RemainingSteps -> Maybe Address -> ExecutorLog -> ~OperationHash -> HashSet GlobalCounter -> ExecutorState
+ Morley.Michelson.Runtime: [_elInterpreterResults] :: ExecutorLog -> [(Address, InterpretResult)]
+ Morley.Michelson.Runtime: [_elUpdates] :: ExecutorLog -> [GStateUpdate]
+ Morley.Michelson.Runtime: [_esGState] :: ExecutorState -> GState
+ Morley.Michelson.Runtime: [_esLog] :: ExecutorState -> ExecutorLog
+ Morley.Michelson.Runtime: [_esOperationHash] :: ExecutorState -> ~OperationHash
+ Morley.Michelson.Runtime: [_esPrevCounters] :: ExecutorState -> HashSet GlobalCounter
+ Morley.Michelson.Runtime: [_esRemainingSteps] :: ExecutorState -> RemainingSteps
+ Morley.Michelson.Runtime: [_esSourceAddress] :: ExecutorState -> Maybe Address
+ Morley.Michelson.Runtime: data ExecutorLog
+ Morley.Michelson.Runtime: data ExecutorState
+ Morley.Michelson.Runtime: esGState :: Lens' ExecutorState GState
+ Morley.Michelson.Runtime: esLog :: Lens' ExecutorState ExecutorLog
+ Morley.Michelson.Runtime: esOperationHash :: Lens' ExecutorState OperationHash
+ Morley.Michelson.Runtime: esPrevCounters :: Lens' ExecutorState (HashSet GlobalCounter)
+ Morley.Michelson.Runtime: esRemainingSteps :: Lens' ExecutorState RemainingSteps
+ Morley.Michelson.Runtime: esSourceAddress :: Lens' ExecutorState (Maybe Address)
+ Morley.Michelson.Runtime: parseContractExt :: MichelsonSource -> Text -> Either ParserException (Contract' ParsedOp)
+ Morley.Michelson.Runtime: parseExpandContractExt :: MichelsonSource -> Text -> Either ParserException Contract
+ Morley.Michelson.Runtime: prepareContractExt :: Maybe FilePath -> IO Contract
+ Morley.Michelson.Runtime: readAndParseContractExt :: Maybe FilePath -> IO (Contract' ParsedOp)
+ Morley.Michelson.Runtime.GState: genesisAddressN :: forall n. (SingIPeano n, (ToPeano GenesisAddressesNum > ToPeano n) ~ 'True) => Address
+ Morley.Michelson.Runtime.GState: instance GHC.Classes.Eq Morley.Michelson.Runtime.GState.AddressState
+ Morley.Michelson.Runtime.GState: instance GHC.Classes.Eq Morley.Michelson.Runtime.GState.ContractState
+ Morley.Michelson.Runtime.GState: instance GHC.Classes.Eq Morley.Michelson.Runtime.GState.GState
+ Morley.Michelson.Runtime.GState: instance GHC.Classes.Eq Morley.Michelson.Runtime.GState.VotingPowers
+ Morley.Michelson.Runtime.Import: readContractExt :: forall cp st. Each '[SingI] [cp, st] => MichelsonSource -> Text -> Either ContractReadError (Contract cp st)
+ Morley.Michelson.Runtime.Import: readSomeContractExt :: MichelsonSource -> Text -> Either ContractReadError SomeContract
+ Morley.Michelson.Runtime.Import: readUntypedContractExt :: MichelsonSource -> Text -> Either ContractReadError Contract
+ Morley.Michelson.TypeCheck: typeVerifyView :: forall arg ret st. (SingI arg, SingI ret, WellTyped st) => Notes st -> View -> TypeCheckResult (View arg st ret)
+ Morley.Michelson.TypeCheck.Error: TCIncompletelyTypedView :: TCError -> View' TypeCheckedOp -> TCError
+ Morley.Michelson.TypeCheck.Error: instance Formatting.Buildable.Buildable Morley.Michelson.TypeCheck.Error.StackSize
+ Morley.Michelson.TypeCheck.Instr: typeVerifyView :: forall arg ret st. (SingI arg, SingI ret, WellTyped st) => Notes st -> View -> TypeCheckResult (View arg st ret)
+ Morley.Michelson.Typed: BtHasSaplingState :: BadTypeForScope
+ Morley.Michelson.Typed: NotWellTyped :: T -> BadTypeForScope -> NotWellTyped
+ Morley.Michelson.Typed: TSaplingState :: Peano -> T
+ Morley.Michelson.Typed: TSaplingTransaction :: Peano -> T
+ Morley.Michelson.Typed: [NTSaplingState] :: forall (n :: Peano). TypeAnn -> Sing n -> Notes ('TSaplingState n)
+ Morley.Michelson.Typed: [NTSaplingTransaction] :: forall (n :: Peano). TypeAnn -> Sing n -> Notes ('TSaplingTransaction n)
+ Morley.Michelson.Typed: [SAPLING_EMPTY_STATE] :: Sing n -> Instr s ('TSaplingState n : s)
+ Morley.Michelson.Typed: [SAPLING_VERIFY_UPDATE] :: Instr ('TSaplingTransaction n : ('TSaplingState n : s)) ('TOption ('TPair 'TInt ('TSaplingState n)) : s)
+ Morley.Michelson.Typed: [STSaplingState] :: forall (n_a22W3 :: Nat). () => Sing n_a22W3 -> SingT ('TSaplingState n_a22W3 :: T)
+ Morley.Michelson.Typed: [STSaplingTransaction] :: forall (n_a22W5 :: Nat). () => Sing n_a22W5 -> SingT ('TSaplingTransaction n_a22W5 :: T)
+ Morley.Michelson.Typed: [SUB_MUTEZ] :: Instr ('TMutez : ('TMutez : s)) ('TOption 'TMutez : s)
+ Morley.Michelson.Typed: [ceaPostStep] :: CtorEffectsApp m -> forall i o. Monad m => Instr i o -> m (Instr i o) -> m (Instr i o)
+ Morley.Michelson.Typed: [nwtBadType] :: NotWellTyped -> T
+ Morley.Michelson.Typed: [nwtCause] :: NotWellTyped -> BadTypeForScope
+ Morley.Michelson.Typed: analyzeInstrFailure :: HasCallStack => Instr i o -> RemFail Instr i o
+ Morley.Michelson.Typed: data NotWellTyped
+ Morley.Michelson.Typed: data SubMutez
+ Morley.Michelson.Typed: dfsTraverseInstr :: forall m inp out. Monad m => DfsSettings m -> (forall i o. Instr i o -> m (Instr i o)) -> Instr inp out -> m (Instr inp out)
+ Morley.Michelson.Typed: getWTP :: forall t. SingI t => Either NotWellTyped (Dict (WellTyped t))
+ Morley.Michelson.Typed: getWTP' :: Sing t -> Either NotWellTyped (Dict (WellTyped t))
+ Morley.Michelson.Typed: instrGetField :: forall dt name st. (InstrGetFieldC dt name, DupableScope (ToT (GetFieldType dt name))) => Label name -> Instr (ToT dt : st) (ToT (GetFieldType dt name) : (ToT dt : st))
+ Morley.Michelson.Typed: instrGetFieldOpen :: forall dt name res st. InstrGetFieldC dt name => Instr '[ToT (GetFieldType dt name)] '[res, ToT (GetFieldType dt name)] -> Instr '[ToT (GetFieldType dt name)] '[res] -> Label name -> Instr (ToT dt : st) (res : (ToT dt : st))
+ Morley.Michelson.Typed: instrSetFieldOpen :: forall dt name new st. InstrSetFieldC dt name => Instr '[new, ToT (GetFieldType dt name)] '[ToT (GetFieldType dt name)] -> Label name -> Instr (new : (ToT dt : st)) (ToT dt : st)
+ Morley.Michelson.Typed: isMichelsonInstr :: Instr i o -> Bool
+ Morley.Michelson.Typed: pattern SomeStorage :: () => StorageScope t => Value t -> SomeStorage
+ Morley.Michelson.Typed: type ComparableSuperC _ = ();
+ Morley.Michelson.Typed: type SomeConstant = SomeConstrainedValue ConstantScope
+ Morley.Michelson.Typed: type SomePackedVal = SomeConstrainedValue PackedValScope
+ Morley.Michelson.Typed: type SomeStorage = SomeConstrainedValue StorageScope
+ Morley.Michelson.Typed: type SomeValue = SomeConstrainedValue SingI
+ Morley.Michelson.Typed: type WellTypedSuperC _ = ();
+ Morley.Michelson.Typed.AnnotatedValue: instance Formatting.Buildable.Buildable (Morley.Michelson.Typed.AnnotatedValue.AnnotatedValue v)
+ Morley.Michelson.Typed.Annotation: [NTSaplingState] :: forall (n :: Peano). TypeAnn -> Sing n -> Notes ('TSaplingState n)
+ Morley.Michelson.Typed.Annotation: [NTSaplingTransaction] :: forall (n :: Peano). TypeAnn -> Sing n -> Notes ('TSaplingTransaction n)
+ Morley.Michelson.Typed.Annotation: instance Language.Haskell.TH.Syntax.Lift (Morley.Michelson.Typed.Annotation.Notes t)
+ Morley.Michelson.Typed.Annotation: mkUType :: Notes x -> Ty
+ Morley.Michelson.Typed.Arith: data SubMutez
+ Morley.Michelson.Typed.Arith: instance (Formatting.Buildable.Buildable n, Formatting.Buildable.Buildable m) => Formatting.Buildable.Buildable (Morley.Michelson.Typed.Arith.ArithError n m)
+ Morley.Michelson.Typed.Arith: instance Morley.Michelson.Typed.Arith.ArithOp Morley.Michelson.Typed.Arith.SubMutez 'Morley.Michelson.Typed.T.TMutez 'Morley.Michelson.Typed.T.TMutez
+ Morley.Michelson.Typed.Existential: instance (forall (t :: Morley.Michelson.Typed.T.T). cs t => Data.Singletons.Internal.SingI t) => GHC.Classes.Eq (Morley.Michelson.Typed.Existential.SomeConstrainedValue cs)
+ Morley.Michelson.Typed.Existential: instance (forall (t :: Morley.Michelson.Typed.T.T). cs t => Morley.Michelson.Typed.Scope.HasNoOp t) => Morley.Michelson.Printer.Util.RenderDoc (Morley.Michelson.Typed.Existential.SomeConstrainedValue cs)
+ Morley.Michelson.Typed.Existential: instance Formatting.Buildable.Buildable (Morley.Michelson.Typed.Existential.SomeConstrainedValue c)
+ Morley.Michelson.Typed.Existential: pattern SomePackedVal :: () => PackedValScope t => Value t -> SomePackedVal
+ Morley.Michelson.Typed.Existential: type SomeConstant = SomeConstrainedValue ConstantScope
+ Morley.Michelson.Typed.Existential: type SomePackedVal = SomeConstrainedValue PackedValScope
+ Morley.Michelson.Typed.Existential: type SomeStorage = SomeConstrainedValue StorageScope
+ Morley.Michelson.Typed.Existential: type SomeValue = SomeConstrainedValue SingI
+ Morley.Michelson.Typed.Haskell: instrGetField :: forall dt name st. (InstrGetFieldC dt name, DupableScope (ToT (GetFieldType dt name))) => Label name -> Instr (ToT dt : st) (ToT (GetFieldType dt name) : (ToT dt : st))
+ Morley.Michelson.Typed.Haskell: instrGetFieldOpen :: forall dt name res st. InstrGetFieldC dt name => Instr '[ToT (GetFieldType dt name)] '[res, ToT (GetFieldType dt name)] -> Instr '[ToT (GetFieldType dt name)] '[res] -> Label name -> Instr (ToT dt : st) (res : (ToT dt : st))
+ Morley.Michelson.Typed.Haskell: instrSetFieldOpen :: forall dt name new st. InstrSetFieldC dt name => Instr '[new, ToT (GetFieldType dt name)] '[ToT (GetFieldType dt name)] -> Label name -> Instr (new : (ToT dt : st)) (ToT dt : st)
+ Morley.Michelson.Typed.Haskell.Instr.Product: instrGetField :: forall dt name st. (InstrGetFieldC dt name, DupableScope (ToT (GetFieldType dt name))) => Label name -> Instr (ToT dt : st) (ToT (GetFieldType dt name) : (ToT dt : st))
+ Morley.Michelson.Typed.Haskell.Instr.Product: instrGetFieldOpen :: forall dt name res st. InstrGetFieldC dt name => Instr '[ToT (GetFieldType dt name)] '[res, ToT (GetFieldType dt name)] -> Instr '[ToT (GetFieldType dt name)] '[res] -> Label name -> Instr (ToT dt : st) (res : (ToT dt : st))
+ Morley.Michelson.Typed.Haskell.Instr.Product: instrSetFieldOpen :: forall dt name new st. InstrSetFieldC dt name => Instr '[new, ToT (GetFieldType dt name)] '[ToT (GetFieldType dt name)] -> Label name -> Instr (new : (ToT dt : st)) (ToT dt : st)
+ Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Scope.Comparable (Morley.Michelson.Typed.Haskell.Value.ToT a), Morley.Michelson.Typed.Haskell.Value.IsoValue a) => Morley.Michelson.Typed.Haskell.Value.IsoValue (Morley.Michelson.Typed.Haskell.Value.Ticket a)
+ Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Scope.Comparable (Morley.Michelson.Typed.Haskell.Value.ToT c), GHC.Classes.Ord c, Morley.Michelson.Typed.Haskell.Value.IsoValue c) => Morley.Michelson.Typed.Haskell.Value.IsoValue (Data.Set.Internal.Set c)
+ Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Scope.Comparable (Morley.Michelson.Typed.Haskell.Value.ToT k), GHC.Classes.Ord k, Morley.Michelson.Typed.Haskell.Value.IsoValue k, Morley.Michelson.Typed.Haskell.Value.IsoValue v) => Morley.Michelson.Typed.Haskell.Value.IsoValue (Data.Map.Internal.Map k v)
+ Morley.Michelson.Typed.Haskell.Value: instance (Morley.Michelson.Typed.Scope.Comparable (Morley.Michelson.Typed.Haskell.Value.ToT k), GHC.Classes.Ord k, Morley.Michelson.Typed.Haskell.Value.IsoValue k, Morley.Michelson.Typed.Haskell.Value.IsoValue v, Morley.Michelson.Typed.Haskell.Value.HasNoBigMapToT v, Morley.Michelson.Typed.Haskell.Value.HasNoOpToT v) => Morley.Michelson.Typed.Haskell.Value.IsoValue (Morley.Michelson.Typed.Haskell.Value.BigMap k v)
+ Morley.Michelson.Typed.Haskell.Value: instance GHC.Classes.Ord k => Morley.Michelson.Typed.Haskell.Value.ToBigMap (Morley.Util.SizedList.SizedList' n (k, v))
+ Morley.Michelson.Typed.Haskell.Value: instance Morley.Michelson.Typed.Scope.WellTyped t => Morley.Michelson.Typed.Haskell.Value.IsoValue (Morley.Michelson.Typed.Aliases.Value t)
+ Morley.Michelson.Typed.Instr: [SAPLING_EMPTY_STATE] :: Sing n -> Instr s ('TSaplingState n : s)
+ Morley.Michelson.Typed.Instr: [SAPLING_VERIFY_UPDATE] :: Instr ('TSaplingTransaction n : ('TSaplingState n : s)) ('TOption ('TPair 'TInt ('TSaplingState n)) : s)
+ Morley.Michelson.Typed.Instr: [SUB_MUTEZ] :: Instr ('TMutez : ('TMutez : s)) ('TOption 'TMutez : s)
+ Morley.Michelson.Typed.Polymorphic: instance Morley.Michelson.Typed.Polymorphic.MapOp ('Morley.Michelson.Typed.T.TOption e)
+ Morley.Michelson.Typed.Scope: -- | Constraints required for instance of a given type.
+ Morley.Michelson.Typed.Scope: BtHasSaplingState :: BadTypeForScope
+ Morley.Michelson.Typed.Scope: NotWellTyped :: T -> BadTypeForScope -> NotWellTyped
+ Morley.Michelson.Typed.Scope: [CanBeCompared] :: Comparable t => Comparability t
+ Morley.Michelson.Typed.Scope: [CannotBeCompared] :: IsComparable t ~ 'False => Comparability t
+ Morley.Michelson.Typed.Scope: [nwtBadType] :: NotWellTyped -> T
+ Morley.Michelson.Typed.Scope: [nwtCause] :: NotWellTyped -> BadTypeForScope
+ Morley.Michelson.Typed.Scope: checkComparability :: Sing t -> Comparability t
+ Morley.Michelson.Typed.Scope: class (IsComparable t ~ 'True, SingI t, ComparableSuperC t) => Comparable t where {
+ Morley.Michelson.Typed.Scope: class (SingI t, WellTypedSuperC t) => WellTyped (t :: T) where {
+ Morley.Michelson.Typed.Scope: comparabilityPresence :: Sing t -> Maybe (Dict $ Comparable t)
+ Morley.Michelson.Typed.Scope: data Comparability t
+ Morley.Michelson.Typed.Scope: data NotWellTyped
+ Morley.Michelson.Typed.Scope: getComparableProofS :: Sing (a :: T) -> Maybe (Dict (Comparable a))
+ Morley.Michelson.Typed.Scope: getWTP :: forall t. SingI t => Either NotWellTyped (Dict (WellTyped t))
+ Morley.Michelson.Typed.Scope: getWTP' :: Sing t -> Either NotWellTyped (Dict (WellTyped t))
+ Morley.Michelson.Typed.Scope: instance (Data.Singletons.Internal.SingI t, Morley.Michelson.Typed.Scope.WellTyped t, Morley.Michelson.Typed.Scope.HasNoOp t, Morley.Michelson.Typed.Scope.HasNoBigMap t, Morley.Michelson.Typed.Scope.HasNoContract t, Morley.Michelson.Typed.Scope.HasNoTicket t, Morley.Michelson.Typed.Scope.HasNoSaplingState t) => Morley.Michelson.Typed.Scope.ConstantScope t
+ Morley.Michelson.Typed.Scope: instance (Data.Singletons.Internal.SingI t, Morley.Michelson.Typed.Scope.WellTyped t, Morley.Michelson.Typed.Scope.HasNoOp t, Morley.Michelson.Typed.Scope.HasNoBigMap t, Morley.Michelson.Typed.Scope.HasNoTicket t, Morley.Michelson.Typed.Scope.HasNoSaplingState t) => Morley.Michelson.Typed.Scope.PackedValScope t
+ Morley.Michelson.Typed.Scope: instance (Data.Singletons.Internal.SingI t, Morley.Michelson.Typed.Scope.WellTyped t, Morley.Michelson.Typed.Scope.HasNoOp t, Morley.Michelson.Typed.Scope.HasNoNestedBigMaps t) => Morley.Michelson.Typed.Scope.ParameterScope t
+ Morley.Michelson.Typed.Scope: instance (Data.Singletons.Internal.SingI t, Morley.Michelson.Typed.Scope.WellTyped t, Morley.Michelson.Typed.Scope.HasNoOp t, Morley.Michelson.Typed.Scope.HasNoNestedBigMaps t, Morley.Michelson.Typed.Scope.HasNoContract t) => Morley.Michelson.Typed.Scope.StorageScope t
+ Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.ContainsSaplingState t GHC.Types.~ 'GHC.Types.False) => Morley.Michelson.Typed.Scope.HasNoSaplingState t
+ Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WellTyped t, Morley.Michelson.Typed.Scope.PackedValScope t, Morley.Michelson.Typed.Scope.ConstantScope t) => Morley.Michelson.Typed.Scope.UnpackedValScope t
+ Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoOp t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoBigMap t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoContract t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoTicket t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoSaplingState t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b, Morley.Michelson.Typed.Scope.WellTyped a, Morley.Michelson.Typed.Scope.WellTyped b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.ConstantScope t a b
+ Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoOp t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoBigMap t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoTicket t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoSaplingState t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b, Morley.Michelson.Typed.Scope.WellTyped a, Morley.Michelson.Typed.Scope.WellTyped b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.PackedValScope t a b
+ Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoOp t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoNestedBigMaps t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b, Morley.Michelson.Typed.Scope.WellTyped a, Morley.Michelson.Typed.Scope.WellTyped b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.ParameterScope t a b
+ Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoOp t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoNestedBigMaps t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.HasNoContract t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b, Morley.Michelson.Typed.Scope.WellTyped a, Morley.Michelson.Typed.Scope.WellTyped b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.StorageScope t a b
+ Morley.Michelson.Typed.Scope: instance (Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.PackedValScope t a b, Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.ConstantScope t a b, Data.Singletons.Internal.SingI a, Data.Singletons.Internal.SingI b, Morley.Michelson.Typed.Scope.WellTyped a, Morley.Michelson.Typed.Scope.WellTyped b) => Morley.Michelson.Typed.Scope.WithDeMorganScope Morley.Michelson.Typed.Scope.UnpackedValScope t a b
+ Morley.Michelson.Typed.Scope: instance Data.Singletons.Internal.SingI n => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TSaplingState n)
+ Morley.Michelson.Typed.Scope: instance Data.Singletons.Internal.SingI n => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TSaplingTransaction n)
+ Morley.Michelson.Typed.Scope: instance Data.Singletons.Internal.SingI t => Morley.Michelson.Typed.Scope.CheckScope (Morley.Michelson.Typed.Scope.ComparabilityScope t)
+ Morley.Michelson.Typed.Scope: instance Data.Singletons.Internal.SingI t => Morley.Michelson.Typed.Scope.CheckScope (Morley.Michelson.Typed.Scope.Comparable t)
+ Morley.Michelson.Typed.Scope: instance Data.Singletons.Internal.SingI t => Morley.Michelson.Typed.Scope.CheckScope (Morley.Michelson.Typed.Scope.HasNoSaplingState t)
+ Morley.Michelson.Typed.Scope: instance Data.Singletons.Internal.SingI t => Morley.Michelson.Typed.Scope.CheckScope (Morley.Michelson.Typed.Scope.WellTyped t)
+ Morley.Michelson.Typed.Scope: instance Formatting.Buildable.Buildable Morley.Michelson.Typed.Scope.NotWellTyped
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TAddress
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TBool
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TBytes
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TChainId
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TInt
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TKey
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TKeyHash
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TMutez
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TNat
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TNever
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TSignature
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TString
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TTimestamp
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.Comparable 'Morley.Michelson.Typed.T.TUnit
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.ComparableSuperC ('Morley.Michelson.Typed.T.TOption t) => Morley.Michelson.Typed.Scope.Comparable ('Morley.Michelson.Typed.T.TOption t)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.ComparableSuperC ('Morley.Michelson.Typed.T.TOr t1 t2) => Morley.Michelson.Typed.Scope.Comparable ('Morley.Michelson.Typed.T.TOr t1 t2)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.ComparableSuperC ('Morley.Michelson.Typed.T.TPair t1 t2) => Morley.Michelson.Typed.Scope.Comparable ('Morley.Michelson.Typed.T.TPair t1 t2)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TAddress
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TBls12381Fr
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TBls12381G1
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TBls12381G2
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TBool
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TBytes
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TChainId
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TChest
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TChestKey
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TInt
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TKey
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TKeyHash
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TMutez
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TNat
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TNever
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TOperation
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TSignature
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TString
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TTimestamp
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTyped 'Morley.Michelson.Typed.T.TUnit
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TBigMap k v) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TBigMap k v)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TContract t) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TContract t)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TLambda t1 t2) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TLambda t1 t2)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TList t) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TList t)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TMap k v) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TMap k v)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TOption t) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TOption t)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TOr t1 t2) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TOr t1 t2)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TPair t1 t2) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TPair t1 t2)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TSet t) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TSet t)
+ Morley.Michelson.Typed.Scope: instance Morley.Michelson.Typed.Scope.WellTypedSuperC ('Morley.Michelson.Typed.T.TTicket t) => Morley.Michelson.Typed.Scope.WellTyped ('Morley.Michelson.Typed.T.TTicket t)
+ Morley.Michelson.Typed.Scope: type ComparabilityScope t = (SingI t, Comparable t)
+ Morley.Michelson.Typed.Scope: type ComparableSuperC _ = ();
+ Morley.Michelson.Typed.Scope: type WellTypedSuperC _ = ();
+ Morley.Michelson.Typed.Scope: }
+ Morley.Michelson.Typed.Sing: [STSaplingState] :: forall (n_a22W3 :: Nat). () => Sing n_a22W3 -> SingT ('TSaplingState n_a22W3 :: T)
+ Morley.Michelson.Typed.Sing: [STSaplingTransaction] :: forall (n_a22W5 :: Nat). () => Sing n_a22W5 -> SingT ('TSaplingTransaction n_a22W5 :: T)
+ Morley.Michelson.Typed.Sing: instance (Data.Singletons.Decide.SDecide Morley.Michelson.Typed.T.T, Data.Singletons.Decide.SDecide Morley.Util.Peano.Peano) => Data.Singletons.Decide.SDecide Morley.Michelson.Typed.T.T
+ Morley.Michelson.Typed.Sing: instance (Data.Singletons.Decide.SDecide Morley.Michelson.Typed.T.T, Data.Singletons.Decide.SDecide Morley.Util.Peano.Peano) => Data.Type.Coercion.TestCoercion Morley.Michelson.Typed.Sing.SingT
+ Morley.Michelson.Typed.Sing: instance (Data.Singletons.Decide.SDecide Morley.Michelson.Typed.T.T, Data.Singletons.Decide.SDecide Morley.Util.Peano.Peano) => Data.Type.Equality.TestEquality Morley.Michelson.Typed.Sing.SingT
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.Internal.SingI Morley.Michelson.Typed.Sing.TSaplingStateSym0
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.Internal.SingI Morley.Michelson.Typed.Sing.TSaplingTransactionSym0
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.Internal.SingI n => Data.Singletons.Internal.SingI ('Morley.Michelson.Typed.T.TSaplingState n)
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.Internal.SingI n => Data.Singletons.Internal.SingI ('Morley.Michelson.Typed.T.TSaplingTransaction n)
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TBigMapSym1 a6989586621679497684)
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TLambdaSym1 a6989586621679497678)
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TMapSym1 a6989586621679497681)
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TOrSym1 a6989586621679497675)
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings (Morley.Michelson.Typed.Sing.TPairSym1 a6989586621679497672)
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings Morley.Michelson.Typed.Sing.TSaplingStateSym0
+ Morley.Michelson.Typed.Sing: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings Morley.Michelson.Typed.Sing.TSaplingTransactionSym0
+ Morley.Michelson.Typed.Sing: instance Morley.Util.Sing.SingI1 'Morley.Michelson.Typed.T.TOption
+ Morley.Michelson.Typed.T: TSaplingState :: Peano -> T
+ Morley.Michelson.Typed.T: TSaplingTransaction :: Peano -> T
+ Morley.Michelson.Typed.T: instance Formatting.Buildable.Buildable (Morley.Util.MismatchError.MismatchError Morley.Michelson.Typed.T.T)
+ Morley.Michelson.Typed.T: instance Formatting.Buildable.Buildable (Morley.Util.MismatchError.MismatchError [Morley.Michelson.Typed.T.T])
+ Morley.Michelson.Typed.T: instance Morley.Michelson.Printer.Util.RenderDoc (Morley.Michelson.Printer.Util.Prettier Morley.Michelson.Typed.T.T)
+ Morley.Michelson.Typed.T: instance Morley.Michelson.Printer.Util.RenderDoc (Morley.Util.MismatchError.MismatchError Morley.Michelson.Typed.T.T)
+ Morley.Michelson.Typed.T: instance Morley.Michelson.Printer.Util.RenderDoc (Morley.Util.MismatchError.MismatchError [Morley.Michelson.Typed.T.T])
+ Morley.Michelson.Typed.Util: [ceaPostStep] :: CtorEffectsApp m -> forall i o. Monad m => Instr i o -> m (Instr i o) -> m (Instr i o)
+ Morley.Michelson.Typed.Util: analyzeInstrFailure :: HasCallStack => Instr i o -> RemFail Instr i o
+ Morley.Michelson.Typed.Util: dfsTraverseInstr :: forall m inp out. Monad m => DfsSettings m -> (forall i o. Instr i o -> m (Instr i o)) -> Instr inp out -> m (Instr inp out)
+ Morley.Michelson.Typed.Util: instance Formatting.Buildable.Buildable (Morley.Michelson.Typed.Util.CtorEffectsApp x)
+ Morley.Michelson.Typed.Util: isMichelsonInstr :: Instr i o -> Bool
+ Morley.Michelson.Typed.Value: instance Morley.Michelson.Typed.Scope.Comparable t => GHC.Classes.Ord (Morley.Michelson.Typed.Value.Value' instr t)
+ Morley.Michelson.Untyped.Annotation: instance forall k (tag :: k). Data.Typeable.Internal.Typeable tag => GHC.Show.Show (Morley.Michelson.Untyped.Annotation.Annotation tag)
+ Morley.Michelson.Untyped.Contract: instance Formatting.Buildable.Buildable (Morley.Michelson.Untyped.Contract.ContractBlock op)
+ Morley.Michelson.Untyped.Instr: SAPLING_EMPTY_STATE :: VarAnn -> Natural -> InstrAbstract op
+ Morley.Michelson.Untyped.Instr: SAPLING_VERIFY_UPDATE :: VarAnn -> InstrAbstract op
+ Morley.Michelson.Untyped.Instr: SUB_MUTEZ :: VarAnn -> InstrAbstract op
+ Morley.Michelson.Untyped.Instr: instance GHC.Show.Show op => GHC.Show.Show (Morley.Michelson.Untyped.Instr.InstrAbstract op)
+ Morley.Michelson.Untyped.Type: TSaplingState :: Natural -> T
+ Morley.Michelson.Untyped.Type: TSaplingTransaction :: Natural -> T
+ Morley.Michelson.Untyped.Type: instance Formatting.Buildable.Buildable (Morley.Util.MismatchError.MismatchError Morley.Michelson.Untyped.Type.Ty)
+ Morley.Michelson.Untyped.Type: instance Morley.Michelson.Printer.Util.RenderDoc (Morley.Util.MismatchError.MismatchError Morley.Michelson.Untyped.Type.Ty)
+ Morley.Tezos.Core: tz :: QuasiQuoter
+ Morley.Tezos.Crypto: toTLTime :: (Integral a, CheckIntSubType a Word62) => a -> TLTime
+ Morley.Tezos.Crypto.Ed25519: randomSecretKey :: MonadRandom m => m SecretKey
+ Morley.Tezos.Crypto.Timelock: toTLTime :: (Integral a, CheckIntSubType a Word62) => a -> TLTime
+ Morley.Util.CustomGeneric: fromDepthsStrategy' :: (Int -> [Natural]) -> (Int -> [Natural]) -> GenericStrategy
+ Morley.Util.CustomGeneric: makeRightBalDepths :: Int -> [Natural]
+ Morley.Util.Interpolate.Internal: Polymorphic :: Transformation
+ Morley.Util.Interpolate.Internal: Trimming :: Transformation
+ Morley.Util.Interpolate.Internal: Unescaping :: Transformation
+ Morley.Util.Interpolate.Internal: Unindenting :: Transformation
+ Morley.Util.Interpolate.Internal: data Transformation
+ Morley.Util.Interpolate.Internal: generateName :: Transformations -> Name
+ Morley.Util.Interpolate.Internal: instance GHC.Classes.Eq Morley.Util.Interpolate.Internal.Transformation
+ Morley.Util.Interpolate.Internal: instance GHC.Classes.Ord Morley.Util.Interpolate.Internal.Transformation
+ Morley.Util.Interpolate.Internal: instance GHC.Enum.Bounded Morley.Util.Interpolate.Internal.Transformation
+ Morley.Util.Interpolate.Internal: instance GHC.Enum.Enum Morley.Util.Interpolate.Internal.Transformation
+ Morley.Util.Interpolate.Internal: mkQuoter :: Transformations -> QuasiQuoter
+ Morley.Util.Interpolate.Internal: transformationsPowerSet :: [Transformations]
+ Morley.Util.Interpolate.Internal: type Transformations = Set Transformation
+ Morley.Util.MismatchError: MkMismatchError :: a -> a -> MismatchError a
+ Morley.Util.MismatchError: [meActual] :: MismatchError a -> a
+ Morley.Util.MismatchError: [meExpected] :: MismatchError a -> a
+ Morley.Util.MismatchError: data MismatchError a
+ Morley.Util.MismatchError: instance Control.DeepSeq.NFData a => Control.DeepSeq.NFData (Morley.Util.MismatchError.MismatchError a)
+ Morley.Util.MismatchError: instance Data.Foldable.Foldable Morley.Util.MismatchError.MismatchError
+ Morley.Util.MismatchError: instance Formatting.Buildable.Buildable a => Formatting.Buildable.Buildable (Morley.Util.MismatchError.MismatchError a)
+ Morley.Util.MismatchError: instance GHC.Base.Functor Morley.Util.MismatchError.MismatchError
+ Morley.Util.MismatchError: instance GHC.Classes.Eq a => GHC.Classes.Eq (Morley.Util.MismatchError.MismatchError a)
+ Morley.Util.MismatchError: instance GHC.Generics.Generic (Morley.Util.MismatchError.MismatchError a)
+ Morley.Util.MismatchError: instance GHC.Show.Show a => GHC.Show.Show (Morley.Util.MismatchError.MismatchError a)
+ Morley.Util.MismatchError: instance Morley.Michelson.Printer.Util.RenderDoc a => Morley.Michelson.Printer.Util.RenderDoc (Morley.Util.MismatchError.MismatchError a)
+ Morley.Util.MismatchError: instance Universum.Container.Class.Container (Morley.Util.MismatchError.MismatchError a)
+ Morley.Util.MismatchError: renderDocDiff :: RenderDoc a => RenderContext -> MismatchError a -> Doc
+ Morley.Util.MismatchError: renderDocDiffList :: RenderDoc a => RenderContext -> MismatchError [a] -> Doc
+ Morley.Util.Named: arg :: forall (name :: Symbol) a. Name name -> (name :! a) -> a
+ Morley.Util.Named: argF :: forall (name :: Symbol) f a. Name name -> NamedF f a name -> f a
+ Morley.Util.Peano: (|-) :: forall k (a :: k) (b :: k) r. (a :~: b) -> (a ~ b => r) -> r
+ Morley.Util.Peano: additivity :: forall k m n. AddPeano k ('S m) ~ n => SingNat m -> SingNat n -> SingNat k -> (n > k) :~: 'True
+ Morley.Util.Peano: associativity :: SingNat x -> SingNat y -> AddPeano x ('S y) :~: 'S (AddPeano x y)
+ Morley.Util.Peano: commutativity :: SingNat x -> SingNat y -> AddPeano x y :~: AddPeano y x
+ Morley.Util.Peano: infixr 1 |-
+ Morley.Util.Peano: instance Control.DeepSeq.NFData Data.Vinyl.TypeLevel.Nat
+ Morley.Util.Peano: instance Data.Singletons.Decide.SDecide Data.Vinyl.TypeLevel.Nat => Data.Singletons.Decide.SDecide Data.Vinyl.TypeLevel.Nat
+ Morley.Util.Peano: instance Data.Singletons.Decide.SDecide Data.Vinyl.TypeLevel.Nat => Data.Type.Coercion.TestCoercion Morley.Util.Peano.SingNat
+ Morley.Util.Peano: instance Data.Singletons.Decide.SDecide Data.Vinyl.TypeLevel.Nat => Data.Type.Equality.TestEquality Morley.Util.Peano.SingNat
+ Morley.Util.Peano: instance Data.Singletons.Internal.SingI Morley.Util.Peano.SSym0
+ Morley.Util.Peano: instance Data.Singletons.Internal.SingKind Data.Vinyl.TypeLevel.Nat
+ Morley.Util.Peano: instance Data.Singletons.SuppressUnusedWarnings.SuppressUnusedWarnings Morley.Util.Peano.SSym0
+ Morley.Util.Peano: instance GHC.Classes.Eq Data.Vinyl.TypeLevel.Nat
+ Morley.Util.Peano: instance GHC.Generics.Generic Data.Vinyl.TypeLevel.Nat
+ Morley.Util.Peano: instance GHC.Show.Show Data.Vinyl.TypeLevel.Nat
+ Morley.Util.Peano: instance Language.Haskell.TH.Syntax.Lift (Morley.Util.Peano.SingNat n)
+ Morley.Util.Peano: minIdempotency :: SingNat n -> MinPeano n n :~: n
+ Morley.Util.Peano: pattern S :: () => !Nat -> Nat
+ Morley.Util.Peano: pattern Z :: () => Nat
+ Morley.Util.Peano: peanoSing' :: forall (n :: Nat). KnownNat n => SingNat (ToPeano n)
+ Morley.Util.Peano: peanoSingAdd :: SingNat n -> SingNat m -> SingNat (AddPeano n m)
+ Morley.Util.Peano: someSingNat :: Natural -> SomeSing Peano
+ Morley.Util.Peano: toNatural :: Peano -> Natural
+ Morley.Util.Peano: transitivity :: ((x >= y) ~ 'True, (y > z) ~ 'True) => SingNat x -> SingNat y -> SingNat z -> (x > z) :~: 'True
+ Morley.Util.Peano: type IsoNatPeano (n :: Nat) (p :: Peano) = (n ~ FromPeano p, ToPeano n ~ p)
+ Morley.Util.Peano: type SingIPeano (n :: Nat) = SingI (ToPeano n)
+ Morley.Util.Peano: withPeanoSingI :: forall (n :: Nat) r. KnownNat n => (SingIPeano n => r) -> r
+ Morley.Util.Peano: withSomePeano :: Natural -> (forall n. (KnownNat n, SingIPeano n) => Proxy n -> r) -> r
+ Morley.Util.PeanoNatural: eqPeanoNat :: PeanoNatural a -> PeanoNatural b -> Maybe (a :~: b)
+ Morley.Util.PeanoNatural: singPeanoNat :: PeanoNatural a -> SingNat a
+ Morley.Util.Sing: genSingletonsType :: OptionsMonad q => Name -> q [Dec]
+ Morley.Util.SizedList: [:<] :: a -> SizedList' n a -> SizedList' ('S n) a
+ Morley.Util.SizedList: [Nil] :: SizedList' 'Z a
+ Morley.Util.SizedList: [SomeSizedList] :: SingNat n -> SizedList' n a -> SomeSizedList a
+ Morley.Util.SizedList: append :: SizedList' n a -> SizedList' m a -> SizedList' (AddPeano n m) a
+ Morley.Util.SizedList: data SizedList' (n :: Peano) a
+ Morley.Util.SizedList: data SomeSizedList a
+ Morley.Util.SizedList: drop :: forall n n' m a. ((m >= ToPeano n) ~ 'True, SingIPeano n, IsoNatPeano n n') => SizedList' m a -> SizedList' (SubPeano m (ToPeano n)) a
+ Morley.Util.SizedList: fromList :: forall a. [a] -> SomeSizedList a
+ Morley.Util.SizedList: fromListMaybe :: forall n n' a. (SingIPeano n, IsoNatPeano n n') => [a] -> Maybe (SizedList n a)
+ Morley.Util.SizedList: fromListMaybe' :: SingNat m -> [a] -> Maybe (SizedList' m a)
+ Morley.Util.SizedList: generate :: forall n n' a. (SingIPeano n, IsoNatPeano n n') => (Natural -> a) -> SizedList n a
+ Morley.Util.SizedList: generate' :: forall n a. SingNat n -> (forall m. (n > m) ~ 'True => (SingNat m, Natural) -> a) -> SizedList' n a
+ Morley.Util.SizedList: head :: SizedList' ('S n) a -> a
+ Morley.Util.SizedList: index :: forall i m a. ((m > ToPeano i) ~ 'True, SingIPeano i) => SizedList' m a -> a
+ Morley.Util.SizedList: index' :: (m > n) ~ 'True => SingNat n -> SizedList' m a -> a
+ Morley.Util.SizedList: indexMaybe :: Natural -> SizedList' m a -> Maybe a
+ Morley.Util.SizedList: infixr 5 `append`
+ Morley.Util.SizedList: instance (n GHC.Types.~ 'Data.Vinyl.TypeLevel.S 'Data.Vinyl.TypeLevel.Z) => Universum.Container.Class.One (Morley.Util.SizedList.SizedList' n a)
+ Morley.Util.SizedList: instance Data.Foldable.Foldable (Morley.Util.SizedList.SizedList' n)
+ Morley.Util.SizedList: instance Data.Foldable.Foldable Morley.Util.SizedList.SomeSizedList
+ Morley.Util.SizedList: instance Data.Singletons.Internal.SingI n => GHC.Base.Applicative (Morley.Util.SizedList.SizedList' n)
+ Morley.Util.SizedList: instance Data.Singletons.Internal.SingI n => GHC.Base.Monad (Morley.Util.SizedList.SizedList' n)
+ Morley.Util.SizedList: instance Data.Traversable.Traversable (Morley.Util.SizedList.SizedList' n)
+ Morley.Util.SizedList: instance Data.Traversable.Traversable Morley.Util.SizedList.SomeSizedList
+ Morley.Util.SizedList: instance Formatting.Buildable.Buildable a => Formatting.Buildable.Buildable (Morley.Util.SizedList.SizedList' n a)
+ Morley.Util.SizedList: instance Formatting.Buildable.Buildable a => Formatting.Buildable.Buildable (Morley.Util.SizedList.SomeSizedList a)
+ Morley.Util.SizedList: instance GHC.Base.Functor (Morley.Util.SizedList.SizedList' n)
+ Morley.Util.SizedList: instance GHC.Base.Functor Morley.Util.SizedList.SomeSizedList
+ Morley.Util.SizedList: instance GHC.Base.Monoid (Morley.Util.SizedList.SomeSizedList a)
+ Morley.Util.SizedList: instance GHC.Base.Semigroup (Morley.Util.SizedList.SomeSizedList a)
+ Morley.Util.SizedList: instance GHC.Classes.Eq a => GHC.Classes.Eq (Morley.Util.SizedList.SizedList' n a)
+ Morley.Util.SizedList: instance GHC.Classes.Ord a => GHC.Classes.Ord (Morley.Util.SizedList.SizedList' n a)
+ Morley.Util.SizedList: instance GHC.Show.Show a => GHC.Show.Show (Morley.Util.SizedList.SizedList' n a)
+ Morley.Util.SizedList: instance GHC.Show.Show a => GHC.Show.Show (Morley.Util.SizedList.SomeSizedList a)
+ Morley.Util.SizedList: instance Universum.Container.Class.Container (Morley.Util.SizedList.SizedList' n a)
+ Morley.Util.SizedList: instance Universum.Container.Class.Container (Morley.Util.SizedList.SomeSizedList a)
+ Morley.Util.SizedList: length' :: forall n a. SingI n => SizedList' n a -> SingNat n
+ Morley.Util.SizedList: pattern (::<) :: a -> SizedList' n a -> SizedList' ('S n) a
+ Morley.Util.SizedList: pattern Nil' :: SizedList' 'Z a
+ Morley.Util.SizedList: replicate :: Natural -> a -> SomeSizedList a
+ Morley.Util.SizedList: replicate' :: SingNat n -> a -> SizedList' n a
+ Morley.Util.SizedList: replicateT :: forall n n' a. (SingIPeano n, IsoNatPeano n n') => a -> SizedList n a
+ Morley.Util.SizedList: reverse :: forall n a. SingI n => SizedList' n a -> SizedList' n a
+ Morley.Util.SizedList: singleton :: a -> SizedList 1 a
+ Morley.Util.SizedList: splitAt :: forall n n' m a. ((m >= ToPeano n) ~ 'True, SingIPeano n, IsoNatPeano n n') => SizedList' m a -> (SizedList n a, SizedList' (SubPeano m n') a)
+ Morley.Util.SizedList: tail :: SizedList' ('S n) a -> SizedList' n a
+ Morley.Util.SizedList: take :: forall n n' m a. ((m >= ToPeano n) ~ 'True, SingIPeano n, IsoNatPeano n n') => SizedList' m a -> SizedList n a
+ Morley.Util.SizedList: toNonEmpty :: SizedList' ('S n) a -> NonEmpty a
+ Morley.Util.SizedList: type IsoNatPeano (n :: Nat) (p :: Peano) = (n ~ FromPeano p, ToPeano n ~ p)
+ Morley.Util.SizedList: type SingIPeano (n :: Nat) = SingI (ToPeano n)
+ Morley.Util.SizedList: type SizedList (n :: Nat) a = SizedList' (ToPeano n) a
+ Morley.Util.SizedList: unsafeFromList :: forall n n' a. (SingIPeano n, IsoNatPeano n n', HasCallStack) => [a] -> SizedList n a
+ Morley.Util.SizedList: unzip :: SizedList' n (b, c) -> (SizedList' n b, SizedList' n c)
+ Morley.Util.SizedList: unzipWith :: (a -> (b, c)) -> SizedList' n a -> (SizedList' n b, SizedList' n c)
+ Morley.Util.SizedList: withList :: forall a r. [a] -> (forall n. SingNat n -> SizedList' n a -> r) -> r
+ Morley.Util.SizedList: withNonEmpty :: forall a r. NonEmpty a -> (forall n. SingNat ('S n) -> SizedList' ('S n) a -> r) -> r
+ Morley.Util.SizedList: zip :: SizedList' n a -> SizedList' m b -> SizedList' (MinPeano n m) (a, b)
+ Morley.Util.SizedList: zipWith :: (a -> b -> c) -> SizedList' n a -> SizedList' m b -> SizedList' (MinPeano n m) c
+ Morley.Util.SizedList.Types: [:<] :: a -> SizedList' n a -> SizedList' ('S n) a
+ Morley.Util.SizedList.Types: [Nil] :: SizedList' 'Z a
+ Morley.Util.SizedList.Types: [SomeSizedList] :: SingNat n -> SizedList' n a -> SomeSizedList a
+ Morley.Util.SizedList.Types: data SizedList' (n :: Peano) a
+ Morley.Util.SizedList.Types: data SomeSizedList a
+ Morley.Util.SizedList.Types: infixr 5 ::<
+ Morley.Util.SizedList.Types: pattern (::<) :: a -> SizedList' n a -> SizedList' ('S n) a
+ Morley.Util.SizedList.Types: pattern Nil' :: SizedList' 'Z a
+ Morley.Util.SizedList.Types: type IsoNatPeano (n :: Nat) (p :: Peano) = (n ~ FromPeano p, ToPeano n ~ p)
+ Morley.Util.SizedList.Types: type SingIPeano (n :: Nat) = SingI (ToPeano n)
+ Morley.Util.SizedList.Types: type SizedList (n :: Nat) a = SizedList' (ToPeano n) a
+ Morley.Util.TH: addTypeVariables :: Name -> Q Type
+ Morley.Util.Type: knownListFromSingI :: forall xs. SingI xs => Dict (KnownList xs)
- Morley.Michelson.ErrorPos: mkPos :: Int -> Maybe Pos
+ Morley.Michelson.ErrorPos: mkPos :: Int -> Either Text Pos
- Morley.Michelson.FailPattern: modifyTypicalFailWith :: HasCallStack => (MText -> SomeConstrainedValue ConstantScope) -> Instr inp out -> Instr inp out
+ Morley.Michelson.FailPattern: modifyTypicalFailWith :: HasCallStack => (MText -> SomeConstant) -> Instr inp out -> Instr inp out
- Morley.Michelson.Interpret: [MichelsonArithError] :: (Typeable n, Typeable m, Typeable instr) => ArithError (Value' instr n) (Value' instr m) -> MichelsonFailed
+ Morley.Michelson.Interpret: [MichelsonArithError] :: (Typeable n, Typeable m) => ArithError (Value n) (Value m) -> MichelsonFailed
- Morley.Michelson.Interpret: assignBigMapIds :: MonadState BigMapCounter m => Value t -> m (Value t)
+ Morley.Michelson.Interpret: assignBigMapIds :: MonadState BigMapCounter m => Bool -> Value t -> m (Value t)
- Morley.Michelson.Parser: bytesLiteral :: Parser (Value' op)
+ Morley.Michelson.Parser: bytesLiteral :: Parser le (Value' op)
- Morley.Michelson.Parser: codeEntry :: Parser [ParsedOp]
+ Morley.Michelson.Parser: codeEntry :: Parser le [ParsedOp]
- Morley.Michelson.Parser: intLiteral :: Parser (Value' op)
+ Morley.Michelson.Parser: intLiteral :: Parser le (Value' op)
- Morley.Michelson.Parser: letInner :: Parser ParsedOp -> Parser LetEnv
+ Morley.Michelson.Parser: letInner :: Parser' LetEnv ParsedOp -> Parser' LetEnv LetEnv
- Morley.Michelson.Parser: letType :: Parser LetType
+ Morley.Michelson.Parser: letType :: Parser' LetEnv LetType
- Morley.Michelson.Parser: ops :: Parser [ParsedOp]
+ Morley.Michelson.Parser: ops :: Parser le [ParsedOp]
- Morley.Michelson.Parser: parseNoEnv :: Parser a -> MichelsonSource -> Text -> Either (ParseErrorBundle Text CustomParserException) a
+ Morley.Michelson.Parser: parseNoEnv :: Default le => Parser' le a -> MichelsonSource -> Text -> Either (ParseErrorBundle Text CustomParserException) a
- Morley.Michelson.Parser: parsedOp :: Parser ParsedOp
+ Morley.Michelson.Parser: parsedOp :: Parser le ParsedOp
- Morley.Michelson.Parser: printComment :: Parser PrintComment
+ Morley.Michelson.Parser: printComment :: Parser' LetEnv PrintComment
- Morley.Michelson.Parser: stringLiteral :: Parser ParsedValue
+ Morley.Michelson.Parser: stringLiteral :: forall le. Parser le ParsedValue
- Morley.Michelson.Parser: type_ :: Parser Ty
+ Morley.Michelson.Parser: type_ :: Parser le Ty
- Morley.Michelson.Parser: value :: Parser ParsedValue
+ Morley.Michelson.Parser: value :: Parser le ParsedValue
- Morley.Michelson.Parser.Annotations: fieldType :: Default a => Parser a -> Parser (a, TypeAnn)
+ Morley.Michelson.Parser.Annotations: fieldType :: Default a => Parser le a -> Parser le (a, TypeAnn)
- Morley.Michelson.Parser.Annotations: note :: forall tag. KnownAnnTag tag => Parser (Annotation tag)
+ Morley.Michelson.Parser.Annotations: note :: forall tag le. KnownAnnTag tag => Parser le (Annotation tag)
- Morley.Michelson.Parser.Annotations: noteDef :: KnownAnnTag tag => Parser (Annotation tag)
+ Morley.Michelson.Parser.Annotations: noteDef :: KnownAnnTag tag => Parser le (Annotation tag)
- Morley.Michelson.Parser.Annotations: noteF :: Parser FieldAnn
+ Morley.Michelson.Parser.Annotations: noteF :: Parser le FieldAnn
- Morley.Michelson.Parser.Annotations: noteV :: Parser VarAnn
+ Morley.Michelson.Parser.Annotations: noteV :: Parser le VarAnn
- Morley.Michelson.Parser.Annotations: noteV2Def :: Parser (VarAnn, VarAnn)
+ Morley.Michelson.Parser.Annotations: noteV2Def :: Parser le (VarAnn, VarAnn)
- Morley.Michelson.Parser.Annotations: notesTF :: Parser (TypeAnn, FieldAnn)
+ Morley.Michelson.Parser.Annotations: notesTF :: Parser le (TypeAnn, FieldAnn)
- Morley.Michelson.Parser.Annotations: notesTV :: Parser (TypeAnn, VarAnn)
+ Morley.Michelson.Parser.Annotations: notesTV :: Parser le (TypeAnn, VarAnn)
- Morley.Michelson.Parser.Annotations: notesTVF :: Parser (TypeAnn, VarAnn, FieldAnn)
+ Morley.Michelson.Parser.Annotations: notesTVF :: Parser le (TypeAnn, VarAnn, FieldAnn)
- Morley.Michelson.Parser.Annotations: notesTVF2Def :: Parser (TypeAnn, VarAnn, (FieldAnn, FieldAnn))
+ Morley.Michelson.Parser.Annotations: notesTVF2Def :: Parser le (TypeAnn, VarAnn, (FieldAnn, FieldAnn))
- Morley.Michelson.Parser.Annotations: notesVF :: Parser (VarAnn, FieldAnn)
+ Morley.Michelson.Parser.Annotations: notesVF :: Parser le (VarAnn, FieldAnn)
- Morley.Michelson.Parser.Annotations: notesVVFF :: Parser ((VarAnn, VarAnn), (FieldAnn, FieldAnn))
+ Morley.Michelson.Parser.Annotations: notesVVFF :: Parser le ((VarAnn, VarAnn), (FieldAnn, FieldAnn))
- Morley.Michelson.Parser.Common: viewName_ :: Parser ViewName
+ Morley.Michelson.Parser.Common: viewName_ :: Parser le ViewName
- Morley.Michelson.Parser.Ext: extInstr :: Parser [ParsedOp] -> Parser ParsedUExtInstr
+ Morley.Michelson.Parser.Ext: extInstr :: Parser' LetEnv [ParsedOp] -> Parser' LetEnv ParsedUExtInstr
- Morley.Michelson.Parser.Ext: printComment :: Parser PrintComment
+ Morley.Michelson.Parser.Ext: printComment :: Parser' LetEnv PrintComment
- Morley.Michelson.Parser.Ext: stackType :: Parser StackTypePattern
+ Morley.Michelson.Parser.Ext: stackType :: Parser' LetEnv StackTypePattern
- Morley.Michelson.Parser.Helpers: mkParser :: (a -> Text) -> a -> Parser a
+ Morley.Michelson.Parser.Helpers: mkParser :: (a -> Text) -> a -> Parser le a
- Morley.Michelson.Parser.Helpers: parseDef :: Default a => Parser a -> Parser a
+ Morley.Michelson.Parser.Helpers: parseDef :: Default a => Parser le a -> Parser le a
- Morley.Michelson.Parser.Helpers: positive :: Parser Positive
+ Morley.Michelson.Parser.Helpers: positive :: Parser le Positive
- Morley.Michelson.Parser.Instr: carOp :: Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: carOp :: Parser le ParsedInstr
- Morley.Michelson.Parser.Instr: cdrOp :: Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: cdrOp :: Parser le ParsedInstr
- Morley.Michelson.Parser.Instr: cmpOp :: Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: cmpOp :: Parser le ParsedInstr
- Morley.Michelson.Parser.Instr: dupOp :: Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: dupOp :: Parser le ParsedInstr
- Morley.Michelson.Parser.Instr: mapOp :: Parser ParsedOp -> Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: mapOp :: Parser' le ParsedOp -> Parser le ParsedInstr
- Morley.Michelson.Parser.Instr: ops' :: Parser ParsedOp -> Parser [ParsedOp]
+ Morley.Michelson.Parser.Instr: ops' :: Parser' le ParsedOp -> Parser le [ParsedOp]
- Morley.Michelson.Parser.Instr: pairNOp :: Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: pairNOp :: Parser le ParsedInstr
- Morley.Michelson.Parser.Instr: pairOp :: Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: pairOp :: Parser le ParsedInstr
- Morley.Michelson.Parser.Instr: primInstr :: Parser (Contract' ParsedOp) -> Parser ParsedOp -> Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: primInstr :: Parser' le (Contract' ParsedOp) -> Parser' le ParsedOp -> Parser le ParsedInstr
- Morley.Michelson.Parser.Instr: unpairOp :: Parser ParsedInstr
+ Morley.Michelson.Parser.Instr: unpairOp :: Parser le ParsedInstr
- Morley.Michelson.Parser.Let: letBlock :: Parser ParsedOp -> Parser LetEnv
+ Morley.Michelson.Parser.Let: letBlock :: forall le. Parser' le ParsedOp -> Parser le le
- Morley.Michelson.Parser.Let: letInner :: Parser ParsedOp -> Parser LetEnv
+ Morley.Michelson.Parser.Let: letInner :: Parser' LetEnv ParsedOp -> Parser' LetEnv LetEnv
- Morley.Michelson.Parser.Let: letType :: Parser LetType
+ Morley.Michelson.Parser.Let: letType :: Parser' LetEnv LetType
- Morley.Michelson.Parser.Let: mkLetMac :: Map Text LetMacro -> Parser LetMacro
+ Morley.Michelson.Parser.Let: mkLetMac :: Map Text LetMacro -> Parser' LetEnv LetMacro
- Morley.Michelson.Parser.Lexer: braces :: Parser a -> Parser a
+ Morley.Michelson.Parser.Lexer: braces :: Parser le a -> Parser le a
- Morley.Michelson.Parser.Lexer: brackets :: Parser a -> Parser a
+ Morley.Michelson.Parser.Lexer: brackets :: Parser le a -> Parser le a
- Morley.Michelson.Parser.Lexer: brackets' :: Parser a -> Parser a
+ Morley.Michelson.Parser.Lexer: brackets' :: Parser le a -> Parser le a
- Morley.Michelson.Parser.Lexer: comma :: Parser ()
+ Morley.Michelson.Parser.Lexer: comma :: Parser le ()
- Morley.Michelson.Parser.Lexer: lexeme :: Parser a -> Parser a
+ Morley.Michelson.Parser.Lexer: lexeme :: Parser le a -> Parser le a
- Morley.Michelson.Parser.Lexer: mSpace :: Parser ()
+ Morley.Michelson.Parser.Lexer: mSpace :: Parser le ()
- Morley.Michelson.Parser.Lexer: parens :: Parser a -> Parser a
+ Morley.Michelson.Parser.Lexer: parens :: Parser le a -> Parser le a
- Morley.Michelson.Parser.Lexer: semicolon :: Parser ()
+ Morley.Michelson.Parser.Lexer: semicolon :: Parser le ()
- Morley.Michelson.Parser.Lexer: string' :: (MonadParsec e s f, Tokens s ~ Text) => Text -> f Text
+ Morley.Michelson.Parser.Lexer: string' :: Text -> Parser le Text
- Morley.Michelson.Parser.Lexer: symbol :: Tokens Text -> Parser ()
+ Morley.Michelson.Parser.Lexer: symbol :: Tokens Text -> Parser le ()
- Morley.Michelson.Parser.Lexer: symbol' :: Text -> Parser ()
+ Morley.Michelson.Parser.Lexer: symbol' :: Text -> Parser le ()
- Morley.Michelson.Parser.Lexer: varID :: Parser Var
+ Morley.Michelson.Parser.Lexer: varID :: Parser le Var
- Morley.Michelson.Parser.Lexer: word :: Tokens Text -> a -> Parser a
+ Morley.Michelson.Parser.Lexer: word :: Tokens Text -> a -> Parser le a
- Morley.Michelson.Parser.Lexer: word' :: Tokens Text -> a -> Parser a
+ Morley.Michelson.Parser.Lexer: word' :: Tokens Text -> a -> Parser le a
- Morley.Michelson.Parser.Macro: cadrMac :: Parser Macro
+ Morley.Michelson.Parser.Macro: cadrMac :: Parser le Macro
- Morley.Michelson.Parser.Macro: carnMac :: Parser Macro
+ Morley.Michelson.Parser.Macro: carnMac :: Parser le Macro
- Morley.Michelson.Parser.Macro: cdrnMac :: Parser Macro
+ Morley.Michelson.Parser.Macro: cdrnMac :: Parser le Macro
- Morley.Michelson.Parser.Macro: duupMac :: Parser Macro
+ Morley.Michelson.Parser.Macro: duupMac :: Parser le Macro
- Morley.Michelson.Parser.Macro: ifCmpMac :: Parser ParsedOp -> Parser Macro
+ Morley.Michelson.Parser.Macro: ifCmpMac :: Parser le ParsedOp -> Parser le Macro
- Morley.Michelson.Parser.Macro: macro :: Parser ParsedOp -> Parser Macro
+ Morley.Michelson.Parser.Macro: macro :: Parser' le ParsedOp -> Parser le Macro
- Morley.Michelson.Parser.Macro: mapCadrMac :: Parser ParsedOp -> Parser Macro
+ Morley.Michelson.Parser.Macro: mapCadrMac :: Parser le ParsedOp -> Parser le Macro
- Morley.Michelson.Parser.Macro: pairMac :: Parser Macro
+ Morley.Michelson.Parser.Macro: pairMac :: Parser le Macro
- Morley.Michelson.Parser.Type: field :: Parser (FieldAnn, Ty)
+ Morley.Michelson.Parser.Type: field :: Parser le (FieldAnn, Ty)
- Morley.Michelson.Parser.Type: type_ :: Parser Ty
+ Morley.Michelson.Parser.Type: type_ :: Parser le Ty
- Morley.Michelson.Parser.Value: bytesLiteral :: Parser (Value' op)
+ Morley.Michelson.Parser.Value: bytesLiteral :: Parser le (Value' op)
- Morley.Michelson.Parser.Value: intLiteral :: Parser (Value' op)
+ Morley.Michelson.Parser.Value: intLiteral :: Parser le (Value' op)
- Morley.Michelson.Parser.Value: mkLetVal :: Map Text LetValue -> Parser LetValue
+ Morley.Michelson.Parser.Value: mkLetVal :: Map Text LetValue -> Parser le LetValue
- Morley.Michelson.Parser.Value: stringLiteral :: Parser ParsedValue
+ Morley.Michelson.Parser.Value: stringLiteral :: forall le. Parser le ParsedValue
- Morley.Michelson.Parser.Value: value' :: Parser ParsedOp -> Parser ParsedValue
+ Morley.Michelson.Parser.Value: value' :: Parser le ParsedOp -> Parser le ParsedValue
- Morley.Michelson.Runtime: EEUnexpectedParameterType :: a -> T -> T -> ExecutorError' a
+ Morley.Michelson.Runtime: EEUnexpectedParameterType :: a -> MismatchError T -> ExecutorError' a
- Morley.Michelson.Runtime: executeTransfer :: ("isGlobalOp" :! Bool) -> TypeCheckOptions -> TransferOperation -> ExecutorM [ExecutorOp]
+ Morley.Michelson.Runtime: executeTransfer :: ("isGlobalOp" :! Bool) -> Maybe Mutez -> TypeCheckOptions -> TransferOperation -> ExecutorM [ExecutorOp]
- Morley.Michelson.Runtime.GState: genesisAddresses :: NonEmpty Address
+ Morley.Michelson.Runtime.GState: genesisAddresses :: GenesisList Address
- Morley.Michelson.Runtime.GState: genesisKeyHashes :: NonEmpty KeyHash
+ Morley.Michelson.Runtime.GState: genesisKeyHashes :: GenesisList KeyHash
- Morley.Michelson.Runtime.GState: genesisSecrets :: NonEmpty SecretKey
+ Morley.Michelson.Runtime.GState: genesisSecrets :: GenesisList SecretKey
- Morley.Michelson.TypeCheck.Error: StackEqError :: [T] -> [T] -> TCTypeError
+ Morley.Michelson.TypeCheck.Error: StackEqError :: MismatchError [T] -> TCTypeError
- Morley.Michelson.TypeCheck.Error: TypeEqError :: T -> T -> TCTypeError
+ Morley.Michelson.TypeCheck.Error: TypeEqError :: MismatchError T -> TCTypeError
- Morley.Michelson.TypeCheck.Error: UnexpectedTopLevelType :: TopLevelType -> ("expected" :! T) -> ("got" :! T) -> TCTypeError
+ Morley.Michelson.TypeCheck.Error: UnexpectedTopLevelType :: TopLevelType -> MismatchError T -> TCTypeError
- Morley.Michelson.TypeCheck.Helpers: ensureDistinctAsc :: (Ord b, Show a) => (a -> b) -> [a] -> Either Text [a]
+ Morley.Michelson.TypeCheck.Helpers: ensureDistinctAsc :: (Ord b, Buildable a) => (a -> b) -> [a] -> Either Text [a]
- Morley.Michelson.TypeCheck.TypeCheck: SomeParamType :: Sing t -> ParamNotes t -> SomeParamType
+ Morley.Michelson.TypeCheck.TypeCheck: SomeParamType :: ParamNotes t -> SomeParamType
- Morley.Michelson.Typed: CtorEffectsApp :: Text -> (forall i o. Semigroup x => x -> x -> Instr i o -> (Instr i o, x)) -> CtorEffectsApp x
+ Morley.Michelson.Typed: CtorEffectsApp :: Text -> (forall i o. Monad m => Instr i o -> m (Instr i o) -> m (Instr i o)) -> CtorEffectsApp m
- Morley.Michelson.Typed: DfsSettings :: Bool -> CtorEffectsApp x -> DfsSettings x
+ Morley.Michelson.Typed: DfsSettings :: Bool -> CtorEffectsApp m -> DfsSettings m
- Morley.Michelson.Typed: [STBigMap] :: forall (n_a1CB6 :: T) (n_a1CB7 :: T). () => Sing n_a1CB6 -> Sing n_a1CB7 -> SingT ('TBigMap n_a1CB6 n_a1CB7 :: T)
+ Morley.Michelson.Typed: [STBigMap] :: forall (n_a22VZ :: T) (n_a22W0 :: T). () => Sing n_a22VZ -> Sing n_a22W0 -> SingT ('TBigMap n_a22VZ n_a22W0 :: T)
- Morley.Michelson.Typed: [STContract] :: forall (n_a1CAM :: T). () => Sing n_a1CAM -> SingT ('TContract n_a1CAM :: T)
+ Morley.Michelson.Typed: [STContract] :: forall (n_a22VF :: T). () => Sing n_a22VF -> SingT ('TContract n_a22VF :: T)
- Morley.Michelson.Typed: [STLambda] :: forall (n_a1CAY :: T) (n_a1CAZ :: T). () => Sing n_a1CAY -> Sing n_a1CAZ -> SingT ('TLambda n_a1CAY n_a1CAZ :: T)
+ Morley.Michelson.Typed: [STLambda] :: forall (n_a22VR :: T) (n_a22VS :: T). () => Sing n_a22VR -> Sing n_a22VS -> SingT ('TLambda n_a22VR n_a22VS :: T)
- Morley.Michelson.Typed: [STList] :: forall (n_a1CAI :: T). () => Sing n_a1CAI -> SingT ('TList n_a1CAI :: T)
+ Morley.Michelson.Typed: [STList] :: forall (n_a22VB :: T). () => Sing n_a22VB -> SingT ('TList n_a22VB :: T)
- Morley.Michelson.Typed: [STMap] :: forall (n_a1CB2 :: T) (n_a1CB3 :: T). () => Sing n_a1CB2 -> Sing n_a1CB3 -> SingT ('TMap n_a1CB2 n_a1CB3 :: T)
+ Morley.Michelson.Typed: [STMap] :: forall (n_a22VV :: T) (n_a22VW :: T). () => Sing n_a22VV -> Sing n_a22VW -> SingT ('TMap n_a22VV n_a22VW :: T)
- Morley.Michelson.Typed: [STOption] :: forall (n_a1CAG :: T). () => Sing n_a1CAG -> SingT ('TOption n_a1CAG :: T)
+ Morley.Michelson.Typed: [STOption] :: forall (n_a22Vz :: T). () => Sing n_a22Vz -> SingT ('TOption n_a22Vz :: T)
- Morley.Michelson.Typed: [STOr] :: forall (n_a1CAU :: T) (n_a1CAV :: T). () => Sing n_a1CAU -> Sing n_a1CAV -> SingT ('TOr n_a1CAU n_a1CAV :: T)
+ Morley.Michelson.Typed: [STOr] :: forall (n_a22VN :: T) (n_a22VO :: T). () => Sing n_a22VN -> Sing n_a22VO -> SingT ('TOr n_a22VN n_a22VO :: T)
- Morley.Michelson.Typed: [STPair] :: forall (n_a1CAQ :: T) (n_a1CAR :: T). () => Sing n_a1CAQ -> Sing n_a1CAR -> SingT ('TPair n_a1CAQ n_a1CAR :: T)
+ Morley.Michelson.Typed: [STPair] :: forall (n_a22VJ :: T) (n_a22VK :: T). () => Sing n_a22VJ -> Sing n_a22VK -> SingT ('TPair n_a22VJ n_a22VK :: T)
- Morley.Michelson.Typed: [STSet] :: forall (n_a1CAK :: T). () => Sing n_a1CAK -> SingT ('TSet n_a1CAK :: T)
+ Morley.Michelson.Typed: [STSet] :: forall (n_a22VD :: T). () => Sing n_a22VD -> SingT ('TSet n_a22VD :: T)
- Morley.Michelson.Typed: [STTicket] :: forall (n_a1CAO :: T). () => Sing n_a1CAO -> SingT ('TTicket n_a1CAO :: T)
+ Morley.Michelson.Typed: [STTicket] :: forall (n_a22VH :: T). () => Sing n_a22VH -> SingT ('TTicket n_a22VH :: T)
- Morley.Michelson.Typed: [SomeConstrainedValue] :: forall (t :: T) (c :: T -> Constraint). c t => Value t -> SomeConstrainedValue c
+ Morley.Michelson.Typed: [SomeConstrainedValue] :: forall t c. c t => Value t -> SomeConstrainedValue c
- Morley.Michelson.Typed: [ceaName] :: CtorEffectsApp x -> Text
+ Morley.Michelson.Typed: [ceaName] :: CtorEffectsApp m -> Text
- Morley.Michelson.Typed: [dsCtorEffectsApp] :: DfsSettings x -> CtorEffectsApp x
+ Morley.Michelson.Typed: [dsCtorEffectsApp] :: DfsSettings m -> CtorEffectsApp m
- Morley.Michelson.Typed: [dsGoToValues] :: DfsSettings x -> Bool
+ Morley.Michelson.Typed: [dsGoToValues] :: DfsSettings m -> Bool
- Morley.Michelson.Typed: castM :: forall (a :: T) (b :: T) t m. (SingI a, SingI b, Monad m) => t a -> (forall x. Demote (KindOf a) -> Demote (KindOf b) -> m x) -> m (t b)
+ Morley.Michelson.Typed: castM :: forall (a :: T) (b :: T) t m. (SingI a, SingI b, Monad m) => t a -> (forall x. MismatchError T -> m x) -> m (t b)
- Morley.Michelson.Typed: class (IsComparable t ~ 'True) => Comparable t
+ Morley.Michelson.Typed: class (IsComparable t ~ 'True, SingI t, ComparableSuperC t) => Comparable t where {
- Morley.Michelson.Typed: class (SingI t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t) => ConstantScope t
+ Morley.Michelson.Typed: class (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t, HasNoSaplingState t) => ConstantScope t
- Morley.Michelson.Typed: class (SingI t, HasNoOp t, HasNoBigMap t, HasNoTicket t) => PackedValScope t
+ Morley.Michelson.Typed: class (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoTicket t, HasNoSaplingState t) => PackedValScope t
- Morley.Michelson.Typed: class (SingI t, HasNoOp t, HasNoNestedBigMaps t) => ParameterScope t
+ Morley.Michelson.Typed: class (SingI t, WellTyped t, HasNoOp t, HasNoNestedBigMaps t) => ParameterScope t
- Morley.Michelson.Typed: class (SingI t, HasNoOp t, HasNoNestedBigMaps t, HasNoContract t) => StorageScope t
+ Morley.Michelson.Typed: class (SingI t, WellTyped t, HasNoOp t, HasNoNestedBigMaps t, HasNoContract t) => StorageScope t
- Morley.Michelson.Typed: class (PackedValScope t, ConstantScope t) => UnpackedValScope t
+ Morley.Michelson.Typed: class (WellTyped t, PackedValScope t, ConstantScope t) => UnpackedValScope t
- Morley.Michelson.Typed: class (SingI t, WellTypedSuperC t) => WellTyped (t :: T)
+ Morley.Michelson.Typed: class (SingI t, WellTypedSuperC t) => WellTyped (t :: T) where {
- Morley.Michelson.Typed: convertParamNotes :: SingI cp => ParamNotes cp -> ParameterType
+ Morley.Michelson.Typed: convertParamNotes :: ParamNotes cp -> ParameterType
- Morley.Michelson.Typed: crDescriptionL :: forall a_a6Pns. Lens' (ConstructorRep a_a6Pns) (Maybe Text)
+ Morley.Michelson.Typed: crDescriptionL :: forall a_a7szG. Lens' (ConstructorRep a_a7szG) (Maybe Text)
- Morley.Michelson.Typed: crFieldsL :: forall a_a6Pns a_a6PoE. Lens (ConstructorRep a_a6Pns) (ConstructorRep a_a6PoE) [FieldRep a_a6Pns] [FieldRep a_a6PoE]
+ Morley.Michelson.Typed: crFieldsL :: forall a_a7szG a_a7sAS. Lens (ConstructorRep a_a7szG) (ConstructorRep a_a7sAS) [FieldRep a_a7szG] [FieldRep a_a7sAS]
- Morley.Michelson.Typed: crNameL :: forall a_a6Pns. Lens' (ConstructorRep a_a6Pns) Text
+ Morley.Michelson.Typed: crNameL :: forall a_a7szG. Lens' (ConstructorRep a_a7szG) Text
- Morley.Michelson.Typed: data CtorEffectsApp x
+ Morley.Michelson.Typed: data CtorEffectsApp m
- Morley.Michelson.Typed: data DfsSettings x
+ Morley.Michelson.Typed: data DfsSettings m
- Morley.Michelson.Typed: data SingT z_a1CBV
+ Morley.Michelson.Typed: data SingT z_a22WY
- Morley.Michelson.Typed: dfsFoldInstr :: forall x inp out. Semigroup x => DfsSettings x -> (forall i o. Instr i o -> x) -> Instr inp out -> x
+ Morley.Michelson.Typed: dfsFoldInstr :: forall x inp out. Monoid x => DfsSettings (Writer x) -> (forall i o. Instr i o -> x) -> Instr inp out -> x
- Morley.Michelson.Typed: dfsInstr :: forall x inp out. Semigroup x => DfsSettings x -> (forall i o. Instr i o -> (Instr i o, x)) -> Instr inp out -> (Instr inp out, x)
+ Morley.Michelson.Typed: dfsInstr :: forall x inp out. Monoid x => DfsSettings (Writer x) -> (forall i o. Instr i o -> (Instr i o, x)) -> Instr inp out -> (Instr inp out, x)
- Morley.Michelson.Typed: dfsModifyInstr :: DfsSettings () -> (forall i o. Instr i o -> Instr i o) -> Instr inp out -> Instr inp out
+ Morley.Michelson.Typed: dfsModifyInstr :: DfsSettings Identity -> (forall i o. Instr i o -> Instr i o) -> Instr inp out -> Instr inp out
- Morley.Michelson.Typed: flattenEntrypoints :: SingI t => ParamNotes t -> Map EpName Ty
+ Morley.Michelson.Typed: flattenEntrypoints :: ParamNotes t -> Map EpName Ty
- Morley.Michelson.Typed: frDescriptionL :: forall a_a6Pnr. Lens' (FieldRep a_a6Pnr) (Maybe Text)
+ Morley.Michelson.Typed: frDescriptionL :: forall a_a7szF. Lens' (FieldRep a_a7szF) (Maybe Text)
- Morley.Michelson.Typed: frNameL :: forall a_a6Pnr. Lens' (FieldRep a_a6Pnr) (Maybe Text)
+ Morley.Michelson.Typed: frNameL :: forall a_a7szF. Lens' (FieldRep a_a7szF) (Maybe Text)
- Morley.Michelson.Typed: frTypeRepL :: forall a_a6Pnr a_a6Pqm. Lens (FieldRep a_a6Pnr) (FieldRep a_a6Pqm) a_a6Pnr a_a6Pqm
+ Morley.Michelson.Typed: frTypeRepL :: forall a_a7szF a_a7sCA. Lens (FieldRep a_a7szF) (FieldRep a_a7sCA) a_a7szF a_a7sCA
- Morley.Michelson.Typed: mkStackRef :: forall (gn :: Nat) st n. (n ~ ToPeano gn, SingI (ToPeano gn), RequireLongerThan st n) => StackRef st
+ Morley.Michelson.Typed: mkStackRef :: forall (gn :: Nat) st n. (n ~ ToPeano gn, SingIPeano gn, RequireLongerThan st n) => StackRef st
- Morley.Michelson.Typed: mkUType :: SingI x => Notes x -> Ty
+ Morley.Michelson.Typed: mkUType :: Notes x -> Ty
- Morley.Michelson.Typed: notesSing :: SingI t => Notes t -> Sing t
+ Morley.Michelson.Typed: notesSing :: Notes t -> Sing t
- Morley.Michelson.Typed: notesT :: SingI t => Notes t -> T
+ Morley.Michelson.Typed: notesT :: Notes t -> T
- Morley.Michelson.Typed: requireEq :: forall (a :: T) (b :: T) m. (SingI a, SingI b, Monad m) => (forall x. Demote (KindOf a) -> Demote (KindOf b) -> m x) -> m (a :~: b)
+ Morley.Michelson.Typed: requireEq :: forall (a :: T) (b :: T) m. (SingI a, SingI b, Monad m) => (forall x. MismatchError T -> m x) -> m (a :~: b)
- Morley.Michelson.Typed: sampleTypedValue :: Sing t -> Maybe (Value t)
+ Morley.Michelson.Typed: sampleTypedValue :: forall t. Sing t -> Maybe (Value t)
- Morley.Michelson.Typed: type ConstraintDIG' kind (n :: Peano) (inp :: [kind]) (out :: [kind]) (a :: kind) = (RequireLongerThan inp n, inp ~ (Take n inp ++ (a : Drop ('S n) inp)), out ~ (a : Take n inp ++ Drop ('S n) inp))
+ Morley.Michelson.Typed: type ConstraintDIG' kind (n :: Peano) (inp :: [kind]) (out :: [kind]) (a :: kind) = (KnownList inp, RequireLongerThan inp n, inp ~ (Take n inp ++ (a : Drop ('S n) inp)), out ~ (a : Take n inp ++ Drop ('S n) inp))
- Morley.Michelson.Typed: type ProperConstantBetterErrors t = (SingI t, ForbidOp t, ForbidBigMap t, ForbidContract t, ForbidTicket t)
+ Morley.Michelson.Typed: type ProperConstantBetterErrors t = (SingI t, WellTyped t, ForbidOp t, ForbidBigMap t, ForbidContract t, ForbidTicket t, ForbidSaplingState t)
- Morley.Michelson.Typed: type ProperPackedValBetterErrors t = (SingI t, ForbidOp t, ForbidBigMap t, ForbidTicket t)
+ Morley.Michelson.Typed: type ProperPackedValBetterErrors t = (SingI t, WellTyped t, ForbidOp t, ForbidBigMap t, ForbidTicket t, ForbidSaplingState t)
- Morley.Michelson.Typed: type ProperParameterBetterErrors t = (SingI t, ForbidOp t, ForbidNestedBigMaps t)
+ Morley.Michelson.Typed: type ProperParameterBetterErrors t = (SingI t, WellTyped t, ForbidOp t, ForbidNestedBigMaps t)
- Morley.Michelson.Typed: type ProperStorageBetterErrors t = (SingI t, ForbidOp t, ForbidNestedBigMaps t, ForbidContract t)
+ Morley.Michelson.Typed: type ProperStorageBetterErrors t = (SingI t, WellTyped t, ForbidOp t, ForbidNestedBigMaps t, ForbidContract t)
- Morley.Michelson.Typed.Annotation: notesSing :: SingI t => Notes t -> Sing t
+ Morley.Michelson.Typed.Annotation: notesSing :: Notes t -> Sing t
- Morley.Michelson.Typed.Annotation: notesT :: SingI t => Notes t -> T
+ Morley.Michelson.Typed.Annotation: notesT :: Notes t -> T
- Morley.Michelson.Typed.Convert: convertParamNotes :: SingI cp => ParamNotes cp -> ParameterType
+ Morley.Michelson.Typed.Convert: convertParamNotes :: ParamNotes cp -> ParameterType
- Morley.Michelson.Typed.Convert: flattenEntrypoints :: SingI t => ParamNotes t -> Map EpName Ty
+ Morley.Michelson.Typed.Convert: flattenEntrypoints :: ParamNotes t -> Map EpName Ty
- Morley.Michelson.Typed.Convert: sampleTypedValue :: Sing t -> Maybe (Value t)
+ Morley.Michelson.Typed.Convert: sampleTypedValue :: forall t. Sing t -> Maybe (Value t)
- Morley.Michelson.Typed.Existential: [SomeConstrainedValue] :: forall (t :: T) (c :: T -> Constraint). c t => Value t -> SomeConstrainedValue c
+ Morley.Michelson.Typed.Existential: [SomeConstrainedValue] :: forall t c. c t => Value t -> SomeConstrainedValue c
- Morley.Michelson.Typed.Haskell: crDescriptionL :: forall a_a6Pns. Lens' (ConstructorRep a_a6Pns) (Maybe Text)
+ Morley.Michelson.Typed.Haskell: crDescriptionL :: forall a_a7szG. Lens' (ConstructorRep a_a7szG) (Maybe Text)
- Morley.Michelson.Typed.Haskell: crFieldsL :: forall a_a6Pns a_a6PoE. Lens (ConstructorRep a_a6Pns) (ConstructorRep a_a6PoE) [FieldRep a_a6Pns] [FieldRep a_a6PoE]
+ Morley.Michelson.Typed.Haskell: crFieldsL :: forall a_a7szG a_a7sAS. Lens (ConstructorRep a_a7szG) (ConstructorRep a_a7sAS) [FieldRep a_a7szG] [FieldRep a_a7sAS]
- Morley.Michelson.Typed.Haskell: crNameL :: forall a_a6Pns. Lens' (ConstructorRep a_a6Pns) Text
+ Morley.Michelson.Typed.Haskell: crNameL :: forall a_a7szG. Lens' (ConstructorRep a_a7szG) Text
- Morley.Michelson.Typed.Haskell: frDescriptionL :: forall a_a6Pnr. Lens' (FieldRep a_a6Pnr) (Maybe Text)
+ Morley.Michelson.Typed.Haskell: frDescriptionL :: forall a_a7szF. Lens' (FieldRep a_a7szF) (Maybe Text)
- Morley.Michelson.Typed.Haskell: frNameL :: forall a_a6Pnr. Lens' (FieldRep a_a6Pnr) (Maybe Text)
+ Morley.Michelson.Typed.Haskell: frNameL :: forall a_a7szF. Lens' (FieldRep a_a7szF) (Maybe Text)
- Morley.Michelson.Typed.Haskell: frTypeRepL :: forall a_a6Pnr a_a6Pqm. Lens (FieldRep a_a6Pnr) (FieldRep a_a6Pqm) a_a6Pnr a_a6Pqm
+ Morley.Michelson.Typed.Haskell: frTypeRepL :: forall a_a7szF a_a7sCA. Lens (FieldRep a_a7szF) (FieldRep a_a7sCA) a_a7szF a_a7sCA
- Morley.Michelson.Typed.Haskell.Doc: crDescriptionL :: forall a_a6Pns. Lens' (ConstructorRep a_a6Pns) (Maybe Text)
+ Morley.Michelson.Typed.Haskell.Doc: crDescriptionL :: forall a_a7szG. Lens' (ConstructorRep a_a7szG) (Maybe Text)
- Morley.Michelson.Typed.Haskell.Doc: crFieldsL :: forall a_a6Pns a_a6PoE. Lens (ConstructorRep a_a6Pns) (ConstructorRep a_a6PoE) [FieldRep a_a6Pns] [FieldRep a_a6PoE]
+ Morley.Michelson.Typed.Haskell.Doc: crFieldsL :: forall a_a7szG a_a7sAS. Lens (ConstructorRep a_a7szG) (ConstructorRep a_a7sAS) [FieldRep a_a7szG] [FieldRep a_a7sAS]
- Morley.Michelson.Typed.Haskell.Doc: crNameL :: forall a_a6Pns. Lens' (ConstructorRep a_a6Pns) Text
+ Morley.Michelson.Typed.Haskell.Doc: crNameL :: forall a_a7szG. Lens' (ConstructorRep a_a7szG) Text
- Morley.Michelson.Typed.Haskell.Doc: frDescriptionL :: forall a_a6Pnr. Lens' (FieldRep a_a6Pnr) (Maybe Text)
+ Morley.Michelson.Typed.Haskell.Doc: frDescriptionL :: forall a_a7szF. Lens' (FieldRep a_a7szF) (Maybe Text)
- Morley.Michelson.Typed.Haskell.Doc: frNameL :: forall a_a6Pnr. Lens' (FieldRep a_a6Pnr) (Maybe Text)
+ Morley.Michelson.Typed.Haskell.Doc: frNameL :: forall a_a7szF. Lens' (FieldRep a_a7szF) (Maybe Text)
- Morley.Michelson.Typed.Haskell.Doc: frTypeRepL :: forall a_a6Pnr a_a6Pqm. Lens (FieldRep a_a6Pnr) (FieldRep a_a6Pqm) a_a6Pnr a_a6Pqm
+ Morley.Michelson.Typed.Haskell.Doc: frTypeRepL :: forall a_a7szF a_a7sCA. Lens (FieldRep a_a7szF) (FieldRep a_a7sCA) a_a7szF a_a7sCA
- Morley.Michelson.Typed.Haskell.Value: type family ToTs' (t :: [k]) :: [T]
+ Morley.Michelson.Typed.Haskell.Value: type family ToTs' t
- Morley.Michelson.Typed.Instr: mkStackRef :: forall (gn :: Nat) st n. (n ~ ToPeano gn, SingI (ToPeano gn), RequireLongerThan st n) => StackRef st
+ Morley.Michelson.Typed.Instr: mkStackRef :: forall (gn :: Nat) st n. (n ~ ToPeano gn, SingIPeano gn, RequireLongerThan st n) => StackRef st
- Morley.Michelson.Typed.Instr: type ConstraintDIG' kind (n :: Peano) (inp :: [kind]) (out :: [kind]) (a :: kind) = (RequireLongerThan inp n, inp ~ (Take n inp ++ (a : Drop ('S n) inp)), out ~ (a : Take n inp ++ Drop ('S n) inp))
+ Morley.Michelson.Typed.Instr: type ConstraintDIG' kind (n :: Peano) (inp :: [kind]) (out :: [kind]) (a :: kind) = (KnownList inp, RequireLongerThan inp n, inp ~ (Take n inp ++ (a : Drop ('S n) inp)), out ~ (a : Take n inp ++ Drop ('S n) inp))
- Morley.Michelson.Typed.Scope: class (SingI t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t) => ConstantScope t
+ Morley.Michelson.Typed.Scope: class (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t, HasNoSaplingState t) => ConstantScope t
- Morley.Michelson.Typed.Scope: class (SingI t, HasNoOp t, HasNoBigMap t, HasNoTicket t) => PackedValScope t
+ Morley.Michelson.Typed.Scope: class (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoTicket t, HasNoSaplingState t) => PackedValScope t
- Morley.Michelson.Typed.Scope: class (SingI t, HasNoOp t, HasNoNestedBigMaps t) => ParameterScope t
+ Morley.Michelson.Typed.Scope: class (SingI t, WellTyped t, HasNoOp t, HasNoNestedBigMaps t) => ParameterScope t
- Morley.Michelson.Typed.Scope: class (SingI t, HasNoOp t, HasNoNestedBigMaps t, HasNoContract t) => StorageScope t
+ Morley.Michelson.Typed.Scope: class (SingI t, WellTyped t, HasNoOp t, HasNoNestedBigMaps t, HasNoContract t) => StorageScope t
- Morley.Michelson.Typed.Scope: class (PackedValScope t, ConstantScope t) => UnpackedValScope t
+ Morley.Michelson.Typed.Scope: class (WellTyped t, PackedValScope t, ConstantScope t) => UnpackedValScope t
- Morley.Michelson.Typed.Scope: type ProperConstantBetterErrors t = (SingI t, ForbidOp t, ForbidBigMap t, ForbidContract t, ForbidTicket t)
+ Morley.Michelson.Typed.Scope: type ProperConstantBetterErrors t = (SingI t, WellTyped t, ForbidOp t, ForbidBigMap t, ForbidContract t, ForbidTicket t, ForbidSaplingState t)
- Morley.Michelson.Typed.Scope: type ProperPackedValBetterErrors t = (SingI t, ForbidOp t, ForbidBigMap t, ForbidTicket t)
+ Morley.Michelson.Typed.Scope: type ProperPackedValBetterErrors t = (SingI t, WellTyped t, ForbidOp t, ForbidBigMap t, ForbidTicket t, ForbidSaplingState t)
- Morley.Michelson.Typed.Scope: type ProperParameterBetterErrors t = (SingI t, ForbidOp t, ForbidNestedBigMaps t)
+ Morley.Michelson.Typed.Scope: type ProperParameterBetterErrors t = (SingI t, WellTyped t, ForbidOp t, ForbidNestedBigMaps t)
- Morley.Michelson.Typed.Scope: type ProperStorageBetterErrors t = (SingI t, ForbidOp t, ForbidNestedBigMaps t, ForbidContract t)
+ Morley.Michelson.Typed.Scope: type ProperStorageBetterErrors t = (SingI t, WellTyped t, ForbidOp t, ForbidNestedBigMaps t, ForbidContract t)
- Morley.Michelson.Typed.Sing: [STBigMap] :: forall (n_a1CB6 :: T) (n_a1CB7 :: T). () => Sing n_a1CB6 -> Sing n_a1CB7 -> SingT ('TBigMap n_a1CB6 n_a1CB7 :: T)
+ Morley.Michelson.Typed.Sing: [STBigMap] :: forall (n_a22VZ :: T) (n_a22W0 :: T). () => Sing n_a22VZ -> Sing n_a22W0 -> SingT ('TBigMap n_a22VZ n_a22W0 :: T)
- Morley.Michelson.Typed.Sing: [STContract] :: forall (n_a1CAM :: T). () => Sing n_a1CAM -> SingT ('TContract n_a1CAM :: T)
+ Morley.Michelson.Typed.Sing: [STContract] :: forall (n_a22VF :: T). () => Sing n_a22VF -> SingT ('TContract n_a22VF :: T)
- Morley.Michelson.Typed.Sing: [STLambda] :: forall (n_a1CAY :: T) (n_a1CAZ :: T). () => Sing n_a1CAY -> Sing n_a1CAZ -> SingT ('TLambda n_a1CAY n_a1CAZ :: T)
+ Morley.Michelson.Typed.Sing: [STLambda] :: forall (n_a22VR :: T) (n_a22VS :: T). () => Sing n_a22VR -> Sing n_a22VS -> SingT ('TLambda n_a22VR n_a22VS :: T)
- Morley.Michelson.Typed.Sing: [STList] :: forall (n_a1CAI :: T). () => Sing n_a1CAI -> SingT ('TList n_a1CAI :: T)
+ Morley.Michelson.Typed.Sing: [STList] :: forall (n_a22VB :: T). () => Sing n_a22VB -> SingT ('TList n_a22VB :: T)
- Morley.Michelson.Typed.Sing: [STMap] :: forall (n_a1CB2 :: T) (n_a1CB3 :: T). () => Sing n_a1CB2 -> Sing n_a1CB3 -> SingT ('TMap n_a1CB2 n_a1CB3 :: T)
+ Morley.Michelson.Typed.Sing: [STMap] :: forall (n_a22VV :: T) (n_a22VW :: T). () => Sing n_a22VV -> Sing n_a22VW -> SingT ('TMap n_a22VV n_a22VW :: T)
- Morley.Michelson.Typed.Sing: [STOption] :: forall (n_a1CAG :: T). () => Sing n_a1CAG -> SingT ('TOption n_a1CAG :: T)
+ Morley.Michelson.Typed.Sing: [STOption] :: forall (n_a22Vz :: T). () => Sing n_a22Vz -> SingT ('TOption n_a22Vz :: T)
- Morley.Michelson.Typed.Sing: [STOr] :: forall (n_a1CAU :: T) (n_a1CAV :: T). () => Sing n_a1CAU -> Sing n_a1CAV -> SingT ('TOr n_a1CAU n_a1CAV :: T)
+ Morley.Michelson.Typed.Sing: [STOr] :: forall (n_a22VN :: T) (n_a22VO :: T). () => Sing n_a22VN -> Sing n_a22VO -> SingT ('TOr n_a22VN n_a22VO :: T)
- Morley.Michelson.Typed.Sing: [STPair] :: forall (n_a1CAQ :: T) (n_a1CAR :: T). () => Sing n_a1CAQ -> Sing n_a1CAR -> SingT ('TPair n_a1CAQ n_a1CAR :: T)
+ Morley.Michelson.Typed.Sing: [STPair] :: forall (n_a22VJ :: T) (n_a22VK :: T). () => Sing n_a22VJ -> Sing n_a22VK -> SingT ('TPair n_a22VJ n_a22VK :: T)
- Morley.Michelson.Typed.Sing: [STSet] :: forall (n_a1CAK :: T). () => Sing n_a1CAK -> SingT ('TSet n_a1CAK :: T)
+ Morley.Michelson.Typed.Sing: [STSet] :: forall (n_a22VD :: T). () => Sing n_a22VD -> SingT ('TSet n_a22VD :: T)
- Morley.Michelson.Typed.Sing: [STTicket] :: forall (n_a1CAO :: T). () => Sing n_a1CAO -> SingT ('TTicket n_a1CAO :: T)
+ Morley.Michelson.Typed.Sing: [STTicket] :: forall (n_a22VH :: T). () => Sing n_a22VH -> SingT ('TTicket n_a22VH :: T)
- Morley.Michelson.Typed.Sing: castM :: forall (a :: T) (b :: T) t m. (SingI a, SingI b, Monad m) => t a -> (forall x. Demote (KindOf a) -> Demote (KindOf b) -> m x) -> m (t b)
+ Morley.Michelson.Typed.Sing: castM :: forall (a :: T) (b :: T) t m. (SingI a, SingI b, Monad m) => t a -> (forall x. MismatchError T -> m x) -> m (t b)
- Morley.Michelson.Typed.Sing: data SingT z_a1CBV
+ Morley.Michelson.Typed.Sing: data SingT z_a22WY
- Morley.Michelson.Typed.Sing: requireEq :: forall (a :: T) (b :: T) m. (SingI a, SingI b, Monad m) => (forall x. Demote (KindOf a) -> Demote (KindOf b) -> m x) -> m (a :~: b)
+ Morley.Michelson.Typed.Sing: requireEq :: forall (a :: T) (b :: T) m. (SingI a, SingI b, Monad m) => (forall x. MismatchError T -> m x) -> m (a :~: b)
- Morley.Michelson.Typed.Util: CtorEffectsApp :: Text -> (forall i o. Semigroup x => x -> x -> Instr i o -> (Instr i o, x)) -> CtorEffectsApp x
+ Morley.Michelson.Typed.Util: CtorEffectsApp :: Text -> (forall i o. Monad m => Instr i o -> m (Instr i o) -> m (Instr i o)) -> CtorEffectsApp m
- Morley.Michelson.Typed.Util: DfsSettings :: Bool -> CtorEffectsApp x -> DfsSettings x
+ Morley.Michelson.Typed.Util: DfsSettings :: Bool -> CtorEffectsApp m -> DfsSettings m
- Morley.Michelson.Typed.Util: [ceaName] :: CtorEffectsApp x -> Text
+ Morley.Michelson.Typed.Util: [ceaName] :: CtorEffectsApp m -> Text
- Morley.Michelson.Typed.Util: [dsCtorEffectsApp] :: DfsSettings x -> CtorEffectsApp x
+ Morley.Michelson.Typed.Util: [dsCtorEffectsApp] :: DfsSettings m -> CtorEffectsApp m
- Morley.Michelson.Typed.Util: [dsGoToValues] :: DfsSettings x -> Bool
+ Morley.Michelson.Typed.Util: [dsGoToValues] :: DfsSettings m -> Bool
- Morley.Michelson.Typed.Util: data CtorEffectsApp x
+ Morley.Michelson.Typed.Util: data CtorEffectsApp m
- Morley.Michelson.Typed.Util: data DfsSettings x
+ Morley.Michelson.Typed.Util: data DfsSettings m
- Morley.Michelson.Typed.Util: dfsFoldInstr :: forall x inp out. Semigroup x => DfsSettings x -> (forall i o. Instr i o -> x) -> Instr inp out -> x
+ Morley.Michelson.Typed.Util: dfsFoldInstr :: forall x inp out. Monoid x => DfsSettings (Writer x) -> (forall i o. Instr i o -> x) -> Instr inp out -> x
- Morley.Michelson.Typed.Util: dfsInstr :: forall x inp out. Semigroup x => DfsSettings x -> (forall i o. Instr i o -> (Instr i o, x)) -> Instr inp out -> (Instr inp out, x)
+ Morley.Michelson.Typed.Util: dfsInstr :: forall x inp out. Monoid x => DfsSettings (Writer x) -> (forall i o. Instr i o -> (Instr i o, x)) -> Instr inp out -> (Instr inp out, x)
- Morley.Michelson.Typed.Util: dfsModifyInstr :: DfsSettings () -> (forall i o. Instr i o -> Instr i o) -> Instr inp out -> Instr inp out
+ Morley.Michelson.Typed.Util: dfsModifyInstr :: DfsSettings Identity -> (forall i o. Instr i o -> Instr i o) -> Instr inp out -> Instr inp out
- Morley.Tezos.Core: UnsafeMutez :: Word64 -> Mutez
+ Morley.Tezos.Core: UnsafeMutez :: Word63 -> Mutez
- Morley.Tezos.Core: [unMutez] :: Mutez -> Word64
+ Morley.Tezos.Core: [unMutez] :: Mutez -> Word63
- Morley.Tezos.Core: divModMutez :: Mutez -> Mutez -> Maybe (Word64, Mutez)
+ Morley.Tezos.Core: divModMutez :: Mutez -> Mutez -> Maybe (Word63, Mutez)
- Morley.Tezos.Core: mkChainId :: ByteString -> Maybe ChainId
+ Morley.Tezos.Core: mkChainId :: ByteString -> Either ParseChainIdError ChainId
- Morley.Tezos.Core: mkMutez :: (Integral i, Bits i) => i -> Either Text Mutez
+ Morley.Tezos.Core: mkMutez :: Integral i => i -> Either Text Mutez
- Morley.Tezos.Core: toMutez :: Word32 -> Mutez
+ Morley.Tezos.Core: toMutez :: (Integral a, CheckIntSubType a Word63) => a -> Mutez
- Morley.Tezos.Crypto: UnsafeTLTime :: Word64 -> TLTime
+ Morley.Tezos.Crypto: UnsafeTLTime :: Word62 -> TLTime
- Morley.Tezos.Crypto: [unTLTime] :: TLTime -> Word64
+ Morley.Tezos.Crypto: [unTLTime] :: TLTime -> Word62
- Morley.Tezos.Crypto: mkTLTime :: (Integral i, Bits i) => i -> Either Text TLTime
+ Morley.Tezos.Crypto: mkTLTime :: Integral i => i -> Either Text TLTime
- Morley.Tezos.Crypto: pattern TLTime :: Word64 -> TLTime
+ Morley.Tezos.Crypto: pattern TLTime :: Word62 -> TLTime
- Morley.Tezos.Crypto.Ed25519: publicKeyLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n
+ Morley.Tezos.Crypto.Ed25519: publicKeyLengthBytes :: (Integral n, CheckIntSubType Int n) => n
- Morley.Tezos.Crypto.Ed25519: signatureLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n
+ Morley.Tezos.Crypto.Ed25519: signatureLengthBytes :: (Integral n, CheckIntSubType Int n) => n
- Morley.Tezos.Crypto.P256: publicKeyLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n
+ Morley.Tezos.Crypto.P256: publicKeyLengthBytes :: (Integral n, CheckIntSubType Int n) => n
- Morley.Tezos.Crypto.P256: signatureLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n
+ Morley.Tezos.Crypto.P256: signatureLengthBytes :: (Integral n, CheckIntSubType Int n) => n
- Morley.Tezos.Crypto.Secp256k1: publicKeyLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n
+ Morley.Tezos.Crypto.Secp256k1: publicKeyLengthBytes :: (Integral n, CheckIntSubType Int n) => n
- Morley.Tezos.Crypto.Secp256k1: signatureLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n
+ Morley.Tezos.Crypto.Secp256k1: signatureLengthBytes :: (Integral n, CheckIntSubType Int n) => n
- Morley.Tezos.Crypto.Timelock: UnsafeTLTime :: Word64 -> TLTime
+ Morley.Tezos.Crypto.Timelock: UnsafeTLTime :: Word62 -> TLTime
- Morley.Tezos.Crypto.Timelock: [unTLTime] :: TLTime -> Word64
+ Morley.Tezos.Crypto.Timelock: [unTLTime] :: TLTime -> Word62
- Morley.Tezos.Crypto.Timelock: mkTLTime :: (Integral i, Bits i) => i -> Either Text TLTime
+ Morley.Tezos.Crypto.Timelock: mkTLTime :: Integral i => i -> Either Text TLTime
- Morley.Tezos.Crypto.Timelock: pattern TLTime :: Word64 -> TLTime
+ Morley.Tezos.Crypto.Timelock: pattern TLTime :: Word62 -> TLTime
- Morley.Tezos.Crypto.Util: publicKeyLengthBytes_ :: (Integral n, IsIntSubType Int n ~ 'True) => Curve -> n
+ Morley.Tezos.Crypto.Util: publicKeyLengthBytes_ :: (Integral n, CheckIntSubType Int n) => Curve -> n
- Morley.Tezos.Crypto.Util: signatureLengthBytes_ :: (Integral n, IsIntSubType Int n ~ 'True) => Curve -> n
+ Morley.Tezos.Crypto.Util: signatureLengthBytes_ :: (Integral n, CheckIntSubType Int n) => Curve -> n
- Morley.Util.Peano: [SS] :: !SingNat n -> SingNat ('S n)
+ Morley.Util.Peano: [SS] :: forall (n_a1Nbp :: Nat). () => Sing n_a1Nbp -> SingNat ('S n_a1Nbp :: Nat)
- Morley.Util.Peano: [SZ] :: SingNat 'Z
+ Morley.Util.Peano: [SZ] :: SingNat ('Z :: Nat)
- Morley.Util.Peano: data SingNat (n :: Nat)
+ Morley.Util.Peano: data SingNat z_a1Nbw
- Morley.Util.Peano: peanoSing :: forall (n :: Nat). SingI (ToPeano n) => SingNat (ToPeano n)
+ Morley.Util.Peano: peanoSing :: forall (n :: Nat). SingIPeano n => SingNat (ToPeano n)
- Morley.Util.PeanoNatural: data PeanoNatural (n :: Nat)
+ Morley.Util.PeanoNatural: data PeanoNatural (n :: Peano)
- Morley.Util.PeanoNatural: singPeanoVal :: forall (n :: Nat). SingNat n -> Natural
+ Morley.Util.PeanoNatural: singPeanoVal :: forall (n :: Peano). SingNat n -> Natural
- Morley.Util.PeanoNatural: toPeanoNatural' :: forall (n :: Nat). SingI (ToPeano n) => PeanoNatural (ToPeano n)
+ Morley.Util.PeanoNatural: toPeanoNatural' :: forall (n :: Nat). SingIPeano n => PeanoNatural (ToPeano n)

Files

CHANGES.md view
@@ -1,6 +1,129 @@ <!-- Unreleased: append new entries here -->  +1.16.3+======+* [!1113](https://gitlab.com/morley-framework/morley/-/merge_requests/1113)+  Remove uses of `Parser LetEnv` due to redundant constraint.+* [!1092](https://gitlab.com/morley-framework/morley/-/merge_requests/1092)+  Add quasiquoter for `Notes t`+* [!1094](https://gitlab.com/morley-framework/morley/-/merge_requests/1094)+  Deprecate morley language extensions+  + Morley language extensions now require `--deprecated-morley-extensions` flag to parse.+  + AST constructors corresponding to the Morley language extensions are deprecated+  + Functions for parsing Michelson with Morley extensions are added and marked as deprecated:  `parseContractExt`, `parseExpandContractExt`, `readAndParseContractExt`, `prepareContractExt`.+* [!1100](https://gitlab.com/morley-framework/morley/-/merge_requests/1100)+  Support `MAP` instruction over option type+  + Add `instance SingI1 'TOption`+  + Add `instance MapOp ('TOption e)`+* [!1084](https://gitlab.com/morley-framework/morley/-/merge_requests/1084)+  Switch to the new mutez subtraction operation+* [!1107](https://gitlab.com/morley-framework/morley/-/merge_requests/1107)+  Fix redundant `SDecide Nat` constraint warning+* [!1099](https://gitlab.com/morley-framework/morley/-/merge_requests/1099)+  Update utils for `Instr` type further.+  + `CtorEffectsApp` is now applied to the leaves in the `Instr` tree.+* [!1083](https://gitlab.com/morley-framework/morley/-/merge_requests/1083)+  Add typechecking and better errors for sapling+* [!965](https://gitlab.com/morley-framework/morley/-/merge_requests/965)+  Add fixed-size lists to Morley+  + Add `Morley.Util.SizedList` introducing Peano-based fixed-size homogenous lists.+  + Use `SizedList` for `genesisAddressN`.+  + Use `SizedList` to simplify `Morley.Util.Interpolate`.+  + Add instance `ToBigMap (SizedList' n (k, v))`+  + Add `Morley.Michelson.Parser.Helpers.count`, a fixed-size list version of `Text.Megaparsec.count`.+* [!1042](https://gitlab.com/morley-framework/morley/-/merge_requests/1042)+  Amend Morley.Util.Named+  + Re-export `arg` and `argF`+  + Deprecate `N`, `M`, `SomeArg`, `NoArg` patterns due to potential for abuse (use `arg` or `argF` with view patterns instead)+  + Do not re-export `Name` data constructor (use `fromLabel` with a type annotation/application instead)+* [!1089](https://gitlab.com/morley-framework/morley/-/merge_requests/1089)+  Enhance and rename mutez quasiquote+  + Remove `mtzQ` quasiquoter+  + Add `tz` quasiquoter; units are XTZ by default, but can be changed with a suffix; use `[tz|123u|]`, `[tz|123μ]` or `[tz|123 micro|]` for mutez.+* [!1095](https://gitlab.com/morley-framework/morley/-/merge_requests/1095)+  Put run, transfer and originate commands under emulate parent command+* [!1072](https://gitlab.com/morley-framework/morley/-/merge_requests/1072)+  Add `runCode` to Cleveland+  + `Morley.Michelson.Runtime`:+    - Don't assign IDs to bigmaps that already have one.+    - Allow overriding a contract's balance during a `transfer`.+  + Added `MaybeRPC` and `replaceBigMapIds`.+* [!1075](https://gitlab.com/morley-framework/morley/-/merge_requests/1075)+  Handle oddly-sized integral types with the `int-cast` facilities+  + Redefine `Mutez`, `TLTime` as newtype wrappers for `Word63`, `Word62` types respectively.+  + Implement `toTLTime` conversion function using `fromIntegralNoOverflow`.+  + Delegate `mkMutez`, `toMutez`, `mkTLTime` conversion functions to convenient and safe `fromIntegral` and `fromIntegralNoOverflow`.+  + Implement safe `mtzQ` quasiquoter for creating `Mutez` values.+* [!1071](https://gitlab.com/morley-framework/morley/-/merge_requests/1071)+  Add `HasRPCRepr` typeclass+* [!1068](https://gitlab.com/morley-framework/morley/-/merge_requests/1068)+  Update some utils for `Instr` type.+  * `dfsInstr` itself got deprecated in favor of other variations of this function.+  * `CtorEffectsApp` setting in `dfsInstr`-like functions now works differently.+    Instead of specifying complex combining function as the second `ceaApplyEffects` field,+    now you should specify how to transform the monadic action (and the field is now called `ceaPostStep`).+    Please create an issue if this change does not work for you.+  * Added `isMichelsonInstr`.+  * Now exporing `analyzeInstrFailure`.+* [!1076](https://gitlab.com/morley-framework/morley/-/merge_requests/1076)+  Fix escaping in haddock for Morley.Util.Interpolate+* [!1025](https://gitlab.com/morley-framework/morley/-/merge_requests/1025)+  Reduce the number of unsafe functions at the call site+  + Remove the following `unsafeFName` constructors/converters that are used as counter-parts of safe functions and replaced with `unsafe . fName`:+    - `unsafeMkMText`+    - `unsafeMkPos`+    - `unsafeParseEpAddress`+    - `unsafeMkMutez`+    - `unsafeMkAnnotation`+    - `unsafeMkViewName`+    - `unsafeFromMichelsonBytes`+    - `unsafeParseAddressRaw`+    - `unsafeBuildEpName`+    - `unsafeMkSomeParamType`+    - `unsafeParseKeyHash`+    - `unsafeParseEpAddressRaw`+    - `unsafeMkTLTime`+    - `unsafeParseAddress`+    - `unsafeParseContractHash`+    - `unsafeMkChainId`+  + Refactor `mkPos` and `mkChainId` to return `Either` instead of `Maybe`.+* [!1063](https://gitlab.com/morley-framework/morley/-/merge_requests/1063)+  Remove redundant `SingI` constraints+* [!1060](https://gitlab.com/morley-framework/morley/-/merge_requests/1060)+  Add `Morley.AsRPC` module for mapping types to their Tezos RPC representations+* [!978](https://gitlab.com/morley-framework/morley/-/merge_requests/978)+  Make it difficult to misuse 'Show'+  + Use `Buildable` and `pretty` preferrentially.+  + Add `Buildable` instances to that effect for `ArithError`, `StackSize`, `CtorEffectsApp`, `ContractBlock`,+  + Avoid using `(+||)` and `(||+)`.+  + Use `Debug.show` where we can't use `pretty` for some reason.+* [!1057](https://gitlab.com/morley-framework/morley/-/merge_requests/1057)+  Fix `Show`, `RenderDoc`, `Builder` instances of `Annotation t`, `AnnotationSet`, `Notes t`, `InstrAbstract op`+* [!997](https://gitlab.com/morley-framework/morley/-/merge_requests/997)+  Check necessity in initial `cast` automatically in Lorentz contracts+* [!1043](https://gitlab.com/morley-framework/morley/-/merge_requests/1043)+  Extract actual + expected pattern into a datatype and show diff in type mismatch+* [!1055](https://gitlab.com/morley-framework/morley/-/merge_requests/1055)+  Add more optimization rules+  + Rules added: `DUP 1 -> DUP`, `IF x x -> x`, `DIP n { } -> Nop`, `DIG n ; DUG n -> Nop`.+  + `TestEquality` instance added for `Morley.Util.Peano.SingNat`.+  + `Morley.Util.PeanoNatural` exports two new utility functions, `eqPeanoNat` and `singPeanoNat`.+  + `Morley.Util.Type` exports a new utility function, `knownListFromSingI`+* [!1013](https://gitlab.com/morley-framework/morley/-/merge_requests/1013)+  Add `WellTyped` to complex scope constraints+  + Make `WellTyped` constraint a part of complex constraints, namely `ParameterScope`, `StorageScope`, `ConstantScope`, `PackedValScope`, `UnpackedValScope`.+* [!987](https://gitlab.com/morley-framework/morley/-/merge_requests/987)+  Make parser's separators between values and instructions mandatory+  + Add `spaces` parser which doesn't accept zero white spaces+  + Change `ops'`, that parses sequence of operations, to accept absence of `;` separator after code in brackets `a; {b; c; ...} d`+  + Add backtracking with `try` to `symbol1`+* [!1037](https://gitlab.com/morley-framework/morley/-/merge_requests/1037)+  Add synonyms for `SomeConstrainedValue`+  + Reimplement `SomeConstant`, `SomeValue`, `SomeStorage` via `SomeConstrainedValue`.+* [!1035](https://gitlab.com/morley-framework/morley/-/merge_requests/1035)+  Better type errors on invalid int casts+ 1.16.2 ====== * [!1045](https://gitlab.com/morley-framework/morley/-/merge_requests/1045)
LICENSE view
@@ -1,4 +1,6 @@-MIT License Copyright (c) 2020 Tocqueville Group+MIT License+Copyright (c) 2021-2022 Oxhead Alpha+Copyright (c) 2019-2021 Tocqueville Group  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
README.md view
@@ -8,6 +8,7 @@ 2. A [library](https://gitlab.com/morley-framework/morley/-/tree/master/code/morley#morley-library) with core Tezos and Michelson data types, and functions such as Michelson typechecker and interpreter. 3. A superset of the Michelson language that we call the [Morley language](https://gitlab.com/morley-framework/morley/-/tree/master/code/morley#morley-language). It relaxes Michelson parser rules, adds some syntax sugar and simple features.+**deprecated**  ## Morley executable @@ -40,9 +41,9 @@ Morley executable does not interact with Tezos node and Tezos network. It works in _emulated environment_ which is stored in a simple JSON file on disk. The following commands depend on environment and may modify it:-- `originate` a contract.-- `transfer` tokens to a given address (and call a smart contract if it's the destination).-- `run` a contract. A given contract is being originated first, and then the transaction is being sent to it.+- `emulate originate` a contract.+- `emulate transfer` tokens to a given address (and call a smart contract if it's the destination).+- `emulate run` a contract. A given contract is being originated first, and then the transaction is being sent to it.  The following commands don't depend on environment: - `optimize` a contract by replacing certain sequences of instructions with equivalent but more efficient ones.@@ -78,6 +79,8 @@ - The `Morley.Util.*` hierarchy defines various `Morley`-related utilities that are used all over the project.  ## Morley language++**NOTE:** Morley-the-language is deprecated and support for it will be removed in not-so-distant future. Features of morley-the-language are done better in `lorentz` and in some cases are superseded by new Michelson revisions.  Morley-the-language is a superset of the Michelson language, which means that each Michelson contract is also a valid Morley contract but not vice versa. There are several extensions which make it more convenient to write Michelson contracts and test them.
app/Main.hs view
@@ -1,18 +1,20 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ module Main   ( main   ) where -import qualified Data.Text.Lazy.IO.Utf8 as Utf8 (writeFile)+import Data.Text.Lazy.IO.Utf8 qualified as Utf8 (writeFile) import Data.Version (showVersion) import Fmt (pretty) import Options.Applicative   (execParser, footerDoc, fullDesc, header, help, helper, info, infoOption, long, progDesc, short,   subparser, switch)-import qualified Options.Applicative as Opt+import Options.Applicative qualified as Opt import Options.Applicative.Help.Pretty (Doc, linebreak) import Paths_morley (version) import Text.Hex (encodeHex)@@ -22,15 +24,15 @@ import Morley.Michelson.Optimizer (optimize) import Morley.Michelson.Printer (printSomeContract, printUntypedContract) import Morley.Michelson.Runtime-  (TxData(..), originateContract, prepareContract, runContract, transfer)+  (TxData(..), originateContract, prepareContract, prepareContractExt, runContract, transfer) import Morley.Michelson.Runtime.GState (genesisAddress) import Morley.Michelson.TypeCheck (tcVerbose, typeCheckContract, typeCheckingWith)-import qualified Morley.Michelson.TypeCheck as TypeCheck+import Morley.Michelson.TypeCheck qualified as TypeCheck import Morley.Michelson.TypeCheck.Types (mapSomeContract) import Morley.Michelson.Typed (Contract'(..), SomeContract(..))-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Tezos.Address (Address)-import Morley.Tezos.Core (Mutez, Timestamp(..), toMutez)+import Morley.Tezos.Core (Mutez, Timestamp(..), tz) import Morley.Tezos.Crypto import Morley.Tezos.Crypto.Timelock (chestBytes, chestKeyBytes, createChestAndChestKey) import Morley.Util.CLI (mkCommandParser, outputOption)@@ -110,18 +112,20 @@   , toDryRun :: Bool   } -argParser :: Opt.Parser CmdLnArgs-argParser = subparser $+argParser :: Opt.Parser (Bool, CmdLnArgs)+argParser = ((,) <$> enableExtsOption <*>) . subparser $   printSubCmd <>   typecheckSubCmd <>-  runSubCmd <>-  originateSubCmd <>-  transferSubCmd <>+  emulateSubCmd <>   optimizeSubCmd <>   analyzeSubCmd <>   createChestSubCmd <>   replSubCmd   where+    enableExtsOption = switch $+      long "deprecated-morley-extensions" <>+      help "Enable parsing deprecated Morley extensions"+     typecheckSubCmd =       mkCommandParser "typecheck"         (TypeCheck <$> typeCheckOptions) $@@ -135,6 +139,13 @@       ("Parse a Morley contract and print corresponding Michelson " <>        "contract that can be parsed by the OCaml reference client: tezos-client") +    emulateSubCmd =+      mkCommandParser "emulate"+      (subparser $ runSubCmd+                <> originateSubCmd+                <> transferSubCmd)+      ("Set of commands to run in an emulated environment")+     runSubCmd =       mkCommandParser "run"       (Run <$> runOptions) $@@ -202,7 +213,7 @@       <*> typeCheckOptionsOption      defaultBalance :: Mutez-    defaultBalance = toMutez 4000000+    defaultBalance = [tz|4|]      optimizeOptions :: Opt.Parser OptimizeOptions     optimizeOptions = OptimizeOptions@@ -279,8 +290,8 @@  main :: IO () main = wrapMain $ do-  cmdLnArgs <- execParser programInfo-  run cmdLnArgs+  (exts, cmdLnArgs) <- execParser programInfo+  run exts cmdLnArgs   where     programInfo = info (helper <*> versionOption <*> argParser) $       mconcat@@ -293,16 +304,16 @@     versionOption = infoOption ("morley-" <> showVersion version)       (long "version" <> help "Show version.") -    run :: CmdLnArgs -> IO ()-    run args = case args of-      Print (M mInputFile)-            (M mOutputFile)-            (N forceSingleLine) -> do-        contract <- prepareContract mInputFile+    run :: Bool -> CmdLnArgs -> IO ()+    run exts args = case args of+      Print (argF #input -> mInputFile)+            (argF #output -> mOutputFile)+            (arg #singleLine -> forceSingleLine) -> do+        contract <- prepareContract' mInputFile         let write = maybe putStrLn Utf8.writeFile mOutputFile         write $ printUntypedContract forceSingleLine contract       Optimize OptimizeOptions{..} -> do-        untypedContract <- prepareContract optoContractFile+        untypedContract <- prepareContract' optoContractFile         checkedContract <-           either throwM pure . typeCheckingWith laxTcOptions $             typeCheckContract untypedContract@@ -310,13 +321,13 @@         let write = maybe putStrLn Utf8.writeFile optoOutput         write $ printSomeContract optoSingleLine optimizedContract       Analyze AnalyzeOptions{..} -> do-        untypedContract <- prepareContract aoContractFile+        untypedContract <- prepareContract' aoContractFile         SomeContract contract <-           either throwM pure . typeCheckingWith laxTcOptions $             typeCheckContract untypedContract         putTextLn $ pretty $ analyze (cCode contract)       TypeCheck TypeCheckOptions{..} -> do-        morleyContract <- prepareContract tcoContractFile+        morleyContract <- prepareContract' tcoContractFile         -- At the moment of writing, 'tcStrict' option does not change anything         -- because it affects only values parsing; but this may change         contract <- either throwM pure . typeCheckingWith tcoTcOptions@@ -325,12 +336,12 @@           putStrLn $ printSomeContract False contract         putTextLn "Contract is well-typed"       Run RunOptions {..} -> do-        michelsonContract <- prepareContract roContractFile+        michelsonContract <- prepareContract' roContractFile         void $ runContract roNow roLevel roMaxSteps roInitBalance roDBPath roTcOptions roStorageValue michelsonContract roTxData           ! #verbose roVerbose           ! #dryRun (not roWrite)       Originate OriginateOptions {..} -> do-        michelsonContract <- prepareContract ooContractFile+        michelsonContract <- prepareContract' ooContractFile         addr <-           originateContract             ooDBPath@@ -351,13 +362,18 @@         (chest, key) <- createChestAndChestKey ccPayload ccTime         putStrLn $ "Chest: 0x" <> encodeHex (chestBytes chest)         putStrLn $ "Key: 0x" <> encodeHex (chestKeyBytes key)+      where+        -- TODO [#712]: Remove this next major release+        prepareContract'+          | exts = prepareContractExt+          | otherwise = prepareContract   usageDoc :: Maybe Doc usageDoc = Just $ mconcat    [ "You can use help for specific COMMAND", linebreak    , "EXAMPLE:", linebreak-   , "  morley run --help", linebreak+   , "  morley emulate run --help", linebreak    , linebreak    , "Documentation for morley tools can be found at the following links:", linebreak    , "  https://gitlab.com/morley-framework/morley/blob/master/README.md", linebreak@@ -372,7 +388,7 @@    , "  This command will parse contract stored in add1.tz", linebreak    , "  and return its representation in haskell types", linebreak    , linebreak-   , "  morley originate --contract add1.tz --storage 1 --verbose", linebreak+   , "  morley emulate originate --contract add1.tz --storage 1 --verbose", linebreak    , linebreak    , "  This command will originate contract with code stored in add1.tz", linebreak    , "  with initial storage value set to 1 and return info about", linebreak
app/REPL.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA {-| Implements an REPL that can execute Morley instructions.  REPL starts with an empty stack. At each instruction entered, the modified stack, or an error is@@ -18,15 +17,16 @@  import Control.Exception (IOException) import Control.Monad.Random (randomIO)-import qualified Data.Aeson as Aeson-import qualified Data.ByteString.Base58 as Base58-import qualified Data.ByteString.Lazy as BSL+import Data.Aeson qualified as Aeson+import Data.ByteString.Base58 qualified as Base58+import Data.ByteString.Lazy qualified as BSL import Data.List (stripPrefix) import Data.Text as T (length, replicate, strip)-import qualified Data.Text as T (stripPrefix)+import Data.Text qualified as T (stripPrefix) import Data.Vinyl (Rec(..)) import Fmt (fmt, pretty) import System.Console.Haskeline+  (InputT, Interrupt(..), defaultSettings, getInputLine, runInputT, withInterrupt) import Text.Megaparsec (parse)  import Morley.Michelson.Interpret (interpretInstr)@@ -38,12 +38,11 @@ import Morley.Michelson.Runtime.Dummy import Morley.Michelson.Runtime.Import (readValue) import Morley.Michelson.TypeCheck-  (SomeInstr(..), SomeInstrOut(..), TypeCheckOptions(..), getWTP, runTypeCheckIsolated,-  typeCheckingWith)+  (SomeInstr(..), SomeInstrOut(..), TypeCheckOptions(..), runTypeCheckIsolated, typeCheckingWith) import Morley.Michelson.TypeCheck.Instr (typeCheckList, typeCheckParameter)-import Morley.Michelson.TypeCheck.Types (HST(..), NotWellTyped(..))-import qualified Morley.Michelson.Typed as T-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.TypeCheck.Types (HST(..))+import Morley.Michelson.Typed qualified as T+import Morley.Michelson.Untyped qualified as U import Morley.Tezos.Crypto import Morley.Util.Sing (castSing) import Text.Hex (decodeHex, encodeHex)@@ -199,7 +198,7 @@                     printStack                   Left michelsonFail -> putTextLn (pretty michelsonFail)                 _ :/ (AnyOutInstr _) -> putTextLn "Encountered a FAILWITH instruction"-            Left err -> printErr $ show err+            Left err -> printErr $ pretty err           Nothing -> printErr "Casting stack failed"  printHelp :: ReplM ()@@ -225,7 +224,7 @@  parseInstructions :: Text -> Either Text [ParsedOp] parseInstructions src =-  case parseNoEnv ops MSUnspecified src of+  case parseNoEnv @() ops MSUnspecified src of     Right p -> Right p     Left err -> Left (toText $ errorBundlePretty err) @@ -243,15 +242,15 @@   -> HST xs   -> Either Text (T.Dict (T.SingI (t ': xs)), HST (t ': xs)) addValueToHST v hstIn = case T.valueTypeSanity v of-  T.Dict -> case getWTP @t of+  T.Dict -> case T.getWTP @t of     Right wtpDict -> Right (T.Dict, (T.starNotes @t, wtpDict, U.noAnn) ::&  hstIn)-    Left (NotWellTyped t cause) -> let+    Left (T.NotWellTyped t cause) -> let       U.Ty t' tann = T.toUType t       in Left $ "Value of type '" <> (renderT t' (U.fullAnnSet [tann] [] []))                 <> "' is not well typed in the provided Value because it "                 <> pretty cause <> "." -renderType :: T.SingI t => T.Notes t -> U.VarAnn -> Text+renderType :: T.Notes t -> U.VarAnn -> Text renderType notes vann = let   U.Ty t tann = T.mkUType notes   in renderT t (U.fullAnnSet [tann] [] [vann])@@ -308,7 +307,7 @@               case addValueToHST tVal hst of                 Right (T.Dict, newHst) -> Right $ SomeStack (tVal :& stk) newHst                 Left err -> Left err-            Left tcError -> Left $ show tcError+            Left tcError -> Left $ pretty tcError         (Left err, _) -> Left $ pretty err         (_, Left err) -> Left $ toText $ errorBundlePretty err @@ -321,6 +320,6 @@     _ ->          -- else just call show, and indicate value has operation inside       case (v, T.sing @a) of         (T.VList [], T.STList T.STOperation) -> "{ } :: list operation\n" <> showStack rst rHst-        _ -> addSuffix $ "(operations container:" <> show v <> ")"+        _ -> addSuffix $ "(operations container:" <> pretty v <> ")"   where     addSuffix val = val <>" :: " <> renderType notes vann <> "\n" <> showStack rst rHst
docs/language/morleyInstructions.md view
@@ -4,6 +4,8 @@ SPDX-License-Identifier: LicenseRef-MIT-TQ --> +**NOTE:** Morley extended instructions are _deprecated_. The internal representation still uses instructions described here, as those are used by Lorentz, but parsing contracts using these instructions is deprecated and requires `--deprecated-morley-extensions` flag when invoking `morley`. This flag will be removed in the not-so-distant future.+ # Morley Ext Instructions  Morley adds some additional instructions of its own to the existing set of
docs/language/morleyLanguage.md view
@@ -1,8 +1,9 @@ <!---SPDX-FileCopyrightText: 2020 Tocqueville Group--SPDX-License-Identifier: LicenseRef-MIT-TQ+SPDX-FileCopyrightText: 2021 Oxhead Alpha+SPDX-License-Identifier: LicenseRef-MIT-OA -->++**NOTE:** Morley language is _deprecated_. The internal representation still uses some of the extended instructions, as those are used by Lorentz, but parsing contracts using the morley language is deprecated and requires `--deprecated-morley-extensions` flag when invoking `morley`. This flag will be removed in the not-so-distant future.  # Morley Language 
docs/language/morleyLet.md view
@@ -4,6 +4,8 @@ SPDX-License-Identifier: LicenseRef-MIT-TQ --> +**NOTE:** Morley language is _deprecated_, which includes let-block definitions. Parsing contracts using the morley language is deprecated and requires `--deprecated-morley-extensions` flag when invoking `morley`. This flag will be removed in the not-so-distant future.+ # Let-block Definitions  In addition to the built-in macros defined in the Michelson specification,
docs/language/morleyMacros.md view
@@ -4,6 +4,8 @@ SPDX-License-Identifier: LicenseRef-MIT-TQ --> +**NOTE:** Morley language is _deprecated_, which includes these macros. Parsing contracts using the morley language is deprecated and requires `--deprecated-morley-extensions` flag when invoking `morley`. This flag will be removed in the not-so-distant future.+ # Morley Language: Macros and Type synonyms  Morley language supports all macros from the OCaml reference implementation and additionally introduces some extra macros and type synonyms.
docs/language/morleySyntaxSugar.md view
@@ -4,6 +4,8 @@ SPDX-License-Identifier: LicenseRef-MIT-TQ --> +**NOTE:** Morley language is _deprecated_, which includes the syntax sugar described here. Parsing contracts using the morley language is deprecated and requires `--deprecated-morley-extensions` flag when invoking `morley`. This flag will be removed in the not-so-distant future.+ # Morley Language: Syntax Sugar  ## Summary
docs/michelsonTypes.md view
@@ -1,7 +1,6 @@ <!---SPDX-FileCopyrightText: 2020 Tocqueville Group--SPDX-License-Identifier: LicenseRef-MIT-TQ+SPDX-FileCopyrightText: 2021 Oxhead Alpha+SPDX-License-Identifier: LicenseRef-MIT-OA -->  # Michelson Types
docs/morleyInterpreter.md view
@@ -1,7 +1,6 @@ <!---SPDX-FileCopyrightText: 2020 Tocqueville Group--SPDX-License-Identifier: LicenseRef-MIT-TQ+SPDX-FileCopyrightText: 2021 Oxhead Alpha+SPDX-License-Identifier: LicenseRef-MIT-OA -->  # Morley Interpreter@@ -35,11 +34,11 @@ 3. Write an updated blockchain state on disk.  An end user can apply one of the following commands to run the executor.-* The `transfer` command sends a transaction from one address to another address.+* The `emulate transfer` command sends a transaction from one address to another address. If the destination address is a smart contract, its code will be executed. Its storage will be updated, and it may return some operations which will also be executed. The destination contract must be originated first.-* The `run` command originates a smart contract and transfers tokens to it.+* The `emulate run` command originates a smart contract and transfers tokens to it. By default, it doesn't update the global state. It's intended to be used when one just wants to quickly interpret one contract and doesn't care about a global state file. The command still needs to read the DB (JSON file) to know about all originated contracts and their parameters.@@ -47,8 +46,8 @@ Other environment data can be passed from CLI, but it's not mandatory, and default values are used if they are not passed explicitly.  Examples:-* `morley transfer --to KT1L39q6uCg1wQPB796q5oQQgDW673uo1s5y --parameter 'Left 10'` (`KT1L39q6uCg1wQPB796q5oQQgDW673uo1s5y` must be originated first).-* `morley run --contract foo.tz --parameter '"aaa"' --storage Unit` (in this case the contract will be originated automatically).+* `morley emulate transfer --to KT1L39q6uCg1wQPB796q5oQQgDW673uo1s5y --parameter 'Left 10'` (`KT1L39q6uCg1wQPB796q5oQQgDW673uo1s5y` must be originated first).+* `morley emulate run --contract foo.tz --parameter '"aaa"' --storage Unit` (in this case the contract will be originated automatically).  By default, each operation uses _genesis address_ as a sender. This address initially has a lot of tokens.
docs/morleyRuntime.md view
@@ -1,7 +1,6 @@ <!---SPDX-FileCopyrightText: 2020 Tocqueville Group--SPDX-License-Identifier: LicenseRef-MIT-TQ+SPDX-FileCopyrightText: 2021 Oxhead Alpha+SPDX-License-Identifier: LicenseRef-MIT-OA -->  # Morley Runtime
docs/morleyTypechecker.md view
@@ -1,7 +1,6 @@ <!---SPDX-FileCopyrightText: 2020 Tocqueville Group--SPDX-License-Identifier: LicenseRef-MIT-TQ+SPDX-FileCopyrightText: 2021 Oxhead Alpha+SPDX-License-Identifier: LicenseRef-MIT-OA -->  # Morley Typechecker
morley.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           morley-version:        1.16.2+version:        1.16.3 synopsis:       Developer tools for the Michelson Language description:    A library to make writing smart contracts in Michelson — the smart contract language of the Tezos blockchain — pleasant and effective. category:       Language@@ -13,7 +13,7 @@ bug-reports:    https://gitlab.com/morley-framework/morley/-/issues author:         camlCase, Serokell, Tocqueville Group maintainer:     Serokell <hi@serokell.io>-copyright:      2018 camlCase, 2019-2021 Tocqueville Group+copyright:      2018 camlCase, 2019-2021 Tocqueville Group, 2021-2022 Oxhead Alpha license:        MIT license-file:   LICENSE build-type:     Simple@@ -37,6 +37,7 @@  library   exposed-modules:+      Morley.AsRPC       Morley.CLI       Morley.Micheline       Morley.Micheline.Binary@@ -151,15 +152,19 @@       Morley.Util.Generic       Morley.Util.Instances       Morley.Util.Interpolate+      Morley.Util.Interpolate.Internal       Morley.Util.Label       Morley.Util.Lens       Morley.Util.Main       Morley.Util.Markdown+      Morley.Util.MismatchError       Morley.Util.Named       Morley.Util.Peano       Morley.Util.PeanoNatural       Morley.Util.Positive       Morley.Util.Sing+      Morley.Util.SizedList+      Morley.Util.SizedList.Types       Morley.Util.Text       Morley.Util.TH       Morley.Util.Type@@ -194,24 +199,26 @@       FlexibleInstances       GADTs       GeneralizedNewtypeDeriving+      ImportQualifiedPost       LambdaCase       MultiParamTypeClasses       MultiWayIf       NamedFieldPuns       NegativeLiterals-      NumericUnderscores       NumDecimals+      NumericUnderscores       OverloadedLabels       OverloadedStrings       PatternSynonyms       PolyKinds-      QuasiQuotes       QuantifiedConstraints+      QuasiQuotes       RankNTypes       RecordWildCards       RecursiveDo       ScopedTypeVariables       StandaloneDeriving+      StandaloneKindSignatures       StrictData       TemplateHaskell       TupleSections@@ -223,7 +230,8 @@       ViewPatterns   ghc-options: -Weverything -Wno-missing-exported-signatures -Wno-missing-import-lists -Wno-missed-specialisations -Wno-all-missed-specialisations -Wno-unsafe -Wno-safe -Wno-missing-local-signatures -Wno-monomorphism-restriction -Wno-implicit-prelude -Wno-prepositive-qualified-module -Wno-missing-safe-haskell-mode -Wno-unused-packages   build-depends:-      MonadRandom+      Diff+    , MonadRandom     , aeson     , aeson-casing     , aeson-pretty@@ -262,6 +270,7 @@     , text-manipulate     , th-lift     , th-lift-instances+    , th-reify-many     , time     , timerep     , uncaught-exception@@ -302,24 +311,26 @@       FlexibleInstances       GADTs       GeneralizedNewtypeDeriving+      ImportQualifiedPost       LambdaCase       MultiParamTypeClasses       MultiWayIf       NamedFieldPuns       NegativeLiterals-      NumericUnderscores       NumDecimals+      NumericUnderscores       OverloadedLabels       OverloadedStrings       PatternSynonyms       PolyKinds-      QuasiQuotes       QuantifiedConstraints+      QuasiQuotes       RankNTypes       RecordWildCards       RecursiveDo       ScopedTypeVariables       StandaloneDeriving+      StandaloneKindSignatures       StrictData       TemplateHaskell       TupleSections
+ src/Morley/AsRPC.hs view
@@ -0,0 +1,982 @@+-- SPDX-FileCopyrightText: 2022 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA++-- | This module contains a type family for converting a type to its RPC representation,+-- and TemplateHaskell functions for deriving RPC representations for custom types.+module Morley.AsRPC+  ( TAsRPC+  , HasRPCRepr(..)+  , MaybeRPC(..)+  , deriveRPC+  , deriveRPCWithStrategy+  , deriveManyRPC+  , deriveManyRPCWithStrategy+  -- * Conversions+  , valueAsRPC+  , replaceBigMapIds+  , notesAsRPC+  -- * Entailments+  , rpcSingIEvi+  , rpcHasNoOpEvi+  , rpcHasNoBigMapEvi+  , rpcHasNoNestedBigMapsEvi+  , rpcHasNoContractEvi+  , rpcStorageScopeEvi+  ) where++import Prelude hiding (Type)+import Prelude qualified++import Control.Lens.Plated (universe)+import Data.Constraint (Dict(..), (***), (:-)(Sub), (\\))+import Data.List qualified as List ((\\))+import Data.Singletons (Sing, withSingI)+import GHC.Generics qualified as G+import Language.Haskell.TH+  (Con(InfixC, NormalC, RecC), Cxt, Dec(DataD, NewtypeD, TySynD, TySynInstD),+  DerivStrategy(AnyclassStrategy), Info(TyConI), Kind, Loc(loc_module), Name, Q, TyLit(StrTyLit),+  TySynEqn(..), TyVarBndr, Type(..), cxt, instanceD, location, mkName, nameBase, ppr, reify,+  reifyInstances, standaloneDerivWithStrategyD)+import Language.Haskell.TH.ReifyMany (reifyManyTyCons)+import Language.Haskell.TH.ReifyMany.Internal (decConcreteNames)++import Morley.Micheline (ToExpression(..))+import Morley.Michelson.Text (MText)+import Morley.Michelson.Typed+  (BigMap, BigMapId, ContractPresence(ContractAbsent), ContractRef, EpAddress, HasNoBigMap,+  HasNoContract, HasNoNestedBigMaps, HasNoOp, IsoValue, Notes(..), OpPresence(..), Operation,+  SingI(sing), SingT(..), StorageScope, T(..), ToT, Value, Value'(..), WellTyped,+  checkContractTypePresence, checkOpPresence, toVal, withDict)+import Morley.Tezos.Address (Address)+import Morley.Tezos.Core (ChainId, Mutez, Timestamp)+import Morley.Tezos.Crypto+import Morley.Util.CustomGeneric+  (GenericStrategy, customGeneric', deriveFullType, haskellBalanced, reifyDataType)+import Morley.Util.Named hiding (Name)+import Morley.Util.TH (isTypeAlias, lookupTypeNameOrFail)++{-# ANN module ("HLint: ignore Avoid lambda using `infix`" :: Text) #-}++-- $setup+-- >>> import Morley.Michelson.Typed (T(..), BigMap, mkBigMap)+-- >>> import Morley.Michelson.Typed.Haskell.Value (BigMapId(..))+-- >>> import Morley.Michelson.Text (MText)++----------------------------------------------------------------------------+-- TAsRPC+----------------------------------------------------------------------------++{- | A type-level function that maps a Michelson type to its Tezos RPC representation.++For example, when we retrieve a contract's storage using the Tezos RPC,+all its @big_map@s will be replaced by @nat@, representing a big_map ID.++>>> :k! TAsRPC ('TBigMap 'TInt 'TString)+...+= 'TNat++>>> :k! TAsRPC ('TList ('TBigMap 'TInt 'TString))+...+= 'TList 'TNat++>>> :k! TAsRPC ('TPair 'TString ('TPair 'TAddress ('TBigMap 'TInt 'TString)))+...+= 'TPair 'TString ('TPair 'TAddress 'TNat)+++NB: As far as we are aware, details of RPC representation of Michelson+types are not documented. We know empirically that @big_map@s are+represented as their ids, and are the only type with an explicitly+different representation.++Whether @TAsRPC@ needs to propagate into type parameters then depends on+whether a value can hold big_map values.++* Values of type @option a@, @list a@, @pair a b@, and @or a b@ can+  contain big_map values, so their RPC representations are @option (TAsRPC a)@,+  @list (TAsRPC a)@, @pair (TAsRPC a) (TAsRPC b)@ and @or (TAsRPC a) (TAsRPC b)@.+* The keys of a @map k v@ cannot be big_maps, but the values can, so its+  RPC representation is @map k (TAsRPC v)@.+* Values of type @set a@ cannot contain big_maps, so its RPC+  representation is just @set a@.+* Values of type @contract a@ cannot contain big_maps either, because+  it's just a wrapper for an address and an entrypoint name, so its RPC+  representation is just @contract a@. The same reasoning applies to+  @ticket a@ and @lambda a b@.++-}+type TAsRPC :: T -> T+type family TAsRPC t where+  TAsRPC 'TKey = 'TKey+  TAsRPC 'TUnit = 'TUnit+  TAsRPC 'TSignature = 'TSignature+  TAsRPC 'TChainId = 'TChainId+  TAsRPC ('TOption t) = 'TOption (TAsRPC t)+  TAsRPC ('TList t) = 'TList (TAsRPC t)+  TAsRPC ('TSet t) = 'TSet t+  TAsRPC 'TOperation = 'TOperation+  TAsRPC ('TContract t) = 'TContract t+  TAsRPC ('TTicket t) = 'TTicket t+  TAsRPC ('TPair t1 t2) = 'TPair (TAsRPC t1) (TAsRPC t2)+  TAsRPC ('TOr t1 t2) = 'TOr (TAsRPC t1) (TAsRPC t2)+  TAsRPC ('TLambda t1 t2) = 'TLambda t1 t2+  TAsRPC ('TMap k v) = 'TMap k (TAsRPC v)+  TAsRPC ('TBigMap _ _) = 'TNat+  TAsRPC 'TInt = 'TInt+  TAsRPC 'TNat = 'TNat+  TAsRPC 'TString = 'TString+  TAsRPC 'TBytes = 'TBytes+  TAsRPC 'TMutez = 'TMutez+  TAsRPC 'TBool = 'TBool+  TAsRPC 'TKeyHash = 'TKeyHash+  TAsRPC 'TTimestamp = 'TTimestamp+  TAsRPC 'TAddress = 'TAddress+  TAsRPC 'TNever = 'TNever+  TAsRPC 'TBls12381Fr = 'TBls12381Fr+  TAsRPC 'TBls12381G1 = 'TBls12381G1+  TAsRPC 'TBls12381G2 = 'TBls12381G2+  TAsRPC 'TChest = 'TChest+  TAsRPC 'TChestKey = 'TChestKey+  TAsRPC ('TSaplingState n) = ('TSaplingState n)+  TAsRPC ('TSaplingTransaction n) = ('TSaplingTransaction n)++----------------------------------------------------------------------------+-- AsRPC+----------------------------------------------------------------------------++{- | A type-level function that maps a type to its Tezos RPC representation.++For example, when we retrieve a contract's storage using the Tezos RPC, all its 'BigMap's will be replaced+by 'BigMapId's.++So if a contract has a storage of type @T@, when we call the Tezos RPC+to retrieve it, we must deserialize the micheline expression to the type @AsRPC T@.++> AsRPC (BigMap Integer MText) ~ BigMapId Integer MText+> AsRPC [BigMap Integer MText] ~ [BigMapId Integer MText]+> AsRPC (MText, (Address, BigMap Integer MText)) ~ (MText, (Address, BigMapId Integer MText))++The following law must hold:++> TAsRPC (ToT t) ~ ToT (AsRPC t)++In other words, `ToT` and `AsRPC`/`TAsRPC` must be commutative.++@+   Storage ----------(applying ToT)-------------> ToT Storage+      |                                                |+      |                                                |+      |                                                |+(applying AsRPC)                                (applying TAsRPC)+      |                                                |+      |                                                |+      |                                                |+      |                                                V+      |                                        TAsRPC (ToT Storage)+      V                                                ~+AsRPC Storage ------(applying ToT)-----------> ToT (AsRPC Storage)+@+++This law ensures that we can go from some type @Storage@ to @AsRPC Storage@ by+composing @fromVal . valueAsRPC . toVal@.++@+   Storage ------------(toVal)--------------> Value (ToT Storage)+      |                                                |+      |                                                |+      |                                                |+(fromVal . valueAsRPC . toVal)                    (valueAsRPC)+      |                                                |+      |                                                |+      |                                                |+      |                                                V+      |                                   Value (TAsRPC (ToT Storage))+      V                                                ~+AsRPC Storage <--------(fromVal)--------- Value (ToT (AsRPC Storage))+@++-}+class (TAsRPC (ToT t) ~ ToT (AsRPC t)) => HasRPCRepr (t :: Prelude.Type) where+  type AsRPC t :: Prelude.Type++-- Morley types++-- Note: We don't recursively apply @AsRPC@ to @k@ or @v@ because+-- bigmaps cannot contain nested bigmaps.+-- If this constraint is ever lifted, we'll have to change this instance+-- to @BigMapId k (AsRPC v)@+instance HasRPCRepr (BigMap k v) where type AsRPC (BigMap k v) = BigMapId k v+instance HasRPCRepr (Value t) where type AsRPC (Value t) = Value (TAsRPC t)+instance HasRPCRepr Integer where type AsRPC Integer = Integer+instance HasRPCRepr Natural where type AsRPC Natural = Natural+instance HasRPCRepr MText where type AsRPC MText = MText+instance HasRPCRepr Bool where type AsRPC Bool = Bool+instance HasRPCRepr ByteString where type AsRPC ByteString = ByteString+instance HasRPCRepr Mutez where type AsRPC Mutez = Mutez+instance HasRPCRepr KeyHash where type AsRPC KeyHash = KeyHash+instance HasRPCRepr Timestamp where type AsRPC Timestamp = Timestamp+instance HasRPCRepr Address where type AsRPC Address = Address+instance HasRPCRepr EpAddress where type AsRPC EpAddress = EpAddress+instance HasRPCRepr PublicKey where type AsRPC PublicKey = PublicKey+instance HasRPCRepr Signature where type AsRPC Signature = Signature+instance HasRPCRepr ChainId where type AsRPC ChainId = ChainId+instance HasRPCRepr Bls12381Fr where type AsRPC Bls12381Fr = Bls12381Fr+instance HasRPCRepr Bls12381G1 where type AsRPC Bls12381G1 = Bls12381G1+instance HasRPCRepr Bls12381G2 where type AsRPC Bls12381G2 = Bls12381G2+instance HasRPCRepr () where type AsRPC () = ()+instance HasRPCRepr a => HasRPCRepr [a] where+  type AsRPC [a] = [AsRPC a]+instance HasRPCRepr a => HasRPCRepr (Maybe a) where+  type AsRPC (Maybe a) = Maybe (AsRPC a)+instance (HasRPCRepr l, HasRPCRepr r) => HasRPCRepr (Either l r) where+  type AsRPC (Either l r) = Either (AsRPC l) (AsRPC r)+instance (HasRPCRepr a, HasRPCRepr b) => HasRPCRepr (a, b) where+  type AsRPC (a, b) = (AsRPC a, AsRPC b)+instance HasRPCRepr (Set a) where+  type AsRPC (Set a) = Set a+instance HasRPCRepr v => HasRPCRepr (Map k v) where+  type AsRPC (Map k v) = Map k (AsRPC v)+instance HasRPCRepr Operation where+  type AsRPC Operation = Operation+instance HasRPCRepr a => HasRPCRepr (Identity a) where+  type AsRPC (Identity a) = Identity (AsRPC a)+instance HasRPCRepr a => HasRPCRepr (NamedF Identity a name) where+  type AsRPC (NamedF Identity a name) = NamedF Identity (AsRPC a) name+instance HasRPCRepr a => HasRPCRepr (NamedF Maybe a name) where+  type AsRPC (NamedF Maybe a name) = NamedF Maybe (AsRPC a) name+instance Each '[HasRPCRepr] '[a, b, c] => HasRPCRepr (a, b, c) where+  type AsRPC (a, b, c) = (AsRPC a, AsRPC b, AsRPC c)+instance Each '[HasRPCRepr] '[a, b, c, d] => HasRPCRepr (a, b, c, d) where+  type AsRPC (a, b, c, d) = (AsRPC a, AsRPC b, AsRPC c, AsRPC d)+instance Each '[HasRPCRepr] '[a, b, c, d, e] => HasRPCRepr (a, b, c, d, e) where+  type AsRPC (a, b, c, d, e) = (AsRPC a, AsRPC b, AsRPC c, AsRPC d, AsRPC e)+instance Each '[HasRPCRepr] '[a, b, c, d, e, f] => HasRPCRepr (a, b, c, d, e, f) where+  type AsRPC (a, b, c, d, e, f) = (AsRPC a, AsRPC b, AsRPC c, AsRPC d, AsRPC e, AsRPC f)+instance Each '[HasRPCRepr] '[a, b, c, d, e, f, g] => HasRPCRepr (a, b, c, d, e, f, g) where+  type AsRPC (a, b, c, d, e, f, g) = (AsRPC a, AsRPC b, AsRPC c, AsRPC d, AsRPC e, AsRPC f, AsRPC g)+instance HasRPCRepr (ContractRef arg) where+  type AsRPC (ContractRef arg) = ContractRef arg+instance HasRPCRepr Chest where+  type AsRPC Chest = Chest+instance HasRPCRepr ChestKey where+  type AsRPC ChestKey = ChestKey++----------------------------------------------------------------------------+-- MaybeRPC+----------------------------------------------------------------------------++-- | Represents a value that may or may not be in its RPC representation.+--+-- >>> :t NotRPC @(BigMap Integer MText) (mkBigMap @[(Integer, MText)] [])+-- ...+--   :: MaybeRPC (BigMap Integer MText)+--+-- >>> :t IsRPC @(BigMap Integer MText) (BigMapId 1)+-- ...+--   :: MaybeRPC (BigMap Integer MText)+data MaybeRPC v where+  NotRPC :: IsoValue  v => v -> MaybeRPC v+  IsRPC :: (SingI (ToT v), IsoValue (AsRPC v), HasRPCRepr v) => AsRPC v -> MaybeRPC v++instance HasNoOp (ToT v) => ToExpression (MaybeRPC v) where+  toExpression = \case+    NotRPC v -> toExpression (toVal v)+    IsRPC v -> withDict (rpcHasNoOpEvi @(ToT v)) $ toExpression (toVal v)++----------------------------------------------------------------------------+-- Derive RPC repr+----------------------------------------------------------------------------++-- | Derive an RPC representation for a type, as well as instances for 'Generic', 'IsoValue' and 'HasRPCRepr'.+--+-- > data ExampleStorage a b = ExampleStorage+-- >   { esField1 :: Integer+-- >   , esField2 :: [BigMap Integer MText]+-- >   , esField3 :: a+-- >   }+-- >   deriving stock Generic+-- >   deriving anyclass IsoValue+-- >+-- > deriveRPC "ExampleStorage"+--+-- Will generate:+--+-- > data ExampleStorageRPC a b = ExampleStorageRPC+-- >   { esField1RPC :: AsRPC Integer+-- >   , esField2RPC :: AsRPC [BigMap Integer MText]+-- >   , esField3RPC :: AsRPC a+-- >   }+-- >+-- > instance HasRPCRepr a => HasRPCRepr (ExampleStorage a b) where+-- >   type AsRPC (ExampleStorage a b) = ExampleStorageRPC a b+-- > deriving anyclass instance (IsoValue (AsRPC a), IsoValue (AsRPC b)) => IsoValue (ExampleStorageRPC a b)+-- > instance Generic (ExampleStorageRPC a b) where+-- >   ...+deriveRPC :: String -> Q [Dec]+deriveRPC typeStr = deriveRPCWithStrategy typeStr haskellBalanced++-- | Recursively enumerate @data@, @newtype@ and @type@ declarations,+-- and derives an RPC representation for each type that doesn't yet have one.+--+-- You can also pass in a list of types for which you _don't_ want+-- an RPC representation to be derived.+--+-- In this example, 'deriveManyRPC' will generate an RPC+-- representation for @A@ and @B@,+-- but not for @C@ (because we explicitly said we don't want one)+-- or @D@ (because it already has one).+--+-- > data B = B+-- > data C = C+-- > data D = D+-- > deriveRPC "D"+-- >+-- > data A = A B C D+-- > deriveManyRPC "A" ["C"]+deriveManyRPC :: String -> [String] -> Q [Dec]+deriveManyRPC typeStr skipTypes =+  deriveManyRPCWithStrategy typeStr skipTypes haskellBalanced++-- | Same as 'deriveManyRPC', but uses a custom strategy for deriving a 'Generic' instance.+deriveManyRPCWithStrategy :: String -> [String] -> GenericStrategy -> Q [Dec]+deriveManyRPCWithStrategy typeStr skipTypes gs = do+  skipTypeNames <- traverse lookupTypeNameOrFail skipTypes+  typeName <- lookupTypeNameOrFail typeStr+  whenM (isTypeAlias typeName) $ fail $ typeStr <> " is a 'type' alias but not 'data' or 'newtype'."+  allTypeNames <- findWithoutInstance typeName+  join <$> forM (allTypeNames List.\\ skipTypeNames) \name -> deriveRPCWithStrategy' name gs+  where++    -- | Recursively enumerate @data@, @newtype@ and @type@ declarations,+    -- and returns the names of only @data@ and @newtype@ of those that+    -- don't yet have an 'AsRPC' instance. Type aliases don't need instances+    -- and respectively there is no need to derive 'AsRPC' for them.+    findWithoutInstance :: Name -> Q [Name]+    findWithoutInstance typeName =+      fmap fst <$>+        reifyManyTyCons+          (\(name, dec) ->+            ifM (isTypeAlias name)+              (pure (False, decConcreteNames dec))+              (ifM (hasRPCInstance name)+                (pure (False, []))+                (pure (True, decConcreteNames dec)))+          )+          [typeName]++    hasRPCInstance :: Name -> Q Bool+    hasRPCInstance typeName = do+      deriveFullTypeFromName typeName >>= \case+        Nothing ->+          fail $ "Found a field with a type that is neither a 'data' nor a 'newtype' nor a 'type': "+            <> show typeName+        Just typ ->+          not . null <$> reifyInstances ''AsRPC [typ]++    -- | Given a type name, return the corresponding type expression+    -- (applied to any type variables, if necessary).+    --+    -- For example, assuming a data type like @data F a b = ...@ exists in the type environment,+    -- then @deriveFullTypeFromName ''F@ will return the type expression @[t|F a b|]@.+    --+    -- Note that only @data@, @newtype@ and @type@ declarations are supported at the moment.+    deriveFullTypeFromName :: Name -> Q (Maybe Type)+    deriveFullTypeFromName typeName = do+      typeInfo <- reify typeName+      case typeInfo of+        TyConI (DataD _ _ vars mKind _ _) -> Just <$> deriveFullType typeName mKind vars+        TyConI (NewtypeD _ _ vars mKind _ _) -> Just <$> deriveFullType typeName mKind vars+        TyConI (TySynD _ vars _) -> Just <$> deriveFullType typeName Nothing vars+        _ -> pure Nothing++-- | Same as 'deriveRPC', but uses a custom strategy for deriving a 'Generic' instance.+deriveRPCWithStrategy :: String -> GenericStrategy -> Q [Dec]+deriveRPCWithStrategy typeStr gs = do+  typeName <- lookupTypeNameOrFail typeStr+  whenM (isTypeAlias typeName) $ fail $ typeStr <> " is a 'type' alias but not 'data' or 'newtype'."+  deriveRPCWithStrategy' typeName gs++deriveRPCWithStrategy' :: Name -> GenericStrategy -> Q [Dec]+deriveRPCWithStrategy' typeName gs = do+  (_, decCxt, mKind, tyVars, constructors) <- reifyDataType typeName++  -- TODO: use `reifyInstances` to check that 'AsRPC' exists for `fieldType`+  -- Print user-friendly error msg if it doesn't.+  let typeNameRPC = convertName typeName+  constructorsRPC <- traverse convertConstructor constructors+  fieldTypes <- getFieldTypes constructors+  fieldTypesRPC <- getFieldTypes constructorsRPC++  derivedType <- deriveFullType typeName mKind tyVars+  derivedTypeRPC <- deriveFullType typeNameRPC mKind tyVars++  -- Note: we can't use `makeRep0Inline` to derive a `Rep` instance for `derivedTypeRPC`+  -- It internally uses `reify` to lookup info about `derivedTypeRPC`, and because `derivedTypeRPC` hasn't+  -- been spliced *yet*, the lookup fails.+  -- So, instead, we fetch the `Rep` instance for `derivedType`, and+  -- append "RPC" to the type/constructor/field names in its metadata.+  --+  -- If, for some reason, we find out that this approach doesn't work for some edge cases,+  -- we should get rid of it and patch the @generic-deriving@ package to export a version of `makeRep0Inline`+  -- that doesn't use `reify` (it should be easy enough).+  repInstance <- reifyRepInstance typeName derivedType+  currentModuleName <- loc_module <$> location+  let repTypeRPC = convertRep currentModuleName repInstance+  typeDecOfRPC <- mkTypeDeclaration typeName decCxt typeNameRPC tyVars mKind constructorsRPC++  mconcat <$> sequence+    [ pure . one $ typeDecOfRPC+    , one <$> mkAsRPCInstance fieldTypes derivedType derivedTypeRPC+    , mkIsoValueInstance fieldTypesRPC derivedTypeRPC+    , customGeneric' (Just repTypeRPC) typeNameRPC derivedTypeRPC constructorsRPC gs+    ]++  where+    -- | Given the field type @FieldType a b@, returns @AsRPC (FieldType a b)@.+    convertFieldType :: Type -> Type+    convertFieldType tp = ConT ''AsRPC `AppT` tp++    convertNameStr :: String -> String+    convertNameStr s = s <> "RPC"++    convertName :: Name -> Name+    convertName = mkName . convertNameStr . nameBase++    -- | Given the constructor+    -- @C { f :: Int }@,+    -- returns the constructor+    -- @CRPC { fRPC :: AsRPC Int }@.+    convertConstructor :: Con -> Q Con+    convertConstructor = \case+      RecC conName fields -> pure $+        RecC+          (convertName conName)+          (fields <&> \(fieldName, fieldBang, fieldType) ->+            (convertName fieldName, fieldBang, convertFieldType fieldType)+          )+      NormalC conName fields -> pure $+        NormalC (convertName conName) (second convertFieldType <$> fields)+      InfixC fieldType1 conName fieldType2 -> pure $+        InfixC (second convertFieldType fieldType1) (convertName conName) (second convertFieldType fieldType2)+      constr -> fail $ "Unsupported constructor for '" <> show typeName <> "': " <> show (ppr constr)++    -- | Get a list of all the unique types of all the fields of all the given constructors.+    getFieldTypes :: [Con] -> Q [Type]+    getFieldTypes constrs = ordNub . join <$> forM constrs \case+      RecC _ fields -> pure $ fields <&> \(_, _, fieldType) -> fieldType+      NormalC _ fields -> pure $ snd <$> fields+      InfixC field1 _ field2 -> pure [snd field1, snd field2]+      constr -> fail $ "Unsupported constructor for '" <> show typeName <> "': " <> show (ppr constr)++    mkTypeDeclaration :: Name -> Cxt -> Name -> [TyVarBndr] -> Maybe Kind -> [Con] -> Q Dec+    mkTypeDeclaration tyName decCxt typeNameRPC tyVars mKind constructorsRPC = do+      typeInfo <- reify tyName+      case typeInfo of+        TyConI DataD {} -> pure $ DataD decCxt typeNameRPC tyVars mKind constructorsRPC []+        TyConI NewtypeD {} -> (case constructorsRPC of+          [con] -> pure $ NewtypeD decCxt typeNameRPC tyVars mKind con []+          _ -> fail "Newtype has only one constructor")+        _ -> fail $ "Only newtypes and data types are supported, but '" <>+          show tyName <> "' is:\n" <> show (ppr typeInfo)++    -- | Traverse a 'Rep' type and:+    --+    -- 1. Inspect its metadata and append @RPC@ to the type/constructor/field names.+    -- 2. Convert field types (e.g. @T@ becomes @AsRPC T@).+    -- 3. Replace the Rep's module name with the name of the module of where this Q is being spliced.+    convertRep :: String -> TySynEqn -> Type+    convertRep currentModuleName (TySynEqn _tyVars _lhs rhs) = go rhs+      where+        go :: Type -> Type+        go = \case+          -- Rename type name and module name+          PromotedT t `AppT` LitT (StrTyLit tyName) `AppT` LitT (StrTyLit _moduleName)+            | t == 'G.MetaData+            -> PromotedT t `AppT` LitT (StrTyLit (convertNameStr tyName)) `AppT` LitT (StrTyLit currentModuleName)+          -- Rename constructor names+          PromotedT t `AppT` LitT (StrTyLit conName)+            | t == 'G.MetaCons+            -> PromotedT t `AppT` LitT (StrTyLit (convertNameStr conName))+          -- Rename field names+          PromotedT t `AppT` (PromotedT just `AppT` LitT (StrTyLit fieldName))+            | t == 'G.MetaSel+            -> PromotedT t `AppT` (PromotedT just `AppT` LitT (StrTyLit (convertNameStr fieldName)))+          -- Replace field type @T@ with @AsRPC T@+          ConT x `AppT` fieldType+            | x == ''G.Rec0+            -> ConT x `AppT` convertFieldType fieldType+          x `AppT` y -> go x `AppT` go y+          x -> x++    -- | Lookup the generic 'Rep' type instance for the given type.+    reifyRepInstance :: Name -> Type -> Q TySynEqn+    reifyRepInstance name tp =+      reifyInstances ''G.Rep [tp] >>= \case+        [TySynInstD repInstance] -> pure repInstance+        (_:_) -> fail $ "Found multiple instances of 'Generic' for '" <> show name <> "'."+        [] -> fail $ "Type '" <> show name <> "' must implement 'Generic'."++    -- | Given the type @Foo a b = Foo (Bar a)@, generate an 'IsoValue' instance like:+    --+    -- > deriving anyclass instance IsoValue (AsRPC (Bar a)) => IsoValue (FooRPC a b)+    --+    -- Note that if a type variable @t@ is a phantom type variable, then no @IsoValue (AsRPC t)@+    -- constraint is generated for it.+    mkIsoValueInstance :: [Type] -> Type -> Q [Dec]+    mkIsoValueInstance fieldTypes tp =+      one <$> standaloneDerivWithStrategyD (Just AnyclassStrategy) constraints [t|IsoValue $(pure tp)|]+      where+        constraints :: Q Cxt+        constraints =+          cxt $ filter hasTyVar fieldTypes <&> \fieldType ->+            [t|IsoValue $(pure fieldType)|]++    -- | Given the type @Foo a b = Foo (Bar a)@, generate an 'HasRPCRepr' instance like:+    --+    -- > instance HasRPCRepr (Bar a) => HasRPCRepr (Foo a b) where+    -- >   type AsRPC (Foo a b) = FooRPC a b+    --+    -- Note that if a type variable @t@ is a phantom type variable, then no @HasRPCRepr@+    -- constraint is generated for it.+    mkAsRPCInstance :: [Type] -> Type -> Type -> Q Dec+    mkAsRPCInstance fieldTypes tp tpRPC = do+      typeInstance <- [d|type instance AsRPC $(pure tp) = $(pure tpRPC)|]+      instanceD constraints [t|HasRPCRepr $(pure tp)|]+        (pure <$> typeInstance)+      where+        constraints :: Q Cxt+        constraints =+          cxt $ filter hasTyVar fieldTypes <&> \fieldType ->+            [t|HasRPCRepr $(pure fieldType)|]++    -- | Checks if the given type has any type variables.+    hasTyVar :: Type -> Bool+    hasTyVar ty =+      flip any (universe ty) \case+        VarT _ -> True+        _ -> False++----------------------------------------------------------------------------+-- Conversions+----------------------------------------------------------------------------++-- | Replace all big_maps in a value with the respective big_map IDs.+--+-- Throws an error if it finds a big_map without an ID.+valueAsRPC :: HasCallStack => Value t -> Value (TAsRPC t)+valueAsRPC v =+  case v of+    VKey {} -> v+    VUnit {} -> v+    VSignature {} -> v+    VChainId {} -> v+    VChest {} -> v+    VChestKey {} -> v+    VOption (vMaybe :: Maybe (Value elem)) ->+      withDict (rpcSingIEvi @elem) $+        VOption $ valueAsRPC <$> vMaybe+    VList (vList :: [Value elem]) ->+      withDict (rpcSingIEvi @elem) $+        VList $ valueAsRPC <$> vList+    VSet {} -> v+    VOp {} -> v+    VContract {} -> v+    VTicket {} -> v+    VPair (x, y) -> VPair (valueAsRPC x, valueAsRPC y)+    VOr (vEither :: Either (Value l) (Value r)) ->+      withDict (rpcSingIEvi @l *** rpcSingIEvi @r) $+        case vEither of+          Right r -> VOr (Right (valueAsRPC r))+          Left l -> VOr (Left (valueAsRPC l))+    VLam {} -> v+    VMap (vMap :: Map (Value k) (Value v)) ->+      withDict (rpcSingIEvi @v) $+        VMap $ valueAsRPC <$> vMap+    VBigMap (Just bmId) _ -> VNat bmId+    VBigMap Nothing _ ->+      error $ unlines+        [ "Expected all big_maps to have an ID, but at least one big_map didn't."+        , "This is most likely a bug."+        ]+    VInt {} -> v+    VNat {} -> v+    VString {} -> v+    VBytes {} -> v+    VMutez {} -> v+    VBool {} -> v+    VKeyHash {} -> v+    VTimestamp {} -> v+    VAddress {} -> v+    VBls12381Fr {} -> v+    VBls12381G1 {} -> v+    VBls12381G2 {} -> v++-- | Replaces all bigmap IDs with their corresponding bigmap values.+-- This is the inverse of `valueAsRPC`.+replaceBigMapIds+  :: forall t m. Monad m+  => (forall k v. (SingI k, SingI v) => Natural -> m (Value ('TBigMap k v)))+  -- ^ A function for looking up a bigmap using its ID.+  -> Sing t -> Value (TAsRPC t) -> m (Value t)+replaceBigMapIds findBigMapById = go+  where+    go :: forall t1. Sing t1 -> Value (TAsRPC t1) -> m (Value t1)+    go s v = case (s, v) of+      (STKey {}, _) -> pure v+      (STUnit {}, _) -> pure v+      (STSignature {}, _) -> pure v+      (STChainId {}, _) -> pure v+      (STChest {}, _) -> pure v+      (STChestKey {}, _) -> pure v+      (STOption sMaybe, VOption vMaybe) ->+        withSingI sMaybe $+          VOption <$> traverse (go sMaybe) vMaybe+      (STList sList, VList vList) ->+        withSingI sList $+          VList <$> traverse (go sList) vList+      (STSet {}, _) -> pure v+      (STOperation {}, _) -> pure v+      (STContract {}, _) -> pure v+      (STTicket {}, _) -> pure v+      (STPair sa sb, VPair (a, b)) -> do+        a' <- go sa a+        b' <- go sb b+        pure $ VPair (a', b')+      (STOr sl sr, VOr vEither) -> withSingI sl $ withSingI sr $+        case vEither of+          Right r -> VOr . Right <$> go sr r+          Left l -> VOr . Left <$> go sl l+      (STLambda {}, _) -> pure v+      (STMap _ sv, VMap vList) ->+        withSingI sv $+          VMap <$> traverse (go sv) vList+      (STBigMap sk sv, VNat bigMapId) -> withSingI sk $ withSingI sv $ findBigMapById bigMapId+      (STInt {}, _) -> pure v+      (STNat {}, _) -> pure v+      (STString {}, _) -> pure v+      (STBytes {}, _) -> pure v+      (STMutez {}, _) -> pure v+      (STBool {}, _) -> pure v+      (STKeyHash {}, _) -> pure v+      (STTimestamp {}, _) -> pure v+      (STAddress {}, _) -> pure v+      (STBls12381Fr {}, _) -> pure v+      (STBls12381G1 {}, _) -> pure v+      (STBls12381G2 {}, _) -> pure v++-- | Replace all @big_map@ annotations in a value with @nat@ annotations.+notesAsRPC :: Notes t -> Notes (TAsRPC t)+notesAsRPC notes =+  case notes of+    NTKey {} -> notes+    NTUnit {} -> notes+    NTSignature {} -> notes+    NTChainId {} -> notes+    NTChest {} -> notes+    NTChestKey {} -> notes+    NTOption typeAnn elemNotes -> NTOption typeAnn $ notesAsRPC elemNotes+    NTList typeAnn elemNotes -> NTList typeAnn $ notesAsRPC elemNotes+    NTSet {} -> notes+    NTOperation {} -> notes+    NTContract {} -> notes+    NTTicket {} -> notes+    NTPair typeAnn fieldAnn1 fieldAnn2 varAnn1 varAnn2 notes1 notes2 ->+      NTPair typeAnn fieldAnn1 fieldAnn2 varAnn1 varAnn2 (notesAsRPC notes1) (notesAsRPC notes2)+    NTOr typeAnn fieldAnn1 fieldAnn2 notes1 notes2 ->+      NTOr typeAnn fieldAnn1 fieldAnn2 (notesAsRPC notes1) (notesAsRPC notes2)+    NTLambda {} -> notes+    NTMap typeAnn keyAnns valueNotes -> NTMap typeAnn keyAnns (notesAsRPC valueNotes)+    NTBigMap typeAnn _ _ -> NTNat typeAnn+    NTInt {} -> notes+    NTNat {} -> notes+    NTString {} -> notes+    NTBytes {} -> notes+    NTMutez {} -> notes+    NTBool {} -> notes+    NTKeyHash {} -> notes+    NTTimestamp {} -> notes+    NTAddress {} -> notes+    NTBls12381Fr {} -> notes+    NTBls12381G1 {} -> notes+    NTBls12381G2 {} -> notes+    NTNever {} -> notes+    NTSaplingState {} -> notes+    NTSaplingTransaction {} -> notes++----------------------------------------------------------------------------+-- Entailments+----------------------------------------------------------------------------++-- | A proof that if a singleton exists for @t@,+-- then so it does for @TAsRPC t@.+rpcSingIEvi :: forall (t :: T). SingI t :- SingI (TAsRPC t)+rpcSingIEvi =+  Sub $+    case sing @t of+      STKey -> Dict+      STUnit {} -> Dict+      STSignature {} -> Dict+      STChainId {} -> Dict+      STChest {} -> Dict+      STChestKey {} -> Dict+      STOption (s :: Sing elem) -> withSingI s $ Dict \\ rpcSingIEvi @elem+      STList (s :: Sing elem) -> withSingI s $  Dict \\ rpcSingIEvi @elem+      STSet (s :: Sing elem) -> withSingI s $ Dict \\ rpcSingIEvi @elem+      STOperation {} -> Dict+      STContract {} -> Dict+      STTicket {} -> Dict+      STPair (sa :: Sing a) (sb :: Sing b) ->+        withSingI sa $ withSingI sb $+          Dict \\ rpcSingIEvi @a \\ rpcSingIEvi @b+      STOr (sl :: Sing l) (sr :: Sing r) ->+        withSingI sl $ withSingI sr $+          Dict \\ rpcSingIEvi @l \\ rpcSingIEvi @r+      STLambda {} -> Dict+      STMap (sk :: Sing k) (sv :: Sing v) ->+        withSingI sk $ withSingI sv $+          Dict \\ rpcSingIEvi @k \\ rpcSingIEvi @v+      STBigMap {} -> Dict+      STInt {} -> Dict+      STNat {} -> Dict+      STString {} -> Dict+      STBytes {} -> Dict+      STMutez {} -> Dict+      STBool {} -> Dict+      STKeyHash {} -> Dict+      STBls12381Fr {} -> Dict+      STBls12381G1 {} -> Dict+      STBls12381G2 {} -> Dict+      STTimestamp {} -> Dict+      STAddress {} -> Dict+      STNever {} -> Dict+      STSaplingState _ -> Dict+      STSaplingTransaction _ -> Dict++-- | A proof that if @t@ is well-typed, then @TAsRPC t@ is also well-typed.+rpcWellTypedEvi :: forall (t :: T). WellTyped t => WellTyped t :- WellTyped (TAsRPC t)+rpcWellTypedEvi = rpcWellTypedEvi' sing++rpcWellTypedEvi'+  :: WellTyped t+  => Sing t+  -> WellTyped t :- WellTyped (TAsRPC t)+rpcWellTypedEvi' sng = Sub $ case sng of+  STKey -> Dict+  STUnit {} -> Dict+  STSignature {} -> Dict+  STChainId {} -> Dict+  STOption s -> Dict \\ rpcWellTypedEvi' s+  STList s -> Dict \\ rpcWellTypedEvi' s+  STSet s -> Dict \\ rpcWellTypedEvi' s+  STOperation {} -> Dict+  STContract s -> Dict \\ rpcWellTypedEvi' s+  STTicket s -> Dict \\ rpcWellTypedEvi' s+  STPair sa sb -> Dict \\ rpcWellTypedEvi' sa \\ rpcWellTypedEvi' sb+  STOr sl sr -> Dict \\ rpcWellTypedEvi' sl \\ rpcWellTypedEvi' sr+  STLambda sa sb -> Dict \\ rpcWellTypedEvi' sa \\ rpcWellTypedEvi' sb+  STMap sk sv -> Dict \\ rpcWellTypedEvi' sk \\ rpcWellTypedEvi' sv+  STBigMap sk sv -> Dict \\ rpcWellTypedEvi' sk \\ rpcWellTypedEvi' sv+  STInt {} -> Dict+  STNat {} -> Dict+  STString {} -> Dict+  STBytes {} -> Dict+  STMutez {} -> Dict+  STBool {} -> Dict+  STKeyHash {} -> Dict+  STBls12381Fr {} -> Dict+  STBls12381G1 {} -> Dict+  STBls12381G2 {} -> Dict+  STTimestamp {} -> Dict+  STAddress {} -> Dict+  STChest {} -> Dict+  STChestKey {} -> Dict+  STNever {} -> Dict+  STSaplingState _ -> Dict+  STSaplingTransaction _ -> Dict++-- | A proof that if @t@ does not contain any operations, then neither does @TAsRPC t@.+rpcHasNoOpEvi :: forall (t :: T). (SingI t, HasNoOp t) => HasNoOp t :- HasNoOp (TAsRPC t)+rpcHasNoOpEvi = rpcHasNoOpEvi' sing++rpcHasNoOpEvi'+  :: HasNoOp t+  => Sing t+  -> HasNoOp t :- HasNoOp (TAsRPC t)+rpcHasNoOpEvi' sng = Sub $ case sng of+  STKey -> Dict+  STUnit {} -> Dict+  STSignature {} -> Dict+  STChainId {} -> Dict+  STChest {} -> Dict+  STChestKey {} -> Dict+  STOption s -> Dict \\ rpcHasNoOpEvi' s+  STList s -> Dict \\ rpcHasNoOpEvi' s+  STSet s -> Dict \\ rpcHasNoOpEvi' s+  STContract {} -> Dict+  STTicket {} -> Dict+  STPair sa sb -> case checkOpPresence sa of+    OpAbsent -> Dict \\ rpcHasNoOpEvi' sa \\ rpcHasNoOpEvi' sb+  STOr sl sr -> case checkOpPresence sl of+    OpAbsent -> Dict \\ rpcHasNoOpEvi' sl \\ rpcHasNoOpEvi' sr+  STLambda {} -> Dict+  STMap _ sv -> case checkOpPresence sv of+    OpAbsent -> Dict \\ rpcHasNoOpEvi' sv+  STBigMap {} -> Dict+  STInt {} -> Dict+  STNat {} -> Dict+  STString {} -> Dict+  STBytes {} -> Dict+  STMutez {} -> Dict+  STBool {} -> Dict+  STKeyHash {} -> Dict+  STBls12381Fr {} -> Dict+  STBls12381G1 {} -> Dict+  STBls12381G2 {} -> Dict+  STTimestamp {} -> Dict+  STAddress {} -> Dict+  STNever {} -> Dict+  STSaplingState {} -> Dict+  STSaplingTransaction {} -> Dict++-- | A proof that @AsRPC (Value t)@ does not contain big_maps.+rpcHasNoBigMapEvi :: forall (t :: T). SingI t => Dict (HasNoBigMap (TAsRPC t))+rpcHasNoBigMapEvi = rpcHasNoBigMapEvi' (sing @t)++rpcHasNoBigMapEvi' :: Sing t -> Dict (HasNoBigMap (TAsRPC t))+rpcHasNoBigMapEvi' = \case+  STKey -> Dict+  STUnit {} -> Dict+  STSignature {} -> Dict+  STChainId {} -> Dict+  STChest {} -> Dict+  STChestKey {} -> Dict+  STOption s -> Dict \\ rpcHasNoBigMapEvi' s+  STList s -> Dict \\ rpcHasNoBigMapEvi' s+  STSet s -> Dict \\ rpcHasNoBigMapEvi' s+  STOperation {} -> Dict+  STContract {} -> Dict+  STTicket {} -> Dict+  STPair sa sb -> Dict \\ rpcHasNoBigMapEvi' sa \\ rpcHasNoBigMapEvi' sb+  STOr sl sr -> Dict \\ rpcHasNoBigMapEvi' sl \\ rpcHasNoBigMapEvi' sr+  STLambda {} -> Dict+  STMap sk sv -> Dict \\ rpcHasNoBigMapEvi' sk \\ rpcHasNoBigMapEvi' sv+  STBigMap {} -> Dict+  STInt {} -> Dict+  STNat {} -> Dict+  STString {} -> Dict+  STBytes {} -> Dict+  STMutez {} -> Dict+  STBool {} -> Dict+  STKeyHash {} -> Dict+  STBls12381Fr {} -> Dict+  STBls12381G1 {} -> Dict+  STBls12381G2 {} -> Dict+  STTimestamp {} -> Dict+  STAddress {} -> Dict+  STNever {} -> Dict+  STSaplingState {} -> Dict+  STSaplingTransaction {} -> Dict++-- | A proof that @AsRPC (Value t)@ does not contain big_maps.+rpcHasNoNestedBigMapsEvi+  :: forall (t :: T).+     SingI t+  => Dict (HasNoNestedBigMaps (TAsRPC t))+rpcHasNoNestedBigMapsEvi = rpcHasNoNestedBigMapsEvi' (sing @t)++rpcHasNoNestedBigMapsEvi' :: Sing t -> Dict (HasNoNestedBigMaps (TAsRPC t))+rpcHasNoNestedBigMapsEvi' = \case+  STKey -> Dict+  STUnit {} -> Dict+  STSignature {} -> Dict+  STChainId {} -> Dict+  STChest {} -> Dict+  STChestKey {} -> Dict+  STOption s -> Dict \\ rpcHasNoNestedBigMapsEvi' s+  STList s -> Dict \\ rpcHasNoNestedBigMapsEvi' s+  STSet s -> Dict \\ rpcHasNoNestedBigMapsEvi' s+  STOperation {} -> Dict+  STContract {} -> Dict+  STTicket {} -> Dict+  STPair sa sb ->+    Dict \\ rpcHasNoNestedBigMapsEvi' sa \\ rpcHasNoNestedBigMapsEvi' sb+  STOr sl sr ->+    Dict \\ rpcHasNoNestedBigMapsEvi' sl \\ rpcHasNoNestedBigMapsEvi' sr+  STLambda {} -> Dict+  STMap sk sv ->+    Dict \\ rpcHasNoNestedBigMapsEvi' sk \\ rpcHasNoNestedBigMapsEvi' sv+  STBigMap {} -> Dict+  STInt {} -> Dict+  STNat {} -> Dict+  STString {} -> Dict+  STBytes {} -> Dict+  STMutez {} -> Dict+  STBool {} -> Dict+  STKeyHash {} -> Dict+  STBls12381Fr {} -> Dict+  STBls12381G1 {} -> Dict+  STBls12381G2 {} -> Dict+  STTimestamp {} -> Dict+  STAddress {} -> Dict+  STNever {} -> Dict+  STSaplingState {} -> Dict+  STSaplingTransaction {} -> Dict++-- | A proof that if @t@ does not contain any contract values, then neither does @TAsRPC t@.+rpcHasNoContractEvi+  :: forall (t :: T).+     (SingI t, HasNoContract t)+  => HasNoContract t :- HasNoContract (TAsRPC t)+rpcHasNoContractEvi = rpcHasNoContractEvi' sing++rpcHasNoContractEvi'+  :: HasNoContract t+  => Sing t+  -> HasNoContract t :- HasNoContract (TAsRPC t)+rpcHasNoContractEvi' sng = Sub $ case sng of+  STKey -> Dict+  STUnit {} -> Dict+  STSignature {} -> Dict+  STChainId {} -> Dict+  STChest {} -> Dict+  STChestKey {} -> Dict+  STOption s -> Dict \\ rpcHasNoContractEvi' s+  STList s -> Dict \\ rpcHasNoContractEvi' s+  STSet _ -> Dict+  STOperation {} -> Dict+  STTicket {} -> Dict+  STPair sa sb -> case checkContractTypePresence sa of+    ContractAbsent ->+      Dict \\ rpcHasNoContractEvi' sa \\ rpcHasNoContractEvi' sb+  STOr sl sr -> case checkContractTypePresence sl of+    ContractAbsent ->+      Dict \\ rpcHasNoContractEvi' sl \\ rpcHasNoContractEvi' sr+  STLambda {} -> Dict+  STMap _ sv -> Dict \\ rpcHasNoContractEvi' sv+  STBigMap {} -> Dict+  STInt {} -> Dict+  STNat {} -> Dict+  STString {} -> Dict+  STBytes {} -> Dict+  STMutez {} -> Dict+  STBool {} -> Dict+  STKeyHash {} -> Dict+  STBls12381Fr {} -> Dict+  STBls12381G1 {} -> Dict+  STBls12381G2 {} -> Dict+  STTimestamp {} -> Dict+  STAddress {} -> Dict+  STNever {} -> Dict+  STSaplingState {} -> Dict+  STSaplingTransaction {} -> Dict++-- | A proof that if @t@ is a valid storage type, then so is @TAsRPC t@.+rpcStorageScopeEvi :: forall (t :: T). StorageScope t :- StorageScope (TAsRPC t)+rpcStorageScopeEvi =+  Sub $ Dict+    \\ rpcSingIEvi @t+    \\ rpcHasNoOpEvi @t+    \\ rpcHasNoNestedBigMapsEvi @t+    \\ rpcHasNoContractEvi @t+    \\ rpcWellTypedEvi @t
src/Morley/CLI.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-orphans #-} @@ -31,17 +30,17 @@ import Options.Applicative   (footerDoc, fullDesc, header, help, helper, info, long, metavar, option, progDesc, strOption,   switch)-import qualified Options.Applicative as Opt+import Options.Applicative qualified as Opt import Options.Applicative.Help.Pretty (Doc) import Text.Read (read)  import Morley.Michelson.Parser (MichelsonSource(..))-import qualified Morley.Michelson.Parser as P+import Morley.Michelson.Parser qualified as P import Morley.Michelson.Runtime (TxData(..), TxParam(..)) import Morley.Michelson.Runtime.GState (genesisAddress) import Morley.Michelson.Text (MText) import Morley.Michelson.Untyped (EpName)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Tezos.Address (Address) import Morley.Tezos.Core (Mutez, Timestamp, parseTimestamp, timestampFromSeconds) import Morley.Tezos.Crypto@@ -61,10 +60,10 @@   -> "parser" :! Opt.Parser s   -> Opt.ParserInfo s parserInfo-  (N usage)-  (N description)-  (N clientHeader)-  (N parser) =+  (arg #usage -> usage)+  (arg #description -> description)+  (arg #header -> clientHeader)+  (arg #parser -> parser) =   info (helper <*> parser) $   mconcat     [ fullDesc
src/Morley/Micheline.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Micheline   ( module Exports
src/Morley/Micheline/Binary.hs view
@@ -1,7 +1,6 @@ -- SPDX-FileCopyrightText: 2020 Tocqueville Group--- SPDX-FileCopyrightText: 2018 obsidian.systems------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA -- SPDX-License-Identifier: LicenseRef-MIT-obsidian-systems  -- | Module that define encoding and decoding function from Expression type@@ -13,12 +12,12 @@   , encodeExpression'   ) where -import qualified Data.Binary.Builder as Bi-import qualified Data.Binary.Get as Bi-import qualified Data.ByteString as BS-import qualified Data.ByteString.Lazy as LBS-import qualified Data.Sequence as Seq-import qualified Unsafe (fromIntegral)+import Data.Binary.Builder qualified as Bi+import Data.Binary.Get qualified as Bi+import Data.ByteString qualified as BS+import Data.ByteString.Lazy qualified as LBS+import Data.Sequence qualified as Seq+import Unsafe qualified (fromIntegral)  import Morley.Micheline.Binary.Internal import Morley.Micheline.Expression
src/Morley/Micheline/Binary/Internal.hs view
@@ -1,7 +1,6 @@ -- SPDX-FileCopyrightText: 2021 Tocqueville Group--- SPDX-FileCopyrightText: 2018 obsidian.systems------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA -- SPDX-License-Identifier: LicenseRef-MIT-obsidian-systems  -- | Defines binary encoding primitives which mimic Tezos' binary encoding.@@ -25,12 +24,12 @@   ) where  import Control.Exception (assert)-import qualified Data.Binary.Builder as Bi-import qualified Data.Binary.Get as Bi+import Data.Binary.Builder qualified as Bi+import Data.Binary.Get qualified as Bi import Data.Bits (Bits, bit, setBit, shift, testBit, zeroBits, (.&.), (.|.))-import qualified Data.ByteString.Lazy as LBS-import qualified Data.Text.Encoding as TE-import qualified Unsafe (fromIntegral)+import Data.ByteString.Lazy qualified as LBS+import Data.Text.Encoding qualified as TE+import Unsafe qualified (fromIntegral)  newtype DynamicSize a = DynamicSize { unDynamicSize :: a } 
src/Morley/Micheline/Class.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Module that provides type classes for converting to and from low-level -- Micheline representation.@@ -12,7 +11,7 @@  import Control.Lens ((<>~)) import Data.Bits (toIntegralSized)-import Data.Default+import Data.Default (def) import Data.Singletons (SingI(..), demote) import Fmt (Buildable(..), indentF, pretty, unlinesF) @@ -27,7 +26,7 @@   (Contract, HasNoOp, Instr, Notes(..), T(..), Value, Value'(..), fromUType, mkUType, rfAnyInstr,   toUType) import Morley.Michelson.Typed.Convert (convertContract, instrToOpsOptimized, untypeValueOptimized)-import qualified Morley.Michelson.Untyped as Untyped+import Morley.Michelson.Untyped qualified as Untyped import Morley.Michelson.Untyped.Annotation   (AnnotationSet(..), FieldAnn, FieldTag, RootAnn, TypeAnn, TypeTag, VarAnn, VarTag, annsCount,   emptyAnnSet, firstAnn, noAnn, secondAnn)@@ -74,7 +73,7 @@ instance ToExpression T where   toExpression = toExpression . toUType -instance SingI t => ToExpression (Notes t) where+instance ToExpression (Notes t) where   toExpression = toExpression . mkUType  instance ToExpression Untyped.T where@@ -116,6 +115,8 @@     Untyped.TChest -> PrimExpr "chest" [] []     Untyped.TChestKey -> PrimExpr "chest_key" [] []     Untyped.TNever -> PrimExpr "never" [] []+    Untyped.TSaplingState n -> PrimExpr "sapling_state" [naturalToExpr n] []+    Untyped.TSaplingTransaction n -> PrimExpr "sapling_transaction" [naturalToExpr n] []      where       addAnns :: Expression -> [Annotation] -> Expression@@ -229,6 +230,7 @@     ISNAT va -> PrimExpr "ISNAT" [] $ mkAnns [] [] [va]     ADD va -> PrimExpr "ADD" [] $ mkAnns [] [] [va]     SUB va -> PrimExpr "SUB" [] $ mkAnns [] [] [va]+    SUB_MUTEZ va -> PrimExpr "SUB_MUTEZ" [] $ mkAnns [] [] [va]     MUL va -> PrimExpr "MUL" [] $ mkAnns [] [] [va]     EDIV va -> PrimExpr "EDIV" [] $ mkAnns [] [] [va]     ABS va -> PrimExpr "ABS" [] $ mkAnns [] [] [va]@@ -286,9 +288,8 @@     OPEN_CHEST va -> PrimExpr "OPEN_CHEST" [] $ mkAnns [] [] [va]     NEVER -> PrimExpr "NEVER" [] []     EXT _ -> ExpressionSeq []-    where-      wordToExpr :: Word -> Expression-      wordToExpr = toExpression @(Value 'TInt) . VInt . fromIntegral @Word @Integer+    SAPLING_EMPTY_STATE va n -> PrimExpr "SAPLING_EMPTY_STATE" [naturalToExpr n] $ mkAnns [] [] [va]+    SAPLING_VERIFY_UPDATE va -> PrimExpr "SAPLING_VERIFY_UPDATE" [] $ mkAnns [] [] [va]  instance ToExpression Untyped.Contract where   toExpression contract@@ -608,6 +609,7 @@     PrimExpr "ISNAT" [] anns -> mkInstrWithVarAnn ISNAT anns     PrimExpr "ADD" [] anns -> mkInstrWithVarAnn ADD anns     PrimExpr "SUB" [] anns -> mkInstrWithVarAnn SUB anns+    PrimExpr "SUB_MUTEZ" [] anns -> mkInstrWithVarAnn SUB_MUTEZ anns     PrimExpr "MUL" [] anns -> mkInstrWithVarAnn MUL anns     PrimExpr "EDIV" [] anns -> mkInstrWithVarAnn EDIV anns     PrimExpr "ABS" [] anns -> mkInstrWithVarAnn ABS anns@@ -688,13 +690,6 @@     _ -> Left $ FromExpressionError e "Expected an instruction"      where-      intExprToWord :: Expression -> Either FromExpressionError Word-      intExprToWord n = do-        v <- fromExpression @(Value 'TInt) n-        case v of-          VInt n' -> maybeToRight (FromExpressionError n "Value is out of bounds")-            (toIntegralSized @Integer @Word n')-       mkInstrWithVarAnn         :: (VarAnn -> ExpandedInstr)         -> [Annotation]@@ -861,6 +856,12 @@     PrimExpr "chest" [] [] -> pure Untyped.TChest     PrimExpr "chest_key" [] [] -> pure Untyped.TChestKey     PrimExpr "never" [] [] -> pure Untyped.TNever+    PrimExpr "sapling_state" [n] [] -> do+      n' <- natExprToNatural n+      pure $ Untyped.TSaplingState n'+    PrimExpr "sapling_transaction" [n] [] -> do+      n' <- natExprToNatural n+      pure $ Untyped.TSaplingState n'     _ -> Left $ FromExpressionError e "Expected a type"     where       mkDoubleParamType@@ -946,7 +947,7 @@   -- Currently this error can't happen because parameter type   -- must be a Micheline primitive. If it ever changes, we   -- would like to notice it ASAP and update this place.-  _ -> error $ "parameter is not a primitive: " <> show expr+  _ -> error $ "parameter is not a primitive: " <> pretty expr  -- | Checks for a given expression that the number of annotations -- of each type in it doesn't exceed the specified threshold.@@ -973,3 +974,22 @@ forbidSingletonList = \case   _ :| [] -> Nothing   x       -> Just x++wordToExpr :: Word -> Expression+wordToExpr = toExpression @(Value 'TInt) . VInt . fromIntegral @Word @Integer++intExprToWord :: Expression -> Either FromExpressionError Word+intExprToWord n = do+  v <- fromExpression @(Value 'TInt) n+  case v of+    VInt n' -> maybeToRight (FromExpressionError n "Value is out of bounds")+      (toIntegralSized @Integer @Word n')++naturalToExpr :: Natural -> Expression+naturalToExpr = toExpression @(Value 'TNat) . VNat++natExprToNatural :: Expression -> Either FromExpressionError Natural+natExprToNatural n = do+  v <- fromExpression @(Value 'TNat) n+  case v of+    VNat n' -> Right n'
src/Morley/Micheline/Expression.hs view
@@ -1,7 +1,6 @@ -- SPDX-FileCopyrightText: 2020 Tocqueville Group--- SPDX-FileCopyrightText: 2018 obsidian.systems------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA -- SPDX-License-Identifier: LicenseRef-MIT-obsidian-systems  {-# LANGUAGE DeriveLift #-}@@ -41,22 +40,22 @@   ) where  import Control.Lens (Plated)-import Control.Lens.TH+import Control.Lens.TH (makeLensesWith, makePrisms)  import Data.Aeson   (FromJSON, ToJSON, object, parseJSON, toEncoding, toJSON, withObject, withText, (.!=), (.:),   (.:?), (.=))-import qualified Data.Aeson.Encoding.Internal as Aeson-import qualified Data.Aeson.Types as Aeson+import Data.Aeson.Encoding.Internal qualified as Aeson+import Data.Aeson.Types qualified as Aeson import Data.Data (Data)-import qualified Data.HashMap.Strict as HashMap-import qualified Data.Sequence as Seq-import qualified Data.Text as T (uncons)+import Data.HashMap.Strict qualified as HashMap+import Data.Sequence qualified as Seq+import Data.Text qualified as T (uncons) import Fmt (Buildable(..), pretty, (+|), (|+))  import Language.Haskell.TH.Lift (Lift) import Morley.Micheline.Json (StringEncode(StringEncode, unStringEncode))-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Michelson.Untyped.Annotation   (AnnotationSet(..), FieldAnn, FieldTag, KnownAnnTag(..), TypeAnn, TypeTag, VarAnn, VarTag,   annPrefix, fullAnnSet, minimizeAnnSet, mkAnnotation)@@ -108,7 +107,7 @@   "never", "NEVER", "UNPAIR", "VOTING_POWER", "TOTAL_VOTING_POWER", "KECCAK", "SHA3", "PAIRING_CHECK",   "bls12_381_g1", "bls12_381_g2", "bls12_381_fr", "sapling_state", "sapling_transaction", "SAPLING_EMPTY_STATE", "SAPLING_VERIFY_UPDATE", "ticket",   "TICKET", "READ_TICKET", "SPLIT_TICKET", "JOIN_TICKETS", "GET_AND_UPDATE", "chest", "chest_key", "OPEN_CHEST",-  "VIEW", "view", "constant"+  "VIEW", "view", "constant", "SUB_MUTEZ"   ]  -- | Type for Micheline Expression
src/Morley/Micheline/Json.hs view
@@ -14,16 +14,17 @@   ) where  import Data.Aeson (FromJSON, ToJSON, parseJSON, toEncoding, toJSON)-import qualified Data.Aeson.Encoding as AE-import qualified Data.Aeson.Types as Aeson+import Data.Aeson.Encoding qualified as AE+import Data.Aeson.Types qualified as Aeson import Data.Bits (Bits) import Data.Typeable (typeRep) import Fmt (Buildable(..))-import qualified Text.Show as T+import Text.Show qualified as T  import Morley.Tezos.Core (Mutez(..), mkMutez)+import Unsafe qualified (unsafeM) -printAsString :: Show a => a -> Aeson.Value+printAsString :: (PrettyShow a, Show a) => a -> Aeson.Value printAsString a = Aeson.String $ show a  parseAsString :: forall a. (Read a, Typeable a) => Aeson.Value -> Aeson.Parser a@@ -54,7 +55,7 @@   parseJSON = parseStringEncodedIntegral  instance Buildable TezosInt64 where-  build = show+  build = show . unStringEncode  instance ToJSON TezosInt64 where   toJSON (StringEncode x) = Aeson.String $ show x@@ -68,13 +69,14 @@  instance FromJSON TezosMutez where   parseJSON v = do-    i <- parseAsString @Int64 v-    either (fail . toString) (pure . TezosMutez) $ mkMutez i+    i     <- parseAsString @Int64 v+    mutez <- Unsafe.unsafeM $ mkMutez i+    pure $ TezosMutez mutez  type TezosNat = StringEncode Natural  instance Buildable TezosNat where-  build = show+  build = show . unStringEncode  instance ToJSON TezosNat where   toJSON (StringEncode x) = Aeson.String $ show x
src/Morley/Michelson/Analyzer.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Static analysis of Michelson code. @@ -10,10 +9,10 @@   ) where  import Data.Default (def)-import qualified Data.HashMap.Strict as HM-import qualified Data.List.NonEmpty as NE+import Data.HashMap.Strict qualified as HM+import Data.List.NonEmpty qualified as NE import Fmt (Buildable(..), Builder, blockMapF', hexF, nameF, (+|))-import qualified Unsafe (fromIntegral)+import Unsafe qualified (fromIntegral)  import Morley.Michelson.FailPattern import Morley.Michelson.Text (MText)
src/Morley/Michelson/Doc.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# LANGUAGE TypeFamilyDependencies, UndecidableSuperClasses #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-}@@ -44,6 +43,7 @@   , buildDoc   , buildMarkdownDoc   , modifyDoc+  , docBlockToMarkdown    , DGeneralInfoSection (..)   , DName (..)@@ -61,18 +61,18 @@   , attachDocCommons   ) where -import qualified Data.Map as M-import qualified Data.Map.Merge.Strict as M-import qualified Data.Set as S-import qualified Data.Text as T-import qualified Data.Text.Lazy as LT+import Data.Map qualified as M+import Data.Map.Merge.Strict qualified as M+import Data.Set qualified as S+import Data.Text qualified as T+import Data.Text.Lazy qualified as LT import Data.Typeable (cast, typeRep) import Development.GitRev (gitCommitDate, gitHash)-import Fmt (Buildable, build, fmt, (+|), (+||), (|+), (||+))-import qualified Language.Haskell.TH as TH-import qualified Language.Haskell.TH.Lift as TH+import Fmt (Buildable, build, fmt, (+|), (|+))+import Language.Haskell.TH qualified as TH+import Language.Haskell.TH.Lift qualified as TH import System.Environment (lookupEnv)-import qualified Text.Show+import Text.Show qualified  import Morley.Util.Instances () import Morley.Util.Lens@@ -337,7 +337,8 @@   where     onTypeMismatch =       error $ "appending doc sections for doc items of different types:"-              +|| typeRep (Proxy @d1) ||+ " and " +|| typeRep (Proxy @d2) ||+ ""+              +| show @Text (typeRep (Proxy @d1)) |+ " and "+              +| show @Text (typeRep (Proxy @d2)) |+ ""  -- | A map from positions to document elements. --@@ -445,7 +446,7 @@ lookupDocBlockSection block = do   DocSection (ds :: NonEmpty (DocElem d')) <- M.lookup (docItemPosition @d) block   case eqT @d @d' of-    Nothing -> error $ "Invalid DocBlock: item of type " +|| typeRep (Proxy @d) ||+ " \+    Nothing -> error $ "Invalid DocBlock: item of type " +| show @Text (typeRep (Proxy @d)) |+ " \                        \under position " +| docItemPosition @d |+ ""     Just Refl -> pure $ map deItem ds @@ -717,7 +718,7 @@               \environmental variable."             return Nothing           TH.LitE (TH.StringL str) -> return (Just str)-          value -> error $ "Unknown value returned by git: " <> show value+          value -> error $ "Unknown value returned by git: " <> show (TH.ppr value)  instance DocItem DGitRevision where   docItemPos = 2
src/Morley/Michelson/ErrorPos.hs view
@@ -1,10 +1,8 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.ErrorPos   ( mkPos-  , unsafeMkPos   , Pos (..)   , SrcPos (..)   , srcPos@@ -13,33 +11,27 @@   , LetName (..)   ) where +import Unsafe qualified (fromIntegral)+ import Data.Aeson.TH (deriveJSON) import Data.Data (Data(..)) import Data.Default (Default(..))-import qualified Data.Text as T+import Data.Text qualified as T import Fmt (Buildable(..)) import Morley.Michelson.Printer.Util (RenderDoc(..), buildRenderDocExtended, renderAnyBuildable)-import Text.PrettyPrint.Leijen.Text-import qualified Unsafe (fromIntegral)-+import Text.PrettyPrint.Leijen.Text (list, (<+>))  import Morley.Util.Aeson - newtype Pos = Pos {unPos :: Word}   deriving stock (Eq, Ord, Show, Generic, Data)  instance NFData Pos -unsafeMkPos :: Int -> Pos-unsafeMkPos x-  | x < 0     = error $ "negative pos: " <> show x-  | otherwise = Pos $ Unsafe.fromIntegral @Int @Word x--mkPos :: Int -> Maybe Pos+mkPos :: Int -> Either Text Pos mkPos x-  | x < 0     = Nothing-  | otherwise = Just $ Pos $ Unsafe.fromIntegral @Int @Word x+  | x < 0     = Left $ "negative pos: " <> show x+  | otherwise = Right $ Pos $ Unsafe.fromIntegral @Int @Word x  data SrcPos =   SrcPos@@ -72,7 +64,7 @@     "Error occurred on line" <+> (renderAnyBuildable (row + 1)) <+> "char" <+> (renderAnyBuildable (col + 1))     <> case icsCallStack of          [] -> "."-         _ -> " inside these let defenitions:" <+> (list $ fmap (text . show) icsCallStack) <> "."+         _ -> " inside these let defenitions:" <+> (list $ fmap renderAnyBuildable icsCallStack) <> "."  instance Buildable InstrCallStack where   build = buildRenderDocExtended
src/Morley/Michelson/FailPattern.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- NOTE this pragmas. -- We disable some wargnings for the sake of speed up.@@ -27,7 +26,7 @@ data TypicalFailWith   = FailWithString MText   -- ^ Push a constant string and fail with it.-  | FailWithConstantPair MText (SomeConstrainedValue ConstantScope)+  | FailWithConstantPair MText SomeConstant   -- ^ Push a constant pair where the first item is a string and the   -- second one is an arbitrary constant. Fail afterwards.   | FailWithStackValue MText@@ -69,7 +68,7 @@   | VPair (VString str, secondItem) <- v =       -- We need to pattern match to deduce `singI` for second item of the pair.       case sing @t of-        STPair l r -> withSingI l $ withSingI r $ Just (FailWithConstantPair str (SomeConstrainedValue secondItem))+        STPair l r -> withSingI l $ withSingI r $ Just (FailWithConstantPair str (SomeConstant secondItem))   | otherwise = Nothing  -- | If given instruction ends with a typical 'FAILWITH' usage, modify@@ -77,7 +76,7 @@ -- return any value, not necessarily a string. modifyTypicalFailWith   :: HasCallStack-  => (MText -> SomeConstrainedValue ConstantScope)+  => (MText -> SomeConstant)   -> Instr inp out   -> Instr inp out modifyTypicalFailWith f = modifyTypicalFailWith' . linearizeLeft@@ -98,7 +97,7 @@               , _ :: Instr (b ': s) ('TPair a b ': s) <- i1 ->                 case sing @('TPair a b) of                   STPair l r -> withSingI l $ withSingI r $ case isStringValue v of-                    Just (f -> SomeConstrainedValue v') ->+                    Just (f -> SomeConstant v') ->                       PUSH v' `Seq` PAIR `Seq` FAILWITH                     Nothing ->                       PUSH v `Seq` PAIR `Seq` FAILWITH@@ -107,7 +106,7 @@               , _ :: Instr s0 ('TPair a b ': s) <- i1 ->                 case sing @('TPair a b) of                   STPair l r -> withSingI l $ withSingI r $ Seq i0 $ case isStringValue v of-                    Just (f -> SomeConstrainedValue v') ->+                    Just (f -> SomeConstant v') ->                       PUSH v' `Seq` PAIR `Seq` FAILWITH                     Nothing ->                       PUSH v `Seq` PAIR `Seq` FAILWITH@@ -119,8 +118,8 @@     onPush ::       (HasCallStack, ConstantScope v) => Value v -> Instr inp out     onPush v = case isTypicalErrorConstant v of-      Just (FailWithString (f -> SomeConstrainedValue v')) -> PUSH v' `Seq` FAILWITH-      Just (FailWithConstantPair (f -> SomeConstrainedValue v') (SomeConstrainedValue arg)) ->+      Just (FailWithString (f -> SomeConstant v')) -> PUSH v' `Seq` FAILWITH+      Just (FailWithConstantPair (f -> SomeConstant v') (SomeConstant arg)) ->         PUSH (VPair (v', arg)) `Seq` FAILWITH       Just _ -> error "Unexpected TypicalFailWith"       Nothing -> PUSH v `Seq` FAILWITH
src/Morley/Michelson/Interpret.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ -- | Module, containing function to interpret Michelson -- instructions against given context and input stack. module Morley.Michelson.Interpret@@ -50,13 +52,13 @@ import Control.Monad.RWS.Strict (RWS, RWST, runRWS) import Control.Monad.Writer (MonadWriter, WriterT, tell) import Data.Default (Default(..))-import qualified Data.Map as Map-import qualified Data.Set as Set+import Data.Map qualified as Map+import Data.Set qualified as Set import Data.Singletons.Decide (decideEquality) import Data.Vinyl (Rec(..), (<+>)) import Data.Vinyl.Recursive (rmap)-import Fmt (Buildable(build), blockListF, pretty, prettyLn)-import qualified Unsafe (fromIntegral)+import Fmt (Buildable(build), blockListF, pretty, prettyLn, (+|), (|+))+import Unsafe qualified (fromIntegral)  import Morley.Michelson.ErrorPos (InstrCallStack(..)) import Morley.Michelson.Interpret.Pack (packValue')@@ -64,10 +66,10 @@ import Morley.Michelson.Runtime.GState import Morley.Michelson.TypeCheck (matchTypes) import Morley.Michelson.Typed hiding (Branch(..))-import qualified Morley.Michelson.Typed as T+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Typed.Operation   (OperationHash(..), OriginationOperation(..), mkContractAddress, mkOriginationOperationHash)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Michelson.Untyped.Annotation (annQ) import Morley.Tezos.Address (Address(..), GlobalCounter(..)) import Morley.Tezos.Core (ChainId, Mutez, Timestamp, zeroMutez)@@ -175,10 +177,11 @@ data MichelsonFailed where   MichelsonFailedWith :: (SingI t, ConstantScope t) => T.Value t -> MichelsonFailed   MichelsonArithError-    :: (Typeable n, Typeable m, Typeable instr)-    => ArithError (Value' instr n) (Value' instr m) -> MichelsonFailed+    :: (Typeable n, Typeable m)+    => ArithError (Value n) (Value m) -> MichelsonFailed   MichelsonGasExhaustion :: MichelsonFailed   MichelsonFailedTestAssert :: Text -> MichelsonFailed+  MichelsonUnsupported :: Text -> MichelsonFailed  deriving stock instance Show MichelsonFailed @@ -191,16 +194,20 @@   MichelsonGasExhaustion == _ = False   MichelsonFailedTestAssert t1 == MichelsonFailedTestAssert t2 = t1 == t2   MichelsonFailedTestAssert _ == _ = False+  MichelsonUnsupported i1 == MichelsonUnsupported i2 = i1 == i2+  MichelsonUnsupported _ == _ = False  instance Buildable MichelsonFailed where   build =     \case       MichelsonFailedWith v ->-        "Reached FAILWITH instruction with " <> build v+        "Reached FAILWITH instruction with " +| v |+ ""       MichelsonArithError v -> build v       MichelsonGasExhaustion ->         "Gas limit exceeded on contract execution"       MichelsonFailedTestAssert t -> build t+      MichelsonUnsupported instr ->+        build instr <> " instruction is not supported."  -- | Carries a 'MichelsonFailed' error and the 'InstrCallStack' at which it was raised data MichelsonFailureWithStack = MichelsonFailureWithStack@@ -495,8 +502,10 @@     go :: forall (n :: Peano) inp out a. ConstraintDIG n inp out a        => PeanoNatural n -> Rec StkEl inp -> Rec StkEl out     go Zero stack = stack-    go (Succ n') (b :& r) = case go n' r of-      (a :& resTail) -> a :& b :& resTail+    go (Succ n') (b :& r) =+      case klist @inp of+        KCons _ Proxy -> case go n' r of+          (a :& resTail) -> a :& b :& resTail runInstrImpl _ (DUG s) input0 =   pure $ go s input0   where@@ -667,6 +676,7 @@   else pure $ starNotesStkEl (VOption (Just (VNat $ fromInteger i))) :& r runInstrImpl _ ADD (l :& r :& rest) = (:& rest) <$> runArithOp (Proxy @Add) l r runInstrImpl _ SUB (l :& r :& rest) = (:& rest) <$> runArithOp (Proxy @Sub) l r+runInstrImpl _ SUB_MUTEZ (l :& r :& rest) = (:& rest) <$> runArithOp (Proxy @SubMutez) l r runInstrImpl _ MUL (l :& r :& rest) = (:& rest) <$> runArithOp (Proxy @Mul) l r runInstrImpl _ EDIV (l :& r :& rest) = (:& rest) <$> runArithOp (Proxy @EDiv) l r runInstrImpl _ ABS ((seValue -> a) :& rest) =@@ -883,6 +893,8 @@           BogusCipher   -> VOr (Right (VBool False))         Left _ -> VOr (Right (VBool True))   pure $ starNotesStkEl result :& r+runInstrImpl _ (SAPLING_EMPTY_STATE _) _ = throwMichelson $ MichelsonUnsupported "SAPLING_EMPTY_STATE"+runInstrImpl _ SAPLING_VERIFY_UPDATE _ = throwMichelson $ MichelsonUnsupported "SAPLING_VERIFY_UPDATE"  -- | Evaluates an arithmetic operation and either fails or proceeds. runArithOp@@ -965,17 +977,22 @@ assignBigMapIds' :: EvalM m => Value t -> m (Value t) assignBigMapIds' val = do   bigMapCounter0 <- view isBigMapCounterL <$> getInterpreterState-  let (storageWithIds, bigMapCounter1) = runState (assignBigMapIds val) bigMapCounter0+  let (storageWithIds, bigMapCounter1) = runState (assignBigMapIds True val) bigMapCounter0   modifyInterpreterState (set isBigMapCounterL bigMapCounter1)   pure storageWithIds  -- | All big_maps stored in a chain have a globally unique ID. -- -- We use this function to assign a new ID whenever a big_map is created.-assignBigMapIds :: MonadState BigMapCounter m => Value t -> m (Value t)-assignBigMapIds =+assignBigMapIds+  :: (MonadState BigMapCounter m)+  => Bool+  -- ^ If true, assign a new ID even if the bigmap already has one.+  -- Otherwise, assign IDs only to bigmaps that don't have one yet.+  -> Value t -> m (Value t)+assignBigMapIds overwriteExistingId =   dfsTraverseValue \case-    VBigMap _ vBigMap -> do+    VBigMap existingId vBigMap | overwriteExistingId || isNothing existingId -> do       bigMapId <- bigMapCounter <<+= 1       pure $ VBigMap (Just bigMapId) vBigMap     v -> pure v
src/Morley/Michelson/Interpret/Pack.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Module, carrying logic of @PACK@ instruction. --
src/Morley/Michelson/Interpret/Unpack.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {- | Module, carrying logic of @UNPACK@ instruction. @@ -24,16 +23,16 @@  import Prelude hiding (EQ, Ordering(..), get) -import qualified Data.ByteString as BS+import Data.ByteString qualified as BS import Data.Constraint (Dict(..)) import Fmt (pretty)  import Morley.Micheline.Binary (eitherDecodeExpression) import Morley.Micheline.Class (FromExpression(..)) import Morley.Michelson.Typed (UnpackedValScope)-import qualified Morley.Michelson.Typed as T+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Untyped-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Util.Binary  {- Implementation notes:
src/Morley/Michelson/Interpret/Utils.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | General utilities used by interpreter. --@@ -10,8 +9,8 @@   ) where  import Control.Exception (assert)-import qualified Data.Bits as Bits-import qualified Unsafe (fromIntegral)+import Data.Bits qualified as Bits+import Unsafe qualified (fromIntegral)  -- | Encode a number as tezos does this. --
src/Morley/Michelson/Let.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Let   ( LetType (..)@@ -8,7 +7,7 @@   ) where  import Data.Aeson.TH (deriveJSON)-import qualified Data.Text as T+import Data.Text qualified as T  import Morley.Michelson.Macro (ParsedOp) import Morley.Michelson.Untyped (Ty, Value')@@ -20,6 +19,8 @@   , lvSig :: Ty   , lvVal :: (Value' ParsedOp)   } deriving stock (Eq, Show)++{-# DEPRECATED LetValue, LetType "Let macros are deprecated" #-}  -- | A programmer-defined type-synonym data LetType = LetType
src/Morley/Michelson/Macro.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ module Morley.Michelson.Macro   (   -- * Macros types@@ -39,8 +41,8 @@  import Data.Aeson.TH (deriveJSON) import Data.Data (Data(..))-import qualified Data.Text as T-import Fmt (Buildable(build), GenericBuildable(..), (+|), (+||), (|+), (||+))+import Data.Text qualified as T+import Fmt (Buildable(build), GenericBuildable(..), (+|), (|+))  import Morley.Michelson.ErrorPos import Morley.Michelson.Printer (RenderDoc(..))@@ -58,6 +60,8 @@   deriving stock (Eq, Show, Data, Generic)   deriving Buildable via GenericBuildable LetMacro +{-# DEPRECATED LetMacro "Let macros are deprecated" #-}+ instance NFData LetMacro  data PairStruct@@ -115,6 +119,10 @@  type ParsedValue = Value' ParsedOp +{-# DEPRECATED+  CASE, TAG, ACCESS, SET, CONSTRUCT, VIEW_, VOID+  "Morley-specific macros are deprecated" #-}+ -- | Built-in Michelson Macros defined by the specification data Macro   = CASE (NonEmpty [ParsedOp])@@ -151,10 +159,10 @@  instance Buildable Macro where   build = \case-    TAG idx ty -> "<TAG: #"+||idx||+" from "+|toList ty|+""+    TAG idx ty -> "<TAG: #"+|idx|+" from "+|toList ty|+""     CASE parsedInstrs -> "<CASE: "+|toList parsedInstrs|+">"-    ACCESS idx size -> "<ACCESS: #"+||idx||+"/"+|size|+""-    SET idx size -> "<SET: #"+||idx||+"/"+|size|+""+    ACCESS idx size -> "<ACCESS: #"+|idx|+"/"+|size|+""+    SET idx size -> "<SET: #"+|idx|+"/"+|size|+""     CONSTRUCT parsedInstrs -> "<CONSTRUCT: "+|toList parsedInstrs|+">"     VIEW_ code -> "<VIEW_: "+|code|+">"     VOID code -> "<VOID: "+|code|+">"@@ -165,8 +173,8 @@     PAPAIR pairStruct typeAnn varAnn -> "<PAPAIR: "+|pairStruct|+", "+|typeAnn|+", "+|varAnn|+">"     UNPAPAIR pairStruct -> "<UNPAPAIR: "+|pairStruct|+">"     CADR cadrStructs varAnn fieldAnn -> "<CADR: "+|cadrStructs|+", "+|varAnn|+", "+|fieldAnn|+">"-    CARN varAnn idx -> "<CAR: #"+||idx||+","+||varAnn||+">"-    CDRN varAnn idx -> "<CDR: #"+||idx||+","+||varAnn||+">"+    CARN varAnn idx -> "<CAR: #"+|idx|+","+|varAnn|+">"+    CDRN varAnn idx -> "<CDR: #"+|idx|+","+|varAnn|+">"     SET_CADR cadrStructs varAnn fieldAnn -> "<SET_CADR: "+|cadrStructs|+", "+|varAnn|+", "+|fieldAnn|+">"     MAP_CADR cadrStructs varAnn fieldAnn parsedOps -> "<MAP_CADR: "+|cadrStructs|+", "+|varAnn|+", "+|fieldAnn|+", "+|parsedOps|+">"     DIIP integer parsedOps -> "<DIIP: "+|integer|+", "+|parsedOps|+">"
src/Morley/Michelson/Optimizer.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- NOTE this pragmas. -- We disable some wargnings for the sake of speed up.@@ -8,6 +7,9 @@ {-# OPTIONS_GHC -Wno-incomplete-patterns #-} {-# OPTIONS_GHC -Wno-overlapping-patterns #-} +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ -- | Optimizer for typed instructions. -- -- It's quite experimental and incomplete.@@ -28,9 +30,11 @@ import Prelude hiding (EQ, GT, LT)  import Control.Lens (makeLensesFor)-import Data.Constraint (Dict(..))+import Data.Constraint (Dict(..), (\\)) import Data.Default (Default(def)) import Data.Singletons (sing)+import Data.Type.Equality ((:~:)(Refl))+import Unsafe.Coerce (unsafeCoerce)  import Morley.Michelson.Interpret.Pack (packValue') import Morley.Michelson.Typed.Aliases (Value)@@ -39,9 +43,11 @@ import Morley.Michelson.Typed.Scope (ConstantScope, PackedValScope, checkScope) import Morley.Michelson.Typed.Sing import Morley.Michelson.Typed.T-import Morley.Michelson.Typed.Util (DfsSettings(..), dfsInstr)+import Morley.Michelson.Typed.Util (DfsSettings(..), dfsModifyInstr) import Morley.Michelson.Typed.Value+import Morley.Util.Peano import Morley.Util.PeanoNatural+import Morley.Util.Type  ---------------------------------------------------------------------------- -- High level@@ -75,10 +81,8 @@ optimizeWithConf (OptimizerConf ocGotoValues rules) instr = foldl (flip performOneStage) instrRHS rules   where     dfsSettings = def{ dsGoToValues = ocGotoValues }-    performOneStage stageRules = (fst .)-      $ dfsInstr dfsSettings-      $ (adapter .)-      $ applyOnce stageRules+    performOneStage stageRules =+      dfsModifyInstr dfsSettings $ applyOnce stageRules     instrRHS = applyOnce (fixpoint flattenSeqLHS) instr  ----------------------------------------------------------------------------@@ -130,8 +134,12 @@     `orSimpleRule` simpleDrops     `orSimpleRule` internalNop     `orSimpleRule` simpleDips+    `orSimpleRule` simpleDups     `orSimpleRule` adjacentDips     `orSimpleRule` isSomeOnIf+    `orSimpleRule` redundantIf+    `orSimpleRule` emptyDip+    `orSimpleRule` digDug     `orSimpleRule` specificPush     `orSimpleRule` pairUnpair     `orSimpleRule` pairMisc@@ -359,6 +367,14 @@    _ -> Nothing +simpleDups :: Rule+simpleDups = Rule $ \case+  -- DUP 1 is just DUP+  DUPN One :# xs -> Just $ DUP :# xs+  DUPN One -> Just $ DUP++  _ -> Nothing+ adjacentDips :: Rule adjacentDips = Rule $ \case   DIP f :# DIP g -> Just (DIP (f :# g))@@ -366,6 +382,62 @@    _ -> Nothing +redundantIf :: Rule+redundantIf = Rule \case+  IF x y :# xs+    | x == y+    -> Just $ DROP :# x :# xs+  IF x y+    | x == y+    -> Just $ DROP :# x+  _ -> Nothing++emptyDip :: Rule+emptyDip = Rule \case+  DIP Nop :# xs -> Just xs+  DIP Nop -> Just Nop+  DIPN _ Nop :# xs -> Just xs+  DIPN _ Nop -> Just Nop+  _ -> Nothing++digDug :: Rule+digDug = Rule \case+  (DIG (x :: PeanoNatural n) :: Instr inp t) :# (DUG y :: Instr t out) :# xs+    | Just Refl <- eqPeanoNat x y+    -> Just xs \\ digDugProof @inp @out @t @n (singPeanoNat x)+  (DIG (x :: PeanoNatural n) :: Instr inp t) :# (DUG y :: Instr t out)+    | Just Refl <- eqPeanoNat x y+    -> Just Nop \\ digDugProof @inp @out @t @n (singPeanoNat x)+  _ -> Nothing++digDugProof+  :: forall inp out t n a.+     ( KnownList inp+     , inp ~ (Take n inp ++ (a ': Drop ('S n) inp))+     , t ~ (a ': Take n inp ++ Drop ('S n) inp)+     , out ~ (Take n (Drop ('S 'Z) t) ++ (a ': Drop ('S n) t))+     )+  => SingNat n -> inp :~: out+{-# RULES "digDugProof" forall n. digDugProof n = unsafeCoerce Refl #-}+{-# INLINE[1] digDugProof #-}+digDugProof n = Refl+  \\ lemma1 n inpS+  \\ lemma2 n inpS+  where+    inpS = klist @inp+    lemma1 :: forall xs m. SingNat m -> KList xs -> Take m xs :~: Take m (Take m xs ++ Drop ('S m) xs)+    lemma1 = \case+      SZ -> const Refl+      SS m -> \case+        KNil -> Refl+        KCons _ (Proxy :: Proxy ys) -> Refl \\ lemma1 m (klist @ys)+    lemma2 :: forall xs m. SingNat m -> KList xs -> Drop ('S m) xs :~: Drop m (Take m xs ++ Drop ('S m) xs)+    lemma2 = \case+      SZ -> const Refl+      SS m -> \case+        KNil -> Refl+        KCons _ (Proxy :: Proxy ys) -> lemma2 m (klist @ys)+ -- TODO (#299): optimize sequences of more than 2 DROPs. -- | Sequences of @DROP@s can be turned into single @DROP n@. -- When @n@ is greater than 2 it saves size and gas.@@ -553,6 +625,7 @@   CONCAT       :# DROP :# c -> Just $ DROP :# DROP :# c   ADD          :# DROP :# c -> Just $ DROP :# DROP :# c   SUB          :# DROP :# c -> Just $ DROP :# DROP :# c+  SUB_MUTEZ    :# DROP :# c -> Just $ DROP :# DROP :# c   MUL          :# DROP :# c -> Just $ DROP :# DROP :# c   EDIV         :# DROP :# c -> Just $ DROP :# DROP :# c   OR           :# DROP :# c -> Just $ DROP :# DROP :# c@@ -570,6 +643,7 @@   CONCAT       :# DROP      -> Just $ DROP :# DROP   ADD          :# DROP      -> Just $ DROP :# DROP   SUB          :# DROP      -> Just $ DROP :# DROP+  SUB_MUTEZ    :# DROP      -> Just $ DROP :# DROP   MUL          :# DROP      -> Just $ DROP :# DROP   EDIV         :# DROP      -> Just $ DROP :# DROP   OR           :# DROP      -> Just $ DROP :# DROP@@ -622,10 +696,6 @@ -- | Apply the rule once, if it fails, return the instruction unmodified. applyOnce :: Rule -> Instr inp out -> Instr inp out applyOnce r i = maybe i id (unRule r $ i)---- | An adapter for `dfsInstr`.-adapter :: a -> (a, ())-adapter a = (a, ())  -- | Apply a rule to the same code, until it fails. whileApplies :: Rule -> Rule
src/Morley/Michelson/Parser.hs view
@@ -1,13 +1,16 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations -Wno-redundant-constraints #-}+ module Morley.Michelson.Parser   ( -- * Main parser type     Parser    -- * Parsers   , program+  , programExt   , value    -- * Errors@@ -38,6 +41,7 @@   -- * Quoters   , utypeQ   , uparamTypeQ+  , notes    -- * Re-exports   , errorBundlePretty@@ -45,17 +49,18 @@  import Prelude hiding (try) -import Fmt (pretty)-import qualified Language.Haskell.TH.Lift as TH-import qualified Language.Haskell.TH.Quote as TH+import Data.Default (Default(..))+import Fmt (pretty, (+|), (|+))+import Language.Haskell.TH qualified as TH+import Language.Haskell.TH.Lift qualified as TH+import Language.Haskell.TH.Quote qualified as TH import Text.Megaparsec   (Parsec, choice, customFailure, eitherP, eof, errorBundlePretty, getSourcePos, hidden, lookAhead,   parse, sepEndBy, try) import Text.Megaparsec.Pos (SourcePos(..), unPos) -import Morley.Michelson.ErrorPos (SrcPos(..), unsafeMkPos)-import Morley.Michelson.Macro-  (LetMacro, Macro(..), ParsedInstr, ParsedOp(..), ParsedValue, expandValue)+import Morley.Michelson.ErrorPos (SrcPos(..), mkPos)+import Morley.Michelson.Macro (Macro(..), ParsedInstr, ParsedOp(..), ParsedValue, expandValue) import Morley.Michelson.Parser.Annotations (noteF) import Morley.Michelson.Parser.Common import Morley.Michelson.Parser.Error@@ -67,8 +72,9 @@ import Morley.Michelson.Parser.Type import Morley.Michelson.Parser.Types import Morley.Michelson.Parser.Value+import Morley.Michelson.Typed.Extract (withUType) import Morley.Michelson.Untyped-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U  ---------------------------------------------------------------------------- -- Helpers@@ -76,11 +82,12 @@  -- | Parse with empty environment parseNoEnv ::-     Parser a+     Default le+  => Parser' le a   -> MichelsonSource   -> Text   -> Either (ParseErrorBundle Text CustomParserException) a-parseNoEnv p src = parse (runReaderT p noLetEnv <* eof) (pretty src)+parseNoEnv p src = parse (runReaderT p def <* eof) (pretty src)  ------------------------------------------------------------------------------- -- Parsers@@ -89,20 +96,27 @@ -- Contract ------------------ --- | Michelson contract with let definitions+-- | Michelson contract program :: Parsec CustomParserException Text (Contract' ParsedOp)-program = runReaderT programInner noLetEnv <* eof-  where-    programInner :: Parser (Contract' ParsedOp)-    programInner = do-      mSpace-      env <- fromMaybe noLetEnv <$> (optional (letBlock parsedOp))-      local (const env) contract+program = runReaderT (programInner @()) def <* eof -cbParameter :: Parser ParameterType-cbParameter = symbol "parameter" *> cbParameterBare+programInner+  :: forall env. (Default env)+  => Parser env (Contract' ParsedOp)+programInner = do+  mSpace+  env <- fromMaybe def <$> (optional (letBlock parsedOp))+  local (const env) contract -cbParameterBare :: Parser ParameterType+-- TODO [#712]: Remove this next major release+-- | Michelson contract with let definitions+programExt :: Parsec CustomParserException Text (Contract' ParsedOp)+programExt = runReaderT (programInner @LetEnv) def <* eof++cbParameter :: Parser le ParameterType+cbParameter = symbol1 "parameter" *> cbParameterBare++cbParameterBare :: Parser le ParameterType cbParameterBare = do   prefixRootAnn <- optional noteF   (inTypeRootAnn, t) <- field@@ -115,13 +129,13 @@     (Just _, _) -> customFailure MultiRootAnnotationException   pure $ ParameterType t rootAnn -cbStorage :: Parser Ty-cbStorage = symbol "storage" *> type_+cbStorage :: Parser le Ty+cbStorage = symbol1 "storage" *> type_ -cbCode :: Parser [ParsedOp]+cbCode :: Parser le [ParsedOp] cbCode = symbol "code" *> codeEntry -cbView :: Parser (View' ParsedOp)+cbView :: Parser le (View' ParsedOp) cbView = do   symbol "view"   viewName <- viewName_@@ -130,7 +144,7 @@   viewCode <- ops   return View{..} -contractBlock :: Parser (ContractBlock ParsedOp)+contractBlock :: Parser le (ContractBlock ParsedOp) contractBlock = choice   [ (CBParam <$> cbParameter)   , (CBStorage <$> cbStorage)@@ -139,21 +153,21 @@   ]  -- | This ensures that the error message will point to the correct line.-ensureNotDuplicate :: [ContractBlock ParsedOp] -> ContractBlock ParsedOp -> Parser ()+ensureNotDuplicate :: [ContractBlock ParsedOp] -> ContractBlock ParsedOp -> Parser le () ensureNotDuplicate blocks result =   let-    failDuplicateField a = fail $ "Duplicate contract field: " <> a+    failDuplicateField a = fail $ "Duplicate contract field: " +| a |+ ""   in     case (result, blocks) of-      (CBParam _, CBParam _ : _) -> failDuplicateField "parameter"-      (CBStorage _, CBStorage _: _) -> failDuplicateField "storage"-      (CBCode _, CBCode _: _) -> failDuplicateField "code"+      (CBParam _, CBParam _ : _) -> failDuplicateField result+      (CBStorage _, CBStorage _: _) -> failDuplicateField result+      (CBCode _, CBCode _: _) -> failDuplicateField result       (CBView _, _) -> pure ()       (_, _:xs) -> ensureNotDuplicate xs result       (_, []) -> pure ()  -- | Michelson contract-contract :: Parser (Contract' ParsedOp)+contract :: Parser le (Contract' ParsedOp) contract = do   mSpace   result <- braces contractTuple <|> contractTuple@@ -161,7 +175,7 @@     Just contract' ->       return contract'     Nothing ->-      fail $ "Duplicate contract field: " <> show result+      fail $ "Duplicate contract field: " <> pretty result   where     -- | @ensureNotDuplicate@ provides a better message and point to the correct line     -- when the parser fails.@@ -174,15 +188,15 @@ -- Value ------------------ -value :: Parser ParsedValue+value :: Parser le ParsedValue value = value' parsedOp  -- | Parse untyped value from text which comes from something that is -- not a file (which is often the case). So we assume it does not need -- any parsing environment. ----- >>> parseValue MSUnspecified "{PUSH int aaa}"--- Left 1:11:+-- >>> parseValue MSUnspecified "{PUSH int aaa}" & either (putStrLn . displayException) (const $ pure ())+-- 1:11: --   | -- 1 | {PUSH int aaa} --   |           ^^^^@@ -190,7 +204,7 @@ -- expecting value -- <BLANKLINE> parseValue :: MichelsonSource -> Text -> Either ParserException ParsedValue-parseValue = first ParserException ... parseNoEnv value+parseValue = first ParserException ... (parseNoEnv @()) value  -- | Like 'parseValue', but also expands macros. parseExpandValue :: MichelsonSource -> Text -> Either ParserException U.Value@@ -199,7 +213,7 @@ -- Primitive instruction ------------------ -prim :: Parser ParsedInstr+prim :: Parser le ParsedInstr prim = primInstr contract parsedOp  -- Parsed operations (primitive instructions, macros, extras, etc.)@@ -208,58 +222,68 @@ -- | Parses code block after "code" keyword of a contract. -- -- This function is part of the module API, its semantics should not change.-codeEntry :: Parser [ParsedOp]+codeEntry :: Parser le [ParsedOp] codeEntry = bracewrappedOps -bracewrappedOps :: Parser [ParsedOp]+bracewrappedOps :: Parser le [ParsedOp] bracewrappedOps = lookAhead (symbol "{") *> ops  -- |--- >>> first ParserException $ parseNoEnv parsedOp "" "{a}"--- Left 1:2:+-- >>> parseNoEnv @() parsedOp "" "{a}" & either (putStrLn . displayException . ParserException) (const $ pure ())+-- 1:2: --   | -- 1 | {a} --   |  ^ -- unexpected 'a'+-- expecting '{', '}', macro, or primitive instruction+-- <BLANKLINE>+-- >>> :m + Morley.Michelson.Parser.Types+-- >>> parseNoEnv @LetEnv parsedOp "" "{a}" & either (putStrLn . displayException . ParserException) (const $ pure ())+-- ...+-- 1:2:+--   |+-- 1 | {a}+--   |  ^+-- unexpected 'a' -- expecting '{', '}', macro, morley instruction, or primitive instruction -- <BLANKLINE>-parsedOp :: Parser ParsedOp+parsedOp :: Parser le ParsedOp parsedOp = do-  lms <- asks letMacros   pos <- getSrcPos   choice-    [ flip Prim pos <$> (EXT <$> extInstr ops)-    , lmacWithPos (mkLetMac lms)+    [ withLetEnv $ flip Prim pos <$> (EXT <$> extInstr ops)+    , withLetEnv $ lmacWithPos     , flip Prim pos <$> prim     , flip Mac pos <$> macro parsedOp     , primOrMac     , flip Seq pos <$> bracewrappedOps     ]   where-    lmacWithPos :: Parser LetMacro -> Parser ParsedOp-    lmacWithPos act = do+    lmacWithPos :: Parser' LetEnv ParsedOp+    lmacWithPos = do+      act <- mkLetMac <$> asks letMacros       srcPos <- getSrcPos       flip LMac srcPos <$> act -getSrcPos :: Parser SrcPos+getSrcPos :: Parser le SrcPos getSrcPos = do   sp <- getSourcePos   let l = unPos $ sourceLine sp   let c = unPos $ sourceColumn sp   -- reindexing starting from 0-  pure $ SrcPos (unsafeMkPos $ l - 1) (unsafeMkPos $ c - 1)+  pure . unsafe $ SrcPos <$> (mkPos $ l - 1) <*> (mkPos $ c - 1) -primWithPos :: Parser ParsedInstr -> Parser ParsedOp+primWithPos :: Parser le ParsedInstr -> Parser le ParsedOp primWithPos act = do   srcPos <- getSrcPos   flip Prim srcPos <$> act -macWithPos :: Parser Macro -> Parser ParsedOp+macWithPos :: Parser le Macro -> Parser le ParsedOp macWithPos act = do   srcPos <- getSrcPos   flip Mac srcPos <$> act -ops :: Parser [ParsedOp]+ops :: Parser le [ParsedOp] ops = ops' parsedOp  -------------------------------------------------------------------------------@@ -267,7 +291,7 @@ -- These are needed for better error messages ------------------------------------------------------------------------------- -ifOrIfX :: Parser ParsedOp+ifOrIfX :: Parser le ParsedOp ifOrIfX = do   pos <- getSrcPos   symbol' "IF"@@ -278,7 +302,7 @@  -- Some of the operations and macros have the same prefixes in their names -- So this case should be handled separately-primOrMac :: Parser ParsedOp+primOrMac :: Parser le ParsedOp primOrMac = hidden    $  (macWithPos (ifCmpMac parsedOp) <|> ifOrIfX)   <|> (macWithPos (mapCadrMac parsedOp) <|> primWithPos (mapOp parsedOp))@@ -290,12 +314,12 @@ -- Safe construction of Haskell values ------------------------------------------------------------------------------- -parserToQuasiQuoter :: TH.Lift a => Parser a -> TH.QuasiQuoter+parserToQuasiQuoter :: Parser () (TH.Q TH.Exp) -> TH.QuasiQuoter parserToQuasiQuoter parser = TH.QuasiQuoter   { TH.quoteExp = \s ->       case parseNoEnv (mSpace *> parser) "quasi-quoter" (toText s) of         Left err -> fail $ errorBundlePretty err-        Right res -> [e| res |]+        Right qexp -> qexp   , TH.quotePat = \_ -> fail "Cannot be used as pattern"   , TH.quoteType = \_ -> fail "Cannot be used as type"   , TH.quoteDec = \_ -> fail "Cannot be used as declaration"@@ -303,8 +327,8 @@  -- | Creates 'U.Ty' by its Morley representation. ----- >>> [utypeQ| (int :a | nat :b) |]--- Ty (TOr % % (Ty TInt :a) (Ty TNat :b)) :+-- >>> [utypeQ| or (int :a) (nat :b) |]+-- Ty (TOr (UnsafeAnnotation @FieldTag "") (UnsafeAnnotation @FieldTag "") (Ty TInt (UnsafeAnnotation @TypeTag "a")) (Ty TNat (UnsafeAnnotation @TypeTag "b"))) (UnsafeAnnotation @TypeTag "") -- -- >>> [utypeQ|a|] -- <BLANKLINE>@@ -316,8 +340,18 @@ -- expecting type -- ... utypeQ :: TH.QuasiQuoter-utypeQ = parserToQuasiQuoter type_+utypeQ = parserToQuasiQuoter (TH.lift <$> type_)  -- | Creates 'U.ParameterType' by its Morley representation. uparamTypeQ :: TH.QuasiQuoter-uparamTypeQ = parserToQuasiQuoter cbParameterBare+uparamTypeQ = parserToQuasiQuoter (TH.lift <$> cbParameterBare)++-- | Parses and typechecks a 'Morley.Michelson.Typed.Notes'.+--+-- >>> [notes|int :ty|]+-- NTInt (UnsafeAnnotation @TypeTag "ty")+notes :: TH.QuasiQuoter+notes =+  parserToQuasiQuoter do+    t <- type_+    pure $ withUType t TH.lift
src/Morley/Michelson/Parser/Annotations.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Parser.Annotations   ( note@@ -22,7 +21,7 @@ import Prelude hiding (note)  import Control.Applicative.Permutations (runPermutation, toPermutationWithDefault)-import qualified Data.Text as T+import Data.Text qualified as T import Text.Megaparsec (satisfy, takeWhileP) import Text.Megaparsec.Char (string) @@ -33,35 +32,35 @@ import Morley.Util.Default  -- | General T/V/F Annotation parser, including Special Annotations-note :: forall tag. KnownAnnTag tag => Parser (Annotation tag)+note :: forall tag le. KnownAnnTag tag => Parser le (Annotation tag) note = lexeme $ string (annPrefix @tag) >> (specialNote <|> note' <|> emptyNote)   where     -- TODO [#48] these are special annotations and should not always be accepted-    specialVNote = unsafeMkAnnotation <$> asum (map string specialVarAnns)-    specialFNote = unsafeMkAnnotation <$> string specialFieldAnn+    specialVNote = unsafe . mkAnnotation <$> asum (map string specialVarAnns)+    specialFNote = unsafe . mkAnnotation <$> string specialFieldAnn     specialNote = specialVNote <|> specialFNote     emptyNote = pure noAnn     note' = do       a <- satisfy isValidAnnStart       b <- takeWhileP Nothing isValidAnnBodyChar-      return . unsafeMkAnnotation $ T.cons a b+      return . unsafe . mkAnnotation $ T.cons a b -noteV :: Parser VarAnn+noteV :: Parser le VarAnn noteV = note -noteDef :: KnownAnnTag tag => Parser (Annotation tag)+noteDef :: KnownAnnTag tag => Parser le (Annotation tag) noteDef = parseDef note -noteF :: Parser FieldAnn+noteF :: Parser le FieldAnn noteF = note -noteV2Def :: Parser (VarAnn, VarAnn)+noteV2Def :: Parser le (VarAnn, VarAnn) noteV2Def = permute2Def note note -notesTVF :: Parser (TypeAnn, VarAnn, FieldAnn)+notesTVF :: Parser le (TypeAnn, VarAnn, FieldAnn) notesTVF = permute3Def note note note -notesTVF2Def :: Parser (TypeAnn, VarAnn, (FieldAnn, FieldAnn))+notesTVF2Def :: Parser le (TypeAnn, VarAnn, (FieldAnn, FieldAnn)) notesTVF2Def = permute3Def note note (permute2Def note note)  -- | Parse 0/1/2 var anns and 0/1/2 field anns.@@ -76,21 +75,21 @@ -- * "@c @d %a %b" is valid -- * "@c %a %b @d" is not valid, because the two var anns are not "grouped" together. -- * "%a @c @d %b" is not valid, because the two fields anns are not "grouped" together.-notesVVFF :: Parser ((VarAnn, VarAnn), (FieldAnn, FieldAnn))+notesVVFF :: Parser le ((VarAnn, VarAnn), (FieldAnn, FieldAnn)) notesVVFF = permute2Def (liftA2 (,) note noteDef) (liftA2 (,) note noteDef) -notesVF :: Parser (VarAnn, FieldAnn)+notesVF :: Parser le (VarAnn, FieldAnn) notesVF = permute2Def note note -notesTV :: Parser (TypeAnn, VarAnn)+notesTV :: Parser le (TypeAnn, VarAnn) notesTV = permute2Def note note -notesTF :: Parser (TypeAnn, FieldAnn)+notesTF :: Parser le (TypeAnn, FieldAnn) notesTF = permute2Def note note  fieldType :: Default a-          => Parser a-          -> Parser (a, TypeAnn)+          => Parser le a+          -> Parser le (a, TypeAnn) fieldType fp = runPermutation $   (,) <$> toPermutationWithDefault  def     fp       <*> toPermutationWithDefault noAnn note
src/Morley/Michelson/Parser/Common.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Parser.Common   ( viewName_@@ -14,7 +13,7 @@ import Morley.Michelson.Parser.Types import Morley.Michelson.Untyped -viewName_ :: Parser ViewName+viewName_ :: Parser le ViewName viewName_ = lexeme do   string "\""   str <- manyTill anySingle (string "\"")
src/Morley/Michelson/Parser/Error.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- |  Custom exceptions that can happen during parsing. @@ -14,7 +13,6 @@ import Data.Data (Data(..)) import Fmt (Buildable(build), pretty, (+|), (|+)) import Text.Megaparsec (ParseErrorBundle, ShowErrorComponent(..), errorBundlePretty)-import qualified Text.Show (show)  import Morley.Michelson.Untyped.View import Morley.Util.Instances ()@@ -29,8 +27,17 @@   | WrongSetArgs Natural Positive   | ExcessFieldAnnotation   | MultiRootAnnotationException+  | DeprecatedException   deriving stock (Eq, Data, Ord, Show, Generic) +{-# DEPRECATED+    WrongTagArgs+  , WrongAccessArgs+  , WrongSetArgs++  "Exceptions specific to deprecated Morley language extensions"+  #-}+ instance NFData CustomParserException  instance ShowErrorComponent CustomParserException where@@ -39,6 +46,8 @@   showErrorComponent OddNumberBytesException = "odd number bytes"   showErrorComponent ExcessFieldAnnotation = "excess field annotation"   showErrorComponent MultiRootAnnotationException = "unexpected multiple root annotations"+  showErrorComponent DeprecatedException = "deprecated syntax, use --deprecated-morley-extensions \+    \command-line argument to silence this error"   showErrorComponent (WrongTagArgs idx size) =     "TAG: too large index: " +| idx |+ " \            \exceedes union size " +| size |+ ""@@ -64,13 +73,10 @@  data ParserException =   ParserException (ParseErrorBundle Text CustomParserException)-  deriving stock (Eq)--instance Show ParserException where-  show (ParserException bundle) = errorBundlePretty bundle+  deriving stock (Eq, Show)  instance Exception ParserException where   displayException (ParserException bundle) = errorBundlePretty bundle  instance Buildable ParserException where-  build = build @String . show+  build (ParserException bundle) = build $ errorBundlePretty bundle
src/Morley/Michelson/Parser/Ext.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ -- | Parsing logic for extra instructions (Morley extensions)  module Morley.Michelson.Parser.Ext@@ -16,35 +18,36 @@  import Text.Megaparsec (choice, label, satisfy, try) import Text.Megaparsec.Char (alphaNumChar, string)-import qualified Text.Megaparsec.Char.Lexer as L+import Text.Megaparsec.Char.Lexer qualified as L  import Morley.Michelson.Macro (ParsedOp(..), ParsedUExtInstr) import Morley.Michelson.Parser.Lexer import Morley.Michelson.Parser.Type-import Morley.Michelson.Parser.Types (Parser)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Parser.Types (LetEnv, Parser')+import Morley.Michelson.Untyped qualified as U -extInstr :: Parser [ParsedOp] -> Parser ParsedUExtInstr-extInstr opsParser = label "morley instruction" $ choice [stackOp, testAssertOp opsParser, printOp]+extInstr :: Parser' LetEnv [ParsedOp] -> Parser' LetEnv ParsedUExtInstr+extInstr opsParser = do+  label "morley instruction" $ choice [stackOp, testAssertOp opsParser, printOp] -stackOp :: Parser ParsedUExtInstr+stackOp :: Parser' LetEnv ParsedUExtInstr stackOp = word' "STACKTYPE" U.STACKTYPE <*> stackType -testAssertOp :: Parser [ParsedOp] -> Parser ParsedUExtInstr+testAssertOp :: Parser' LetEnv [ParsedOp] -> Parser' LetEnv ParsedUExtInstr testAssertOp opsParser =   word' "TEST_ASSERT" U.UTEST_ASSERT <*> testAssert opsParser -printOp :: Parser ParsedUExtInstr+printOp :: Parser' LetEnv ParsedUExtInstr printOp = word' "PRINT" U.UPRINT <*> printComment -testAssert :: Parser [ParsedOp] -> Parser (U.TestAssert ParsedOp)+testAssert :: Parser' LetEnv [ParsedOp] -> Parser' LetEnv (U.TestAssert ParsedOp) testAssert opsParser = do   n <- lexeme (toText <$> some alphaNumChar)   c <- printComment   o <- opsParser   return $ U.TestAssert n c o -printComment :: Parser U.PrintComment+printComment :: Parser' LetEnv U.PrintComment printComment = do   string "\""   let validChar = toText <$> some (satisfy (\x -> x /= '%' && x /= '"'))@@ -52,14 +55,15 @@   symbol "\""   return $ U.PrintComment c -stackRef :: Parser U.StackRef+stackRef :: Parser' LetEnv U.StackRef stackRef = do   string "%"   n <- brackets' L.decimal   return $ U.StackRef n -stackType :: Parser U.StackTypePattern-stackType = symbol "'[" >> (emptyStk <|> stkCons <|> stkRest)+stackType :: Parser' LetEnv U.StackTypePattern+stackType = do+  symbol "'[" >> (emptyStk <|> stkCons <|> stkRest)   where     emptyStk = try $ symbol "]" $> U.StkEmpty     stkRest = try $ symbol "..." >> symbol "]" $> U.StkRest@@ -68,5 +72,5 @@       s <- (symbol "," >> stkCons <|> stkRest) <|> emptyStk       return $ U.StkCons t s -tyVar :: Parser U.TyVar+tyVar :: Parser' LetEnv U.TyVar tyVar = (U.TyCon <$> type_) <|> (U.VarID <$> varID)
src/Morley/Michelson/Parser/Helpers.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+ module Morley.Michelson.Parser.Helpers   ( mkParser   , sepEndBy1@@ -10,16 +12,18 @@   , sepBy2   , parseDef   , positive+  , count   ) where  import Data.Default (Default(..))-import qualified Data.List.NonEmpty as NE-import qualified Text.Megaparsec as P+import Data.List.NonEmpty qualified as NE+import Text.Megaparsec qualified as P import Text.Megaparsec.Char.Lexer (decimal)  import Morley.Michelson.Parser.Lexer (word') import Morley.Michelson.Parser.Types (Parser) import Morley.Util.Positive+import Morley.Util.SizedList.Types  -- | Version of 'P.sepEndBy1' returning a 'NonEmpty' list sepEndBy1 :: MonadPlus m => m a -> m sep -> m (NonEmpty a)@@ -42,16 +46,23 @@   return $ e :| es  -- | Make a parser from a string-mkParser :: (a -> Text) -> a -> Parser a-mkParser f a = P.try $ word' (f a) a+mkParser :: (a -> Text) -> a -> Parser le a+mkParser f a = word' (f a) a  -- | Apply given parser and return default value if it fails.-parseDef :: Default a => Parser a -> Parser a+parseDef :: Default a => Parser le a -> Parser le a parseDef a = P.try a <|> pure def  -- | Parse a positive number.-positive :: Parser Positive+positive :: Parser le Positive positive = do   n :: Integer <- decimal   mkPositive n     & either (fail . toString) pure++-- | Parse expression @n@ times, where @n@ is a type-level natural.+-- Essentially, a type-safe version of 'P.count', but requires+-- the count to be known on the type level.+count :: (SingIPeano n, Applicative m) => m a -> m (SizedList n a)+count = sequenceA . pure+{-# INLINE count #-}
src/Morley/Michelson/Parser/Instr.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations -Wno-redundant-constraints #-}+ -- | Parsing of Michelson instructions.  module Morley.Michelson.Parser.Instr@@ -16,12 +18,13 @@   , dupOp   , carOp   , cdrOp+  , viewOp   ) where  import Prelude hiding (EQ, GT, LT, many, note, some, try) -import Text.Megaparsec (choice, label, lookAhead, notFollowedBy, satisfy, sepEndBy, try)-import qualified Text.Megaparsec.Char.Lexer as L+import Text.Megaparsec (choice, label, notFollowedBy, try)+import Text.Megaparsec.Char.Lexer qualified as L  import Morley.Michelson.Let (LetValue(..)) import Morley.Michelson.Macro (ParsedInstr, ParsedOp(..))@@ -29,12 +32,12 @@ import Morley.Michelson.Parser.Common import Morley.Michelson.Parser.Lexer import Morley.Michelson.Parser.Type-import Morley.Michelson.Parser.Types (Parser, letValues)+import Morley.Michelson.Parser.Types (LetEnv, Parser, Parser', letValues, withLetEnv) import Morley.Michelson.Parser.Value import Morley.Michelson.Untyped  -- | Parser for primitive Michelson instruction (no macros and extensions).-primInstr :: Parser (Contract' ParsedOp) -> Parser ParsedOp -> Parser ParsedInstr+primInstr :: Parser' le (Contract' ParsedOp) -> Parser' le ParsedOp -> Parser le ParsedInstr primInstr contractParser opParser = label "primitive instruction" $ choice   [ dropOp, swapOp, digOp, dugOp, pushOp opParser, someOp, noneOp, unitOp   , ifNoneOp opParser, leftOp, rightOp, ifLeftOp opParser, nilOp@@ -42,7 +45,7 @@   , memOp, getAndUpdateOp, getOp, updateOp, loopLOp opParser, loopOp opParser   , lambdaOp opParser, execOp, applyOp, dipOp opParser, failWithOp, castOp, renameOp, levelOp   , concatOp, packOp, unpackOp, sliceOp, isNatOp, addressOp, selfAddressOp, addOp, subOp-  , mulOp, edivOp, absOp, negOp, lslOp, lsrOp, orOp, andOp, xorOp, notOp+  , subMutezOp, mulOp, edivOp, absOp, negOp, lslOp, lsrOp, orOp, andOp, xorOp, notOp   , compareOp, eqOp, neqOp, ltOp, leOp, gtOp, geOp, intOp, viewOp, selfOp, contractOp   , transferTokensOp, setDelegateOp   , createContractOp contractParser, implicitAccountOp, nowOp, amountOp@@ -52,403 +55,424 @@   , unpairOp   , ticketOp, readTicketOp, splitTicketOp, joinTicketsOp   , openChestOp+  , saplingEmptyStateOp, saplingVerifyUpdateOp   ]  -- | Parse a sequence of instructions.-ops' :: Parser ParsedOp -> Parser [ParsedOp]-ops' opParser = (braces $ sepEndBy opParser (optional semicolon)) <|> (pure <$> opParser)+ops' :: Parser' le ParsedOp -> Parser le [ParsedOp]+ops' opParser = (braces $ parseSeq) <|> (pure <$> opParser)+  where+    parseSeq =+      do{ op <- opParser+        ; let separator = case op of+                Seq _ _ -> void (optional semicolon)+                _       -> semicolon+        ; do{ _ <- separator+            ; ops <- parseSeq+            ; return (op:ops)+            }+           <|> return [op]+      }+      <|> return [] + -- Control Structures -failWithOp :: Parser ParsedInstr+failWithOp :: Parser le ParsedInstr failWithOp = word' "FAILWITH" FAILWITH -loopOp :: Parser ParsedOp -> Parser ParsedInstr+loopOp :: Parser' le ParsedOp -> Parser le ParsedInstr loopOp opParser = word' "LOOP" LOOP <*> ops' opParser -loopLOp :: Parser ParsedOp -> Parser ParsedInstr+loopLOp :: Parser' le ParsedOp -> Parser le ParsedInstr loopLOp opParser = word' "LOOP_LEFT" LOOP_LEFT <*> ops' opParser -execOp :: Parser ParsedInstr+execOp :: Parser le ParsedInstr execOp = word' "EXEC" EXEC <*> noteDef -applyOp :: Parser ParsedInstr+applyOp :: Parser le ParsedInstr applyOp = word' "APPLY" APPLY <*> noteDef  -- Parses both `DIP` and `DIP n`.-dipOp :: Parser ParsedOp -> Parser ParsedInstr+dipOp :: Parser' le ParsedOp -> Parser le ParsedInstr dipOp opParser = parseWithOptionalParameter "DIP" DIPN DIP <*> ops' opParser  -- Helper for instructions which have optional numeric non-negative parameter.-parseWithOptionalParameter :: Text -> (Word -> instr) -> instr -> Parser instr+parseWithOptionalParameter :: Text -> (Word -> instr) -> instr -> Parser le instr parseWithOptionalParameter instrName constructorWithParam constructorNoParam =-  symbol' instrName *>+  symbol1' instrName *>   (try (constructorWithParam <$> lexeme L.decimal) <|> pure constructorNoParam)  -- Stack Operations  -- Parses both `DROP` and `DROP n`.-dropOp :: Parser ParsedInstr+dropOp :: Parser le ParsedInstr dropOp = parseWithOptionalParameter "DROP" DROPN DROP -dupOp :: Parser ParsedInstr+dupOp :: Parser le ParsedInstr dupOp = do-  symbol' "DUP"+  symbol1' "DUP"   varAnn <- noteDef   optional (lexeme L.decimal) <&> maybe (DUP varAnn) (DUPN varAnn) -swapOp :: Parser ParsedInstr+swapOp :: Parser le ParsedInstr swapOp = word' "SWAP" SWAP -digOp :: Parser ParsedInstr+digOp :: Parser le ParsedInstr digOp = word' "DIG" DIG <*> lexeme L.decimal -dugOp :: Parser ParsedInstr+dugOp :: Parser le ParsedInstr dugOp = word' "DUG" DUG <*> lexeme L.decimal -pushOp :: Parser ParsedOp -> Parser ParsedInstr+pushOp :: forall le. Parser' le ParsedOp -> Parser le ParsedInstr pushOp opParser = do-  symbol' "PUSH"+  symbol1' "PUSH"   v <- noteDef-  (try $ pushLet v) <|> (push' v)+  (try $ withLetEnv $ pushLet v) <|> (push' v)   where+    pushLet :: VarAnn -> Parser' LetEnv ParsedInstr     pushLet v = do       lvs <- asks letValues       lv <- mkLetVal lvs       return $ PUSH v (lvSig lv) (lvVal lv)+    push' :: VarAnn -> Parser le ParsedInstr     push' v = PUSH v <$> type_ <*> value' opParser -unitOp :: Parser ParsedInstr-unitOp = do symbol' "UNIT"; (t, v) <- notesTV; return $ UNIT t v+unitOp :: Parser le ParsedInstr+unitOp = do symbol1' "UNIT"; (t, v) <- notesTV; return $ UNIT t v -lambdaOp :: Parser ParsedOp -> Parser ParsedInstr+lambdaOp :: Parser' le ParsedOp -> Parser le ParsedInstr lambdaOp opParser =   word' "LAMBDA" LAMBDA <*> noteDef <*> type_ <*> type_ <*> ops' opParser -neverOp :: Parser ParsedInstr+neverOp :: Parser le ParsedInstr neverOp = word' "NEVER" NEVER -- Generic comparison -cmpOp :: Parser ParsedInstr+cmpOp :: Parser le ParsedInstr cmpOp = eqOp <|> neqOp <|> ltOp <|> gtOp <|> leOp <|> gtOp <|> geOp -eqOp :: Parser ParsedInstr+eqOp :: Parser le ParsedInstr eqOp = word' "EQ" EQ <*> noteDef -neqOp :: Parser ParsedInstr+neqOp :: Parser le ParsedInstr neqOp = word' "NEQ" NEQ <*> noteDef -ltOp :: Parser ParsedInstr+ltOp :: Parser le ParsedInstr ltOp = word' "LT" LT <*> noteDef -gtOp :: Parser ParsedInstr+gtOp :: Parser le ParsedInstr gtOp = word' "GT" GT <*> noteDef -leOp :: Parser ParsedInstr+leOp :: Parser le ParsedInstr leOp = word' "LE" LE <*> noteDef -geOp :: Parser ParsedInstr+geOp :: Parser le ParsedInstr geOp = word' "GE" GE <*> noteDef  -- ad-hoc comparison -compareOp :: Parser ParsedInstr+compareOp :: Parser le ParsedInstr compareOp = word' "COMPARE" COMPARE <*> noteDef  -- Operations on booleans -orOp :: Parser ParsedInstr+orOp :: Parser le ParsedInstr orOp = word' "OR"  OR <*> noteDef -andOp :: Parser ParsedInstr+andOp :: Parser le ParsedInstr andOp = word' "AND" AND <*> noteDef -xorOp :: Parser ParsedInstr+xorOp :: Parser le ParsedInstr xorOp = word' "XOR" XOR <*> noteDef -notOp :: Parser ParsedInstr+notOp :: Parser le ParsedInstr notOp = word' "NOT" NOT <*> noteDef  -- Operations on integers and natural numbers -addOp :: Parser ParsedInstr+addOp :: Parser le ParsedInstr addOp = word' "ADD" ADD <*> noteDef -subOp :: Parser ParsedInstr+saplingEmptyStateOp :: Parser le ParsedInstr+saplingEmptyStateOp = word' "SAPLING_EMPTY_STATE" SAPLING_EMPTY_STATE <*> noteDef <*> lexeme L.decimal++saplingVerifyUpdateOp :: Parser le ParsedInstr+saplingVerifyUpdateOp = word' "SAPLING_VERIFY_UPDATE" SAPLING_VERIFY_UPDATE <*> noteDef++subOp :: Parser le ParsedInstr subOp = word' "SUB" SUB <*> noteDef -mulOp :: Parser ParsedInstr+subMutezOp :: Parser le ParsedInstr+subMutezOp = word' "SUB_MUTEZ" SUB_MUTEZ <*> noteDef++mulOp :: Parser le ParsedInstr mulOp = word' "MUL" MUL <*> noteDef -edivOp :: Parser ParsedInstr+edivOp :: Parser le ParsedInstr edivOp = word' "EDIV" EDIV <*> noteDef -absOp :: Parser ParsedInstr+absOp :: Parser le ParsedInstr absOp = word' "ABS" ABS <*> noteDef -negOp :: Parser ParsedInstr+negOp :: Parser le ParsedInstr negOp = word' "NEG" NEG <*> noteDef  -- Bitwise logical operators -lslOp :: Parser ParsedInstr+lslOp :: Parser le ParsedInstr lslOp = word' "LSL" LSL <*> noteDef -lsrOp :: Parser ParsedInstr+lsrOp :: Parser le ParsedInstr lsrOp = word' "LSR" LSR <*> noteDef  -- Operations on string's -concatOp :: Parser ParsedInstr+concatOp :: Parser le ParsedInstr concatOp = word' "CONCAT" CONCAT <*> noteDef -sliceOp :: Parser ParsedInstr+sliceOp :: Parser le ParsedInstr sliceOp = word' "SLICE" SLICE <*> noteDef  -- Operations on pairs-pairOp :: Parser ParsedInstr+pairOp :: Parser le ParsedInstr pairOp = do-  symbol' "PAIR"+  symbol1' "PAIR"   (t, v, (p, q)) <- notesTVF2Def    -- Make sure this is a `PAIR` instruction,   -- and not a `PAIR n` instruction.-  notFollowedBy (lexeme L.decimal :: Parser Word)+  notFollowedBy (lexeme L.decimal :: Parser le Word)    return $ PAIR t v p q -unpairOp :: Parser ParsedInstr+unpairOp :: Parser le ParsedInstr unpairOp = do-  symbol' "UNPAIR"+  symbol1' "UNPAIR"   ((vn1, vn2), (fn1, fn2)) <- notesVVFF    -- Make sure this is an `UNPAIR` instruction,   -- and not an `UNPAIR n` instruction.-  notFollowedBy (lexeme L.decimal :: Parser Word)+  notFollowedBy (lexeme L.decimal :: Parser le Word)    return $ UNPAIR vn1 vn2 fn1 fn2 -pairNOp :: Parser ParsedInstr+pairNOp :: Parser le ParsedInstr pairNOp = do-  symbol' "PAIR"+  symbol1' "PAIR"   PAIRN     <$> noteDef     <*> lexeme L.decimal -unpairNOp :: Parser ParsedInstr+unpairNOp :: Parser le ParsedInstr unpairNOp =   word' "UNPAIR" UNPAIRN <*> lexeme L.decimal -carOp :: Parser ParsedInstr-carOp = do symbol' "CAR"; (v, f) <- notesVF; return $ CAR v f+carOp :: Parser le ParsedInstr+carOp = do symbol1' "CAR"; (v, f) <- notesVF; return $ CAR v f -cdrOp :: Parser ParsedInstr-cdrOp = do symbol' "CDR"; (v, f) <- notesVF; return $ CDR v f+cdrOp :: Parser le ParsedInstr+cdrOp = do symbol1' "CDR"; (v, f) <- notesVF; return $ CDR v f  -- Operations on collections (sets, maps, lists) -emptySetOp :: Parser ParsedInstr-emptySetOp = do symbol' "EMPTY_SET"; (t, v) <- notesTV;+emptySetOp :: Parser le ParsedInstr+emptySetOp = do symbol1' "EMPTY_SET"; (t, v) <- notesTV;                 EMPTY_SET t v <$> type_ -emptyMapOp :: Parser ParsedInstr-emptyMapOp = do symbol' "EMPTY_MAP"; (t, v) <- notesTV; a <- type_;+emptyMapOp :: Parser le ParsedInstr+emptyMapOp = do symbol1' "EMPTY_MAP"; (t, v) <- notesTV; a <- type_;                 EMPTY_MAP t v a <$> type_ -emptyBigMapOp :: Parser ParsedInstr-emptyBigMapOp = do symbol' "EMPTY_BIG_MAP"; (t, v) <- notesTV; a <- type_;+emptyBigMapOp :: Parser le ParsedInstr+emptyBigMapOp = do symbol1' "EMPTY_BIG_MAP"; (t, v) <- notesTV; a <- type_;                    EMPTY_BIG_MAP t v a <$> type_ -memOp :: Parser ParsedInstr+memOp :: Parser le ParsedInstr memOp = word' "MEM" MEM <*> noteDef -updateOp :: Parser ParsedInstr+updateOp :: Parser le ParsedInstr updateOp = do-  symbol' "UPDATE"+  symbol1' "UPDATE"   varAnn <- noteDef   ix <- optional (lexeme L.decimal)   pure $ maybe (UPDATE varAnn) (UPDATEN varAnn) ix -getAndUpdateOp :: Parser ParsedInstr+getAndUpdateOp :: Parser le ParsedInstr getAndUpdateOp = word' "GET_AND_UPDATE" GET_AND_UPDATE <*> noteDef -iterOp :: Parser ParsedOp -> Parser ParsedInstr+iterOp :: Parser' le ParsedOp -> Parser le ParsedInstr iterOp opParser = word' "ITER" ITER <*> ops' opParser -sizeOp :: Parser ParsedInstr+sizeOp :: Parser le ParsedInstr sizeOp = word' "SIZE" SIZE <*> noteDef -mapOp :: Parser ParsedOp -> Parser ParsedInstr+mapOp :: Parser' le ParsedOp -> Parser le ParsedInstr mapOp opParser = word' "MAP" MAP <*>  noteDef <*> ops' opParser -getOp :: Parser ParsedInstr+getOp :: Parser le ParsedInstr getOp = do-  symbol' "GET"+  symbol1' "GET"   varAnn <- noteDef   ix <- optional (lexeme L.decimal)   pure $ maybe (GET varAnn) (GETN varAnn) ix -nilOp :: Parser ParsedInstr-nilOp = do symbol' "NIL"; (t, v) <- notesTV; NIL t v <$> type_+nilOp :: Parser le ParsedInstr+nilOp = do symbol1' "NIL"; (t, v) <- notesTV; NIL t v <$> type_ -consOp :: Parser ParsedInstr-consOp = do-  try . lexeme $ do-    void $ string' "CONS"-    notFollowedBy (string' "T")-  CONS <$> noteDef+consOp :: Parser le ParsedInstr+consOp = word' "CONS" CONS <*> noteDef -ifConsOp :: Parser ParsedOp -> Parser ParsedInstr+ifConsOp :: Parser' le ParsedOp -> Parser le ParsedInstr ifConsOp opParser = word' "IF_CONS" IF_CONS <*> ops' opParser <*> ops' opParser  -- Operations on options -someOp :: Parser ParsedInstr-someOp = do symbol' "SOME"; (t, v) <- notesTV; return $ SOME t v+someOp :: Parser le ParsedInstr+someOp = do symbol1' "SOME"; (t, v) <- notesTV; return $ SOME t v -noneOp :: Parser ParsedInstr-noneOp = do symbol' "NONE"; (t, v) <- notesTV; NONE t v <$> type_+noneOp :: Parser le ParsedInstr+noneOp = do symbol1' "NONE"; (t, v) <- notesTV; NONE t v <$> type_ -ifNoneOp :: Parser ParsedOp -> Parser ParsedInstr+ifNoneOp :: Parser' le ParsedOp -> Parser le ParsedInstr ifNoneOp opParser = word' "IF_NONE" IF_NONE <*> ops' opParser <*> ops' opParser  -- Operations on unions -leftOp :: Parser ParsedInstr-leftOp = do symbol' "LEFT"; (t, v, (f, f')) <- notesTVF2Def;+leftOp :: Parser le ParsedInstr+leftOp = do symbol1' "LEFT"; (t, v, (f, f')) <- notesTVF2Def;                LEFT t v f f' <$> type_ -rightOp :: Parser ParsedInstr-rightOp = do symbol' "RIGHT"; (t, v, (f, f')) <- notesTVF2Def;+rightOp :: Parser le ParsedInstr+rightOp = do symbol1' "RIGHT"; (t, v, (f, f')) <- notesTVF2Def;                RIGHT t v f f' <$> type_ -ifLeftOp :: Parser ParsedOp -> Parser ParsedInstr+ifLeftOp :: Parser' le ParsedOp -> Parser le ParsedInstr ifLeftOp opParser = word' "IF_LEFT" IF_LEFT <*> ops' opParser <*> ops' opParser  -- Operations on contracts -createContractOp :: Parser (Contract' ParsedOp) -> Parser ParsedInstr+createContractOp :: Parser le (Contract' ParsedOp) -> Parser le ParsedInstr createContractOp contractParser =   word' "CREATE_CONTRACT" CREATE_CONTRACT     <*> noteDef <*> noteDef <*> braces contractParser -transferTokensOp :: Parser ParsedInstr+transferTokensOp :: Parser le ParsedInstr transferTokensOp = word' "TRANSFER_TOKENS" TRANSFER_TOKENS <*> noteDef -setDelegateOp :: Parser ParsedInstr+setDelegateOp :: Parser le ParsedInstr setDelegateOp = word' "SET_DELEGATE" SET_DELEGATE <*> noteDef -balanceOp :: Parser ParsedInstr+balanceOp :: Parser le ParsedInstr balanceOp = word' "BALANCE" BALANCE <*> noteDef -contractOp :: Parser ParsedInstr+contractOp :: Parser le ParsedInstr contractOp = word' "CONTRACT" CONTRACT <*> noteDef <*> noteDef <*> type_ -sourceOp :: Parser ParsedInstr+sourceOp :: Parser le ParsedInstr sourceOp = word' "SOURCE" SOURCE <*> noteDef -senderOp :: Parser ParsedInstr+senderOp :: Parser le ParsedInstr senderOp = word' "SENDER" SENDER <*> noteDef -amountOp :: Parser ParsedInstr+amountOp :: Parser le ParsedInstr amountOp = word' "AMOUNT" AMOUNT <*> noteDef -votingPowerOp :: Parser ParsedInstr+votingPowerOp :: Parser le ParsedInstr votingPowerOp = word' "VOTING_POWER" VOTING_POWER <*> noteDef -totalVotingPowerOp :: Parser ParsedInstr+totalVotingPowerOp :: Parser le ParsedInstr totalVotingPowerOp = word' "TOTAL_VOTING_POWER" TOTAL_VOTING_POWER <*> noteDef -implicitAccountOp :: Parser ParsedInstr+implicitAccountOp :: Parser le ParsedInstr implicitAccountOp = word' "IMPLICIT_ACCOUNT" IMPLICIT_ACCOUNT <*> noteDef -viewOp :: Parser ParsedInstr+viewOp :: Parser le ParsedInstr viewOp =   -- @VIEW_@ A1 macro should not be parsed by this-  -- TODO [#557] this 'lookAhead' and 'try' should become unnecessary-  try (word' "VIEW" VIEW <* lookAhead (satisfy (/= '_'))) <*> noteDef <*> viewName_ <*> type_+  word' "VIEW" VIEW <*> noteDef <*> viewName_ <*> type_ -selfOp :: Parser ParsedInstr+selfOp :: Parser le ParsedInstr selfOp = word' "SELF" SELF <*> noteDef <*> noteDef -addressOp :: Parser ParsedInstr+addressOp :: Parser le ParsedInstr addressOp = word' "ADDRESS" ADDRESS <*> noteDef -selfAddressOp :: Parser ParsedInstr+selfAddressOp :: Parser le ParsedInstr selfAddressOp = word' "SELF_ADDRESS" SELF_ADDRESS <*> noteDef  -- Special Operations -nowOp :: Parser ParsedInstr+nowOp :: Parser le ParsedInstr nowOp = word' "NOW" NOW <*> noteDef -levelOp :: Parser ParsedInstr+levelOp :: Parser le ParsedInstr levelOp = word' "LEVEL" LEVEL <*> noteDef -chainIdOp :: Parser ParsedInstr+chainIdOp :: Parser le ParsedInstr chainIdOp = word' "CHAIN_ID" CHAIN_ID <*> noteDef  -- Operations on bytes -packOp :: Parser ParsedInstr+packOp :: Parser le ParsedInstr packOp = word' "PACK" PACK <*> noteDef -unpackOp :: Parser ParsedInstr-unpackOp = do symbol' "UNPACK"; (t, v) <- notesTV; UNPACK t v <$> type_+unpackOp :: Parser le ParsedInstr+unpackOp = do symbol1' "UNPACK"; (t, v) <- notesTV; UNPACK t v <$> type_  -- Cryptographic Primitives -checkSigOp :: Parser ParsedInstr+checkSigOp :: Parser le ParsedInstr checkSigOp = word' "CHECK_SIGNATURE" CHECK_SIGNATURE <*> noteDef -blake2BOp :: Parser ParsedInstr+blake2BOp :: Parser le ParsedInstr blake2BOp = word' "BLAKE2B" BLAKE2B <*> noteDef -sha256Op :: Parser ParsedInstr+sha256Op :: Parser le ParsedInstr sha256Op = word' "SHA256" SHA256 <*> noteDef -sha512Op :: Parser ParsedInstr+sha512Op :: Parser le ParsedInstr sha512Op = word' "SHA512" SHA512 <*> noteDef -sha3Op :: Parser ParsedInstr+sha3Op :: Parser le ParsedInstr sha3Op = word' "SHA3" SHA3 <*> noteDef -keccakOp :: Parser ParsedInstr+keccakOp :: Parser le ParsedInstr keccakOp = word' "KECCAK" KECCAK <*> noteDef -hashKeyOp :: Parser ParsedInstr+hashKeyOp :: Parser le ParsedInstr hashKeyOp = word' "HASH_KEY" HASH_KEY <*> noteDef -pairingCheckOp :: Parser ParsedInstr+pairingCheckOp :: Parser le ParsedInstr pairingCheckOp = word' "PAIRING_CHECK" PAIRING_CHECK <*> noteDef  -- Type operations -castOp :: Parser ParsedInstr+castOp :: Parser le ParsedInstr castOp = word' "CAST" CAST <*> noteDef <*> type_ -renameOp :: Parser ParsedInstr+renameOp :: Parser le ParsedInstr renameOp = word' "RENAME" RENAME <*> noteDef -isNatOp :: Parser ParsedInstr+isNatOp :: Parser le ParsedInstr isNatOp = word' "ISNAT" ISNAT <*> noteDef -intOp :: Parser ParsedInstr+intOp :: Parser le ParsedInstr intOp = word' "INT" INT <*> noteDef  -- Ticket Operations -ticketOp :: Parser ParsedInstr+ticketOp :: Parser le ParsedInstr ticketOp = word' "TICKET" TICKET <*> noteDef -readTicketOp :: Parser ParsedInstr+readTicketOp :: Parser le ParsedInstr readTicketOp = word' "READ_TICKET" READ_TICKET <*> noteDef -splitTicketOp :: Parser ParsedInstr+splitTicketOp :: Parser le ParsedInstr splitTicketOp = word' "SPLIT_TICKET" SPLIT_TICKET <*> noteDef -joinTicketsOp :: Parser ParsedInstr+joinTicketsOp :: Parser le ParsedInstr joinTicketsOp = word' "JOIN_TICKETS" JOIN_TICKETS <*> noteDef -openChestOp :: Parser ParsedInstr+openChestOp :: Parser le ParsedInstr openChestOp = word' "OPEN_CHEST" OPEN_CHEST <*> noteDef
src/Morley/Michelson/Parser/Let.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ -- | Parsing of let blocks  module Morley.Michelson.Parser.Let@@ -14,9 +16,10 @@  import Prelude hiding (try) -import qualified Data.Char as Char-import qualified Data.Map as Map-import qualified Data.Set as Set+import Data.Char qualified as Char+import Data.Map qualified as Map+import Data.Set qualified as Set+import Data.Type.Equality ((:~:)(Refl))  import Text.Megaparsec (choice, satisfy, try) import Text.Megaparsec.Char (lowerChar, upperChar)@@ -28,7 +31,7 @@ import Morley.Michelson.Parser.Instr import Morley.Michelson.Parser.Lexer import Morley.Michelson.Parser.Type-import Morley.Michelson.Parser.Types (LetEnv(..), Parser, noLetEnv)+import Morley.Michelson.Parser.Types (LetEnv(..), Parser, Parser', assertLetEnv, noLetEnv) import Morley.Michelson.Parser.Value import Morley.Michelson.Untyped (StackFn(..), Ty(..), mkAnnotation, noAnn) @@ -36,17 +39,18 @@ data Let = LetM LetMacro | LetV LetValue | LetT LetType  -- | let block parser-letBlock :: Parser ParsedOp -> Parser LetEnv+letBlock :: forall le. Parser' le ParsedOp -> Parser le le letBlock opParser = do   symbol "let"   symbol "{"+  Refl <- assertLetEnv   ls <- local (const noLetEnv) (letInner opParser)   symbol "}"   semicolon   return ls  -- | Incrementally build the let environment-letInner :: Parser ParsedOp -> Parser LetEnv+letInner :: Parser' LetEnv ParsedOp -> Parser' LetEnv LetEnv letInner opParser = do   env <- ask   l <- lets opParser@@ -60,7 +64,7 @@   LetV lv -> LetEnv lms (Map.insert (lvName lv) lv lvs) lts   LetT lt -> LetEnv lms lvs (Map.insert (ltName lt) lt lts) -lets :: Parser ParsedOp -> Parser Let+lets :: Parser' LetEnv ParsedOp -> Parser' LetEnv Let lets opParser = choice   [ (LetM <$> letMacro opParser)   , (LetV <$> letValue opParser)@@ -68,16 +72,14 @@   ]  -- | Build a let name parser from a leading character parser-letName :: Parser Char -> Parser Text+letName :: Parser' LetEnv Char -> Parser' LetEnv Text letName p = lexeme $ do   v <- p-  -- FIXME (#557): It is possible to define a let name such as "add3", but then-  -- the parser doesn't recognize when it's used as an instruction.   let validChar x = Char.isAscii x && (Char.isAlphaNum x || x == '\'' || x == '_')   vs <- many (satisfy validChar)   return $ toText (v:vs) -letMacro :: Parser ParsedOp -> Parser LetMacro+letMacro :: Parser' LetEnv ParsedOp -> Parser' LetEnv LetMacro letMacro opParser = lexeme $ do   n <- try $ do     n <- letName lowerChar@@ -88,7 +90,7 @@   o <- ops' opParser   return $ LetMacro n s o -letType :: Parser LetType+letType :: Parser' LetEnv LetType letType = lexeme $ do   n <- try $ do     symbol "type"@@ -102,7 +104,7 @@       Left err -> fail $ toString err     else return $ LetType n t -letValue :: Parser ParsedOp -> Parser LetValue+letValue :: Parser' LetEnv ParsedOp -> Parser' LetEnv LetValue letValue opParser = lexeme $ do   n <- try $ do     n <- letName upperChar@@ -113,10 +115,10 @@   v <- value' opParser   return $ LetValue n t v -mkLetMac :: Map Text LetMacro -> Parser LetMacro+mkLetMac :: Map Text LetMacro -> Parser' LetEnv LetMacro mkLetMac lms = choice $ mkParser lmName <$> (Map.elems lms) -stackFn :: Parser StackFn+stackFn :: Parser' LetEnv StackFn stackFn = do   vs <- (optional (symbol "forall" >> some varID <* symbol "."))   a <- stackType
src/Morley/Michelson/Parser/Lexer.hs view
@@ -1,12 +1,17 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+ module Morley.Michelson.Parser.Lexer   ( lexeme   , mSpace+  , spaces   , symbol   , symbol'+  , symbol1+  , symbol1'   , word   , word'   , string'@@ -19,63 +24,81 @@   , varID   ) where +import Prelude hiding (try)+ import Data.Char (isDigit, isLower, toLower)-import qualified Data.Text as T-import Text.Megaparsec (MonadParsec, Tokens, between, satisfy)+import Data.Text qualified as T+import Text.Megaparsec (Tokens, between, choice, eof, hidden, lookAhead, satisfy, try) import Text.Megaparsec.Char (lowerChar, space, space1, string)-import qualified Text.Megaparsec.Char.Lexer as L+import Text.Megaparsec.Char.Lexer qualified as L -import Morley.Michelson.Parser.Types (Parser)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Parser.Types (Parser, Parser')+import Morley.Michelson.Untyped qualified as U  -- Lexing-lexeme :: Parser a -> Parser a-lexeme = L.lexeme mSpace+lexeme :: Parser le a -> Parser le a+lexeme = L.lexeme spaces -mSpace :: Parser ()+mSpace :: Parser le () mSpace = L.space space1-  (L.skipLineComment "#")-  (L.skipBlockComment "/*" "*/" >> space >> void (optional semicolon))+  (L.skipLineComment "#" >> optionalSemicolon)+  (L.skipBlockComment "/*" "*/" >> optionalSemicolon)+  where+    optionalSemicolon = space >> void (optional semicolon) +spaces :: Parser le ()+spaces =+  (mandatorySpaceOrComment >> mSpace)+  <|> hasFollowingDelimiter ["}", "{", "]", ")", "|", ",", ";", ":", "."]+  <|> eof+  where+    mandatorySpaceOrComment = hidden (space1 <|> L.skipBlockComment "/*" "*/")+    hasFollowingDelimiter = hidden . choice . map (void . lookAhead . string) -symbol :: Tokens Text -> Parser ()+symbol :: Tokens Text -> Parser le () symbol = void . L.symbol mSpace -symbol' :: Text -> Parser ()+symbol' :: Text -> Parser le () symbol' str = symbol str <|> symbol (T.map toLower str) -word :: Tokens Text -> a -> Parser a-word str val = symbol str $> val+symbol1 :: Tokens Text -> Parser le ()+symbol1 = try . void . L.symbol spaces -word' :: Tokens Text -> a -> Parser a-word' str val = symbol' str $> val+symbol1' :: Text -> Parser le ()+symbol1' str = symbol1 str <|> symbol1 (T.map toLower str) -string' :: (MonadParsec e s f, Tokens s ~ Text) => Text -> f Text+word :: Tokens Text -> a -> Parser le a+word str val = symbol1 str $> val++word' :: Tokens Text -> a -> Parser le a+word' str val = symbol1' str $> val++string' :: Text -> Parser le Text string' str = string str <|> string (T.map toLower str) -parens :: Parser a -> Parser a+parens :: Parser le a -> Parser le a parens = between (symbol "(") (symbol ")") -braces :: Parser a -> Parser a+braces :: Parser le a -> Parser le a braces = between (symbol "{") (symbol "}") -brackets :: Parser a -> Parser a+brackets :: Parser le a -> Parser le a brackets = between (symbol "[") (symbol "]") -brackets' :: Parser a -> Parser a+brackets' :: Parser le a -> Parser le a brackets' = between (string "[") (string "]") -semicolon :: Parser ()+semicolon :: Parser le () semicolon = symbol ";" -comma :: Parser ()+comma :: Parser le () comma = symbol "," -varID :: Parser U.Var+varID :: Parser le U.Var varID = lexeme $ do   v <- lowerChar   vs <- many lowerAlphaNumChar   return $ U.Var (toText (v:vs))   where-    lowerAlphaNumChar :: Parser Char+    lowerAlphaNumChar :: Parser' le Char     lowerAlphaNumChar = satisfy (\x -> isLower x || isDigit x)
src/Morley/Michelson/Parser/Macro.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ -- | Parsing of built-in Michelson macros.  module Morley.Michelson.Parser.Macro@@ -20,126 +22,126 @@  import Text.Megaparsec (customFailure, label, notFollowedBy, skipMany, try) import Text.Megaparsec.Char.Lexer (decimal)-import qualified Unsafe (fromIntegral)+import Unsafe qualified (fromIntegral)  import Morley.Michelson.Macro   (CadrStruct(..), Macro(..), PairStruct(..), ParsedOp(..), UnpairStruct(..))-import qualified Morley.Michelson.Macro as Macro+import Morley.Michelson.Macro qualified as Macro import Morley.Michelson.Parser.Annotations import Morley.Michelson.Parser.Error import Morley.Michelson.Parser.Helpers import Morley.Michelson.Parser.Instr import Morley.Michelson.Parser.Lexer import Morley.Michelson.Parser.Type-import Morley.Michelson.Parser.Types (Parser)+import Morley.Michelson.Parser.Types (Parser, Parser', assertLetEnv) import Morley.Michelson.Untyped (T(..), Ty(..), noAnn) import Morley.Util.Positive -macro :: Parser ParsedOp -> Parser Macro+macro :: Parser' le ParsedOp -> Parser le Macro macro opParser = label "macro"-   $  word' "CASE" CASE <*> someNE ops-  <|> symbol' "TAG" *> tagMac-  <|> symbol' "ACCESS" *> accessMac-  <|> symbol' "SET " *> setMac-  <|> word' "CONSTRUCT" CONSTRUCT <*> someNE ops-  <|> word' "VIEW_" VIEW_ <*> ops-  <|> word' "VOID" VOID <*> ops-  <|> word' "CMP" CMP <*> cmpOp <*> noteDef+   $ setCadrMac+  <|> (word' "CASE" CASE <* assertLetEnv) <*> someNE ops+  <|> (symbol1' "TAG" <* assertLetEnv) *> tagMac+  <|> (symbol1' "ACCESS" <* assertLetEnv) *> accessMac+  <|> (symbol1' "SET" <* assertLetEnv) *> setMac+  <|> (word' "CONSTRUCT" CONSTRUCT <* assertLetEnv) <*> someNE ops+  <|> (word' "VIEW_" VIEW_ <* assertLetEnv) <*> ops+  <|> (word' "VOID" VOID <* assertLetEnv) <*> ops+  <|> (string' "CMP" >> return CMP <*> cmpOp <*> noteDef)   <|> word' "IF_SOME" IF_SOME <*> ops <*> ops   <|> word' "IF_RIGHT" IF_RIGHT <*> ops <*> ops   <|> word' "FAIL" FAIL-  <|> word' "ASSERT_CMP" ASSERT_CMP <*> cmpOp+  <|> (string' "ASSERT_CMP" >> return ASSERT_CMP <*> cmpOp)   <|> word' "ASSERT_NONE" ASSERT_NONE   <|> word' "ASSERT_SOME" ASSERT_SOME   <|> word' "ASSERT_LEFT" ASSERT_LEFT   <|> word' "ASSERT_RIGHT" ASSERT_RIGHT-  <|> word' "ASSERT_" ASSERTX <*> cmpOp+  <|> (string' "ASSERT_" >> return ASSERTX <*> cmpOp)   <|> word' "ASSERT" ASSERT-  <|> do string' "DI"; n <- num "I"; symbol' "P"; DIIP (n + 1) <$> ops+  <|> do string' "DI"; n <- num "I"; symbol1' "P"; DIIP (n + 1) <$> ops   <|> unpairMac-  <|> setCadrMac   where    ops = ops' opParser    num str = Unsafe.fromIntegral @Int @Word . length <$> some (string' str) -duupMac :: Parser Macro-duupMac = do string' "DU"; n <- num "U"; symbol' "P"; DUUP (n + 1) <$> noteDef+duupMac :: Parser le Macro+duupMac = do string' "DU"; n <- num "U"; symbol1' "P"; DUUP (n + 1) <$> noteDef   where     num str = Unsafe.fromIntegral @Int @Word . length <$> some (string' str) -pairMacInner :: Parser PairStruct+pairMacInner :: Parser le PairStruct pairMacInner = do   string' "P"   l <- (string' "A" $> F noAnn) <|> pairMacInner   r <- (string' "I" $> F noAnn) <|> pairMacInner   return $ P l r -pairMac :: Parser Macro+pairMac :: Parser le Macro pairMac = do   a <- pairMacInner-  symbol' "R"+  symbol1' "R"   (tn, vn, fns) <- permute3Def noteDef note (some note)   let ps = Macro.mapPairLeaves fns a   return $ PAPAIR ps tn vn -unpairMacInner :: Parser UnpairStruct+unpairMacInner :: Parser le UnpairStruct unpairMacInner = do   string' "P"   l <- (string' "A" $> UF) <|> unpairMacInner   r <- (string' "I" $> UF) <|> unpairMacInner   return $ UP l r -unpairMac :: Parser Macro+unpairMac :: Parser le Macro unpairMac = do   string' "UN"   a <- unpairMacInner-  symbol' "R"+  symbol1' "R"   skipMany $ (void noteF) <|> (void noteV)   return $ UNPAPAIR a -cadrMac :: Parser Macro+cadrMac :: Parser le Macro cadrMac = lexeme $ do   string' "C"   a <- some $ try $ cadrInner <* notFollowedBy (string' "R")   b <- cadrInner-  symbol' "R"+  symbol1' "R"   (vn, fn) <- notesVF   return $ CADR (a ++ pure b) vn fn -cadrInner :: Parser CadrStruct+cadrInner :: Parser le CadrStruct cadrInner = (string' "A" $> A) <|> (string' "D" $> D) -carnMac :: Parser Macro-carnMac = symbol' "CAR" *> (CARN <$> noteDef <*> lexeme decimal)+carnMac :: Parser le Macro+carnMac = symbol1' "CAR" *> (CARN <$> noteDef <*> lexeme decimal) -cdrnMac :: Parser Macro-cdrnMac = symbol' "CDR" *> (CDRN <$> noteDef <*> lexeme decimal)+cdrnMac :: Parser le Macro+cdrnMac = symbol1' "CDR" *> (CDRN <$> noteDef <*> lexeme decimal)  {-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-}-setCadrMac :: Parser Macro+setCadrMac :: Parser le Macro setCadrMac = do   string' "SET_C"   a <- some cadrInner-  symbol' "R"+  symbol1' "R"   (v, f) <- notesVF   return $ SET_CADR a v f -mapCadrMac :: Parser ParsedOp -> Parser Macro+mapCadrMac :: Parser le ParsedOp -> Parser le Macro mapCadrMac opParser = do   string' "MAP_C"   a <- some cadrInner-  symbol' "R"+  symbol1' "R"   (v, f) <- notesVF   MAP_CADR a v f <$> ops' opParser -ifCmpMac :: Parser ParsedOp -> Parser Macro-ifCmpMac opParser =-  word' "IFCMP" IFCMP <*> cmpOp <*> noteDef <*> ops' opParser <*> ops' opParser+ifCmpMac :: Parser le ParsedOp -> Parser le Macro+ifCmpMac opParser = string' "IFCMP" >> return+  IFCMP <*> cmpOp <*> noteDef <*> ops' opParser <*> ops' opParser -tagMac :: Parser Macro+tagMac :: Parser le Macro tagMac = do   idx <- decimal-  mSpace+  spaces   ty <- type_   let utys = unrollUnion ty []   when (Unsafe.fromIntegral @Natural @Int idx >= length utys) $@@ -151,19 +153,19 @@       Ty (TOr _ _ l r) _ -> unrollUnion l . toList . unrollUnion r       _ -> (ty :|) -accessMac :: Parser Macro+accessMac :: Parser le Macro accessMac = do   idx <- decimal-  mSpace+  spaces   size <- positive   when (idx >= unPositive size) $     customFailure $ WrongAccessArgs idx size   return $ ACCESS idx size -setMac :: Parser Macro+setMac :: Parser le Macro setMac = do   idx <- decimal-  mSpace+  spaces   size <- positive   when (idx >= unPositive size) $     customFailure $ WrongSetArgs idx size
src/Morley/Michelson/Parser/Type.hs view
@@ -1,7 +1,12 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}++-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+ -- | Parsing of Michelson types.  module Morley.Michelson.Parser.Type@@ -12,16 +17,18 @@ import Prelude hiding (note, some, try)  import Data.Default (Default, def)-import qualified Data.Map as Map+import Data.Map qualified as Map+import Data.Type.Equality ((:~:)(Refl)) import Fmt (pretty) import Text.Megaparsec (choice, customFailure, label, sepBy)+import Text.Megaparsec.Char.Lexer qualified as L  import Morley.Michelson.Let (LetType(..)) import Morley.Michelson.Parser.Annotations import Morley.Michelson.Parser.Error import Morley.Michelson.Parser.Helpers import Morley.Michelson.Parser.Lexer-import Morley.Michelson.Parser.Types (Parser, letTypes)+import Morley.Michelson.Parser.Types (LetEnv, Parser, Parser', assertLetEnv, isLetEnv, letTypes) import Morley.Michelson.Untyped import Morley.Util.Generic @@ -29,17 +36,17 @@ -- -- Note that this includes parenthesized ones for efficiency, see 't_operator'. -- That is to say, @int@, @(int)@, @((int))@, etc will match with this parser and produce @TInt@.-type_ :: Parser Ty+type_ :: Parser le Ty type_ = snd <$> typeInner (pure noAnn) -field :: Parser (FieldAnn, Ty)+field :: Parser le (FieldAnn, Ty) field = typeInner note  -- | 't_operator' parses tuples @(a, b, c)@, variants @(a | b | c)@, and also type expressions in -- parentheses @(a)@ and unit @()@. This is done this way for performance considerations. -- -- Consequently, 't_unit' doesn't bother with parsing @()@.-t_operator :: Parser FieldAnn -> Parser (FieldAnn, Ty)+t_operator :: Parser' le FieldAnn -> Parser le (FieldAnn, Ty) t_operator fp = do   whole <- parens do     optional do@@ -54,12 +61,14 @@   (f, t) <- fieldType fp   case whole of     Just (ty, Just (isOr, tys)) -> do+      assertLetEnv       let (f', Ty ty' _) = mkGenericTree (mergeTwo isOr) (ty :| tys)       f'' <- mergeAnnots f f'       return (f'', Ty ty' t)     Just (res, _) -> do       return res     Nothing -> do+      assertLetEnv       return (f, Ty TUnit t)   where     mergeTwo isOr _ (l, a) (r, b) =@@ -71,8 +80,8 @@       | otherwise = customFailure ExcessFieldAnnotation  typeInner-  :: Parser FieldAnn -> Parser (FieldAnn, Ty)-typeInner fp = label "type" $ lexeme $ choice $ (\x -> x fp) <$>+  :: Parser le FieldAnn -> Parser le (FieldAnn, Ty)+typeInner fp = label "type" $ choice $ (\x -> x fp) <$>   [ t_operator   , t_int, t_nat, t_string, t_bytes, t_mutez, t_bool   , t_keyhash, t_timestamp, t_address@@ -81,9 +90,15 @@   , t_option, t_list, t_set   , t_operation, t_contract, t_ticket, t_pair, t_or   , t_lambda, t_map, t_big_map, t_view-  , t_void, t_letType+  , t_void, t_letType'   , t_chestKey, t_chest+  , t_saplingState, t_saplingTransaction   ]+  where+    t_letType' :: forall le fp. Default fp => Parser' le fp -> Parser le (fp, Ty)+    t_letType' = case isLetEnv @le of+      Just Refl -> t_letType+      Nothing -> const mzero  ---------------------------------------------------------------------------- -- Non-comparable types@@ -93,107 +108,107 @@ mkType t (a, ta) = (a, Ty t ta)  -t_int :: (Default a) => Parser a -> Parser (a, Ty)+t_int :: (Default a) => Parser' le a -> Parser le (a, Ty) t_int fp = word' "Int" (mkType TInt) <*> fieldType fp -t_nat :: (Default a) => Parser a -> Parser (a, Ty)+t_nat :: (Default a) => Parser' le a -> Parser le (a, Ty) t_nat fp = word' "Nat" (mkType TNat) <*> fieldType fp -t_string :: (Default a) => Parser a -> Parser (a, Ty)+t_string :: (Default a) => Parser' le a -> Parser le (a, Ty) t_string fp = word' "String" (mkType TString) <*> fieldType fp -t_bytes :: (Default a) => Parser a -> Parser (a, Ty)+t_bytes :: (Default a) => Parser' le a -> Parser le (a, Ty) t_bytes fp = word' "Bytes" (mkType TBytes) <*> fieldType fp -t_mutez :: (Default a) => Parser a -> Parser (a, Ty)+t_mutez :: (Default a) => Parser' le a -> Parser le (a, Ty) t_mutez fp = word' "Mutez" (mkType TMutez) <*> fieldType fp -t_bool :: (Default a) => Parser a -> Parser (a, Ty)+t_bool :: (Default a) => Parser' le a -> Parser le (a, Ty) t_bool fp = word' "Bool" (mkType TBool) <*> fieldType fp -t_keyhash :: (Default a) => Parser a -> Parser (a, Ty)+t_keyhash :: (Default a) => Parser' le a -> Parser le (a, Ty) t_keyhash fp = ((word' "KeyHash" (mkType TKeyHash)) <|> (word "key_hash" (mkType TKeyHash))) <*> fieldType fp -t_timestamp :: (Default a) => Parser a -> Parser (a, Ty)+t_timestamp :: (Default a) => Parser' le a -> Parser le (a, Ty) t_timestamp fp = word' "Timestamp" (mkType TTimestamp) <*> fieldType fp -t_address :: (Default a) => Parser a -> Parser (a, Ty)+t_address :: (Default a) => Parser' le a -> Parser le (a, Ty) t_address fp = word' "Address" (mkType TAddress) <*> fieldType fp -t_key :: (Default a) => Parser a -> Parser (a, Ty)+t_key :: (Default a) => Parser' le a -> Parser le (a, Ty) t_key fp = word' "Key" (mkType TKey) <*> fieldType fp -t_signature :: (Default a) => Parser a -> Parser (a, Ty)+t_signature :: (Default a) => Parser' le a -> Parser le (a, Ty) t_signature fp = word' "Signature" (mkType TSignature) <*> fieldType fp -t_bls12381fr :: (Default a) => Parser a -> Parser (a, Ty)+t_bls12381fr :: (Default a) => Parser' le a -> Parser le (a, Ty) t_bls12381fr fp = do-  symbol' "bls12_381_fr" <|> symbol' "Bls12381Fr"+  symbol1' "bls12_381_fr" <|> symbol1' "Bls12381Fr"   mkType TBls12381Fr <$> fieldType fp -t_bls12381g1 :: (Default a) => Parser a -> Parser (a, Ty)+t_bls12381g1 :: (Default a) => Parser' le a -> Parser le (a, Ty) t_bls12381g1 fp = do-  symbol' "bls12_381_g1" <|> symbol' "Bls12381G1"+  symbol1' "bls12_381_g1" <|> symbol1' "Bls12381G1"   mkType TBls12381G1 <$> fieldType fp -t_bls12381g2 :: (Default a) => Parser a -> Parser (a, Ty)+t_bls12381g2 :: (Default a) => Parser' le a -> Parser le (a, Ty) t_bls12381g2 fp = do-  symbol' "bls12_381_g2" <|> symbol' "Bls12381G2"+  symbol1' "bls12_381_g2" <|> symbol1' "Bls12381G2"   mkType TBls12381G2 <$> fieldType fp -t_chestKey :: (Default a) => Parser a -> Parser (a, Ty)+t_chestKey :: (Default a) => Parser' le a -> Parser le (a, Ty) t_chestKey fp = do   symbol' "ChestKey" <|> symbol' "chest_key"   mkType TChestKey <$> fieldType fp -t_chest :: (Default a) => Parser a -> Parser (a, Ty)+t_chest :: (Default a) => Parser' le a -> Parser le (a, Ty) t_chest fp = word' "Chest" (mkType TChest) <*> fieldType fp -t_chain_id :: (Default a) => Parser a -> Parser (a, Ty)+t_chain_id :: (Default a) => Parser' le a -> Parser le (a, Ty) t_chain_id fp = do-  symbol' "ChainId" <|> symbol' "chain_id"+  symbol1' "ChainId" <|> symbol1' "chain_id"   mkType TChainId <$> fieldType fp -t_operation :: (Default a) => Parser a -> Parser (a, Ty)+t_operation :: (Default a) => Parser' le a -> Parser le (a, Ty) t_operation fp = word' "Operation" (mkType TOperation) <*> fieldType fp -t_contract :: (Default a) => Parser a -> Parser (a, Ty)+t_contract :: (Default a) => Parser' le a -> Parser le (a, Ty) t_contract fp = do-  symbol' "Contract"+  symbol1' "Contract"   (f, t) <- fieldType fp   a <- type_   return (f, Ty (TContract a) t) -t_ticket :: (Default a) => Parser a -> Parser (a, Ty)+t_ticket :: (Default a) => Parser' le a -> Parser le (a, Ty) t_ticket fp = do-  symbol' "Ticket"+  symbol1' "Ticket"   (f, t) <- fieldType fp   a <- type_   return (f, Ty (TTicket a) t)  -- | Parses a @unit@ type. Unit type admits two variants of syntax, @unit@ and @()@. This parser -- handles only the former, the latter is handled in 't_operator'-t_unit :: (Default a) => Parser a -> Parser (a, Ty)+t_unit :: (Default a) => Parser' le a -> Parser le (a, Ty) t_unit fp = do-  symbol' "Unit"+  symbol1' "Unit"   (f,t) <- fieldType fp   return (f, Ty TUnit t) -t_never :: (Default a) => Parser a -> Parser (a, Ty)+t_never :: (Default a) => Parser' le a -> Parser le (a, Ty) t_never fp = do-  symbol' "Never" <|> symbol' "⊥"+  symbol1' "Never" <|> symbol1' "⊥"   (f,t) <- fieldType fp   return (f, Ty TNever t) -t_pair :: (Default a) => Parser a -> Parser (a, Ty)+t_pair :: (Default a) => Parser' le a -> Parser le (a, Ty) t_pair fp = do-  symbol' "Pair"+  symbol1' "Pair"   (fieldAnn, typeAnn) <- fieldType fp   fields <- many field   tPair <- go fields   pure $ (fieldAnn, Ty tPair typeAnn)   where-    go :: [(FieldAnn, Ty)] -> Parser T+    go :: [(FieldAnn, Ty)] -> Parser le T     go = \case       [] -> fail "The 'pair' type expects at least 2 type arguments, but 0 were given."       [(_, t)] -> fail $ "The 'pair' type expects at least 2 type arguments, but only 1 was given: '" <> pretty t <> "'."@@ -203,26 +218,40 @@         rightCombedT <- go fields         pure $ TPair fieldAnnL noAnn noAnn noAnn typeL (Ty rightCombedT noAnn) -t_or :: (Default a) => Parser a -> Parser (a, Ty)+t_or :: (Default a) => Parser' le a -> Parser le (a, Ty) t_or fp = do-  symbol' "Or"+  symbol1' "Or"   (f, t) <- fieldType fp   (l, a) <- field   (r, b) <- field   return (f, Ty (TOr l r a b) t) -t_option :: (Default a) => Parser a -> Parser (a, Ty)+t_option :: (Default a) => Parser' le a -> Parser le (a, Ty) t_option fp = do-  symbol' "Option"+  symbol1' "Option"   (f, t) <- fieldType fp   a <- snd <$> typeInner (pure noAnn)   return (f, Ty (TOption a) t) -t_lambda :: (Default a) => Parser a -> Parser (a, Ty)+t_saplingState :: (Default a) => Parser' le a -> Parser le (a, Ty)+t_saplingState fp = do+  symbol1' "Sapling_state"+  (f,t) <- fieldType fp+  n <- lexeme L.decimal+  return (f, Ty (TSaplingState n) t)++t_saplingTransaction :: (Default a) => Parser' le a -> Parser le (a, Ty)+t_saplingTransaction fp = do+  symbol1' "Sapling_transaction"+  (f,t) <- fieldType fp+  n <- lexeme L.decimal+  return (f, Ty (TSaplingTransaction n) t)++t_lambda :: (Default a) => Parser' le a -> Parser le (a, Ty) t_lambda fp = core <|> slashLambda   where     core = do-      symbol' "Lambda"+      symbol1' "Lambda"       (f, t) <- fieldType fp       a <- type_       b <- type_@@ -232,54 +261,59 @@       (f, t) <- fieldType fp       a <- type_       symbol "->"+      assertLetEnv       b <- type_       return (f, Ty (TLambda a b) t)  -- Container types-t_list :: (Default a) => Parser a -> Parser (a, Ty)+t_list :: forall a le. (Default a) => Parser' le a -> Parser le (a, Ty) t_list fp = core <|> bracketList   where     core = do-      symbol' "List"+      symbol1' "List"       (f, t) <- fieldType fp       a <- type_       return (f, Ty (TList a) t)+    bracketList :: Parser le (a, Ty)     bracketList = do       a <- brackets type_+      assertLetEnv       (f, t) <- fieldType fp       return (f, Ty (TList a) t) -t_set :: (Default a) => Parser a -> Parser (a, Ty)+t_set :: forall a le. (Default a) => Parser' le a -> Parser le (a, Ty) t_set fp = core <|> braceSet   where     core = do-      symbol' "Set"+      symbol1' "Set"       (f, t) <- fieldType fp       a <- type_       return (f, Ty (TSet a) t)+    braceSet :: Parser le (a, Ty)     braceSet = do       a <- braces type_+      assertLetEnv       (f, t) <- fieldType fp       return (f, Ty (TSet a) t)  t_map_like-  :: Default a-  => Parser a -> Parser (Ty, Ty, a, TypeAnn)+  :: (Default a)+  => Parser' le a -> Parser le (Ty, Ty, a, TypeAnn) t_map_like fp = do   (f, t) <- fieldType fp   a <- type_   b <- type_   return (a, b, f, t) -t_map :: (Default a) => Parser a -> Parser (a, Ty)+t_map :: (Default a) => Parser' le a -> Parser le (a, Ty) t_map fp = do-  symbol' "Map"+  symbol1' "Map"   (a, b, f, t) <- t_map_like fp   return (f, Ty (TMap a b) t) -t_big_map :: (Default a) => Parser a -> Parser (a, Ty)+t_big_map :: (Default a) => Parser' le a -> Parser le (a, Ty) t_big_map fp = do-  symbol' "BigMap" <|> symbol "big_map"+  symbol1' "BigMap" <|> symbol1 "big_map"   (a, b, f, t) <- t_map_like fp   return (f, Ty (TBigMap a b) t) @@ -287,7 +321,7 @@ -- Non-standard types (Morley extensions) ---------------------------------------------------------------------------- -t_view :: Default a => Parser a -> Parser (a, Ty)+t_view :: (Default a) => Parser' le a -> Parser le (a, Ty) t_view fp = do   symbol' "View"   a <- type_@@ -296,7 +330,7 @@   let c' = Ty (TContract r) noAnn   return (f, Ty (TPair noAnn noAnn noAnn noAnn a c') t) -t_void :: Default a => Parser a -> Parser (a, Ty)+t_void :: (Default a) => Parser' le a -> Parser le (a, Ty) t_void fp = do   symbol' "Void"   a <- type_@@ -305,12 +339,12 @@   let c = Ty (TLambda b b) noAnn   return (f, Ty (TPair noAnn noAnn noAnn noAnn a c) t) -t_letType :: Default fp => Parser fp -> Parser (fp, Ty)+t_letType :: (Default fp) => Parser' LetEnv fp -> Parser' LetEnv (fp, Ty) t_letType fp = do   lts <- asks letTypes   lt <- ltSig <$> (mkLetType lts)   f <- parseDef fp   return (f, lt) -mkLetType :: Map Text LetType -> Parser LetType+mkLetType :: Map Text LetType -> Parser le LetType mkLetType lts = choice $ mkParser ltName <$> (Map.elems lts)
src/Morley/Michelson/Parser/Types.hs view
@@ -1,33 +1,63 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA ++-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations -Wno-orphans #-}+ -- | Core parser types  module Morley.Michelson.Parser.Types   ( Parser+  , Parser'   , LetEnv (..)   , noLetEnv+  , HasLetEnv(..)+  , assertLetEnv+  , withLetEnv    , MichelsonSource (.., MSStdin, MSCli)   , codeSrc   ) where  import Data.Default (Default(..))-import qualified Data.Map as Map+import Data.Map qualified as Map+import Data.Type.Equality ((:~:)(Refl)) import Fmt (Buildable(..)) import GHC.Stack (SrcLoc(..))-import Text.Megaparsec (Parsec)+import Text.Megaparsec (Parsec, customFailure)  import Morley.Michelson.Let (LetType, LetValue) import Morley.Michelson.Macro (LetMacro) import Morley.Michelson.Parser.Error -type Parser = ReaderT LetEnv (Parsec CustomParserException Text)+type Parser a r = HasLetEnv a => Parser' a r+type Parser' a = ReaderT a (Parsec CustomParserException Text) -instance Default a => Default (Parser a) where+class HasLetEnv a where+  isLetEnv :: Maybe (a :~: LetEnv)++instance HasLetEnv LetEnv where+  isLetEnv = Just Refl++instance HasLetEnv () where+  isLetEnv = Nothing++assertLetEnv :: forall le. Parser le (le :~: LetEnv)+assertLetEnv = maybe (customFailure DeprecatedException) pure $ isLetEnv @le++withLetEnv :: forall le a. Parser' LetEnv a -> Parser le a+withLetEnv p = case isLetEnv @le of+  Just Refl -> p+  Nothing -> mzero++instance Default a => Default (Parser' le a) where   def = pure def +data ParserOptions = ParserOptions+  { poMorleyExts :: Bool+  } deriving stock (Show, Eq)+ -- | The environment containing lets from the let-block data LetEnv = LetEnv   { letMacros :: Map Text LetMacro@@ -35,8 +65,13 @@   , letTypes  :: Map Text LetType   } deriving stock (Show, Eq) +{-# DEPRECATED LetEnv "Let macros are deprecated" #-}+ noLetEnv :: LetEnv noLetEnv = LetEnv Map.empty Map.empty Map.empty++instance Default LetEnv where+  def = noLetEnv  -- | Where a contract or value in Michelson comes from. data MichelsonSource
src/Morley/Michelson/Parser/Value.hs view
@@ -1,7 +1,12 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}++-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+ -- | Parsing of untyped Michelson values.  module Morley.Michelson.Parser.Value@@ -16,22 +21,22 @@  import Prelude hiding (many, note, try) -import qualified Data.Char as Char-import qualified Data.Map as Map-import qualified Text.Hex as Hex+import Data.Char qualified as Char+import Data.Map qualified as Map+import Text.Hex qualified as Hex  import Text.Megaparsec (anySingle, choice, customFailure, label, manyTill, satisfy, takeWhileP, try) import Text.Megaparsec.Char (char, string)-import qualified Text.Megaparsec.Char.Lexer as L+import Text.Megaparsec.Char.Lexer qualified as L  import Morley.Michelson.Let (LetValue(..)) import Morley.Michelson.Macro (ParsedOp, ParsedValue) import Morley.Michelson.Parser.Error import Morley.Michelson.Parser.Helpers import Morley.Michelson.Parser.Lexer-import Morley.Michelson.Parser.Types (Parser, letValues)-import Morley.Michelson.Text (isMChar, unsafeMkMText)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Parser.Types (LetEnv, Parser, Parser', isLetEnv, letValues, withLetEnv)+import Morley.Michelson.Text (isMChar, mkMText)+import Morley.Michelson.Untyped qualified as U  {- Note [Exponential backtracking]@@ -61,36 +66,39 @@  -- | Parse untyped 'ParsedValue'. Take instruction parser as argument -- to avoid cyclic dependencies between modules, hence ' in its name.-value' :: Parser ParsedOp -> Parser ParsedValue-value' opParser = lexeme $ parensOrTuple opParser <|> valueInnerWithoutParens opParser+value' :: Parser le ParsedOp -> Parser le ParsedValue+value' opParser = parensOrTuple opParser <|> valueInnerWithoutParens opParser -parensOrTuple :: Parser ParsedOp -> Parser ParsedValue-parensOrTuple opParser = parens $ foldr1 U.ValuePair <$> value' opParser `sepBy1` comma+parensOrTuple :: forall le. Parser le ParsedOp -> Parser le ParsedValue+parensOrTuple opParser = parens $+  case isLetEnv @le of+    Just{} -> foldr1 U.ValuePair <$> value' opParser `sepBy1` comma+    Nothing -> value' opParser -valueInnerWithoutParens :: Parser ParsedOp -> Parser ParsedValue+valueInnerWithoutParens :: Parser le ParsedOp -> Parser le ParsedValue valueInnerWithoutParens opParser = label "value" $ choice $   [ stringLiteral, bytesLiteral, intLiteral, unitValue   , trueValue, falseValue, pairValueCore opParser, leftValue opParser   , rightValue opParser, someValue opParser, noneValue, nilValue-  , seqOrLambda opParser, mapValue opParser, dataLetValue+  , seqOrLambda opParser, mapValue opParser, withLetEnv dataLetValue   ] -seqOrLambda :: Parser ParsedOp -> Parser ParsedValue+seqOrLambda :: Parser le ParsedOp -> Parser le ParsedValue seqOrLambda opParser = try (lambdaValue opParser) <|> seqValue opParser -stringLiteral :: Parser ParsedValue-stringLiteral = U.ValueString . unsafeMkMText . toText <$> do+stringLiteral :: forall le. Parser le ParsedValue+stringLiteral = lexeme $ U.ValueString . unsafe . mkMText . toText <$> do   _ <- try $ string "\""   manyTill validChar (string "\"")   where-      validChar :: Parser Char+      validChar :: Parser le Char       validChar = choice         [ strEscape         , satisfy (\x -> x /= '"' && isMChar x)         , anySingle >>= stringLiteralFailure . InvalidChar         ] -      strEscape :: Parser Char+      strEscape :: Parser le Char       strEscape = try (char '\\') >> esc         where           esc = choice@@ -103,8 +111,8 @@  -- It is safe not to use `try` here because bytesLiteral is the only -- thing that starts from 0x (at least for now)-bytesLiteral :: Parser (U.Value' op)-bytesLiteral = do+bytesLiteral :: Parser le (U.Value' op)+bytesLiteral = lexeme $ do   string "0x"   hexdigits <- takeWhileP Nothing Char.isHexDigit   let mBytes = Hex.decodeHex hexdigits@@ -113,61 +121,61 @@     (return . U.ValueBytes . U.InternalByteString)     mBytes -intLiteral :: Parser (U.Value' op)-intLiteral = try $ U.ValueInt <$> L.signed pass L.decimal+intLiteral :: Parser le (U.Value' op)+intLiteral = lexeme $ try $ U.ValueInt <$> L.signed pass L.decimal -unitValue :: Parser ParsedValue+unitValue :: Parser le ParsedValue unitValue = word "Unit" U.ValueUnit -trueValue :: Parser ParsedValue+trueValue :: Parser le ParsedValue trueValue = word "True" U.ValueTrue -falseValue :: Parser ParsedValue+falseValue :: Parser le ParsedValue falseValue = word "False" U.ValueFalse -pairValueCore :: Parser ParsedOp -> Parser ParsedValue-pairValueCore opParser = symbol "Pair" *> pairInner+pairValueCore :: Parser le ParsedOp -> Parser le ParsedValue+pairValueCore opParser = symbol1 "Pair" *> pairInner   where     pairInner = U.ValuePair       <$> value' opParser       <*> (foldr1 U.ValuePair <$> some' (value' opParser)) -leftValue :: Parser ParsedOp -> Parser ParsedValue+leftValue :: Parser le ParsedOp -> Parser le ParsedValue leftValue opParser = word "Left" U.ValueLeft <*> value' opParser -rightValue :: Parser ParsedOp -> Parser ParsedValue+rightValue :: Parser le ParsedOp -> Parser le ParsedValue rightValue opParser = word "Right" U.ValueRight <*> value' opParser -someValue :: Parser ParsedOp -> Parser ParsedValue+someValue :: Parser le ParsedOp -> Parser le ParsedValue someValue opParser = word "Some" U.ValueSome <*> value' opParser -noneValue :: Parser ParsedValue+noneValue :: Parser le ParsedValue noneValue = word "None" U.ValueNone -nilValue :: Parser ParsedValue+nilValue :: Parser le ParsedValue nilValue = U.ValueNil <$ (try $ braces pass) -lambdaValue :: Parser ParsedOp -> Parser ParsedValue+lambdaValue :: forall le. Parser le ParsedOp -> Parser le ParsedValue lambdaValue opParser = U.ValueLambda <$> ops1   where-    ops1 :: Parser (NonEmpty ParsedOp)+    ops1 :: Parser le (NonEmpty ParsedOp)     ops1 = braces $ sepEndBy1 opParser semicolon -seqValue :: Parser ParsedOp -> Parser ParsedValue+seqValue :: Parser le ParsedOp -> Parser le ParsedValue seqValue opParser =   U.ValueSeq <$> (try $ braces $ sepEndBy1 (value' opParser) semicolon) -eltValue :: Parser ParsedOp -> Parser (U.Elt ParsedOp)+eltValue :: Parser le ParsedOp -> Parser le (U.Elt ParsedOp) eltValue opParser = word "Elt" U.Elt <*> value' opParser <*> value' opParser -mapValue :: Parser ParsedOp -> Parser ParsedValue+mapValue :: Parser le ParsedOp -> Parser le ParsedValue mapValue opParser =   U.ValueMap <$> (try $ braces $ sepEndBy1 (eltValue opParser) semicolon) -dataLetValue :: Parser ParsedValue+dataLetValue :: Parser' LetEnv ParsedValue dataLetValue = do   lvs <- asks letValues   lvVal <$> (mkLetVal lvs) -mkLetVal :: Map Text LetValue -> Parser LetValue+mkLetVal :: Map Text LetValue -> Parser le LetValue mkLetVal lvs = choice $ mkParser lvName <$> Map.elems lvs
src/Morley/Michelson/Preprocess.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Apply some transformations to Michelson code. @@ -45,9 +44,9 @@   -- ^ Should transform only atomic values, 'dfsMapValue' will be applied to it.   -> Instr inp out   -> Instr inp out-transformConstants dsGoToValues f = fst . dfsInstr def{ dsGoToValues } step+transformConstants dsGoToValues f = dfsModifyInstr def{ dsGoToValues } step   where-    step :: forall i o. Instr i o -> (Instr i o, ())-    step = (,()) . \case+    step :: forall i o. Instr i o -> Instr i o+    step = \case       PUSH v -> PUSH (dfsMapValue f v)       i -> i
src/Morley/Michelson/Printer.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Printer   ( RenderDoc(..)@@ -16,11 +15,11 @@  import Data.Constraint (withDict) import Data.Singletons (SingI)-import qualified Data.Text.Lazy as TL+import Data.Text.Lazy qualified as TL  import Morley.Michelson.Printer.Util (RenderDoc(..), doesntNeedParens, printDoc, renderAnyBuildable)-import qualified Morley.Michelson.Typed as T-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Typed qualified as T+import Morley.Michelson.Untyped qualified as U  -- | Convert an untyped contract into a textual representation which -- will be accepted by the OCaml reference client: tezos-client.
src/Morley/Michelson/Printer/Util.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Utilities for rendering Michelson code in a format compatible with -- Tezos software (e.g @tezos-client@)@@ -29,7 +28,7 @@   ) where  import Control.Exception (assert)-import qualified Data.Text.Lazy as LT+import Data.Text.Lazy qualified as LT import Data.Text.Lazy.Builder (Builder) import Fmt (Buildable, pretty) import Text.PrettyPrint.Leijen.Text@@ -73,6 +72,7 @@ -- instances of the combined value can have a different -- behavior for the pretty printer. newtype Prettier a = Prettier a+  deriving stock Functor  -- | Convert 'Doc' to 'Text' with a line width of 80. printDoc :: Bool -> Doc -> LT.Text
src/Morley/Michelson/Runtime.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Executor and typechecker of a contract in Morley language. @@ -17,6 +16,12 @@   , readAndParseContract   , prepareContract +  -- * Deprecated+  , parseContractExt+  , parseExpandContractExt+  , readAndParseContractExt+  , prepareContractExt+   -- * Re-exports   , ContractState (..)   , AddressState (..)@@ -29,6 +34,10 @@   -- * For testing   , ExecutorOp (..)   , ExecutorRes (..)+  , erGState+  , erUpdates+  , erInterpretResults+  , erRemainingSteps   , ExecutorError' (..)   , ExecutorError   , ExecutorM@@ -38,12 +47,14 @@   , executeGlobalOrigination   , executeOrigination   , executeTransfer--  -- * To avoid warnings (can't generate lenses only for some fields)-  , erInterpretResults-  , erUpdates-  , erGState-  , erRemainingSteps+  , ExecutorState(..)+  , esGState+  , esRemainingSteps+  , esSourceAddress+  , esLog+  , esOperationHash+  , esPrevCounters+  , ExecutorLog(..)   , elInterpreterResults   , elUpdates   ) where@@ -51,10 +62,10 @@ import Control.Lens (assign, at, makeLenses, (.=), (<>=)) import Control.Monad.Except (Except, liftEither, runExcept, throwError) import Data.Default (def)-import qualified Data.HashSet as HS-import Data.Semigroup.Generic+import Data.HashSet qualified as HS+import Data.Semigroup.Generic (GenericSemigroupMonoid(..)) import Data.Text.IO (getContents)-import qualified Data.Text.IO.Utf8 as Utf8 (readFile)+import Data.Text.IO.Utf8 qualified as Utf8 (readFile) import Fmt (Buildable(build), blockListF, fmt, fmtLn, indentF, nameF, pretty, (+|), (|+)) import Text.Megaparsec (parse) @@ -62,21 +73,22 @@   (ContractEnv(..), InterpretError(..), InterpretResult(..), InterpreterState(..), MorleyLogs(..),   RemainingSteps(..), assignBigMapIds, handleContractReturn, interpret) import Morley.Michelson.Macro (ParsedOp, expandContract)-import qualified Morley.Michelson.Parser as P+import Morley.Michelson.Parser qualified as P import Morley.Michelson.Runtime.GState import Morley.Michelson.Runtime.TxData import Morley.Michelson.TypeCheck import Morley.Michelson.Typed-  (CreateContract(..), EntrypointCallT, EpName, Operation'(..), SomeContractAndStorage(..),-  SomeStorage(..), SomeValue(..), TransferTokens(..), untypeValue)-import qualified Morley.Michelson.Typed as T+  (CreateContract(..), EntrypointCallT, EpName, Operation'(..), SomeConstrainedValue(..),+  SomeContractAndStorage(..), SomeStorage, TransferTokens(..), untypeValue)+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Typed.Operation import Morley.Michelson.Untyped (Contract)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Tezos.Address (Address(..), GlobalCounter(..), isKeyAddress) import Morley.Tezos.Core   (Mutez, Timestamp(..), getCurrentTime, unsafeAddMutez, unsafeSubMutez, zeroMutez) import Morley.Tezos.Crypto (KeyHash, parseKeyHash)+import Morley.Util.MismatchError import Morley.Util.Named  ----------------------------------------------------------------------------@@ -123,7 +135,7 @@   -- are executed. In the end they are printed.   , _erRemainingSteps :: RemainingSteps   -- ^ Now much gas all remaining executions can consume.-  } deriving stock (Show)+  } deriving stock Show  data ExecutorEnv = ExecutorEnv   { _eeNow :: Timestamp@@ -177,7 +189,7 @@   -- ^ Failed to apply updates to GState.   | EEIllTypedParameter a TCError   -- ^ Contract parameter is ill-typed.-  | EEUnexpectedParameterType a T.T T.T+  | EEUnexpectedParameterType a (MismatchError T.T)   -- ^ Contract parameter is well-typed, but its type does   -- not match the entrypoint's type.   | EEUnknownEntrypoint EpName@@ -208,10 +220,9 @@         "Transaction of 0ꜩ towards a key address " +| addr |+ " which has no code is prohibited"       EEFailedToApplyUpdates err -> "Failed to update GState: " +| err |+ ""       EEIllTypedParameter _ err -> "The contract parameter is ill-typed: " +| err |+ ""-      EEUnexpectedParameterType _ actualT expectedT ->-        "The contract parameter is well-typed, but did not match the contract's entrypoint's type.\n" <>-        "Expected: " +| expectedT |+ "\n" <>-        "Got: " +| actualT |+ ""+      EEUnexpectedParameterType _ merr ->+        "The contract parameter is well-typed, but did not match the contract's entrypoint's type.\n"+        +| merr |+ ""       EEUnknownEntrypoint epName -> "The contract does not contain entrypoint '" +| epName |+ "'"       EETransactionFromContract addr amount ->         "Global transaction of funds (" +| amount |+ ") from an originated contract (" +| addr |+ ") is prohibited."@@ -230,17 +241,57 @@ ----------------------------------------------------------------------------  -- | Parse a contract from 'Text'.-parseContract ::-     P.MichelsonSource -> Text -> Either P.ParserException (U.Contract' ParsedOp)+parseContract+  :: P.MichelsonSource -> Text -> Either P.ParserException (U.Contract' ParsedOp) parseContract source =   first P.ParserException . parse P.program (pretty source)  -- | Parse a contract from 'Text' and expand macros.-parseExpandContract ::-     P.MichelsonSource -> Text -> Either P.ParserException Contract+parseExpandContract+  :: P.MichelsonSource -> Text -> Either P.ParserException Contract parseExpandContract = fmap expandContract ... parseContract +-- TODO [#712]: Remove this next major release+-- | Parse a contract from 'Text' with Morley extensions.+parseContractExt+  :: P.MichelsonSource -> Text -> Either P.ParserException (U.Contract' ParsedOp)+parseContractExt source =+  first P.ParserException . parse P.programExt (pretty source)++-- TODO [#712]: Remove this next major release+-- | Parse a contract from 'Text' and expand macros with Morley extensions.+parseExpandContractExt+  :: P.MichelsonSource -> Text -> Either P.ParserException Contract+parseExpandContractExt = fmap expandContract ... parseContractExt++-- TODO [#712]: Remove this next major release -- | Read and parse a contract from give path or `stdin` (if the+-- argument is 'Nothing') with Morley extensions. The contract is not expanded.+readAndParseContractExt :: Maybe FilePath -> IO (U.Contract' ParsedOp)+readAndParseContractExt mFilename = do+  code <- readCode mFilename+  either throwM pure $ parseContractExt (toSrc mFilename) code+  where+    readCode :: Maybe FilePath -> IO Text+    readCode = maybe getContents Utf8.readFile++    toSrc :: Maybe FilePath -> P.MichelsonSource+    toSrc = maybe P.MSUnspecified P.MSFile+-- TODO [#712]: Remove this next major release+-- | Read a contract using 'readAndParseContract', expand and+-- flatten with Morley extensions. The contract is not type checked.+prepareContractExt :: Maybe FilePath -> IO Contract+prepareContractExt mFile = expandContract <$> readAndParseContractExt mFile+++{-# DEPRECATED+  parseContractExt,+  parseExpandContractExt,+  readAndParseContractExt,+  prepareContractExt+  "Morley extensions are deprecated" #-}++-- | Read and parse a contract from give path or `stdin` (if the -- argument is 'Nothing'). The contract is not expanded. readAndParseContract :: Maybe FilePath -> IO (U.Contract' ParsedOp) readAndParseContract mFilename = do@@ -303,10 +354,11 @@   -> "dryRun" :! Bool   -> IO SomeStorage runContract maybeNow maybeLevel maxSteps initBalance dbPath tcOpts uStorage uContract txData-  verbose (N dryRun) = do+  verbose (arg #dryRun -> dryRun) = do   origination <- either throwM pure . typeCheckingWith tcOpts $     mkOrigination <$> typeCheckContractAndStorage uContract uStorage-  (_, newSt) <- runExecutorMWithDB maybeNow maybeLevel dbPath (RemainingSteps maxSteps) verbose ! #dryRun dryRun $ do+  (_, newSt) <- runExecutorMWithDB maybeNow maybeLevel dbPath+    (RemainingSteps maxSteps) verbose ! #dryRun dryRun $ do     -- Here we are safe to bypass executeGlobalOperations for origination,     -- since origination can't generate more operations.     addr <- executeGlobalOrigination origination@@ -422,7 +474,7 @@   -> ExecutorM a   -> IO (ExecutorRes, a) runExecutorMWithDB maybeNow maybeLevel dbPath remainingSteps-  (N verbose)+  (arg #verbose -> verbose)   (argDef #dryRun False -> dryRun)   action = do   gState <- readGState dbPath@@ -476,7 +528,7 @@               executeDelegation isGlobalOp operation               executeMany (#isGlobalOp :! False) opsTail             TransferOp transferOperation -> do-              moreOps <- executeTransfer isGlobalOp tcOpts transferOperation+              moreOps <- executeTransfer isGlobalOp Nothing tcOpts transferOperation               executeMany (#isGlobalOp :! False) $ moreOps <> opsTail  -- | Execute a global origination operation.@@ -488,7 +540,7 @@   :: "isGlobalOp" :! Bool   -> OriginationOperation   -> ExecutorM Address-executeOrigination (N isGlobalOp) origination@(OriginationOperation{..}) = do+executeOrigination (arg #isGlobalOp -> isGlobalOp) origination@(OriginationOperation{..}) = do   when isGlobalOp $ do     beginGlobalOperation     assign esOperationHash $ mkOriginationOperationHash origination@@ -501,7 +553,7 @@    -- Add big_map IDS to storage   let bigMapCounter0 = gs ^. gsBigMapCounterL-  let (storageWithIds, bigMapCounter1) = runState (assignBigMapIds ooStorage) bigMapCounter0+  let (storageWithIds, bigMapCounter1) = runState (assignBigMapIds False ooStorage) bigMapCounter0    let contractState = ContractState ooBalance ooContract storageWithIds ooDelegate @@ -541,7 +593,7 @@   :: "isGlobalOp" :! Bool   -> SetDelegateOperation   -> ExecutorM ()-executeDelegation (N isGlobalOp) delegation@(SetDelegateOperation{..}) = do+executeDelegation (arg #isGlobalOp -> isGlobalOp) delegation@(SetDelegateOperation{..}) = do   when isGlobalOp $ do     beginGlobalOperation     assign esOperationHash $ mkDelegationOperationHash delegation@@ -562,10 +614,17 @@ -- | Execute a transfer operation. executeTransfer   :: "isGlobalOp" :! Bool+  -> Maybe Mutez+  -- ^ Whether to override the destination's balance.+  --+  -- When it's a `Just`, the destination's balance will be set to the given amount+  -- and no tz will be debited from the sender's account.+  -- This is useful to emulate the behaviour of the Tezos RPC's @/run_code@ endpoint.   -> TypeCheckOptions   -> TransferOperation   -> ExecutorM [ExecutorOp]-executeTransfer (N isGlobalOp) tcOpts transferOperation@(TransferOperation addr txData _) = do+executeTransfer (arg #isGlobalOp -> isGlobalOp)+  overrideBalanceMb tcOpts transferOperation@(TransferOperation addr txData _) = do     when isGlobalOp $       beginGlobalOperation @@ -589,16 +648,18 @@     -- Transferring 0 XTZ to a key address is prohibited.     when (isZeroTransfer && isKeyAddress addr) $       throwError $ EEZeroTransaction addr-    mDecreaseSenderBalance <- case (isZeroTransfer, addresses ^. at senderAddr) of-      (True, _) -> pure Nothing-      (False, Nothing) -> throwError $ EEUnknownSender senderAddr-      (False, Just (asBalance -> balance))-        | balance < tdAmount txData ->-          throwError $ EENotEnoughFunds senderAddr balance-        | otherwise ->-          -- Subtraction is safe because we have checked its-          -- precondition in guard.-          return $ Just $ GSSetBalance senderAddr (balance `unsafeSubMutez` tdAmount txData)+    mDecreaseSenderBalance <-+      if isNothing overrideBalanceMb && not isZeroTransfer+        then case addresses ^. at senderAddr of+          Nothing -> throwError $ EEUnknownSender senderAddr+          Just (asBalance -> balance)+            | balance < tdAmount txData ->+              throwError $ EENotEnoughFunds senderAddr balance+            | otherwise ->+              -- Subtraction is safe because we have checked its+              -- precondition in guard.+              return $ Just $ GSSetBalance senderAddr (balance `unsafeSubMutez` tdAmount txData)+        else pure Nothing     when (not (isKeyAddress senderAddr) && isGlobalOp && not isZeroTransfer) $       throwError $ EETransactionFromContract senderAddr $ tdAmount txData     let onlyUpdates updates = return (updates, [], Nothing, remainingSteps)@@ -611,20 +672,29 @@           transferAmount = tdAmount txData           addrState = ASSimple transferAmount           upd = GSAddAddress addr addrState+         onlyUpdates [upd]       (Just (ASSimple oldBalance), _) -> do-        -- can't overflow if global state is correct (because we can't-        -- create money out of nowhere)         let-          newBalance = oldBalance `unsafeAddMutez` tdAmount txData+          -- Calculate the account's new balance, unless `overrideBalanceMb` is used.+          -- Note: `unsafeAddMutez` can't overflow if global state is correct (because we can't+          -- create money out of nowhere)+          newBalance =+            fromMaybe+              (oldBalance `unsafeAddMutez` tdAmount txData)+              overrideBalanceMb           upd = GSSetBalance addr newBalance         onlyUpdates [upd]       (Just (ASContract (ContractState {..})), _) -> do         let           existingContracts = extractAllContracts gs-          -- can't overflow if global state is correct (because we can't-          -- create money out of nowhere)-          newBalance = csBalance `unsafeAddMutez` tdAmount txData+          newBalance =+            -- Calculate the contract's new balance, unless `overrideBalanceMb` is used.+            -- Note: `unsafeAddMutez` can't overflow if global state is correct (because we can't+            -- create money out of nowhere)+            fromMaybe+              (csBalance `unsafeAddMutez` tdAmount txData)+              overrideBalanceMb           epName = tdEntrypoint txData          T.MkEntrypointCallRes _ (epc :: EntrypointCallT cp epArg)@@ -644,7 +714,7 @@                 typeVerifyParameter @epArg existingContracts untypedVal          let bigMapCounter0 = gs ^. gsBigMapCounterL-        let (typedParameterWithIds, bigMapCounter1) = runState (assignBigMapIds typedParameter) bigMapCounter0+        let (typedParameterWithIds, bigMapCounter1) = runState (assignBigMapIds False typedParameter) bigMapCounter0          -- I'm not entirely sure why we need to pattern match on `()` here,         -- but, if we don't, we get a compiler error that I suspect is somehow related
src/Morley/Michelson/Runtime/Dummy.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Dummy data to be used in tests or demos where it's not essential. @@ -20,10 +19,10 @@ import Morley.Michelson.Interpret (ContractEnv(..), RemainingSteps) import Morley.Michelson.Runtime.GState (BigMapCounter, dummyVotingPowers, genesisAddress) import Morley.Michelson.Typed (ParameterScope, StorageScope)-import qualified Morley.Michelson.Typed as T+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Typed.Operation (OriginationOperation(..)) import Morley.Tezos.Address (GlobalCounter(..))-import Morley.Tezos.Core (Timestamp(..), dummyChainId, toMutez)+import Morley.Tezos.Core (Timestamp(..), dummyChainId, tz)  -- | Dummy timestamp, can be used to specify current @NOW@ value or -- maybe something else.@@ -54,12 +53,12 @@ dummyContractEnv = ContractEnv   { ceNow = dummyNow   , ceMaxSteps = dummyMaxSteps-  , ceBalance = toMutez 100+  , ceBalance = [tz|100u|]   , ceContracts = mempty   , ceSelf = genesisAddress   , ceSource = genesisAddress   , ceSender = genesisAddress-  , ceAmount = toMutez 100+  , ceAmount = [tz|100u|]   , ceVotingPowers = dummyVotingPowers   , ceChainId = dummyChainId   , ceOperationHash = Nothing@@ -79,7 +78,7 @@ dummyOrigination storage contract counter = OriginationOperation   { ooOriginator = genesisAddress   , ooDelegate = Nothing-  , ooBalance = toMutez 100+  , ooBalance = [tz|100u|]   , ooStorage = storage   , ooContract = contract   , ooCounter = counter
src/Morley/Michelson/Runtime/GState.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Global blockchain state (emulated). @@ -36,6 +35,7 @@   , genesisAddress4   , genesisAddress5   , genesisAddress6+  , genesisAddressN   , genesisKeyHash   -- * Genesis secret keys   , genesisSecretKey@@ -55,20 +55,19 @@  import Control.Lens (at, makeLenses) import Data.Aeson (FromJSON(..), ToJSON(..), object, withObject, (.:), (.:?), (.=))-import qualified Data.Aeson as Aeson-import qualified Data.Aeson.Encode.Pretty as Aeson+import Data.Aeson qualified as Aeson+import Data.Aeson.Encode.Pretty qualified as Aeson import Data.Aeson.TH (deriveJSON)-import qualified Data.ByteString.Lazy as LBS+import Data.ByteString.Lazy qualified as LBS import Data.Default (def)-import Data.List.NonEmpty ((!!))-import qualified Data.Map.Strict as Map+import Data.Map.Strict qualified as Map import Data.Type.Equality ((:~:)(..))-import Fmt (Buildable(build), (+|), (|+))+import Fmt (Buildable(build), pretty, (+|), (|+)) import System.IO.Error (IOError, isDoesNotExistError)  import Morley.Michelson.TypeCheck   (SomeParamType(..), TcOriginatedContracts, typeCheckContractAndStorage, typeCheckingWith)-import qualified Morley.Michelson.Typed as T+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Typed.Existential (SomeContractAndStorage(..)) import Morley.Michelson.Typed.Scope import Morley.Michelson.Untyped (Contract, Value)@@ -77,7 +76,10 @@ import Morley.Tezos.Crypto import Morley.Util.Aeson import Morley.Util.Lens-import Morley.Util.Sing (eqI)+import Morley.Util.Peano+import Morley.Util.Sing (eqI, eqParamSing, eqParamSing2)+import Morley.Util.SizedList qualified as SL+import Morley.Util.SizedList.Types  -- | State of a contract with code. data ContractState =@@ -94,6 +96,13 @@  deriving stock instance Show ContractState +instance Eq ContractState where+  ContractState b1 c1 s1 d1 == ContractState b2 c2 s2 d2 =+    b1 == b2+    && eqParamSing2 c1 c2+    && eqParamSing s1 s2+    && d1 == d2+ instance ToJSON ContractState where   toJSON ContractState{..} =     object .@@ -116,7 +125,7 @@       case typeCheckingWith def $ typeCheckContractAndStorage uContract uStorage of         Right (SomeContractAndStorage contract storage) ->           pure $ ContractState balance contract storage delegate-        Left err -> fail $ "Unable to parse `ContractState`: " <> (show err)+        Left err -> fail $ "Unable to parse `ContractState`: " <> pretty err  instance Buildable ContractState where   build ContractState{..} =@@ -132,7 +141,7 @@   | ASContract ContractState   -- ^ For contracts with code we store more state represented by   -- 'ContractState'.-  deriving stock (Show, Generic)+  deriving stock (Show, Eq, Generic)  instance Buildable AddressState where   build =@@ -158,7 +167,7 @@ -- exported. newtype VotingPowers   = VotingPowers (Map KeyHash Natural)-  deriving stock (Show)+  deriving stock (Show, Eq)  deriveJSON morleyAesonOptions ''VotingPowers @@ -203,62 +212,73 @@   , gsCounter :: GlobalCounter   -- ^ Ever increasing operation counter.   , gsBigMapCounter :: BigMapCounter-  } deriving stock (Show)+  } deriving stock (Show, Eq)  makeLensesWith postfixLFields ''GState  deriveJSON morleyAesonOptions ''GState --- | Number of genesis addresses.-genesisAddressesNum :: Word-genesisAddressesNum = 10+-- | Number of genesis addresses, type-level+type GenesisAddressesNum = 10 +-- | Convenience synonym+type GenesisList a = SizedList GenesisAddressesNum a++-- | Number of genesis addresses, term-level+genesisAddressesNum :: Natural+genesisAddressesNum = natVal @GenesisAddressesNum Proxy+ -- | Secrets from which genesis addresses are derived from.-genesisSecrets :: NonEmpty SecretKey-genesisSecrets = do-  i <- 1 :| [2 .. genesisAddressesNum]-  let seed = encodeUtf8 (show i :: Text)-  return $ detSecretKey seed+genesisSecrets :: GenesisList SecretKey+genesisSecrets = SL.generate @GenesisAddressesNum $ \i ->+    let seed = encodeUtf8 (show (i + 1) :: Text)+    in detSecretKey seed  -- | KeyHash of genesis address.-genesisKeyHashes :: NonEmpty KeyHash+genesisKeyHashes :: GenesisList KeyHash genesisKeyHashes = hashKey . toPublic <$> genesisSecrets  -- | Initially these addresses have a lot of money.-genesisAddresses :: NonEmpty Address+genesisAddresses :: GenesisList Address genesisAddresses = KeyAddress <$> genesisKeyHashes  -- | One of genesis key hashes. genesisKeyHash :: KeyHash-genesisKeyHash = head genesisKeyHashes+genesisKeyHash = SL.head genesisKeyHashes  -- | One of genesis addresses. genesisAddress :: Address-genesisAddress = head genesisAddresses+genesisAddress = SL.head genesisAddresses  -- | Secret key assotiated with 'genesisAddress'. genesisSecretKey :: SecretKey-genesisSecretKey = head genesisSecrets+genesisSecretKey = SL.head genesisSecrets  -- | More genesis addresses------ We know size of @genesisAddresses@, so it is safe to use @!!@ genesisAddress1, genesisAddress2, genesisAddress3 :: Address genesisAddress4, genesisAddress5, genesisAddress6 :: Address-genesisAddress1 = genesisAddresses !! 1-genesisAddress2 = genesisAddresses !! 2-genesisAddress3 = genesisAddresses !! 3-genesisAddress4 = genesisAddresses !! 4-genesisAddress5 = genesisAddresses !! 5-genesisAddress6 = genesisAddresses !! 6+_ :< genesisAddress1 :< genesisAddress2 :< genesisAddress3+  :< genesisAddress4 :< genesisAddress5 :< genesisAddress6+  :< _ = genesisAddresses +{-# DEPRECATED genesisAddress4, genesisAddress5, genesisAddress6+               "Consider using 'genesisAddressN' instead" #-}++-- | More genesis addresses, via a type-level natural+--+-- > genesisAddressN @7+--+-- Note that @'genesisAddress' == genesisAddressN \@0@, @'genesisAddress1' == genesisAddressN \@1@,+-- etc.+genesisAddressN :: forall n. (SingIPeano n, ToPeano GenesisAddressesNum > ToPeano n ~ 'True) => Address+genesisAddressN = SL.index @n genesisAddresses+ -- | Dummy 'VotingPowers'. We give all the voting power to two genesis addreses -- as the addresses holding lot of money. Only two addresses are involved for -- simplicity. dummyVotingPowers :: VotingPowers dummyVotingPowers = case genesisKeyHashes of-  k1 :| k2 : _ -> mkVotingPowers [(k1, 50), (k2, 50)]-  _ -> error "Insufficient number of genesis addresses"+  k1 :< k2 :< _ -> mkVotingPowers [(k1, 50), (k2, 50)]  -- | Initial 'GState'. It's supposed to be used if no 'GState' is -- provided. It puts plenty of money on each genesis address.@@ -429,5 +449,5 @@       \case (KeyAddress _, ASSimple {}) -> Nothing             (KeyAddress _, _) -> error "broken GState"             (ContractAddress ca, ASContract (ContractState{..})) ->-              Just (ca, SomeParamType sing $ T.cParamNotes $ csContract)+              Just (ca, SomeParamType $ T.cParamNotes $ csContract)             (ContractAddress _, _) -> error "broken GState"
src/Morley/Michelson/Runtime/Import.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ module Morley.Michelson.Runtime.Import   (     -- * Read, parse, typecheck contract@@ -12,6 +14,9 @@   , importSomeContract   , importUntypedContract   , ContractReadError(..)+  , readUntypedContractExt+  , readContractExt+  , readSomeContractExt      -- * Read, parse, typecheck value   , readValue@@ -26,18 +31,18 @@   ) where  import Data.Default (def)-import qualified Data.Text.IO.Utf8 as Utf8 (readFile)+import Data.Text.IO.Utf8 qualified as Utf8 (readFile) import Fmt (Buildable(build), pretty, unlessF, (+|), (|+))  import Morley.Michelson.Parser (parseExpandValue) import Morley.Michelson.Parser.Error (ParserException(..)) import Morley.Michelson.Parser.Types (MichelsonSource(..))-import Morley.Michelson.Runtime (parseExpandContract)+import Morley.Michelson.Runtime (parseExpandContract, parseExpandContractExt) import Morley.Michelson.TypeCheck   (TCError, typeCheckContract, typeCheckTopLevelType, typeCheckingWith, typeVerifyContract,   typeVerifyTopLevelType) import Morley.Michelson.Typed (Contract, SingI, SomeContract(..), SomeValue, Value)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U  ---------------------------------------------------------------------------- -- Reading, parsing, typechecking contract@@ -45,7 +50,7 @@  -- | Purely read an untyped contract from Michelson textual representation. ----- 'FilePath' is accepted solely as a hint for error messages.+-- 'MichelsonSource' is accepted solely as a hint for error messages. readUntypedContract   :: MichelsonSource   -> Text@@ -53,6 +58,20 @@ readUntypedContract source txt = do   first (CREParse source) $ parseExpandContract source txt +-- TODO [#712]: Remove this next major release+-- | Purely read an untyped contract from Michelson textual representation+-- with Morley extensions.+--+-- 'MichelsonSource' is accepted solely as a hint for error messages.+readUntypedContractExt+  :: MichelsonSource+  -> Text+  -> Either ContractReadError U.Contract+readUntypedContractExt source txt = do+  first (CREParse source) $ parseExpandContractExt source txt++{-# DEPRECATED readUntypedContractExt "Morley extensions are deprecated" #-}+ -- | Purely read a typed contract from Michelson textual representation. readSomeContract   :: MichelsonSource@@ -63,6 +82,20 @@   first (CRETypeCheck source) $     typeCheckingWith def $ typeCheckContract contract +-- TODO [#712]: Remove this next major release+-- | Purely read a typed contract from Michelson textual representation+-- with Morley extensions.+readSomeContractExt+  :: MichelsonSource+  -> Text+  -> Either ContractReadError SomeContract+readSomeContractExt source txt = do+  contract <- readUntypedContractExt source txt+  first (CRETypeCheck source) $+    typeCheckingWith def $ typeCheckContract contract++{-# DEPRECATED readSomeContractExt "Morley extensions are deprecated" #-}+ -- | Purely read a typed contract from Michelson textual representation, -- failing if parameter or storage types mismatch with the expected ones. readContract@@ -75,6 +108,23 @@   contract <- readUntypedContract source txt   first (CRETypeCheck source) $     typeCheckingWith def $ typeVerifyContract contract++-- TODO [#712]: Remove this next major release+-- | Purely read a typed contract from Michelson textual representation+-- with Morley extensions,+-- failing if parameter or storage types mismatch with the expected ones.+readContractExt+  :: forall cp st .+     Each '[SingI] [cp, st]+  => MichelsonSource+  -> Text+  -> Either ContractReadError (Contract cp st)+readContractExt source txt = do+  contract <- readUntypedContractExt source txt+  first (CRETypeCheck source) $+    typeCheckingWith def $ typeVerifyContract contract++{-# DEPRECATED readContractExt "Morley extensions are deprecated" #-}  -- | Read a thing from a file, using the provided parsing function. importUsing
src/Morley/Michelson/Runtime/TxData.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | 'TxData' type and associated functionality. @@ -16,9 +15,9 @@ import Control.Lens (makeLensesWith)  import Morley.Michelson.Typed (ParameterScope)-import qualified Morley.Michelson.Typed as T+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Untyped (EpName)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Tezos.Address (Address) import Morley.Tezos.Core (Mutez) import Morley.Util.Lens (postfixLFields)
src/Morley/Michelson/Text.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- deriving 'Container' automatically produces extra constraints. {-# OPTIONS_GHC -Wno-redundant-constraints #-}@@ -19,7 +18,6 @@ module Morley.Michelson.Text   ( MText (..)   , mkMText-  , unsafeMkMText   , mkMTextCut   , writeMText   , takeMText@@ -38,12 +36,12 @@   ) where  import Data.Aeson (FromJSON(..), ToJSON(..))-import qualified Data.Char as C+import Data.Char qualified as C import Data.Data (Data)-import qualified Data.Text as T+import Data.Text qualified as T import Fmt (Buildable)-import qualified Language.Haskell.TH as TH-import qualified Language.Haskell.TH.Quote as TH+import Language.Haskell.TH qualified as TH+import Language.Haskell.TH.Quote qualified as TH  import Morley.Util.CLI import Morley.Util.Label (Label(..), labelToText)@@ -65,7 +63,7 @@ -- -- * With 'mkMText' when constructing from a runtime text value. ----- * With 'unsafeMkMText' or 'UnsafeMText' when absolutelly sure that+-- * With 'UnsafeMText' when absolutelly sure that -- given string does not violate invariants. -- -- * With 'mkMTextCut' when not sure about text contents and want@@ -99,11 +97,6 @@       | isMChar c || c == '\n' = pass       | otherwise = Left $ invalidMCharError c --- | Contruct 'MText' from a Haskell text, failing if provided Haskell text--- is invalid Michelson string.-unsafeMkMText :: HasCallStack => Text -> MText-unsafeMkMText = either error id . mkMText- -- | Construct 'MText' from a Haskell text, eliminating all characters which -- should not appear in Michelson strings. -- Characters which can be displayed normally via escaping are preserved.@@ -198,14 +191,14 @@ -- We assume that no unicode characters are used in plain Haskell code, -- so unless special tricky manipulations are used this should be safe. symbolToMText :: forall name. KnownSymbol name => MText-symbolToMText = unsafeMkMText $ symbolValT' @name+symbolToMText = unsafe . mkMText $ symbolValT' @name  -- | Create a 'MText' from label. -- -- We assume that no unicode characters are used in plain Haskell code, -- so unless special tricky manipulations are used this should be safe. labelToMText :: Label name -> MText-labelToMText = unsafeMkMText . labelToText+labelToMText = unsafe . mkMText . labelToText  -- | Leads first character of text to upper case. --
src/Morley/Michelson/TypeCheck.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.TypeCheck   ( typeCheckContract@@ -17,6 +16,7 @@   , typeVerifyParameter   , typeVerifyStorage   , typeVerifyTopLevelType+  , typeVerifyView   , module E   , module M   , module T
src/Morley/Michelson/TypeCheck/Error.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Errors that can occur when some code is being typechecked. @@ -15,10 +14,11 @@   , pairWithElems   ) where -import Fmt (Buildable(..), pretty, (+|), (|+), (||+))+import Fmt (Buildable(..), pretty, (+|), (|+)) import Prelude hiding (empty, (<$>))-import Text.PrettyPrint.Leijen.Text hiding (bool, pretty)-import qualified Text.Show (show)+import Text.PrettyPrint.Leijen.Text+  (Doc, cat, enclose, indent, line, list, punctuate, textStrict, (<$$>), (<$>), (<+>))+import Text.Show qualified (show)  import Morley.Michelson.ErrorPos (InstrCallStack(..)) import Morley.Michelson.Printer.Util@@ -26,14 +26,14 @@   renderDoc, renderDocList) import Morley.Michelson.TypeCheck.TypeCheckedOp (TypeCheckedOp) import Morley.Michelson.TypeCheck.Types (SomeHST(..))-import qualified Morley.Michelson.Typed as T+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Typed.Annotation (AnnConvergeError(..)) import Morley.Michelson.Untyped (StackFn, Ty, Var)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Tezos.Address (Address) import Morley.Tezos.Crypto (CryptoParseError)-import qualified Morley.Tezos.Crypto.BLS12381 as BLS-import Morley.Util.Named+import Morley.Tezos.Crypto.BLS12381 qualified as BLS+import Morley.Util.MismatchError  -- | Contexts where type error can occur. data TypeContext@@ -107,9 +107,9 @@ data TCTypeError   = AnnError AnnConvergeError   -- ^ Annotation unify error-  | TypeEqError T.T T.T+  | TypeEqError (MismatchError T.T)   -- ^ Type equality error-  | StackEqError [T.T] [T.T]+  | StackEqError (MismatchError [T.T])   -- ^ Stacks equality error   | UnsupportedTypeForScope T.T T.BadTypeForScope   -- ^ Error that happens when type cannot be used in the corresponding scope.@@ -123,7 +123,7 @@   -- ^ Error that happens when actual types are different from the type that instruction expects.   -- The param is an non-empty list of all expected stack types that the instruction would accept.   -- Each expected stack types is represented as non-empty list as well.-  | UnexpectedTopLevelType TopLevelType ("expected" :! T.T) ("got" :! T.T)+  | UnexpectedTopLevelType TopLevelType (MismatchError T.T)   -- ^ Error that happens when the caller expected one top-level type, but   -- the contract has another type specified.   | InvalidInstruction U.ExpandedInstr Text@@ -172,10 +172,10 @@ instance RenderDoc TCTypeError where   renderDoc context = \case     AnnError e -> renderAnyBuildable e-    TypeEqError type1 type2 ->-      "Types not equal:" <+> (renderDoc context type1) <+> "/=" <+> (renderDoc context type2)-    StackEqError st1 st2 ->-      "Stacks not equal:"<+> (renderDocList context st1) <+> "/=" <+> (renderDocList context st2)+    TypeEqError merr ->+      "Types not equal:" <$> renderDoc context merr+    StackEqError merr ->+      "Stacks not equal:" <$> renderDoc context merr     UnsupportedTypeForScope typ reason ->       "Type '" <> (renderDoc context typ) <> "' is unsupported here because it"       <+> (renderDoc context reason)@@ -188,11 +188,9 @@           $ fmap (\(x :| xs) -> list $ fmap (renderAnyBuildable) (x:xs))           $ (t:ts)         )-    UnexpectedTopLevelType tyDesc (N expected) (N got) ->-      "Unexpected" <+> renderDoc context tyDesc <+> "type:"-      <$$> renderLargeType got-      <$$> "Expected:"-      <$$> renderLargeType expected+    UnexpectedTopLevelType tyDesc mmerr ->+      "Unexpected" <+> renderDoc context tyDesc <+> "type."+      <$$> renderDoc doesntNeedParens mmerr     InvalidInstruction instr reason ->       "Invalid instruction" <+> (renderDoc context instr)       <$$> "Reason:" <+> textStrict reason@@ -216,9 +214,6 @@       "Cannot use a terminate instruction (like FAILWITH) in this block"     EmptyCode -> "Code block is empty"     AnyError -> "Some of the arguments have invalid types"-    where-      renderLargeType :: T.T -> Doc-      renderLargeType = indent 2 . renderDoc doesntNeedParens . T.toUType  -- | Type check error data TCError@@ -229,6 +224,7 @@   | TCUnreachableCode InstrCallStack (NonEmpty U.ExpandedOp)   | TCExtError SomeHST InstrCallStack ExtError   | TCIncompletelyTyped TCError (U.Contract' TypeCheckedOp)+  | TCIncompletelyTypedView TCError (U.View' TypeCheckedOp)   deriving stock (Eq, Generic)  instance NFData TCError@@ -269,6 +265,9 @@       line       <> renderDoc doesntNeedParens contract       <$> renderDoc context err+    TCIncompletelyTypedView err _view ->+      line+      <> renderDoc context err     where     buildTruncated k l       | null (drop k l) = renderDocList context l@@ -292,6 +291,9 @@  instance NFData StackSize +instance Buildable StackSize where+  build (StackSize n) = "stack size " +| n |+ ""+ -- | Various type errors possible when checking Morley extension commands data ExtError =     LengthMismatch U.StackTypePattern@@ -323,13 +325,13 @@       +| i |+ " with error: " +| e |+ ""     StkRestMismatch stk (SomeHST r) (SomeHST r') e ->       "StkRestMismatch in pattern " +| stk |+-      " against stacks " +| r ||+ " and " +| r' ||++      " against stacks " +| r |+ " and " +| r' |+       " with error: " +| e |+ ""     TestAssertError t ->       "TestAssertError: " +| t |+ ""     InvalidStackReference i lhs ->       "InvalidStackReference: reference is out of the stack: "-      +| i ||+ " >= " +| lhs ||+ ""+      +| i |+ " >= " +| lhs |+ ""  ---------------------------------------------------------------------------- -- Helpers for formatting types
src/Morley/Michelson/TypeCheck/Ext.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ -- | Type-checking of Morley extension. module Morley.Michelson.TypeCheck.Ext   ( typeCheckExt@@ -21,11 +23,12 @@ import Morley.Michelson.TypeCheck.TypeCheckedSeq (IllTypedInstr(..), TypeCheckedSeq(..)) import Morley.Michelson.TypeCheck.Types import Morley.Michelson.Typed (Notes(..), converge, mkUType, notesT, withUType)-import qualified Morley.Michelson.Typed as T+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Untyped   (ExpandedOp, StackFn, Ty, TyVar(..), Var, VarAnn, sfnInPattern, sfnOutPattern, sfnQuantifiedVars,   varSet)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U+import Morley.Util.MismatchError import Morley.Util.PeanoNatural (PeanoNatural(..))  -- | Perform some, possibly throwing, action presumably making use of a supplied@@ -153,7 +156,8 @@         handleType t =           withUType t $ \(tann :: Notes t) -> do             Refl <- first-              (\_ -> TypeMismatch s n $ TypeEqError (notesT xann) (notesT tann))+              (\_ -> TypeMismatch s n $ TypeEqError MkMismatchError+                { meExpected = notesT xann, meActual = notesT tann })               (eqType @xt @t)             void $ first (TypeMismatch s n . AnnError) (converge tann xann)             go m (n + 1) ts xs
src/Morley/Michelson/TypeCheck/Helpers.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ module Morley.Michelson.TypeCheck.Helpers     ( deriveSpecialVN     , deriveSpecialFNs@@ -53,10 +55,10 @@ import Data.Constraint (Dict(..), withDict) import Data.Default (def) import Data.Singletons (Sing, SingI(sing), demote)-import Data.Singletons.Decide-import qualified Data.Text as T+import Data.Singletons.Decide ((:~:)(Refl))+import Data.Text qualified as T import Data.Vinyl (Rec(..))-import Fmt ((+||), (||+))+import Fmt (Buildable, (+|), (|+))  import Morley.Michelson.ErrorPos (InstrCallStack) import Morley.Michelson.TypeCheck.Error (TCError(..), TCTypeError(..), TypeContext(..))@@ -71,9 +73,10 @@ import Morley.Michelson.Typed.Arith (Add, ArithOp(..), EDiv, Mul, Sub, UnaryArithOp(..)) import Morley.Michelson.Typed.Polymorphic   (ConcatOp, EDivOp(..), GetOp(..), MemOp(..), SizeOp, SliceOp, UpdOp(..))-import qualified Morley.Michelson.Untyped as Un+import Morley.Michelson.Untyped qualified as Un import Morley.Michelson.Untyped.Annotation-  (Annotation(..), FieldAnn, VarAnn, annQ, noAnn, orAnn, unsafeMkAnnotation)+  (Annotation(..), FieldAnn, VarAnn, annQ, mkAnnotation, noAnn, orAnn)+import Morley.Util.MismatchError import Morley.Util.Sing (eqI) import Morley.Util.Type (onFirst) @@ -103,7 +106,7 @@     splitLastDot v = case unsnoc $ T.splitOn "." $ unAnnotation v of       Nothing      -> def       Just (_, "") -> (def, Un.convAnn v)-      Just (vs, l) -> (foldMap unsafeMkAnnotation vs, bool (unsafeMkAnnotation l) def (l == "car" || l == "cdr"))+      Just (vs, l) -> (foldMap (unsafe . mkAnnotation) vs, bool (unsafe . mkAnnotation $ l) def (l == "car" || l == "cdr"))      commonPrefix :: VarAnn -> VarAnn -> VarAnn     commonPrefix = curry \case@@ -173,7 +176,7 @@   => HST as -> HST bs -> Either TCTypeError (as :~: bs) eqHST (hst :: HST xs) (hst' :: HST ys) = do   case eqI @as @bs of-    Nothing -> Left $ StackEqError (hstToTs hst) (hstToTs hst')+    Nothing -> Left $ StackEqError MkMismatchError {meActual = hstToTs hst, meExpected = hstToTs hst'}     Just Refl -> do       void $ convergeHST hst hst' `onFirst` AnnError       return Refl@@ -186,7 +189,7 @@ eqHST1 hst = do   let hst' = sing @t -:& SNil   case eqI @'[t] @st of-    Nothing -> Left $ StackEqError (hstToTs hst') (hstToTs hst)+    Nothing -> Left $ StackEqError MkMismatchError {meActual = hstToTs hst, meExpected = hstToTs hst'}     Just Refl -> Right Refl  -- | Version of 'eqHST1' that also checks whether annotations converge@@ -209,12 +212,12 @@  -- | Check whether elements go in strictly ascending order and -- return the original list (to keep only one pass on the original list).-ensureDistinctAsc :: (Ord b, Show a) => (a -> b) -> [a] -> Either Text [a]+ensureDistinctAsc :: (Ord b, Buildable a) => (a -> b) -> [a] -> Either Text [a] ensureDistinctAsc toCmp = \case   (e1 : e2 : l) ->     if toCmp e1 < toCmp e2     then (e1 :) <$> ensureDistinctAsc toCmp (e2 : l)-    else Left $ "Entries are unordered (" +|| e1 ||+ " >= " +|| e2 ||+ ")"+    else Left $ "Entries are unordered (" +| e1 |+ " >= " +| e2 |+ ")"   l -> Right l  -- | Flipped version of 'catchError'.@@ -417,6 +420,7 @@       EXEC -> instr''       ADD -> instr''       SUB -> instr''+      SUB_MUTEZ -> instr''       CONCAT -> instr''       CONCAT' -> instr''       MUL -> instr''@@ -475,6 +479,8 @@       SPLIT_TICKET -> instr''       JOIN_TICKETS -> instr''       OPEN_CHEST -> instr''+      SAPLING_EMPTY_STATE _ -> instr''+      SAPLING_VERIFY_UPDATE -> instr''       where         instr' = addNotesNoVarAnn outputStack instr         instr'' = addNotesOneVarAnn outputStack instr@@ -920,8 +926,9 @@   (STNat, STInt) -> arithImpl @Sub SUB   (STNat, STNat) -> arithImpl @Sub SUB   (STTimestamp, STTimestamp) -> arithImpl @Sub SUB+  (STMutez, STMutez) -> \i _ uInstr -> typeCheckInstrErr' uInstr (SomeHST i) (Just ArithmeticOperation) $+    InvalidInstruction uInstr "Use of SUB on `mutez` operands is deprecated; use SUB_MUTEZ"   (STTimestamp, STInt) -> arithImpl @Sub SUB-  (STMutez, STMutez) -> arithImpl @Sub SUB   _ -> \i _ uInstr -> typeCheckInstrErr' uInstr (SomeHST i) (Just ArithmeticOperation) $     NotNumericTypes (demote @a) (demote @b) 
src/Morley/Michelson/TypeCheck/Instr.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Module, providing functions for conversion from -- instruction and value representation from @Morley.Michelson.Type@ module@@ -42,16 +41,19 @@     , typeVerifyParameter     , typeVerifyStorage     , typeVerifyTopLevelType+    , typeVerifyView     ) where  import Prelude hiding (EQ, GT, LT) -import Control.Monad.Except (MonadError, liftEither, throwError)+import Control.Monad.Except (MonadError, catchError, liftEither, throwError)+import Data.Constraint ((\\)) import Data.Default (def) import Data.Generics (everything, mkQ) import Data.Sequence ((|>))-import qualified Data.Sequence as Seq-import Data.Singletons (Sing, demote, withSingI, withSomeSing)+import Data.Sequence qualified as Seq+import Data.Singletons (Sing, SomeSing(..), demote, withSingI, withSomeSing)+import Data.Type.Equality (TestEquality(..)) import Data.Typeable ((:~:)(..)) import Fmt (pretty) @@ -67,14 +69,15 @@ import Morley.Michelson.TypeCheck.Value import Morley.Michelson.Typed hiding (Branch(..)) -import Morley.Util.Named ((!))+import Morley.Util.MismatchError import Morley.Util.Peano import Morley.Util.PeanoNatural import Morley.Util.Sing (SingI1(..))-import Morley.Util.Type (onFirst, type (++))+import Morley.Util.Type (knownListFromSingI, onFirst, type (++)) -import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Michelson.Untyped.Annotation (FieldTag, VarAnn, VarTag, annQ, convAnn, orAnn)+import Morley.Util.Peano qualified as Peano  -- | Type check a contract and verify that the given storage -- is of the type expected by the contract.@@ -100,21 +103,18 @@   SomeContract tContract@(Contract{} :: Contract cp' st') <-     typeCheckContract uContract   Refl <- requireEq @cp' @cp (mkErr TltParameterType)-  Refl <- requireEq @st' @st (mkErr TltParameterType)+  Refl <- requireEq @st' @st (mkErr TltStorageType)   return tContract   where-    mkErr :: TopLevelType -> T -> T -> TypeCheckResult any-    mkErr tyDesc got expected =+    mkErr :: TopLevelType -> MismatchError T -> TypeCheckResult any+    mkErr tyDesc merr =       throwError $ TCContractError "error in contract type" $ Just $-          UnexpectedTopLevelType tyDesc-            ! #expected expected-            ! #got got+          UnexpectedTopLevelType tyDesc merr  withWTP :: forall t a. SingI t => (WellTyped t => TypeCheck a) -> TypeCheck a withWTP fn = case getWTP @t of   Right Dict -> fn-  Left (NotWellTyped t cause) -> throwError $ TCContractError-    ("Not a well typed value: '" <> show t <> "' because it " <> pretty cause) Nothing+  Left err -> throwError $ TCContractError (pretty err) Nothing  withWTPInstr_ :: forall t a. SingI t => U.ExpandedInstr -> SomeHST -> (WellTyped t => TypeCheckInstr a) -> TypeCheckInstr a withWTPInstr_ v t fn = case getWTP @t of@@ -224,62 +224,96 @@              }         else err +typeVerifyView+  :: forall arg ret st.+     (SingI arg, SingI ret, WellTyped st)+  => Notes st -> U.View -> TypeCheckResult (View arg st ret)+typeVerifyView notes v = do+  SomeView (tcView@View{} :: View arg' st' ret') <-+    runTypeCheck TypeCheckTest $ typeCheckViewImpl notes v+  Refl <- requireEq @arg' @arg (mkErr TltParameterType)+  Refl <- requireEq @st' @st (mkErr TltStorageType)+  Refl <- requireEq @ret' @ret (mkErr TltParameterType)+  return tcView+  where+    mkErr :: TopLevelType -> MismatchError T -> TypeCheckResult any+    mkErr tyDesc merr =+      throwError $ TCContractError "error in view type" $ Just $+          UnexpectedTopLevelType tyDesc merr++typeCheckViewImpl :: WellTyped st => Notes st -> U.View -> TypeCheck (SomeView st)+typeCheckViewImpl storageNote+  uView@U.View+  { U.viewArgument = AsUType (argNote :: Notes param)+  , U.viewReturn = AsUType (returnNote :: Notes ret)+  , U.viewCode = uInstr+  , U.viewName = viewName+  }+  = withWTP @param $ withWTP @ret $ do+    let inp = (NTPair def def def def def argNote storageNote, Dict, def) ::& SNil+    Dict <-+      checkScope @(ViewableScope param)+      & either (hasTypeError @param "parameter") pure+    Dict <-+      checkScope @(ViewableScope ret)+      & either (hasTypeError @ret "return") pure+    codeRes <-+      usingReaderT def $+      liftNoExcept $+      typeCheckImpl typeCheckInstr uInstr inp+    _ :/ instrOut <-+      tcsEither (onFailedViewsTypeCheck uView) pure codeRes++    let vName = viewName+        vArgument = argNote+        vReturn = returnNote+    case instrOut of+      instr ::: out -> liftEither do+        (Refl, _) <- matchHST1 out returnNote+          `onFirst` (TCViewError "view return type mismatch:" viewName . Just)+        return $ SomeView View{ vCode = instr, .. }+      AnyOutInstr instr ->+        return $ SomeView View{ vCode = instr, .. }++  where+    onFailedViewsTypeCheck+      :: U.View -> [TypeCheckedOp] -> TCError -> TypeCheck a+    onFailedViewsTypeCheck v viewOps err = do+      verbose <- asks tcVerbose+      throwError if verbose+        then TCIncompletelyTypedView err v{ U.viewCode = viewOps }+        else err++    hasTypeError :: forall (t :: T) a. SingI t => Text -> BadTypeForScope -> TypeCheck a+    hasTypeError desc reason = throwError $+      TCViewError (desc <> " type error in view") viewName $+      Just $ UnsupportedTypeForScope (demote @t) reason+ typeCheckViewsImpl   :: (WellTyped st)   => U.Contract' TypeCheckedOp -> Notes st -> [U.View] -> TypeCheck [SomeView st] typeCheckViewsImpl tcCotract storageNote cViews =   let myfoldM l acc f = foldM f acc l in   fmap (map snd . toList) $ myfoldM cViews (Seq.Empty :: Seq (U.View, SomeView st))-    \processedViews uView@U.View-    { U.viewArgument = AsUType (argNote :: Notes param)-    , U.viewReturn = AsUType (returnNote :: Notes ret)-    , U.viewCode = uInstr-    , U.viewName = viewName-    } -> withWTP @param $ withWTP @ret $ do-      let inp = (NTPair def def def def def argNote storageNote, Dict, def) ::& SNil-      Dict <--        checkScope @(ViewableScope param)-        & either (hasTypeError @param "parameter" viewName) pure-      Dict <--        checkScope @(ViewableScope ret)-        & either (hasTypeError @ret "return" viewName) pure-      codeRes <--        usingReaderT def $-        liftNoExcept $-        typeCheckImpl typeCheckInstr uInstr inp-      let tcViews = map (uncurry someViewToOp) processedViews-      _ :/ instrOut <--        tcsEither (onFailedViewsTypeCheck tcViews uView) pure codeRes--      let vName = viewName-          vArgument = argNote-          vReturn = returnNote-      resView <- case instrOut of-        instr ::: out -> liftEither do-          (Refl, _) <- matchHST1 out returnNote-            `onFirst` (TCViewError "view return type mismatch:" viewName . Just)-          return $ SomeView View{ vCode = instr, .. }-        AnyOutInstr instr ->-          return $ SomeView View{ vCode = instr, .. }--      return $ processedViews |> (uView, resView)+    \processedViews uView -> do+      resView <- typeCheckViewImpl storageNote uView+      pure $ processedViews |> (uView, resView)+      `catchError` \case+        TCIncompletelyTypedView err view' ->+          let tcViews = map (uncurry someViewToOp) processedViews+          in onFailedViewsTypeCheck tcViews view' err+        err -> throwError err   where     onFailedViewsTypeCheck-      :: Seq (U.View' TypeCheckedOp) -> U.View-      -> [TypeCheckedOp] -> TCError -> TypeCheck a-    onFailedViewsTypeCheck processedViews v viewOps err = do+      :: Seq (U.View' TypeCheckedOp) -> U.View' TypeCheckedOp -> TCError -> TypeCheck a+    onFailedViewsTypeCheck processedViews v err = do       verbose <- asks tcVerbose       throwError if verbose         then TCIncompletelyTyped err tcCotract-             { U.contractViews = toList (processedViews |> v{ U.viewCode = viewOps })+             { U.contractViews = toList (processedViews |> v)              }         else err -    hasTypeError :: forall (t :: T) a. SingI t => Text -> ViewName -> BadTypeForScope -> TypeCheck a-    hasTypeError desc viewName reason = throwError $-      TCViewError (desc <> " type error in view") viewName $-      Just $ UnsupportedTypeForScope (demote @t) reason- -- | Function @typeCheckList@ converts list of Michelson instructions -- given in representation from @Morley.Michelson.Type@ module to representation -- in strictly typed GADT.@@ -531,7 +565,7 @@         -- Even 'DIG 0' is invalid on empty stack (so it is not strictly `Nop`).         (_, SNil) -> notEnoughItemsOnStack' -        (0, i@(_ ::& _)) -> pure (TCDigHelper Zero i)+        (0, i@(_ ::& _)) -> pure (TCDigHelper Zero i \\ knownListFromSingI @inp)          (n, (b ::& iTail)) ->           go (n - 1) iTail <&> \(TCDigHelper s (a ::& resTail)) ->@@ -812,6 +846,11 @@       mapImpl (U.MAP vn) vns uInstr mp inp         (\(rn :: Notes t) hst -> withWTPInstr @t $ pure $ (NTList def rn, Dict, vn) ::& hst) +  (U.MAP vn mp, (STOption l, NTOption _ (vns :: Notes t1), Dict, _vn) ::&+ _) -> withSingI l $ do+    withWTPInstr' @t1 $+      mapImpl (U.MAP vn) vns uInstr mp inp+        (\(rn :: Notes t) hst -> withWTPInstr @t $ pure $ (NTOption def rn, Dict, vn) ::& hst)+   (U.MAP vn mp, (STMap k v, NTMap _ kns vns, Dict, _vn) ::&+ _) -> withSingI k $ withSingI v $ do     case NTPair def def def def def kns vns of       (pns :: Notes ('TPair k v1)) ->@@ -823,6 +862,7 @@     failWithErr $ UnexpectedType       $ ("list 'a" :| []) :|       [ ("map 'k 'v" :| [])+      , ("option 'a" :| [])       ]    (U.MAP _ _, SNil) -> notEnoughItemsOnStack@@ -1182,6 +1222,12 @@    (U.SUB _, _) -> notEnoughItemsOnStack +  (U.SUB_MUTEZ vn, (STMutez, _, _, _) ::&+ (STMutez, _, _, _) ::&+ _) -> workOnInstr uInstr $+    arithImpl @SubMutez SUB_MUTEZ inp vn uInstr+  (U.SUB_MUTEZ _, _ ::&+ _ ::&+ _) ->+    failWithErr $ UnexpectedType $ ("mutez" :| ["mutez"]) :| []+  (U.SUB_MUTEZ _, _) -> notEnoughItemsOnStack+   (U.MUL vn, (a, _, _, _) ::&+ (b, _, _, _) ::&+ _) -> workOnInstr uInstr $     mulImpl a b inp vn uInstr @@ -1372,7 +1418,7 @@     case mode of       TypeCheckValue (value, ty) ->         tcFailedOnValue value ty "The SELF instruction cannot appear in a lambda." Nothing-      TypeCheckContract (SomeParamType _ notescp) -> do+      TypeCheckContract (SomeParamType notescp) -> do         let epName = U.epNameFromSelfAnn fn         MkEntrypointCallRes (argNotes :: Notes arg) epc <-           mkEntrypointCall epName notescp@@ -1560,10 +1606,8 @@     failWithErr $ UnexpectedType $ ("a'" :| ["nat"]) :| []   (U.TICKET _, _) -> notEnoughItemsOnStack -  (U.READ_TICKET vn, ticket@(ntTicket@NTTicket{}, Dict, _) ::& rs) -> workOnInstr uInstr $-    case notesSing ntTicket of-      STTicket{} ->-        pure $ inp :/ READ_TICKET ::: ((starNotes, Dict, vn) ::& ticket ::& rs)+  (U.READ_TICKET vn, ticket@(NTTicket{}, Dict, _) ::& rs) -> workOnInstr uInstr $+      pure $ inp :/ READ_TICKET ::: ((starNotes, Dict, vn) ::& ticket ::& rs)   (U.READ_TICKET _, _ ::& _) ->     failWithErr $ UnexpectedType $ ("ticket 'a" :| []) :| []   (U.READ_TICKET _, _) -> notEnoughItemsOnStack@@ -1598,6 +1642,31 @@   (U.OPEN_CHEST _, _ ::& _ ::& _ ::& _) ->     failWithErr $ UnexpectedType $ ("chest_key" :| ["chest", "nat"]) :| []   (U.OPEN_CHEST _, _) -> notEnoughItemsOnStack++  (U.SAPLING_EMPTY_STATE vn n, _) -> workOnInstr uInstr $+    (\(SomeSing (s :: Sing a)) -> withSingI s $+      pure $ inp :/ (SAPLING_EMPTY_STATE s) ::: ((starNotes, Dict, vn) ::& inp)+    ) $ Peano.someSingNat n++  (U.SAPLING_VERIFY_UPDATE vn,+      (STSaplingTransaction s1, NTSaplingTransaction _ n, Dict, _)+      ::&+ (STSaplingState s2, NTSaplingState _ _, Dict, _)+      ::&+ rs) ->+      workOnInstr uInstr $+        case testEquality s1 s2 of+          Just Refl ->+            pure $ inp :/ SAPLING_VERIFY_UPDATE ::: (+              (NTOption U.noAnn (NTPair U.noAnn U.noAnn U.noAnn U.noAnn U.noAnn+                (NTInt U.noAnn)+                (NTSaplingState U.noAnn n)+              ), Dict, vn)+              ::& rs)+          Nothing -> failWithErr' $ InvalidInstruction uInstr+            "Memo sizes of two sapling states or transactions do not match."++  (U.SAPLING_VERIFY_UPDATE _, _ ::& _ ::& _) ->+    failWithErr $ UnexpectedType $ ("sapling_transaction" :| ["sapling_state"]) :| []+  (U.SAPLING_VERIFY_UPDATE _, _) -> notEnoughItemsOnStack    where     withWTPInstr'
src/Morley/Michelson/TypeCheck/TypeCheck.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.TypeCheck.TypeCheck   ( TcInstrHandler@@ -31,16 +30,15 @@   , TypeCheckMode(..)   , SomeParamType(..)   , mkSomeParamType-  , unsafeMkSomeParamType   ) where +import Debug qualified (show)  import Control.Monad.Except (Except, mapExceptT, runExcept, throwError) import Control.Monad.Reader (mapReaderT) import Data.Default (Default(..))-import Data.Singletons (Sing) import Fmt (Buildable, build, pretty)-import qualified Text.Show+import Text.Show qualified  import Morley.Michelson.ErrorPos (InstrCallStack) import Morley.Michelson.TypeCheck.Error (TCError(..), TCTypeError(..))@@ -48,9 +46,8 @@   (IllTypedInstr(..), TypeCheckedInstr, TypeCheckedOp(..), TypeCheckedSeq(..), someInstrToOp,   tcsEither) import Morley.Michelson.TypeCheck.Types-import Morley.Michelson.Typed (SingI)-import qualified Morley.Michelson.Typed as T-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Typed qualified as T+import Morley.Michelson.Untyped qualified as U import Morley.Tezos.Address (ContractHash) import Morley.Util.Lens @@ -75,11 +72,11 @@     (Except TCError))  data SomeParamType = forall t. (T.ParameterScope t) =>-  SomeParamType (Sing t) (T.ParamNotes t)+  SomeParamType (T.ParamNotes t)  -- | @Show@ instance of @SomeParamType@, mainly used in test. instance Show SomeParamType where-  show = show . someParamToParameterType+  show = Debug.show . someParamToParameterType  -- | @Eq@ instance of @SomeParamType@, mainly used in test. instance Eq SomeParamType where@@ -92,15 +89,8 @@ -- | Helper function means to provide a quick way for creating instance -- of @SomeParamType@ needed in test. someParamToParameterType :: SomeParamType -> U.ParameterType-someParamToParameterType (SomeParamType s T.UnsafeParamNotes{..}) =-  U.ParameterType (T.AsUTypeExt s pnNotes) pnRootAnn---- | Construct @SomeParamType@ from @ParameterType@, mainly used in test.-unsafeMkSomeParamType :: HasCallStack => U.ParameterType -> SomeParamType-unsafeMkSomeParamType p =-  case mkSomeParamType p of-    Right sp -> sp-    Left err -> error $ "Illegal type in parameter of env contract: " <> pretty err+someParamToParameterType (SomeParamType T.UnsafeParamNotes{..}) =+  U.ParameterType (T.AsUType pnNotes) pnRootAnn  mkSomeParamType :: U.ParameterType -> Either TCError SomeParamType mkSomeParamType (U.ParameterType t ann) =@@ -108,7 +98,7 @@     case T.checkScope @(T.ParameterScope t) of       Right T.Dict ->         case T.mkParamNotes notescp ann of-          Right paramNotes -> Right $ SomeParamType T.sing paramNotes+          Right paramNotes -> Right $ SomeParamType paramNotes           Left err ->             Left $ TCContractError "invalid parameter declaration: " $ Just $ IllegalParamDecl err       Left err -> Left $ TCContractError ("Parameter type is invalid: " <> pretty err) Nothing@@ -274,7 +264,7 @@ -- have to be refactored too. -- Therefore, I am using ReaderT over TypeCheck. type TcInstrHandler-   = forall inp. (SingI inp, HasCallStack)+   = forall inp. (T.SingI inp, HasCallStack)       => U.ExpandedInstr       -> HST inp       -> TypeCheckInstrNoExcept (TypeCheckedSeq inp)
src/Morley/Michelson/TypeCheck/TypeCheckedOp.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- This module provides data types for representing partially typed -- instructions.@@ -20,7 +19,7 @@ import Morley.Michelson.Typed.Convert (instrToOps) import Morley.Michelson.Typed.Instr (Instr, castInstr) import Morley.Michelson.Typed.View (SomeView'(..), View'(..))-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Michelson.Untyped.Instr (ExpandedOp, InstrAbstract(..)) import Morley.Util.TH (deriveGADTNFData) 
src/Morley/Michelson/TypeCheck/TypeCheckedSeq.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | This module provides a data type for representing a partially typed -- sequence of instructions.
src/Morley/Michelson/TypeCheck/Types.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.TypeCheck.Types     ( HST (..)@@ -11,9 +10,6 @@     , SomeInstr (..)     , BoundVars (..)     , TcExtFrames-    , NotWellTyped (..)-    , getWTP-    , getWTP'     , withWTPm     , unsafeWithWTP     , mapSomeContract@@ -22,21 +18,22 @@     , noBoundVars     ) where +import Debug qualified (show)+ import Data.Constraint (Dict(..))-import qualified Data.Map.Lazy as Map-import Data.Singletons (Sing, SingI(..), fromSing)+import Data.Map.Lazy qualified as Map+import Data.Singletons (Sing, SingI(..)) import Fmt (Buildable(..), pretty) import Prelude hiding (EQ, GT, LT)-import Text.PrettyPrint.Leijen.Text hiding (pretty)-import qualified Text.Show-+import Text.PrettyPrint.Leijen.Text (Doc, (<+>))+import Text.Show qualified  import Morley.Michelson.Printer.Util-import Morley.Michelson.Typed (Notes(..), SingT(..), SomeContract(..), T(..), notesT, starNotes)-import qualified Morley.Michelson.Typed as T+import Morley.Michelson.Typed (Notes(..), SomeContract(..), T(..), notesT, starNotes)+import Morley.Michelson.Typed qualified as T import Morley.Michelson.Typed.Contract-import Morley.Michelson.Typed.Haskell.Value (WellTyped) import Morley.Michelson.Typed.Instr+import Morley.Michelson.Typed.Scope (WellTyped, getWTP) import Morley.Michelson.Untyped (Ty, Var, noAnn) import Morley.Michelson.Untyped.Annotation (VarAnn) import Morley.Util.Sing (eqParamSing)@@ -81,8 +78,8 @@     where       showDo :: HST (t ': ts_) -> String       showDo ((notesT -> t, Dict, _vn) ::& (b ::& c)) =-          show t <> ", " <> showDo (b ::& c)-      showDo ((notesT -> t, Dict, _vn) ::& SNil) = show t+          Debug.show t <> ", " <> showDo (b ::& c)+      showDo ((notesT -> t, Dict, _vn) ::& SNil) = Debug.show t  instance Buildable (HST ts) where   build = buildRenderDocExtended@@ -162,8 +159,8 @@ infix 9 :::  instance Show (ExtInstr inp) => Show (SomeInstrOut inp) where-  show (i ::: out) = show i <> " :: " <> show out-  show (AnyOutInstr i) = show i <> " :: *"+  show (i ::: out) = Debug.show i <> " :: " <> Debug.show out+  show (AnyOutInstr i) = Debug.show i <> " :: *"  -- | Data type keeping the whole type check result: instruction and -- type representations of instruction's input and output.@@ -185,7 +182,7 @@ mapSomeInstr f (inp :/ instrAndOut) = inp :/ mapSomeInstrOut f instrAndOut  instance Show (ExtInstr inp) => Show (SomeInstr inp) where-  show (inp :/ out) = show inp <> " -> " <> show out+  show (inp :/ out) = Debug.show inp <> " -> " <> Debug.show out  mapSomeContract ::   (forall inp out. Instr inp out -> Instr inp out)@@ -201,94 +198,6 @@  -- | State for type checking @nop@ type TcExtFrames = [BoundVars]---- | Error type for when a value is not well-typed.-data NotWellTyped = NotWellTyped-  { nwtBadType :: T-  , nwtCause :: T.BadTypeForScope-  }--instance Buildable NotWellTyped where-  build (NotWellTyped t c) =-    "Given type is not well typed because '" <> (build t) <> "' " <> (build c)---- | Given a type, provide evidence that it is well typed w.r.t to the---  Michelson rules regarding where comparable types are required.-getWTP :: forall t. (SingI t) => Either NotWellTyped (Dict (WellTyped t))-getWTP = getWTP' sing---- | Version of 'getWTP' that accepts 'Sing' at term-level.-getWTP' :: Sing t -> Either NotWellTyped (Dict (WellTyped t))-getWTP' = \case-  STKey -> Right Dict-  STUnit -> Right Dict-  STSignature -> Right Dict-  STChainId -> Right Dict-  STOption s -> do-    Dict <- getWTP' s-    pure Dict-  STList s -> do-    Dict <- getWTP' s-    pure Dict-  STSet s -> do-    Dict <- getWTP' s-    Dict <- eitherWellTyped T.BtNotComparable T.getComparableProofS s-    pure Dict-  STOperation -> Right Dict-  STContract s -> do-    Dict <- getWTP' s-    Dict <- eitherWellTyped T.BtIsOperation T.opAbsense s-    pure Dict-  STTicket s -> do-    Dict <- getWTP' s-    Dict <- eitherWellTyped T.BtNotComparable T.getComparableProofS s-    pure Dict-  STPair s1 s2 -> do-    Dict <- getWTP' s1-    Dict <- getWTP' s2-    pure Dict-  STOr s1 s2 -> do-    Dict <- getWTP' s1-    Dict <- getWTP' s2-    pure Dict-  STLambda s1 s2 -> do-    Dict <- getWTP' s1-    Dict <- getWTP' s2-    pure Dict-  STMap s1 s2 -> do-    Dict <- getWTP' s1-    Dict <- getWTP' s2-    Dict <- eitherWellTyped T.BtNotComparable T.getComparableProofS s1-    pure Dict-  STBigMap s1 s2 -> do-    Dict <- getWTP' s1-    Dict <- getWTP' s2-    Dict <- eitherWellTyped T.BtNotComparable T.getComparableProofS s1-    Dict <- eitherWellTyped T.BtIsOperation T.opAbsense s2-    Dict <- eitherWellTyped T.BtHasBigMap T.bigMapAbsense s2-    pure Dict-  STInt -> Right Dict-  STNat -> Right Dict-  STString -> Right Dict-  STBytes -> Right Dict-  STMutez -> Right Dict-  STBool -> Right Dict-  STKeyHash -> Right Dict-  STBls12381Fr -> Right Dict-  STBls12381G1 -> Right Dict-  STBls12381G2 -> Right Dict-  STTimestamp -> Right Dict-  STAddress -> Right Dict-  STChest -> Right Dict-  STChestKey -> Right Dict-  STNever -> Right Dict-  where-    eitherWellTyped-      :: T.BadTypeForScope-      -> (Sing (ty :: T) -> Maybe a)-      -> Sing (ty :: T)-      -> Either NotWellTyped a-    eitherWellTyped bt sf sng = maybeToRight (NotWellTyped (fromSing sng) bt) $ sf sng  -- | Given a type and an action that requires evidence that the type is well typed, --  generate the evidence and execute the action, or else fail with an error.
src/Morley/Michelson/TypeCheck/Value.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.TypeCheck.Value     ( typeCheckValImpl@@ -10,9 +9,9 @@ import Control.Monad.Except (liftEither, throwError) import Data.Constraint (Dict(..)) import Data.Default (def)-import qualified Data.List.NonEmpty as NE-import qualified Data.Map as M-import qualified Data.Set as S+import Data.List.NonEmpty qualified as NE+import Data.Map qualified as M+import Data.Set qualified as S import Data.Singletons (Sing, SingI(..), demote, fromSing, withSingI) import Data.Typeable ((:~:)(..)) import Fmt (pretty)@@ -26,12 +25,12 @@   throwingTCError) import Morley.Michelson.TypeCheck.Types import Morley.Michelson.Typed (EpAddress(..), Notes(..), SingT(..), Value'(..), starNotes)-import qualified Morley.Michelson.Typed as T-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Typed qualified as T+import Morley.Michelson.Untyped qualified as U import Morley.Tezos.Address (Address(..)) import Morley.Tezos.Core import Morley.Tezos.Crypto-import qualified Morley.Tezos.Crypto.BLS12381 as BLS+import Morley.Tezos.Crypto.BLS12381 qualified as BLS import Morley.Tezos.Crypto.Timelock (chestFromBytes, chestKeyFromBytes) import Morley.Util.Type (onFirst) @@ -122,7 +121,7 @@        (U.ValueString (parseChainId . unMText -> Right ci), STChainId) ->         pure $ VChainId ci-      (U.ValueBytes (mkChainId . U.unInternalByteString -> Just ci), STChainId) ->+      (U.ValueBytes (mkChainId . U.unInternalByteString -> Right ci), STChainId) ->         pure $ VChainId ci        (cv@(U.ValueString (T.parseEpAddress . unMText -> Right addr))@@ -304,10 +303,9 @@       => U.Value       -> (T.WellTyped t => TypeCheckInstr a)       -> TypeCheckInstr a-    withWTP uvalue fn = case getWTP @t of+    withWTP uvalue fn = case T.getWTP @t of       Right Dict -> fn-      Left (NotWellTyped t cause) -> tcFailedOnValue uvalue (demote @ty)-                  ("Value is not well typed: '" <> show t <> "' because it " <> pretty cause) Nothing+      Left err -> tcFailedOnValue uvalue (demote @ty) (pretty err) Nothing      typeCheckValsImpl       :: ([U.Value], Sing t)@@ -354,7 +352,7 @@         ContractAddress ca -> case mOriginatedContracts of           Nothing -> liftEither . Left $ unsupportedType T.BtHasContract           Just originatedContracts -> case M.lookup ca originatedContracts of-            Just (SomeParamType (_ :: Sing cp') paramNotes) ->+            Just (SomeParamType paramNotes) ->               case T.mkEntrypointCall epName paramNotes of                 Nothing ->                   throwError $
src/Morley/Michelson/Typed.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Typed   ( module Exports
src/Morley/Michelson/Typed/Aliases.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Typed.Aliases   ( Value
src/Morley/Michelson/Typed/AnnotatedValue.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2022 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2022 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Typed.AnnotatedValue   ( AnnotatedValue (..)@@ -19,14 +18,15 @@   ) where  import Control.Lens-import qualified Data.Map as Map+  (Fold, IndexedFold, IndexedTraversal', Prism, folding, ifolding, index, indexed, lens, prism,+  (:~:)(Refl))+import Data.Map qualified as Map import Data.Singletons (SingI, demote) import Fmt (Buildable(..), (+|), (|+))  import Morley.Michelson.Typed.Aliases (Value)-import Morley.Michelson.Typed.Annotation (Notes(..))+import Morley.Michelson.Typed.Annotation (Notes(..), mkUType) import Morley.Michelson.Typed.Convert ()-import Morley.Michelson.Typed.Extract (mkUType) import Morley.Michelson.Typed.Haskell.Value (IsoValue, ToT, fromVal, toVal) import Morley.Michelson.Typed.T (T) import Morley.Michelson.Typed.Value@@ -35,7 +35,8 @@  -- $setup -- >>> import qualified Data.Map as Map--- >>> import Morley.Michelson.Untyped (noAnn, fieldAnnQ)+-- >>> import Morley.Michelson.Parser (notes)+-- >>> import Morley.Michelson.Untyped (fieldAnnQ) -- >>> :m +Morley.Michelson.Typed Morley.Michelson.Text Control.Lens Fmt  data AnnotatedValue v = AnnotatedValue@@ -44,7 +45,7 @@   }   deriving stock (Eq, Show) -instance SingI (ToT v) => Buildable (AnnotatedValue v) where+instance Buildable (AnnotatedValue v) where   build (AnnotatedValue n v) = build v |+ " :: " +| build (mkUType n)  data SomeAnnotatedValue where@@ -76,7 +77,9 @@     do \av v -> av { avValue = toVal v }  -- | Attempts to cast to the given type.-castTo :: forall v1 v2. (IsoValue v1, IsoValue v2) => Prism SomeAnnotatedValue SomeAnnotatedValue (AnnotatedValue v1) (AnnotatedValue v2)+castTo+  :: forall v1 v2. (IsoValue v1, IsoValue v2)+  => Prism SomeAnnotatedValue SomeAnnotatedValue (AnnotatedValue v1) (AnnotatedValue v2) castTo =   prism     do \(AnnotatedValue n v) -> SomeAnnotatedValue n v@@ -92,12 +95,9 @@ If two @or@ branches have the same field annotation, `variant` will match on either branch.  >>> :{-or = Right (Left 3) :: Either Integer (Either Natural Integer)-notes =-  NTOr noAnn [fieldAnnQ|first|] noAnn-    starNotes-    (NTOr noAnn [fieldAnnQ|second|] [fieldAnnQ|third|] starNotes starNotes)-val = SomeAnnotatedValue notes (toVal or)+val = SomeAnnotatedValue+  [notes|or (int %first) (or (nat %second) (int %third))|]+  (toVal (Right (Left 3) :: Either Integer (Either Natural Integer))) :}  >>> val ^? variant [fieldAnnQ|second|] . to pretty@@ -153,18 +153,15 @@ If two fields have the same field annotation, both will be indexed/traversed.  >>> :{-pair = (1, 2, 3) :: (Integer, Natural, Integer)-notes =-  NTPair noAnn [fieldAnnQ|first|] noAnn noAnn noAnn-    starNotes-    (NTPair noAnn [fieldAnnQ|second|] [fieldAnnQ|third|] noAnn noAnn starNotes starNotes)-val = SomeAnnotatedValue notes (toVal pair)+val = SomeAnnotatedValue+  [notes|pair (int %first) (nat %second) (int %third)|]+  (toVal ((1, 2, 3) :: (Integer, Natural, Integer))) :} ->>> mapM_ print $ val ^@.. fields . to pretty-(%first,"1 :: int")-(%second,"2 :: nat")-(%third,"3 :: int")+>>> mapM_ print $ map (bimap pretty pretty) $ val ^@.. fields+("%first","1 :: int")+("%second","2 :: nat")+("%third","3 :: int") -} fields :: IndexedTraversal' FieldAnn SomeAnnotatedValue SomeAnnotatedValue fields (handler :: p SomeAnnotatedValue (f SomeAnnotatedValue)) = \case@@ -194,12 +191,9 @@ If two fields have the same field annotation, both will be indexed/traversed.  >>> :{-pair = (1, 2, 3) :: (Integer, Natural, Integer)-notes =-  NTPair noAnn [fieldAnnQ|first|] noAnn noAnn noAnn-    starNotes-    (NTPair noAnn [fieldAnnQ|second|] [fieldAnnQ|third|] noAnn noAnn starNotes starNotes)-val = SomeAnnotatedValue notes (toVal pair)+val = SomeAnnotatedValue+  [notes|pair (int %first) (nat %second) (int %third)|]+  (toVal ((1, 2, 3) :: (Integer, Natural, Integer))) :}  >>> val ^? field [fieldAnnQ|second|] . castTo @Natural . value@@ -215,19 +209,16 @@ If two fields have the same field annotation, both will be indexed.  >>> :{-pair = (1, 2, 3) :: (Integer, Natural, Integer)-notes =-  NTPair noAnn [fieldAnnQ|first|] noAnn noAnn noAnn-    starNotes-    (NTPair noAnn [fieldAnnQ|second|] [fieldAnnQ|third|] noAnn noAnn starNotes starNotes)-val = SomeAnnotatedValue notes (toVal pair)+val = SomeAnnotatedValue+  [notes|pair (int %first) (nat %second) (int %third)|]+  (toVal ((1, 2, 3) :: (Integer, Natural, Integer))) :} ->>> mapM_ print $ val ^@.. nodes . to pretty-(%first,"1 :: int")-(%,"Pair 2 3 :: pair (nat %second) (int %third)")-(%second,"2 :: nat")-(%third,"3 :: int")+>>> mapM_ print $ map (bimap pretty pretty) $ val ^@.. nodes+("%first","1 :: int")+("%","Pair 2 3 :: pair (nat %second) (int %third)")+("%second","2 :: nat")+("%third","3 :: int") -} nodes :: IndexedFold FieldAnn SomeAnnotatedValue SomeAnnotatedValue nodes = ifolding $ \case@@ -264,7 +255,9 @@ -- >>> val = SomeAnnotatedValue starNotes (toVal map) -- >>> val ^? asMap @Integer . ix 20 . castTo @Bool . value -- Just True-asMap :: forall key. (IsoValue key, Ord key) => Fold SomeAnnotatedValue (Map key SomeAnnotatedValue)+asMap+  :: forall key. (IsoValue key, Ord key)+  => Fold SomeAnnotatedValue (Map key SomeAnnotatedValue) asMap = folding @Maybe \case   SomeAnnotatedValue (NTMap _ _ vNotes) (VMap vmap) -> convert vNotes vmap   SomeAnnotatedValue (NTBigMap _ _ vNotes) (VBigMap _ vmap) -> convert vNotes vmap
src/Morley/Michelson/Typed/Annotation.hs view
@@ -1,7 +1,9 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA+{-# LANGUAGE DeriveLift #-} +{-# OPTIONS_GHC -Wno-orphans #-}+ -- | Module, providing @Notes t@ data type, which holds annotations for a -- given type @t@. --@@ -25,25 +27,29 @@   , insertTypeAnn   , isStar   , starNotes+  , mkUType   , notesSing   , notesT   ) where  import Data.Singletons (Sing, SingI(..), fromSing) import Fmt (Buildable(..), (+|), (|+))-import Text.PrettyPrint.Leijen.Text (Doc, (<+>))-import qualified Text.Show+import Language.Haskell.TH.Lift (Lift) -import Morley.Michelson.Printer.Util-  (RenderDoc(..), addParens, buildRenderDoc, doesntNeedParens, needsParens, printDocS)+import Morley.Michelson.Printer.Util (RenderDoc(..), buildRenderDoc) import Morley.Michelson.Typed.Sing import Morley.Michelson.Typed.T (T(..))+import Morley.Michelson.Untyped qualified as Un import Morley.Michelson.Untyped.Annotation-  (Annotation, FieldAnn, TypeAnn, VarAnn, convergeVarAnns, fullAnnSet, noAnn, singleAnnSet,-  unifyAnn, unifyPairFieldAnn)+  (Annotation, FieldAnn, TypeAnn, VarAnn, convergeVarAnns, noAnn, unifyAnn, unifyPairFieldAnn)+import Morley.Util.Peano qualified as Peano+import Morley.Util.PeanoNatural (singPeanoVal) import Morley.Util.TH import Morley.Util.Typeable +{-# ANN module ("HLint: ignore Avoid lambda using `infix`" :: Text) #-}++ -- | Data type, holding annotation data for a given Michelson type @t@. -- -- Each constructor corresponds to exactly one constructor of 'T'@@ -83,73 +89,99 @@   NTChest     :: TypeAnn -> Notes 'TChest   NTChestKey  :: TypeAnn -> Notes 'TChestKey   NTNever     :: TypeAnn -> Notes 'TNever+  NTSaplingState :: forall (n :: Peano.Peano). TypeAnn -> Sing n -> Notes ('TSaplingState n)+  NTSaplingTransaction :: forall (n :: Peano.Peano). TypeAnn -> Sing n -> Notes ('TSaplingTransaction n)  deriving stock instance Eq (Notes t)+deriving stock instance Show (Notes t)+deriving stock instance Lift (Notes t) $(deriveGADTNFData ''Notes)  -instance Show (Notes t) where-  show = printDocS True . renderDoc doesntNeedParens- instance Buildable (Notes t) where   build = buildRenderDoc  instance RenderDoc (Notes t) where-  renderDoc pn n = addParens pn $ case n of-    NTInt ta                -> "NTInt" <+> rendT ta-    NTNat ta                -> "NTNat" <+> rendT ta-    NTString ta             -> "NTString" <+> rendT ta-    NTBytes ta              -> "NTBytes" <+> rendT ta-    NTMutez ta              -> "NTMutez" <+> rendT ta-    NTBool ta               -> "NTBool" <+> rendT ta-    NTKeyHash ta            -> "NTKeyHash" <+> rendT ta-    NTBls12381Fr ta         -> "NTBls12381Fr" <+> rendT ta-    NTBls12381G1 ta         -> "NTBls12381G1" <+> rendT ta-    NTBls12381G2 ta         -> "NTBls12381G2" <+> rendT ta-    NTTimestamp ta          -> "NTTimestamp" <+> rendT ta-    NTAddress ta            -> "NTAddress" <+> rendT ta-    NTKey ta                -> "NTKey" <+> rendT ta-    NTUnit ta               -> "NTUnit" <+> rendT ta-    NTSignature ta          -> "NTSignature" <+> rendT ta-    NTChainId ta            -> "NTChainId" <+> rendT ta-    NTChest ta              -> "NTChest" <+> rendT ta-    NTChestKey ta           -> "NTChestKey" <+> rendT ta-    NTNever ta              -> "NTNever" <+> rendT ta-    NTOption ta nt          -> "NTOption" <+> rendT ta <+> rendN nt-    NTList ta nt            -> "NTList" <+> rendT ta <+> rendN nt-    NTSet ta nt             -> "NTSet" <+> rendT ta <+> rendN nt-    NTOperation ta          -> "NTOperation" <+> rendT ta-    NTContract ta nt        -> "NTContract" <+> rendT ta <+> rendN nt-    NTTicket ta nt          -> "NTTicket" <+> rendT ta <+> rendN nt-    NTPair ta fa1 fa2 va1 va2 np nq -> "NTPair" <+> rendTFV2 ta fa1 fa2 va1 va2 <+> rendN np <+> rendN nq-    NTOr ta fa1 fa2 np nq   -> "NTOr" <+> rendTF2 ta fa1 fa2 <+> rendN np <+> rendN nq-    NTLambda ta np nq       -> "NTLambda" <+> rendT ta <+> rendN np <+> rendN nq-    NTMap ta np nq          -> "NTMap" <+> rendT ta <+> rendN np <+> rendN nq-    NTBigMap ta np nq       -> "NTBigMap" <+> rendT ta <+> rendN np <+> rendN nq-    where-      rendN :: Notes n -> Doc-      rendN = renderDoc needsParens--      rendT :: TypeAnn -> Doc-      rendT = renderDoc doesntNeedParens . singleAnnSet--      rendTF2 :: TypeAnn -> FieldAnn -> FieldAnn -> Doc-      rendTF2 t f1 f2 = renderDoc doesntNeedParens $ fullAnnSet [t] [f1, f2] []--      rendTFV2 :: TypeAnn -> FieldAnn -> FieldAnn -> VarAnn -> VarAnn -> Doc-      rendTFV2 t f1 f2 v1 v2 = renderDoc doesntNeedParens $ fullAnnSet [t] [f1, f2] [v1, v2]+  renderDoc pn = renderDoc pn . mkUType  -- | Forget information about annotations, pick singleton with the same type.------ Note: currently we cannot derive 'Sing' from 'Notes' without 'SingI' because--- for comparable types notes do not remember which exact comparable was used.-notesSing :: SingI t => Notes t -> Sing t-notesSing _ = sing+notesSing :: Notes t -> Sing t+notesSing = \case+  NTInt _        -> sing+  NTNat _        -> sing+  NTString _     -> sing+  NTBytes _      -> sing+  NTMutez _      -> sing+  NTBool _       -> sing+  NTKeyHash _    -> sing+  NTBls12381Fr _ -> sing+  NTBls12381G1 _ -> sing+  NTBls12381G2 _ -> sing+  NTTimestamp _  -> sing+  NTAddress _    -> sing+  NTKey _        -> sing+  NTUnit _       -> sing+  NTSignature _  -> sing+  NTChainId _    -> sing+  NTOption _ n   -> STOption (notesSing n)+  NTList _ n     -> STList (notesSing n)+  NTSet _ n      -> STSet (notesSing n)+  NTOperation _  -> sing+  NTChest _      -> sing+  NTChestKey _   -> sing+  NTNever _      -> sing+  NTSaplingState _ s -> STSaplingState s+  NTSaplingTransaction _ s -> STSaplingTransaction s+  NTContract _ n -> STContract (notesSing n)+  NTTicket _ n   -> STTicket (notesSing n)+  NTPair _ _ _ _ _ l r -> STPair   (notesSing l) (notesSing r)+  NTOr _ _ _ l r       -> STOr     (notesSing l) (notesSing r)+  NTLambda _ l r       -> STLambda (notesSing l) (notesSing r)+  NTMap _ l r          -> STMap    (notesSing l) (notesSing r)+  NTBigMap _ l r       -> STBigMap (notesSing l) (notesSing r)  -- | Get term-level type of notes.-notesT :: SingI t => Notes t -> T+notesT :: Notes t -> T notesT = fromSing . notesSing +-- | Get the term-level type of notes, preserving annotations.+mkUType :: Notes x -> Un.Ty+mkUType = \case+  NTInt tn        -> Un.Ty Un.TInt tn+  NTNat tn        -> Un.Ty Un.TNat tn+  NTString tn     -> Un.Ty Un.TString tn+  NTBytes tn      -> Un.Ty Un.TBytes tn+  NTMutez tn      -> Un.Ty Un.TMutez tn+  NTBool tn       -> Un.Ty Un.TBool tn+  NTKeyHash tn    -> Un.Ty Un.TKeyHash tn+  NTBls12381Fr tn -> Un.Ty Un.TBls12381Fr tn+  NTBls12381G1 tn -> Un.Ty Un.TBls12381G1 tn+  NTBls12381G2 tn -> Un.Ty Un.TBls12381G2 tn+  NTTimestamp tn  -> Un.Ty Un.TTimestamp tn+  NTAddress tn    -> Un.Ty Un.TAddress tn+  NTKey tn        -> Un.Ty Un.TKey tn+  NTUnit tn       -> Un.Ty Un.TUnit tn+  NTSignature tn  -> Un.Ty Un.TSignature tn+  NTChainId tn    -> Un.Ty Un.TChainId tn+  NTOption tn n   -> Un.Ty (Un.TOption $ mkUType n) tn+  NTList tn n     -> Un.Ty (Un.TList $ mkUType n) tn+  NTSet tn n      -> Un.Ty (Un.TSet $ mkUType n) tn+  NTOperation tn  -> Un.Ty Un.TOperation tn+  NTChest tn      -> Un.Ty Un.TChest tn+  NTChestKey tn   -> Un.Ty Un.TChestKey tn+  NTNever tn      -> Un.Ty Un.TNever tn+  NTSaplingState tn s -> Un.Ty (Un.TSaplingState (singPeanoVal s)) tn+  NTSaplingTransaction tn s -> Un.Ty (Un.TSaplingState (singPeanoVal s)) tn+  NTContract tn n -> Un.Ty (Un.TContract $ mkUType n) tn+  NTTicket tn n   -> Un.Ty (Un.TTicket $ mkUType n) tn+  NTPair tn fl fr vl vr nl nr ->+    Un.Ty (Un.TPair fl fr vl vr (mkUType nl) (mkUType nr)) tn+  NTOr tn fl fr nl nr -> Un.Ty (Un.TOr fl fr (mkUType nl) (mkUType nr)) tn+  NTLambda tn np nq   -> Un.Ty (Un.TLambda (mkUType np) (mkUType nq)) tn+  NTMap tn nk nv      -> Un.Ty (Un.TMap (mkUType nk) (mkUType nv)) tn+  NTBigMap tn nk nv   -> Un.Ty (Un.TBigMap (mkUType nk) (mkUType nv)) tn++ -- | In memory of @NStar@ constructor. --   Generates notes with no annotations. starNotes :: forall t. SingI t => Notes t@@ -172,6 +204,8 @@   STKey -> NTKey noAnn   STUnit -> NTUnit noAnn   STNever -> NTNever noAnn+  STSaplingState s -> NTSaplingState noAnn s+  STSaplingTransaction s -> NTSaplingTransaction noAnn s   STSignature -> NTSignature noAnn   STChainId -> NTChainId noAnn   STOperation -> NTOperation noAnn@@ -215,6 +249,10 @@   (NTChest a, NTChest b) -> NTChest <$> convergeAnns a b   (NTChestKey a, NTChestKey b) -> NTChestKey <$> convergeAnns a b   (NTNever a, NTNever b) -> NTNever <$> convergeAnns a b+  (NTSaplingState a _, NTSaplingState b s) ->+    (\c -> NTSaplingState c s) <$> convergeAnns a b+  (NTSaplingTransaction a _, NTSaplingTransaction b s) ->+    (\c -> NTSaplingTransaction c s) <$> convergeAnns a b   (NTSignature a, NTSignature b) ->     NTSignature <$> convergeAnns a b   (NTChainId a, NTChainId b) ->@@ -279,6 +317,8 @@   NTChest _ -> NTChest nt   NTChestKey _ -> NTChestKey nt   NTNever _ -> NTNever nt+  NTSaplingState _ n -> NTSaplingState nt n+  NTSaplingTransaction _ n -> NTSaplingTransaction nt n  data AnnConvergeError where   AnnConvergeError
src/Morley/Michelson/Typed/Arith.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Module, containing some boilerplate for support of -- arithmetic operations in Michelson language.@@ -14,6 +13,7 @@   , MutezArithErrorType (..)   , Add   , Sub+  , SubMutez   , Mul   , EDiv   , Abs@@ -39,16 +39,18 @@  import Data.Bits (complement, shift, (.&.), (.|.)) import Data.Constraint (Dict(..))-import Fmt (Buildable(build))-import qualified Unsafe (fromIntegral)+import Fmt (Buildable(build), (+|), (|+))+import Unsafe qualified (fromIntegral)  import Morley.Michelson.Typed.Annotation   (AnnConvergeError, Notes(..), converge, convergeAnns, starNotes) import Morley.Michelson.Typed.Polymorphic+import Morley.Michelson.Typed.Scope (Comparable) import Morley.Michelson.Typed.T (T(..))-import Morley.Michelson.Typed.Value (Comparable, Value'(..))+import Morley.Michelson.Typed.Value (Value'(..))+import Morley.Michelson.Untyped.Annotation (noAnn) import Morley.Tezos.Core (addMutez, mulMutez, subMutez, timestampFromSeconds, timestampToSeconds)-import qualified Morley.Tezos.Crypto.BLS12381 as BLS+import Morley.Tezos.Crypto.BLS12381 qualified as BLS import Morley.Util.TypeLits  -- | Class for binary arithmetic operation.@@ -103,7 +105,6 @@ data MutezArithErrorType   = AddOverflow   | MulOverflow-  | SubUnderflow   deriving stock (Show, Eq, Ord, Generic)  instance NFData MutezArithErrorType@@ -127,6 +128,7 @@  data Add data Sub+data SubMutez data Mul data EDiv data Abs@@ -236,12 +238,11 @@   convergeArith _ (NTTimestamp a) (NTTimestamp b) = NTInt <$> (convergeAnns a b)   evalOp _ (VTimestamp i) (VTimestamp j) =     Right $ VInt $ timestampToSeconds i - timestampToSeconds j-instance ArithOp Sub 'TMutez 'TMutez where-  type ArithRes Sub 'TMutez 'TMutez = 'TMutez-  convergeArith _ n1 n2 = converge n1 n2-  evalOp _ n@(VMutez i) m@(VMutez j) = res-    where-      res = maybe (Left $ MutezArithError SubUnderflow n m) (Right . VMutez) $ i `subMutez` j+instance ArithOp SubMutez 'TMutez 'TMutez where+  type ArithRes SubMutez 'TMutez 'TMutez = 'TOption 'TMutez+  convergeArith _ n1 n2 = NTOption noAnn <$> converge n1 n2+  evalOp _ (VMutez i) (VMutez j) =+    Right $ VOption $ fmap VMutez $ i `subMutez` j  instance ArithOp Mul 'TNat 'TInt where   type ArithRes Mul 'TNat 'TInt = 'TInt@@ -490,10 +491,9 @@   build = \case     AddOverflow -> "add overflow"     MulOverflow -> "mul overflow"-    SubUnderflow -> "sub underflow" -instance (Show n, Show m) => Buildable (ArithError n m) where+instance (Buildable n, Buildable m) => Buildable (ArithError n m) where   build (MutezArithError errType n m) = "Mutez "-    <> build errType <> " with " <> show n <> ", " <> show m-  build (ShiftArithError errType n m) =-    build errType <> " with " <> show n <> ", " <> show m+    +| errType |+ " with " +| n |+ ", " +| m |+ ""+  build (ShiftArithError errType n m) = ""+    +| errType |+ " with " +| n |+ ", " +| m |+ ""
src/Morley/Michelson/Typed/Contract.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- 'newtype Container' deriving produced some fake warnings {-# OPTIONS_GHC -Wno-redundant-constraints #-}
src/Morley/Michelson/Typed/Convert.hs view
@@ -1,9 +1,11 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA -{-# OPTIONS_GHC -fno-warn-orphans #-}+-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-} +{-# OPTIONS_GHC -Wno-orphans #-}+ module Morley.Michelson.Typed.Convert   ( convertParamNotes   , convertView@@ -24,46 +26,46 @@   , flattenEntrypoints   ) where -import qualified Data.ByteArray as ByteArray+import Data.ByteArray qualified as ByteArray import Data.Constraint (Dict(..), (\\)) import Data.List.NonEmpty ((<|))-import qualified Data.Map as Map+import Data.Map qualified as Map import Data.Singletons (Sing, demote, withSingI) import Data.Vinyl (Rec(..)) import Fmt (Buildable(..), Builder, blockListF, fmt, indentF, listF, pretty, unlinesF) import Text.PrettyPrint.Leijen.Text (Doc)-import qualified Unsafe (fromIntegral)+import Unsafe qualified (fromIntegral)  import Morley.Michelson.Printer.Util import Morley.Michelson.Text import Morley.Michelson.Typed.Aliases-import Morley.Michelson.Typed.Annotation (Notes(..))+import Morley.Michelson.Typed.Annotation (Notes(..), mkUType) import Morley.Michelson.Typed.Contract import Morley.Michelson.Typed.Entrypoints-import Morley.Michelson.Typed.Extract (mkUType, mkUType', toUType)+import Morley.Michelson.Typed.Extract (toUType) import Morley.Michelson.Typed.Instr as Instr import Morley.Michelson.Typed.Scope import Morley.Michelson.Typed.Sing (SingT(..)) import Morley.Michelson.Typed.T (T(..)) import Morley.Michelson.Typed.Value import Morley.Michelson.Typed.View-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U import Morley.Michelson.Untyped.Annotation (Annotation(unAnnotation)) import Morley.Tezos.Address (Address(..), ContractHash(..)) import Morley.Tezos.Core-  (ChainId(unChainId), mformatChainId, parseChainId, timestampFromSeconds, timestampToSeconds,-  toMutez, unMutez)+  (ChainId(unChainId), mformatChainId, parseChainId, timestampFromSeconds, timestampToSeconds, tz,+  unMutez) import Morley.Tezos.Crypto-import qualified Morley.Tezos.Crypto.BLS12381 as BLS-import qualified Morley.Tezos.Crypto.Ed25519 as Ed25519-import qualified Morley.Tezos.Crypto.P256 as P256-import qualified Morley.Tezos.Crypto.Secp256k1 as Secp256k1+import Morley.Tezos.Crypto.BLS12381 qualified as BLS+import Morley.Tezos.Crypto.Ed25519 qualified as Ed25519+import Morley.Tezos.Crypto.P256 qualified as P256+import Morley.Tezos.Crypto.Secp256k1 qualified as Secp256k1 import Morley.Tezos.Crypto.Timelock (chestBytes, chestKeyBytes)-import Morley.Util.PeanoNatural (fromPeanoNatural)+import Morley.Util.PeanoNatural (fromPeanoNatural, singPeanoVal) import Morley.Util.Sing (eqParamSing)  -- | Convert typed parameter annotations to an untyped 'U.ParameterType'.-convertParamNotes :: SingI cp => ParamNotes cp -> U.ParameterType+convertParamNotes :: ParamNotes cp -> U.ParameterType convertParamNotes (ParamNotes notes rootAnn) =   U.ParameterType (mkUType notes) rootAnn @@ -168,7 +170,7 @@     U.ValueBytes . U.InternalByteString $ BLS.toMichelsonBytes v   (VTimestamp t, _) ->     case opts of-      Readable   -> U.ValueString . unsafeMkMText $ pretty t+      Readable   -> U.ValueString . unsafe . mkMText $ pretty t       _          -> U.ValueInt $ timestampToSeconds t   (VAddress a, _) ->     case opts of@@ -229,7 +231,7 @@     case checkOpPresence lt of       OpAbsent -> U.ValueRight (untypeValueImpl opts rt x) -  (VLam (rfAnyInstr -> ops :: Instr '[inp] '[out]), _) ->+  (VLam (rfAnyInstr -> ops), _) ->     vList U.ValueLambda $ instrToOpsImpl opts ops    (VMap m, STMap kt vt) ->@@ -324,6 +326,7 @@     DocGroup _ _ -> instrToOpsImpl opts i     Ext _ -> instrToOpsImpl opts i     WithLoc _ i0 -> instrToOpsImpl opts (InstrWithNotes proxy n i0)+    Meta _ i0 -> instrToOpsImpl opts (InstrWithNotes proxy n i0)     InstrWithNotes {} -> instrToOpsImpl opts i     -- For inner instruction, filter out values that we don't want to apply     -- annotations to and delegate it's conversion to this function itself.@@ -341,6 +344,7 @@     DocGroup _ _ -> instrToOpsImpl opts i     Ext _ -> instrToOpsImpl opts i     WithLoc _ i0 -> instrToOpsImpl opts (InstrWithVarNotes n i0)+    Meta _ i0 -> instrToOpsImpl opts (InstrWithVarNotes n i0)     InstrWithNotes p0 n0 (InstrWithVarAnns _ i0) ->       instrToOpsImpl opts $ InstrWithNotes p0 n0 $ InstrWithVarNotes n i0     InstrWithNotes _ n0 i0 -> [U.PrimEx $ handleInstrAnnotateWithVarNotes i0 n0 n]@@ -350,8 +354,7 @@   i -> [U.PrimEx $ handleInstr i]   where     handleInstrAnnotateWithVarNotes-      :: forall inp' out' topElems-       . (HasCallStack, Each '[SingI] topElems)+      :: forall inp' out' topElems . HasCallStack       => Instr inp' out'       -> Rec Notes topElems       -> NonEmpty U.VarAnn@@ -360,54 +363,41 @@       addVarNotes (addInstrNote (handleInstr instr) notes) varAnns      handleInstrAnnotate-      :: forall inp' out' topElems.-         (HasCallStack, Each '[SingI] topElems)+      :: forall inp' out' topElems. HasCallStack       => Instr inp' out' -> Rec Notes topElems -> U.ExpandedInstr     handleInstrAnnotate ins' notes =       addInstrNote (handleInstr ins') notes      addInstrNote-      :: forall topElems. (Each '[SingI] topElems, HasCallStack)+      :: forall topElems. HasCallStack       => U.ExpandedInstr -> Rec Notes topElems -> U.ExpandedInstr     addInstrNote instr notes =       case (instr, notes) of         (U.PUSH va _ v, notes' :& _) -> U.PUSH va (mkUType notes') v         (U.SOME _ va, NTOption ta _ :& _) -> U.SOME ta va         (U.NONE _ va _, (NTOption ta nt :: Notes t) :& _) ->-          case sing @t of-            STOption t -> U.NONE ta va $ mkUType' (t, nt)+          U.NONE ta va $ mkUType nt         (U.UNIT _ va, NTUnit ta :& _) -> U.UNIT ta va         (U.PAIRN va n, _) -> U.PAIRN va n         (U.LEFT ta va fa1 fa2 _, (NTOr _ _ _ _ n2 :: Notes t) :& _) ->-          case sing @t of-            STOr _ rt ->-              U.LEFT ta va fa1 fa2 $ mkUType' (rt, n2)+          U.LEFT ta va fa1 fa2 $ mkUType n2         (U.RIGHT ta va fa1 fa2 _, (NTOr _ _ _ n1 _ :: Notes t) :& _) ->-          case sing @t of-            STOr lt _ ->-              U.RIGHT ta va fa1 fa2 $ mkUType' (lt, n1)+          U.RIGHT ta va fa1 fa2 $ mkUType n1         (U.NIL _ va _, (NTList ta n :: Notes t) :& _) ->-          case sing @t of-            STList l -> U.NIL ta va $ mkUType' (l, n)+          U.NIL ta va $ mkUType n         (U.EMPTY_SET _ va _, (NTSet ta1 n :: Notes t) :& _) ->-          case sing @t of-            STSet s -> U.EMPTY_SET ta1 va $ mkUType' (s, n)+          U.EMPTY_SET ta1 va $ mkUType n         (U.EMPTY_MAP _ va _ _, (NTMap ta1 k n :: Notes t) :& _) ->-          case sing @t of-            STMap kt vt -> U.EMPTY_MAP ta1 va (mkUType' (kt, k)) (mkUType' (vt, n))+          U.EMPTY_MAP ta1 va (mkUType k) (mkUType n)         (U.EMPTY_BIG_MAP _ va _ _, (NTBigMap ta1 k n :: Notes t) :& _) ->-          case sing @t of-            STBigMap kt vt -> U.EMPTY_BIG_MAP ta1 va (mkUType' (kt, k)) (mkUType' (vt, n))+          U.EMPTY_BIG_MAP ta1 va (mkUType k) (mkUType n)         (U.LAMBDA va _ _ ops, (NTLambda _ n1 n2 :: Notes t) :& _) ->-          case sing @t of-            STLambda v b -> U.LAMBDA va (mkUType' (v, n1)) (mkUType' (b, n2)) ops+          U.LAMBDA va (mkUType n1) (mkUType n2) ops         (U.CAST va _, n :& _) -> U.CAST va (mkUType n)         (U.UNPACK _ va _, (NTOption ta nt :: Notes t) :& _) ->-          case sing @t of-            STOption op -> U.UNPACK ta va (mkUType' (op, nt))+          U.UNPACK ta va (mkUType nt)         (U.CONTRACT va fa _, (NTOption _ (NTContract _ nt :: Notes t) :: Notes t2) :& _) ->-          case sing @t2 of-            STOption (STContract c) -> U.CONTRACT va fa (mkUType' (c, nt))+          U.CONTRACT va fa (mkUType nt)         (U.CONTRACT va fa t, NTOption _ _ :& _) -> U.CONTRACT va fa t         (U.CAR {}, _) -> instr         (U.CDR {}, _) -> instr@@ -450,6 +440,7 @@         (U.ISNAT _, _) -> instr         (U.ADD _, _) -> instr         (U.SUB _, _) -> instr+        (U.SUB_MUTEZ _, _) -> instr         (U.MUL _, _) -> instr         (U.EDIV _, _) -> instr         (U.ABS _, _) -> instr@@ -521,7 +512,7 @@       va1 :| [va2] -> case ins of         U.CREATE_CONTRACT _ _ c -> U.CREATE_CONTRACT va1 va2 c         _ -> error $-          "addVarNotes: Cannot add two var annotations to instr: " <> show ins+          "addVarNotes: Cannot add two var annotations to instr: " <> pretty ins       va :| [] -> case ins of         U.DUP _ -> U.DUP va         U.DUPN _ s -> U.DUPN va s@@ -558,6 +549,7 @@         U.ISNAT _ -> U.ISNAT va         U.ADD _ -> U.ADD va         U.SUB _ -> U.SUB va+        U.SUB_MUTEZ _ -> U.SUB_MUTEZ va         U.MUL _ -> U.MUL va         U.EDIV _ -> U.EDIV va         U.ABS _ -> U.ABS va@@ -606,14 +598,13 @@         U.SPLIT_TICKET _ -> U.SPLIT_TICKET va         U.JOIN_TICKETS _ -> U.JOIN_TICKETS va         _ -> error $-          "addVarNotes: Cannot add single var annotation to instr: " <> (show ins) <> " with " <> show va+          "addVarNotes: Cannot add single var annotation to instr: " <> (pretty ins) <> " with " <> pretty va       _ -> error $-        "addVarNotes: Trying to add more than two var annotations to instr: " <> (show ins)+        "addVarNotes: Trying to add more than two var annotations to instr: " <> (pretty ins) -    handleInstr :: Instr inp out -> U.ExpandedInstr+    handleInstr :: HasCallStack => Instr inp out -> U.ExpandedInstr     handleInstr = \case       (WithLoc _ _) -> error "impossible"-      Meta _ _ -> error "impossible"       InstrWithNotes {} -> error "impossible"       (InstrWithVarNotes _ _) -> error "impossible"       (InstrWithVarAnns _ _) -> error "impossible"@@ -623,6 +614,7 @@       (Ext _) -> error "impossible"       (Nested _) -> error "impossible"       DocGroup{} -> error "impossible"+      Meta _ i -> handleInstr i       Fn t sfn i -> U.EXT . U.FN t sfn $ instrToOpsImpl opts i       DROP -> U.DROP       (DROPN s) -> U.DROPN (Unsafe.fromIntegral @Natural @Word $ fromPeanoNatural s)@@ -705,6 +697,7 @@       ISNAT -> U.ISNAT U.noAnn       ADD -> U.ADD U.noAnn       SUB -> U.SUB U.noAnn+      SUB_MUTEZ -> U.SUB_MUTEZ U.noAnn       MUL -> U.MUL U.noAnn       EDIV -> U.EDIV U.noAnn       ABS -> U.ABS U.noAnn@@ -766,6 +759,9 @@       SPLIT_TICKET -> U.SPLIT_TICKET U.noAnn       JOIN_TICKETS -> U.JOIN_TICKETS U.noAnn       OPEN_CHEST -> U.OPEN_CHEST U.noAnn+      SAPLING_EMPTY_STATE s ->+        U.SAPLING_EMPTY_STATE U.noAnn (singPeanoVal s)+      SAPLING_VERIFY_UPDATE -> U.SAPLING_VERIFY_UPDATE U.noAnn  untypeStackRef :: StackRef s -> U.StackRef untypeStackRef (StackRef n) = U.StackRef (fromPeanoNatural n)@@ -829,12 +825,12 @@ -- Since not for all types it is possible to produce a sensible example, -- the result is optional. E.g. for operations, @never@, not proper -- types like @contract operation@ we return 'Nothing'.-sampleTypedValue :: Sing t -> Maybe (Value t)+sampleTypedValue :: forall t. Sing t -> Maybe (Value t) sampleTypedValue = \case     STInt              -> Just $ VInt -1     STNat              -> Just $ VNat 0     STString           -> Just $ VString [mt|hello|]-    STMutez            -> Just $ VMutez (toMutez 100)+    STMutez            -> Just $ VMutez [tz|100u|]     STBool             -> Just $ VBool True     STKey              -> Just $ VKey samplePublicKey     STKeyHash          -> Just $ VKeyHash $ hashKey samplePublicKey@@ -854,6 +850,8 @@     STChest            -> Nothing     STChestKey         -> Nothing     STNever            -> Nothing+    STSaplingState _   -> Nothing+    STSaplingTransaction _ -> Nothing     STOption t ->       withSingI t $ VOption . Just <$> sampleTypedValue t     STList t ->@@ -862,6 +860,7 @@       Dict <- comparabilityPresence t       VSet . one <$> sampleTypedValue t     STContract t -> withSingI t $ do+      Dict <- rightToMaybe $ getWTP @t       Dict <- opAbsense t       Dict <- nestedBigMapsAbsense t       pure . VContract (eaAddress sampleAddress) $ SomeEpc unsafeEpcCallRoot@@ -898,7 +897,7 @@           pure $ VLam $ RfNormal (DROP `Seq` PUSH val)         _ -> pure $ VLam $ RfAlwaysFails (PUSH (VString [mt|lambda sample|]) `Seq` FAILWITH)     where-      sampleAddress = unsafeParseEpAddress "KT1AEseqMV6fk2vtvQCVyA7ZCaxv7cpxtXdB"+      sampleAddress = (unsafe . parseEpAddress) "KT1AEseqMV6fk2vtvQCVyA7ZCaxv7cpxtXdB"       samplePublicKey = fromRight (error "impossible") $ parsePublicKey         "edpkuwTWKgQNnhR5v17H2DYHbfcxYepARyrPGbf1tbMoGQAj8Ljr3V"       sampleSignature = fromRight (error "impossible") $ parseSignature@@ -911,7 +910,7 @@ -- | Flatten a provided list of notes to a map of its entrypoints and its -- corresponding utype. Please refer to 'U.mkEntrypointsMap' in regards to how -- duplicate entrypoints are handled.-flattenEntrypoints :: SingI t => ParamNotes t -> Map EpName U.Ty+flattenEntrypoints :: ParamNotes t -> Map EpName U.Ty flattenEntrypoints = U.mkEntrypointsMap . convertParamNotes  -------------------------------------------------------------------------------
src/Morley/Michelson/Typed/Doc.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-orphans #-} @@ -15,6 +14,7 @@   ) where  import Control.Lens (at)+import Control.Monad.Writer.Strict (Writer, runWriter, writer) import Data.Default (def) import Data.Typeable (cast) import Prelude hiding (Ordering(..))@@ -61,7 +61,7 @@ -- | Assemble contract documentation with the revision of the contract. {-# DEPRECATED buildInstrDocWithGitRev     "Use `buildDoc . attachDocCommons gitRev` instead."-#-}+  #-} buildInstrDocWithGitRev :: DGitRevision -> Instr inp out -> ContractDoc buildInstrDocWithGitRev gitRev contract =   let toc = DToc $ contractDocToToc $ buildInstrDoc contract@@ -80,14 +80,14 @@     _ -> mempty   _ -> mempty   where-  dfsSettings :: DfsSettings ContractDoc+  dfsSettings :: DfsSettings (Writer ContractDoc)   dfsSettings = def     { dsCtorEffectsApp = CtorEffectsApp         { ceaName = "Building DocGroup"-        , ceaApplyEffects = \resChildren _ -> \case-            i@(DocGroup grouping _) ->-              (i, docGroupContent grouping resChildren)-            i -> (i, resChildren)+        , ceaPostStep = \_old -> \case+            (runWriter -> (i@(DocGroup grouping _), resChildren)) ->+              writer (i, docGroupContent grouping resChildren)+            other -> other         }     } @@ -142,13 +142,14 @@ cutInstrNonDoc :: (forall i o. Instr i o -> Instr i o) -> Instr inp out -> Instr s s cutInstrNonDoc optimize = optimize . dfsFoldInstr dfsSettings step   where-  dfsSettings :: DfsSettings (Instr s s)+  dfsSettings :: DfsSettings $ Writer (Instr s s)   dfsSettings = def     { dsCtorEffectsApp = CtorEffectsApp         { ceaName = "Wrap into DocGroup"-        , ceaApplyEffects = \resChildren _ -> \case-            i@(DocGroup g _) -> (i, DocGroup g resChildren)-            i -> (i, resChildren)+        , ceaPostStep = \_old -> \case+            (runWriter -> (i@(DocGroup g _), resChildren)) ->+              writer (i, DocGroup g resChildren)+            other -> other         }     }   step :: Instr inp out -> Instr s s
src/Morley/Michelson/Typed/Entrypoints.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Utilities for lightweight entrypoints support. module Morley.Michelson.Typed.Entrypoints@@ -9,9 +8,7 @@   , formatEpAddress   , mformatEpAddress   , parseEpAddress-  , unsafeParseEpAddress   , parseEpAddressRaw-  , unsafeParseEpAddressRaw   , ParamNotes (..)   , pattern ParamNotes   , starParamNotes@@ -45,11 +42,11 @@   ) where  import Control.Monad.Except (throwError)-import qualified Data.ByteString as BS+import Data.ByteString qualified as BS import Data.Constraint (Dict(..))-import qualified Data.List.NonEmpty as NE+import Data.List.NonEmpty qualified as NE import Data.Singletons (withSingI)-import qualified Data.Text as T+import Data.Text qualified as T import Fmt (Buildable(..), hexF, pretty, (+|), (|+)) import Text.PrettyPrint.Leijen.Text (int, punctuate, squotes, textStrict, (<+>)) @@ -98,7 +95,7 @@   let t = formatEpAddress ea      -- Should be safe because set of characters allowed in annotations      -- (and thus in 'EpName') is subset of characters allowed in Michelson strings.-  in unsafeMkMText t+  in unsafe . mkMText $ t  data ParseEpAddressError   = ParseEpAddressBadAddress ParseAddressError@@ -143,9 +140,6 @@       epName <- first ParseEpAddressRefAnnError $ epNameFromRefAnn annot       return $ EpAddress addr epName -unsafeParseEpAddress :: HasCallStack => Text -> EpAddress-unsafeParseEpAddress = either (error . pretty) id . parseEpAddress- -- | Parses byte representation of entrypoint address. -- -- For every address@@ -170,9 +164,6 @@   decodedAnnotation <- first ParseEpAddressBadRefAnn $ mkAnnotation decodedEntrypoint   eaEntrypoint <- first ParseEpAddressRefAnnError $ epNameFromRefAnn decodedAnnotation   pure $ EpAddress {..}--unsafeParseEpAddressRaw :: ByteString -> EpAddress-unsafeParseEpAddressRaw = either (error . pretty) id . parseEpAddressRaw  -- ParamNotes ----------------------------------------------------------------------------
src/Morley/Michelson/Typed/Existential.hs view
@@ -1,15 +1,19 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +{-# LANGUAGE QuantifiedConstraints #-}+ module Morley.Michelson.Typed.Existential-  ( SomeConstant (..)-  , SomeConstrainedValue (..)+  ( -- * SomeConstrainedValue and derivatives+    SomeConstrainedValue (.., SomeValue, SomeConstant, SomeStorage, SomePackedVal)+  , SomeConstant+  , SomeValue+  , SomeStorage+  , SomePackedVal+    -- * Other existentials   , SomeContract (..)   , SomeContractAndStorage (..)   , SomeIsoValue (..)-  , SomeValue (..)-  , SomeStorage(..)   ) where  import Fmt (Buildable(..))@@ -22,40 +26,57 @@ import Morley.Michelson.Typed.T (T(..)) import Morley.Util.Sing (eqParamSing) +----------------------------------------------------------------------------+-- SomeConstrainedValue+----------------------------------------------------------------------------+ data SomeConstrainedValue (c :: T -> Constraint) where-  SomeConstrainedValue-    :: forall (t :: T) (c :: T -> Constraint)-    . (c t)-    => Value t-    -> SomeConstrainedValue c+  SomeConstrainedValue :: forall t c. (c t) => Value t -> SomeConstrainedValue c  deriving stock instance Show (SomeConstrainedValue c) --- TODO--- @gromak: perhaps we should implement `SomeValue` in terms of--- `SomeConstrainedValue`, but it will require changing quite a lot of code,--- so it is postponed.+instance Buildable (SomeConstrainedValue c) where+  build (SomeConstrainedValue v) = build v -data SomeValue where-  SomeValue :: SingI t => Value t -> SomeValue+instance (forall t. cs t => SingI t) => Eq (SomeConstrainedValue cs) where+  SomeConstrainedValue v1 == SomeConstrainedValue v2 = v1 `eqParamSing` v2 -deriving stock instance Show SomeValue+instance (forall t. cs t => HasNoOp t) => RenderDoc (SomeConstrainedValue cs) where+  renderDoc pn (SomeConstrainedValue v) = renderDoc pn v -instance Eq SomeValue where-  SomeValue v1 == SomeValue v2 = v1 `eqParamSing` v2+----------------------------------------------------------------------------+-- SomeConstrainedValue synonyms+---------------------------------------------------------------------------- -data SomeConstant where-  SomeConstant :: (ConstantScope t, SingI t) => Value t -> SomeConstant+type SomeValue = SomeConstrainedValue SingI+pattern SomeValue :: () => SingI t => Value t -> SomeValue+pattern SomeValue x = SomeConstrainedValue x+{-# COMPLETE SomeValue #-} -instance Buildable SomeConstant where-  build (SomeConstant v) = build v+type SomeConstant = SomeConstrainedValue ConstantScope+pattern SomeConstant :: () => ConstantScope t => Value t -> SomeConstant+pattern SomeConstant x = SomeConstrainedValue x+{-# COMPLETE SomeConstant #-} -instance RenderDoc SomeConstant where-  renderDoc pn (SomeConstant v) = renderDoc pn v+type SomeStorage = SomeConstrainedValue StorageScope+pattern SomeStorage :: () => StorageScope t => Value t -> SomeStorage+pattern SomeStorage x = SomeConstrainedValue x+{-# COMPLETE SomeStorage #-} +type SomePackedVal = SomeConstrainedValue PackedValScope+pattern SomePackedVal :: () => PackedValScope t => Value t -> SomePackedVal+pattern SomePackedVal x = SomeConstrainedValue x+{-# COMPLETE SomePackedVal #-}++-- other synonyms should be easy to add by analogy, if needed.++----------------------------------------------------------------------------+-- Other existentials+----------------------------------------------------------------------------+ -- | Hides some Haskell value put in line with Michelson 'Value'. data SomeIsoValue where-  SomeIsoValue :: (KnownIsoT a) => a -> SomeIsoValue+  SomeIsoValue :: KnownIsoT a => a -> SomeIsoValue  data SomeContract where   SomeContract :: Contract cp st -> SomeContract@@ -75,8 +96,3 @@        -> SomeContractAndStorage  deriving stock instance Show SomeContractAndStorage--data SomeStorage where-  SomeStorage :: forall st. StorageScope st => Value st -> SomeStorage--deriving stock instance Show SomeStorage
src/Morley/Michelson/Typed/Extract.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Module, containing functions to convert @Morley.Michelson.Untyped.Ty@ to -- @Morley.Michelson.Typed.T.T@ Michelson type representation (type stripped off all@@ -11,8 +10,6 @@ -- @Notes t@ for which @t@ is a type representation of value @t@. module Morley.Michelson.Typed.Extract   ( fromUType-  , mkUType-  , mkUType'   , toUType   , withUType @@ -20,81 +17,18 @@   , pattern AsUTypeExt   ) where -import Data.Singletons (Sing, SingI, fromSing)+import Data.Singletons (Sing, SingI, SomeSing(..), fromSing, withSingI) -import Morley.Michelson.Typed.Annotation (Notes(..), notesSing)-import Morley.Michelson.Typed.Sing (SingT(..))+import Morley.Michelson.Typed.Annotation (Notes(..), mkUType, notesSing) import Morley.Michelson.Typed.T (T(..), toUType)-import qualified Morley.Michelson.Untyped as Un+import Morley.Michelson.Untyped qualified as Un+import Morley.Util.Peano qualified as Peano  {-# ANN module ("HLint: ignore Avoid lambda using `infix`" :: Text) #-}  fromUType :: Un.Ty -> T fromUType ut = withUType ut (fromSing . notesSing) -mkUType :: SingI x => Notes x -> Un.Ty-mkUType notes = mkUType' (notesSing notes, notes)--mkUType' :: (Sing x, Notes x) -> Un.Ty-mkUType' = \case-  (STInt, NTInt tn)               -> Un.Ty Un.TInt tn-  (STNat, NTNat tn)               -> Un.Ty Un.TNat tn-  (STString, NTString tn)         -> Un.Ty Un.TString tn-  (STBytes, NTBytes tn)           -> Un.Ty Un.TBytes tn-  (STMutez, NTMutez tn)           -> Un.Ty Un.TMutez tn-  (STBool, NTBool tn)             -> Un.Ty Un.TBool tn-  (STKeyHash, NTKeyHash tn)       -> Un.Ty Un.TKeyHash tn-  (STBls12381Fr, NTBls12381Fr tn) -> Un.Ty Un.TBls12381Fr tn-  (STBls12381G1, NTBls12381G1 tn) -> Un.Ty Un.TBls12381G1 tn-  (STBls12381G2, NTBls12381G2 tn) -> Un.Ty Un.TBls12381G2 tn-  (STTimestamp, NTTimestamp tn)   -> Un.Ty Un.TTimestamp tn-  (STAddress, NTAddress tn)       -> Un.Ty Un.TAddress tn-  (STKey, NTKey tn)               -> Un.Ty Un.TKey tn-  (STUnit, NTUnit tn)             -> Un.Ty Un.TUnit tn-  (STSignature, NTSignature tn)   -> Un.Ty Un.TSignature tn-  (STChainId, NTChainId tn)       -> Un.Ty Un.TChainId tn-  (STOption t, NTOption tn n)     -> Un.Ty (Un.TOption $ mkUType' (t, n)) tn-  (STList t, NTList tn n)         -> Un.Ty (Un.TList $ mkUType' (t, n)) tn-  (STSet t, NTSet tn n)           -> Un.Ty (Un.TSet $ mkUType' (t, n)) tn-  (STOperation, NTOperation tn)   -> Un.Ty Un.TOperation tn-  (STChest, NTChest tn)           -> Un.Ty Un.TChest tn-  (STChestKey, NTChestKey tn)     -> Un.Ty Un.TChestKey tn-  (STNever, NTNever tn)           -> Un.Ty Un.TNever tn-  (STContract t, NTContract tn n) ->-    Un.Ty (Un.TContract $ mkUType' (t, n)) tn-  (STTicket t, NTTicket tn n) ->-      Un.Ty (Un.TTicket $ mkUType' (t, n)) tn-  (STPair t t', NTPair tn fl fr vl vr nl nr) ->-    Un.Ty-    (Un.TPair fl fr vl vr-    (mkUType' (t, nl))-    (mkUType' (t', nr)))-    tn-  (STOr t t', NTOr tn fl fr nl nr) ->-    Un.Ty-    (Un.TOr fl fr-    (mkUType' (t, nl))-    (mkUType' (t', nr)))-    tn-  (STLambda t t', NTLambda tn np nq) ->-    Un.Ty-    (Un.TLambda-    (mkUType' (t, np))-    (mkUType' (t', nq)))-    tn-  (STMap t t', NTMap tn nk nv) ->-    Un.Ty-    (Un.TMap-    (mkUType' (t, nk))-    (mkUType' (t', nv)))-    tn-  (STBigMap t t', NTBigMap tn nk nv) ->-    Un.Ty-    (Un.TBigMap-    (mkUType' (t, nk))-    (mkUType' (t', nv)))-    tn- -- | Convert 'Un.Ty' to the isomorphic set of information from typed world. withUType   :: Un.Ty@@ -158,6 +92,16 @@    Un.TNever ->     cont (NTNever tn)++  Un.TSaplingState n ->+    (\(SomeSing s) -> withSingI s $+      cont (NTSaplingState tn s)+    ) $ Peano.someSingNat n++  Un.TSaplingTransaction n ->+    (\(SomeSing s) -> withSingI s $+      cont (NTSaplingTransaction tn s)+    ) $ Peano.someSingNat n    Un.TOption internalT -> withUType internalT $     \(notesInternalT :: Notes internalT) ->
src/Morley/Michelson/Typed/Haskell.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Haskell-Michelson conversions. module Morley.Michelson.Typed.Haskell
src/Morley/Michelson/Typed/Haskell/Compatibility.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Compatibility of Haskell values representation in Michelson. module Morley.Michelson.Typed.Haskell.Compatibility
src/Morley/Michelson/Typed/Haskell/Doc.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- Dunno why it triggers {-# OPTIONS_GHC -Wno-redundant-constraints #-}@@ -55,13 +54,13 @@ import Data.Char (isLower, isUpper, toLower) import Data.List (lookup) import Data.Singletons (SingI, demote)-import qualified Data.Text as T+import Data.Text qualified as T import Data.Typeable (typeRep, typeRepArgs) import Fmt (Buildable, Builder, build, (+|), (|+)) import GHC.Generics ((:*:)(..), (:+:)(..))-import qualified GHC.Generics as G+import GHC.Generics qualified as G import GHC.TypeLits (ErrorMessage(..), KnownSymbol, TypeError, symbolVal)-import qualified Text.Show+import Text.Show qualified import Type.Showtype (Showtype(..))  import Morley.Michelson.Doc
src/Morley/Michelson/Typed/Haskell/Instr.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Typed.Haskell.Instr   ( module Exports
src/Morley/Michelson/Typed/Haskell/Instr/Helpers.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Helpers used for product and sum type representations module Morley.Michelson.Typed.Haskell.Instr.Helpers
src/Morley/Michelson/Typed/Haskell/Instr/Product.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-redundant-constraints #-} {-# LANGUAGE InstanceSigs #-}@@ -11,7 +10,10 @@   , InstrSetFieldC   , InstrConstructC   , instrToField+  , instrGetField+  , instrGetFieldOpen   , instrSetField+  , instrSetFieldOpen   , instrConstruct   , instrConstructStack   , instrDeconstruct@@ -27,13 +29,14 @@  import Data.Vinyl.Core (Rec(..)) import GHC.Generics ((:*:)(..), (:+:)(..))-import qualified GHC.Generics as G+import GHC.Generics qualified as G import GHC.TypeLits (ErrorMessage(..), Symbol, TypeError)  import Morley.Michelson.Text import Morley.Michelson.Typed.Haskell.Instr.Helpers import Morley.Michelson.Typed.Haskell.Value import Morley.Michelson.Typed.Instr+import Morley.Michelson.Typed.Scope import Morley.Util.Label (Label) import Morley.Util.Named import Morley.Util.Type@@ -117,7 +120,51 @@   gInstrToField @name @(G.Rep dt) @(LnrBranch (GetNamed name dt))     @(GetFieldType dt name) --- | Constraint for 'instrToField'.+-- | Make an instruction which copies given field of the given datatype.+--+-- This behaves exactly as @Seq DUP (instrToField #name)@, but does not require+-- the entire datatype to be dupable (the field ofc still must be dupable).+--+-- If we follow the path from the root to the copied field in the pairs tree,+-- the more nodes contain non-dupable elements in the subtree, the less+-- efficient this function becomes.+-- Assuming that all fields are accessed equally often, the most optimal+-- representation would be to put all dupable elements to one subtree+-- of the root, and all non-dupable elements in the second subtree of the root.+instrGetField+  :: forall dt name st.+     (InstrGetFieldC dt name, DupableScope (ToT (GetFieldType dt name)))+  => Label name -> Instr (ToT dt ': st) (ToT (GetFieldType dt name) ': ToT dt ': st)+instrGetField = instrGetFieldOpen @dt DUP Nop++-- | \"Open\" version of 'instrGetField', meaning that it accepts+-- continuations that accept the copied field. This allows chaining+-- getters without requiring 'DupableScope' on the intermediate fields.+--+-- Accepted continuations:+--+-- 1. The one that leaves the field on stack (and does a duplication inside).+--    Used when the datatype had an unfortunate placement of non-dupable fields,+--    or the intermediate field contains non-dupable elements, so the duplication+--    cannot occur automatically in between.+-- 2. The one that consumes the field, used in case we managed to call @DUP@+--    earlier to make the instruction's implementation smaller, and now we+--    only need to access the field with @CAR@ and @CDR@s.+--+-- Note that only one continuation will be chosen eventually, no contract size+-- overhead is expected in this regard.+instrGetFieldOpen+  :: forall dt name res st.+     (InstrGetFieldC dt name)+  => Instr '[ToT (GetFieldType dt name)] '[res, ToT (GetFieldType dt name)]+  -> Instr '[ToT (GetFieldType dt name)] '[res]+  -> Label name+  -> Instr (ToT dt ': st) (res ': ToT dt ': st)+instrGetFieldOpen contWDup contWoDup _ =+  gInstrGetFieldOpen @name @(G.Rep dt) @(LnrBranch (GetNamed name dt))+    @(GetFieldType dt name) contWDup contWoDup++-- | Constraint for 'instrGetField'. type InstrGetFieldC dt name =   ( GenericIsoValue dt   , GInstrGet name (G.Rep dt)@@ -147,19 +194,49 @@   gInstrToField     :: GIsoValue x     => Instr (GValueType x ': s) (ToT fieldTy ': s)+  gInstrGetFieldOpen+    :: (GIsoValue x)+    => Instr '[ToT fieldTy] '[res, ToT fieldTy]+    -> Instr '[ToT fieldTy] '[res]+    -> Instr (GValueType x ': s) (res ': GValueType x ': s) +-- | If the current node in the tree is dupable, this provides the more+-- efficient implementation.+gTryShortCircuitNonDup+  :: forall name x path fieldTy res s.+     (GInstrGet name x path fieldTy)+  => Instr '[ToT fieldTy] '[res]+  -> Maybe $ Instr (GValueType x ': s) (res ': GValueType x ': s)+gTryShortCircuitNonDup cont =+  case checkScope @(DupableScope $ GValueType x) of+    Left{} -> Nothing+    Right Dict -> Just $+      DUP `Seq` gInstrToField @name @x @path @fieldTy `Seq` FrameInstr Proxy cont+ instance GInstrGet name x path f => GInstrGet name (G.M1 t i x) path f where   gInstrToField = gInstrToField @name @x @path @f+  gInstrGetFieldOpen = gInstrGetFieldOpen @name @x @path @f  instance (IsoValue f, ToT f ~ ToT f') =>          GInstrGet name (G.Rec0 f) '[] f' where   gInstrToField = Nop+  gInstrGetFieldOpen contWDup _ = FrameInstr Proxy contWDup  instance (GInstrGet name x path f, GIsoValue y) => GInstrGet name (x :*: y) ('L ': path) f where   gInstrToField = CAR `Seq` gInstrToField @name @x @path @f+  gInstrGetFieldOpen contWDup contWoDup =+    gTryShortCircuitNonDup @name @(x :*: y) @('L ': path) @f contWoDup ?:+    UNPAIR+      `Seq` gInstrGetFieldOpen @name @x @path @f contWDup contWoDup+      `Seq` DIP PAIR  instance (GInstrGet name y path f, GIsoValue x) => GInstrGet name (x :*: y) ('R ': path) f where   gInstrToField = CDR `Seq` gInstrToField @name @y @path @f+  gInstrGetFieldOpen contWDup contWoDup =+    gTryShortCircuitNonDup @name @(x :*: y) @('R ': path) @f contWoDup ?:+    UNPAIR `Seq` SWAP+      `Seq` gInstrGetFieldOpen @name @y @path @f contWDup contWoDup+      `Seq` DIP (SWAP `Seq` PAIR)  -- Examples ----------------------------------------------------------------------------@@ -196,10 +273,24 @@   :: forall dt name st.      InstrSetFieldC dt name   => Label name -> Instr (ToT (GetFieldType dt name) ': ToT dt ': st) (ToT dt ': st)-instrSetField _ =-  gInstrSetField @name @(G.Rep dt) @(LnrBranch (GetNamed name dt))-    @(GetFieldType dt name)+instrSetField =+  instrSetFieldOpen @dt (DIP DROP) +-- | \"Open\" version of 'instrSetField', meaning that it accepts a continuation+-- that describes how to update the field. This allows chaining setters with+-- zero overhead and without requiring 'DupableScope' on the intermediate fields+-- (if we supported only closed setters that work directly with one datatype, we+-- would need to duplicate intermediate fields to chain setters).+instrSetFieldOpen+  :: forall dt name new st.+     InstrSetFieldC dt name+  => Instr '[new, ToT (GetFieldType dt name)] '[ToT (GetFieldType dt name)]+  -> Label name+  -> Instr (new ': ToT dt ': st) (ToT dt ': st)+instrSetFieldOpen cont _ =+  gInstrSetFieldOpen @name @(G.Rep dt) @(LnrBranch (GetNamed name dt))+    @(GetFieldType dt name) cont+ -- | Constraint for 'instrSetField'. type InstrSetFieldC dt name =   ( GenericIsoValue dt@@ -215,26 +306,27 @@     (x :: Type -> Type)     (path :: Path)     (fieldTy :: Type) where-  gInstrSetField-    :: Instr (ToT fieldTy ': GValueType x ': s) (GValueType x ': s)+  gInstrSetFieldOpen+    :: Instr '[new, ToT fieldTy] '[ToT fieldTy]+    -> Instr (new ': GValueType x ': s) (GValueType x ': s)  instance GInstrSetField name x path f => GInstrSetField name (G.M1 t i x) path f where-  gInstrSetField = gInstrSetField @name @x @path @f+  gInstrSetFieldOpen = gInstrSetFieldOpen @name @x @path @f  instance (IsoValue f, ToT f ~ ToT f') =>          GInstrSetField name (G.Rec0 f) '[] f' where-  gInstrSetField = DIP DROP+  gInstrSetFieldOpen cont = FrameInstr Proxy cont  instance (GInstrSetField name x path f, GIsoValue y) => GInstrSetField name (x :*: y) ('L ': path) f where-  gInstrSetField =+  gInstrSetFieldOpen cont =     DIP UNPAIR `Seq`-    gInstrSetField @name @x @path @f `Seq`+    gInstrSetFieldOpen @name @x @path @f cont `Seq`     PAIR  instance (GInstrSetField name y path f, GIsoValue x) => GInstrSetField name (x :*: y) ('R ': path) f where-  gInstrSetField =+  gInstrSetFieldOpen cont =     DIP (UNPAIR `Seq` SWAP) `Seq`-    gInstrSetField @name @y @path @f `Seq`+    gInstrSetFieldOpen @name @y @path @f cont `Seq`     SWAP `Seq` PAIR  -- Examples
src/Morley/Michelson/Typed/Haskell/Instr/Sum.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-redundant-constraints #-} @@ -44,7 +43,7 @@ import Data.Type.Bool (type (||)) import Data.Vinyl.Core (Rec(..)) import GHC.Generics ((:*:)(..), (:+:)(..))-import qualified GHC.Generics as G+import GHC.Generics qualified as G import GHC.TypeLits (AppendSymbol, ErrorMessage(..), Symbol, TypeError) import Type.Reflection ((:~:)(Refl)) import Unsafe.Coerce (unsafeCoerce)@@ -81,7 +80,8 @@   ExtractCtorField 'NoFields = ()  -- | Push field to stack, if any.-type family AppendCtorField (cf :: CtorField) (l :: [k]) :: [k] where+type AppendCtorField :: CtorField -> [k] -> [k]+type family AppendCtorField cf l where   AppendCtorField ('OneField t) (l :: [T]) = ToT t ': l   AppendCtorField ('OneField t) (l :: [Type]) = t ': l   AppendCtorField 'NoFields (l :: [T]) = l
src/Morley/Michelson/Typed/Haskell/LooseSum.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-redundant-constraints #-} @@ -19,9 +18,9 @@   , LooseSumC   ) where -import Data.Singletons+import Data.Singletons (SingI(..), demote) import GHC.Generics ((:*:), (:+:))-import qualified GHC.Generics as G+import GHC.Generics qualified as G  import Morley.Michelson.Typed.Aliases import Morley.Michelson.Typed.Existential
src/Morley/Michelson/Typed/Haskell/ValidateDescription.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Type-level field description validators module Morley.Michelson.Typed.Haskell.ValidateDescription@@ -11,9 +10,9 @@   ) where  import Data.Singletons (Demote)-import Data.Type.Bool-import qualified GHC.Generics as G-import GHC.TypeLits+import Data.Type.Bool (If, type (||))+import GHC.Generics qualified as G+import GHC.TypeLits (ErrorMessage(..), Symbol, TypeError)  -- | Description of constructors and fields of some datatype. --@@ -130,6 +129,7 @@  data T1 a -type family Assert (err :: Constraint) (break :: Type -> Type) (v :: k) :: k where+type Assert :: Constraint -> (Type -> Type) -> k -> k+type family Assert err break v where   Assert _ T1 _ = Any   Assert _ _ k = k
src/Morley/Michelson/Typed/Haskell/Value.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-redundant-constraints #-} @@ -13,7 +12,6 @@   , GIsoValue (GValueType)   , ToT'   , GenericIsoValue-  , WellTyped   , WellTypedIsoValue   , WellTypedToT   , HasNoOpToT@@ -38,20 +36,19 @@   , totsKnownLemma   , totsAppendLemma   ) where--import Control.Lens+import Control.Lens (At(..), Index, Iso, IxValue, Ixed(..), iso) import Data.Constraint (Dict(..)) import Data.Data (Data) import Data.Default (Default(..)) import Data.Fixed (Fixed(..)) import Data.Foldable (Foldable(foldr))-import qualified Data.Map.Strict as Map-import qualified Data.Set as Set+import Data.Map.Strict qualified as Map+import Data.Set qualified as Set import Data.Vinyl.Core (Rec(..)) import Fmt (Buildable(..), mapF) import GHC.Exts as Exts (IsList(..)) import GHC.Generics ((:*:)(..), (:+:)(..))-import qualified GHC.Generics as G+import GHC.Generics qualified as G  import Morley.Michelson.Text import Morley.Michelson.Typed.Aliases@@ -64,6 +61,7 @@ import Morley.Tezos.Crypto   (Bls12381Fr, Bls12381G1, Bls12381G2, Chest, ChestKey, KeyHash, PublicKey, Signature) import Morley.Util.Named+import Morley.Util.SizedList.Types import Morley.Util.Type  ----------------------------------------------------------------------------@@ -96,7 +94,8 @@   fromVal = G.to . gFromValue  -- | Overloaded version of 'ToT' to work on Haskell and @T@ types.-type family ToT' (t :: k) :: T where+type ToT' :: forall k. k -> T+type family ToT' t where   ToT' (t :: T) = t   ToT' (t :: Type) = ToT t @@ -358,6 +357,11 @@   type ToBigMapKey (NonEmpty (k, v)) = k   mkBigMap (h :| t) = one h <> mkBigMap t +instance Ord k => ToBigMap (SizedList' n (k, v)) where+  type ToBigMapValue (SizedList' n (k, v)) = v+  type ToBigMapKey (SizedList' n (k, v)) = k+  mkBigMap = Exts.fromList . Prelude.toList+ instance Ord k => Semigroup (BigMap k v) where   BigMap _ m1 <> BigMap _ m2 = BigMap Nothing (m1 <> m2) @@ -458,7 +462,8 @@   ToTs (x ': xs) = ToT x ': ToTs xs  -- | Overloaded version of 'ToTs' to work on Haskell and @T@ stacks.-type family ToTs' (t :: [k]) :: [T] where+type ToTs' :: forall k. [k] -> [T]+type family ToTs' t where   ToTs' (t :: [T]) = t   ToTs' (a :: [Type]) = ToTs a @@ -489,58 +494,3 @@   KNil -> Dict   KCons _ (_ :: Proxy a') ->     case totsAppendLemma @a' @b of Dict -> Dict---- | This class encodes Michelson rules w.r.t where it requires comparable--- types. Earlier we had a dedicated type for representing comparable types @CT@.--- But then we integreated those types into @T@. This meant that some of the--- types that could be formed with various combinations of @T@ would be--- illegal as per Michelson typing rule. Using this class, we inductively--- enforce that a type and all types it contains are well typed as per--- Michelson's rules.-class (SingI t, WellTypedSuperC t) => WellTyped (t :: T) where-  -- | Constraints required for instance of a given type.-  type WellTypedSuperC t :: Constraint-  type WellTypedSuperC _ = ()--instance WellTyped 'TKey where-instance WellTyped 'TUnit where-instance WellTyped 'TNever where-instance WellTyped 'TSignature where-instance WellTyped 'TChainId where-instance WellTyped 'TChest where-instance WellTyped 'TChestKey where-instance WellTyped t => WellTyped ('TOption t) where-  type WellTypedSuperC ('TOption t) = WellTyped t-instance WellTyped t => WellTyped ('TList t) where-  type WellTypedSuperC ('TList t) = WellTyped t-instance (Comparable t, WellTyped t) => WellTyped ('TSet t) where-  type WellTypedSuperC ('TSet t) = (Comparable t, WellTyped t)-instance WellTyped 'TOperation where-instance (WellTyped t, HasNoOp t) => WellTyped ('TContract t) where-  type WellTypedSuperC ('TContract t) = (WellTyped t, HasNoOp t)-instance (WellTyped t, Comparable t) => WellTyped ('TTicket t) where-  type WellTypedSuperC ('TTicket t) = (WellTyped t, Comparable t)-instance (WellTyped t1, WellTyped t2) => WellTyped ('TPair t1 t2) where-  type WellTypedSuperC ('TPair t1 t2) = (WellTyped t1, WellTyped t2)-instance (WellTyped t1, WellTyped t2) => WellTyped ('TOr t1 t2) where-  type WellTypedSuperC ('TOr t1 t2) = (WellTyped t1, WellTyped t2)-instance (WellTyped t1, WellTyped t2) => WellTyped ('TLambda t1 t2) where-  type WellTypedSuperC ('TLambda t1 t2) = (WellTyped t1, WellTyped t2)-instance (Comparable k, WellTyped k, WellTyped v) => WellTyped ('TMap k v) where-  type WellTypedSuperC ('TMap k v) = (Comparable k, WellTyped k, WellTyped v)-instance (Comparable k, WellTyped k, WellTyped v, HasNoBigMap v, HasNoOp v)-         => WellTyped ('TBigMap k v) where-  type WellTypedSuperC ('TBigMap k v) = ( Comparable k, WellTyped k, WellTyped v-                                        , HasNoBigMap v, HasNoOp v)-instance WellTyped 'TInt-instance WellTyped 'TNat-instance WellTyped 'TString-instance WellTyped 'TBytes-instance WellTyped 'TMutez-instance WellTyped 'TBool-instance WellTyped 'TKeyHash-instance WellTyped 'TBls12381Fr-instance WellTyped 'TBls12381G1-instance WellTyped 'TBls12381G2-instance WellTyped 'TTimestamp-instance WellTyped 'TAddress
src/Morley/Michelson/Typed/Instr.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-orphans #-} @@ -41,12 +40,12 @@   , UpdateN   ) where +import Data.Singletons (Sing) import Data.Type.Equality ((:~:)(..)) import Data.Vinyl (RMap, Rec(..), RecordToList, ReifyConstraint(..))-import Fmt ((+||), (||+))-import GHC.TypeNats (type (+))-import qualified GHC.TypeNats as GHC (Nat)-import qualified Text.Show+import Fmt ((+|), (|+))+import GHC.TypeNats (Nat, type (+))+import Text.Show qualified  import Morley.Michelson.Doc import Morley.Michelson.ErrorPos@@ -60,7 +59,7 @@ import Morley.Michelson.Typed.TypeLevel   (CombedPairLeafCount, CombedPairLeafCountIsAtLeast, CombedPairNodeCount,   CombedPairNodeIndexIsValid, IsPair)-import Morley.Michelson.Typed.Value (Comparable, Value'(..))+import Morley.Michelson.Typed.Value (Value'(..)) import Morley.Michelson.Typed.View import Morley.Michelson.Untyped   (Annotation(..), FieldAnn, StackFn, StackTypePattern, TypeAnn, VarAnn, VarAnns)@@ -179,6 +178,7 @@  -- $setup -- >>> :m +Morley.Michelson.Typed.T Morley.Util.Peano Morley.Util.PeanoNatural+-- >>> import qualified Debug (show) -- >>> :set -XPartialTypeSignatures  -- | Constraint that is used in DUPN, we want to share it with@@ -206,7 +206,8 @@ -- typechecking code and eDSL code. type ConstraintDIG' kind (n :: Peano) (inp :: [kind])   (out :: [kind]) (a :: kind) =-  ( RequireLongerThan inp n+  ( KnownList inp+  , RequireLongerThan inp n   , inp ~ (Take n inp ++ (a ': Drop ('S n) inp))   , out ~ (a ': Take n inp ++ Drop ('S n) inp)   )@@ -662,6 +663,7 @@   SUB     :: ArithOp Sub n m     => Instr (n ': m ': s) (ArithRes Sub n m ': s)+  SUB_MUTEZ :: Instr ('TMutez ': 'TMutez ': s) ('TOption 'TMutez ': s)   MUL     :: ArithOp Mul n m     => Instr (n ':  m ': s) (ArithRes Mul n m ': s)@@ -787,7 +789,16 @@   OPEN_CHEST     :: Instr ('TChestKey ': 'TChest ': 'TNat ': s)              ('TOr 'TBytes 'TBool ': s)+  SAPLING_EMPTY_STATE+    :: Sing n+    -> Instr s+             ('TSaplingState n ': s)+  SAPLING_VERIFY_UPDATE+    :: Instr ('TSaplingTransaction n : 'TSaplingState n ': s)+             ('TOption ('TPair 'TInt ('TSaplingState n)) ': s) +{-# DEPRECATED Fn "Morley let macros are deprecated" #-}+ castInstr   :: forall inp1 out1 inp2 out2.   ( SingI inp1@@ -803,7 +814,7 @@  -- | Right-associative operator for v'Seq'. ----- >>> show (DROP :# UNIT :# Nop) == show (DROP :# (UNIT :# Nop))+-- >>> Debug.show (DROP :# UNIT :# Nop) == Debug.show (DROP :# (UNIT :# Nop)) -- True pattern (:#) :: Instr a b -> Instr b c -> Instr a c pattern a :# b = Seq a b@@ -867,12 +878,12 @@   StackRef snat1 == StackRef snat2 = fromPeanoNatural snat1 == fromPeanoNatural snat2  instance Show (StackRef st) where-  show (StackRef snat) = "StackRef {" +|| fromPeanoNatural snat ||+ "}"+  show (StackRef snat) = "StackRef {" +| fromPeanoNatural snat |+ "}"  -- | Create a stack reference, performing checks at compile time. mkStackRef-  :: forall (gn :: GHC.Nat) st n.-      (n ~ ToPeano gn, SingI (ToPeano gn), RequireLongerThan st n)+  :: forall (gn :: Nat) st n.+      (n ~ ToPeano gn, SingIPeano gn, RequireLongerThan st n)   => StackRef st mkStackRef = StackRef $ toPeanoNatural' @gn 
src/Morley/Michelson/Typed/OpSize.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Measuring operation size of typed stuff. module Morley.Michelson.Typed.OpSize@@ -19,7 +18,7 @@ import Morley.Michelson.Typed.Instr import Morley.Michelson.Typed.Scope import Morley.Michelson.Untyped (OpSize)-import qualified Morley.Michelson.Untyped as U+import Morley.Michelson.Untyped qualified as U  -- | Estimate instruction operation size. instrOpSize :: Instr inp out -> OpSize
src/Morley/Michelson/Typed/Operation.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Typed.Operation   ( OperationHash (..)@@ -14,7 +13,7 @@   ) where  import Data.Binary.Put (putWord64be, runPut)-import qualified Data.ByteString.Lazy as BSL+import Data.ByteString.Lazy qualified as BSL  import Morley.Michelson.Interpret.Pack (toBinary, toBinary') import Morley.Michelson.Runtime.TxData (TxData(..))@@ -85,7 +84,7 @@     -- See https://gitlab.com/tezos/tezos/-/blob/f57c50e3a657956d69a1699978de9873c98f0018/src/proto_006_PsCARTHA/lib_protocol/operation_repr.ml#L314     -- and https://gitlab.com/tezos/tezos/-/blob/f57c50e3a657956d69a1699978de9873c98f0018/src/proto_006_PsCARTHA/lib_protocol/script_repr.ml#L68     packedOperation =-      BSL.toStrict (runPut $ putWord64be $ unMutez ooBalance)+      BSL.toStrict (runPut $ putWord64be $ fromIntegral @Word63 @Word64 $ unMutez ooBalance)       <> packMaybe (toBinary' . toVal) ooDelegate       <> toBinary' (cCode ooContract)       <> toBinary' ooStorage@@ -145,7 +144,7 @@     -- See https://gitlab.com/tezos/tezos/-/blob/f57c50e3a657956d69a1699978de9873c98f0018/src/proto_006_PsCARTHA/lib_protocol/operation_repr.ml#L275-282     packedOperation =       BSL.toStrict $-        (runPut $ putWord64be $ unMutez amount)+        (runPut $ putWord64be $ fromIntegral @Word63 @Word64 $ unMutez amount)         <> (toBinary $ toVal (EpAddress to epName))         <> toBinary param 
src/Morley/Michelson/Typed/Polymorphic.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Module, containing type classes for operating with Michelson values -- in the context of polymorphic stack type operations.@@ -19,11 +18,11 @@   , modMich   ) where -import qualified Data.ByteString as B-import qualified Data.Map as M-import qualified Data.Set as S+import Data.ByteString qualified as B+import Data.Map qualified as M+import Data.Set qualified as S import Data.Singletons (SingI)-import qualified Unsafe (fromIntegral)+import Unsafe qualified (fromIntegral)  import Morley.Michelson.Text import Morley.Michelson.Typed.Annotation@@ -67,6 +66,12 @@   mapOpToList (VList l) = l   mapOpFromList (VList _) l' = VList l'   mapOpNotes (NTList _ n) = n+instance MapOp ('TOption e) where+  type MapOpInp ('TOption e) = e+  type MapOpRes ('TOption e) = 'TOption+  mapOpToList (VOption l) = maybe [] pure l+  mapOpFromList (VOption _) l' = VOption $ listToMaybe l'+  mapOpNotes (NTOption _ n) = n -- If you find it difficult to implement 'MapOp' for your datatype -- because of order of type arguments in it, consider wrapping it -- into a newtype.
src/Morley/Michelson/Typed/Scope.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# LANGUAGE UndecidableSuperClasses #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-}@@ -45,6 +44,7 @@   , UntypedValScope   , UnpackedValScope   , ViewableScope+  , ComparabilityScope    , ProperParameterBetterErrors   , ProperStorageBetterErrors@@ -56,6 +56,8 @@   , ProperViewableBetterErrors   , ProperNonComparableValBetterErrors +  , IsDupableScope+   , properParameterEvi   , properStorageEvi   , properConstantEvi@@ -69,6 +71,9 @@   , BadTypeForScope (..)   , CheckScope (..)   , WithDeMorganScope (..)+  , Comparable (..)+  , WellTyped (..)+  , NotWellTyped (..)      -- * Implementation internals   , HasNoBigMap@@ -106,6 +111,7 @@   , checkTicketPresence   , checkBigMapPresence   , checkNestedBigMapsPresence+  , comparabilityPresence   , opAbsense   , contractTypeAbsense   , bigMapAbsense@@ -115,14 +121,20 @@   , forbiddenBigMap   , forbiddenNestedBigMaps +  , Comparability(..)+  , checkComparability+  , getComparableProofS++  , getWTP+  , getWTP'     -- * Re-exports   , withDict   , SingI (..)   ) where  import Data.Constraint (Dict(..), withDict, (:-)(..), (\\))-import Data.Singletons (Sing, SingI(..))-import Data.Type.Bool (type (&&), type (||))+import Data.Singletons (Sing, SingI(..), fromSing, withSingI)+import Data.Type.Bool (Not, type (&&), type (||)) import Fmt (Buildable(..)) import GHC.TypeLits (ErrorMessage(..), TypeError) @@ -231,6 +243,17 @@   ContainsNestedBigMaps ('TBigMap _ v) = ContainsBigMap v   ContainsNestedBigMaps _ = 'False +-- | Whether a value of this type _may_ contain a @samping_state@ value.+type family ContainsSaplingState (t :: T) :: Bool where+  ContainsSaplingState ('TOption t) = ContainsSaplingState t+  ContainsSaplingState ('TList t) = ContainsSaplingState t+  ContainsSaplingState ('TPair a b) = ContainsSaplingState a || ContainsSaplingState b+  ContainsSaplingState ('TOr a b) = ContainsSaplingState a || ContainsSaplingState b+  ContainsSaplingState ('TMap _ v) = ContainsSaplingState v+  ContainsSaplingState ('TBigMap _ v) = ContainsSaplingState v+  ContainsSaplingState ('TSaplingState _) = 'True+  ContainsSaplingState _ = 'False+ -- | Constraint which ensures that type is comparable. type family IsComparable (t :: T) :: Bool where   IsComparable ('TPair a b) =  IsComparable a && IsComparable b@@ -249,6 +272,8 @@   IsComparable ('TBigMap _ _) = 'False   IsComparable 'TChest = 'False   IsComparable 'TChestKey = 'False+  IsComparable ('TSaplingState _) = 'False+  IsComparable ('TSaplingTransaction _) = 'False   IsComparable _            = 'True  -- | Constraint which ensures that a value of type @t@ does not contain operations.@@ -270,6 +295,10 @@ class (ContainsBigMap t ~ 'False) => HasNoBigMap t instance (ContainsBigMap t ~ 'False) => HasNoBigMap t +-- | Constraint which ensures that a value of type @t@ does not contain @sapling_state@ values.+class (ContainsSaplingState t ~ 'False) => HasNoSaplingState t+instance (ContainsSaplingState t ~ 'False) => HasNoSaplingState t+ -- | Constraint which ensures that there are no nested bigmaps. class (ContainsNestedBigMaps t ~ 'False) => HasNoNestedBigMaps t instance (ContainsNestedBigMaps t ~ 'False) => HasNoNestedBigMaps t@@ -292,6 +321,12 @@     TypeError ('Text "Type `ticket` is not allowed in this scope")   FailOnTicketFound 'False = () +-- | Report a human-readable error about 'TSaplingState' at a wrong place.+type family FailOnSaplingStateFound (enabled :: Bool) :: Constraint where+  FailOnSaplingStateFound 'True =+    TypeError ('Text "Type `sapling_state` is not allowed in this scope")+  FailOnSaplingStateFound 'False = ()+ -- | Report a human-readable error about 'TBigMap' at a wrong place. type family FailOnBigMapFound (enabled :: Bool) :: Constraint where   FailOnBigMapFound 'True =@@ -323,6 +358,8 @@  type ForbidTicket t = FailOnTicketFound (ContainsTicket t) +type ForbidSaplingState t = FailOnSaplingStateFound (ContainsSaplingState t)+ type ForbidBigMap t = FailOnBigMapFound (ContainsBigMap t)  type ForbidNestedBigMaps t = FailOnNestedBigMapsFound (ContainsNestedBigMaps t)@@ -401,6 +438,14 @@     TicketAbsent -> Dict     TicketPresent -> error "impossible" +-- | Reify 'HasNoSaplingState' contraint from 'ForbidSaplingState'.+forbiddenSaplingStateTypeEvi+  :: forall t. (SingI t, ForbidSaplingState t) :- HasNoSaplingState t+forbiddenSaplingStateTypeEvi = Sub $+  case checkSaplingStatePresence (sing @t) of+    SaplingStateAbsent -> Dict+    SaplingStatePresent -> error "impossible"+ -- | Whether a value of this type _may_ contain an operation. data OpPresence (t :: T)   = ContainsOp t ~ 'True => OpPresent@@ -436,6 +481,13 @@   | ContainsNestedBigMaps t ~ 'False => NestedBigMapsAbsent     -- ^ A value of type @t@ cannot contain nested @big_map@s. +-- | Whether a value of this type _may_ contain a @sapling_state@ value.+data SaplingStatePresence (t :: T)+  = ContainsSaplingState t ~ 'True => SaplingStatePresent+    -- ^ A value of type @t@ may or may not contain a @sapling_state@ value.+  | ContainsSaplingState t ~ 'False => SaplingStateAbsent+    -- ^ A value of type @t@ cannot contain @sapling_state@ values.+ -- @rvem: IMO, generalization of OpPresence and BigMapPresence to -- TPresence is not worth it, due to the fact that -- it will require more boilerplate in checkTPresence implementation@@ -499,6 +551,8 @@   STChest -> OpAbsent   STChestKey -> OpAbsent   STNever -> OpAbsent+  STSaplingState _ -> OpAbsent+  STSaplingTransaction _ -> OpAbsent  -- | Check at runtime whether a value of the given type _may_ contain a @contract@ value. checkContractTypePresence :: Sing (ty :: T) -> ContractPresence ty@@ -547,6 +601,8 @@   STChest -> ContractAbsent   STChestKey -> ContractAbsent   STNever -> ContractAbsent+  STSaplingState _ -> ContractAbsent+  STSaplingTransaction _ -> ContractAbsent  -- | Check at runtime whether a value of the given type _may_ contain a @ticket@ value. checkTicketPresence :: Sing (ty :: T) -> TicketPresence ty@@ -595,6 +651,8 @@   STChest -> TicketAbsent   STChestKey -> TicketAbsent   STNever -> TicketAbsent+  STSaplingState _ -> TicketAbsent+  STSaplingTransaction _ -> TicketAbsent  -- | Check at runtime whether a value of the given type _may_ contain a @big_map@ value. checkBigMapPresence :: Sing (ty :: T) -> BigMapPresence ty@@ -643,6 +701,8 @@   STChest -> BigMapAbsent   STChestKey -> BigMapAbsent   STNever -> BigMapAbsent+  STSaplingState _ -> BigMapAbsent+  STSaplingTransaction _ -> BigMapAbsent  -- | Check at runtime whether a value of the given type _may_ contain nested @big_map@s. checkNestedBigMapsPresence :: Sing (ty :: T) -> NestedBigMapsPresence ty@@ -692,7 +752,60 @@   STChest -> NestedBigMapsAbsent   STChestKey -> NestedBigMapsAbsent   STNever -> NestedBigMapsAbsent+  STSaplingState _ -> NestedBigMapsAbsent+  STSaplingTransaction _ -> NestedBigMapsAbsent ++-- | Check at runtime whether a value of the given type _may_ contain a @sapling_state@ value.+checkSaplingStatePresence :: Sing (ty :: T) -> SaplingStatePresence ty+checkSaplingStatePresence = \case+  STKey -> SaplingStateAbsent+  STSignature -> SaplingStateAbsent+  STChainId -> SaplingStateAbsent+  STUnit -> SaplingStateAbsent+  STOption t -> case checkSaplingStatePresence t of+    SaplingStatePresent -> SaplingStatePresent+    SaplingStateAbsent -> SaplingStateAbsent+  STList t -> case checkSaplingStatePresence t of+    SaplingStatePresent -> SaplingStatePresent+    SaplingStateAbsent -> SaplingStateAbsent+  STSet _ -> SaplingStateAbsent+  STOperation -> SaplingStateAbsent+  STContract _ -> SaplingStateAbsent+  STTicket _ -> SaplingStateAbsent+  STPair a b -> case (checkSaplingStatePresence a, checkSaplingStatePresence b) of+    (SaplingStatePresent, _) -> SaplingStatePresent+    (_, SaplingStatePresent) -> SaplingStatePresent+    (SaplingStateAbsent, SaplingStateAbsent) -> SaplingStateAbsent+  STOr a b -> case (checkSaplingStatePresence a, checkSaplingStatePresence b) of+    (SaplingStatePresent, _) -> SaplingStatePresent+    (_, SaplingStatePresent) -> SaplingStatePresent+    (SaplingStateAbsent, SaplingStateAbsent) -> SaplingStateAbsent+  STLambda _ _ -> SaplingStateAbsent+  STMap _ v -> case checkSaplingStatePresence v of+    SaplingStatePresent -> SaplingStatePresent+    SaplingStateAbsent -> SaplingStateAbsent+  STBigMap _ v -> case checkSaplingStatePresence v of+    SaplingStatePresent -> SaplingStatePresent+    SaplingStateAbsent -> SaplingStateAbsent+  STInt -> SaplingStateAbsent+  STNat -> SaplingStateAbsent+  STString -> SaplingStateAbsent+  STBytes -> SaplingStateAbsent+  STMutez -> SaplingStateAbsent+  STBool -> SaplingStateAbsent+  STKeyHash -> SaplingStateAbsent+  STBls12381Fr -> SaplingStateAbsent+  STBls12381G1 -> SaplingStateAbsent+  STBls12381G2 -> SaplingStateAbsent+  STTimestamp -> SaplingStateAbsent+  STAddress -> SaplingStateAbsent+  STChest -> SaplingStateAbsent+  STChestKey -> SaplingStateAbsent+  STNever -> SaplingStateAbsent+  STSaplingState _ -> SaplingStatePresent+  STSaplingTransaction _ -> SaplingStateAbsent+ -- | Check at runtime that a value of the given type cannot contain operations. opAbsense :: Sing (t :: T) -> Maybe (Dict $ HasNoOp t) opAbsense s = case checkOpPresence s of@@ -717,6 +830,12 @@   BigMapPresent -> Nothing   BigMapAbsent -> Just Dict +-- | Check at runtime that a value of the given type cannot containt @sapling_state@ values+saplingStateAbsense :: Sing (t :: T) -> Maybe (Dict $ HasNoSaplingState t)+saplingStateAbsense s = case checkSaplingStatePresence s of+  SaplingStatePresent -> Nothing+  SaplingStateAbsent -> Just Dict+ -- | Check at runtime that a value of the given type cannot contain nested @big_map@s. nestedBigMapsAbsense :: Sing (t :: T) -> Maybe (Dict $ HasNoNestedBigMaps t) nestedBigMapsAbsense s = case checkNestedBigMapsPresence s of@@ -734,6 +853,7 @@   | BtHasNestedBigMap   | BtHasContract   | BtHasTicket+  | BtHasSaplingState   deriving stock (Show, Eq, Generic)   deriving anyclass (NFData) @@ -748,34 +868,39 @@     BtHasNestedBigMap -> "has nested 'big_map'"     BtHasContract -> "has 'contract' type"     BtHasTicket -> "has 'ticket' type"+    BtHasSaplingState -> "has 'sapling_state' type"  -- | Set of constraints that Michelson applies to parameters. -- -- Not just a type alias in order to be able to partially apply it-class (SingI t, HasNoOp t, HasNoNestedBigMaps t) => ParameterScope t-instance (SingI t, HasNoOp t, HasNoNestedBigMaps t) => ParameterScope t+class (SingI t, WellTyped t, HasNoOp t, HasNoNestedBigMaps t) => ParameterScope t+instance (SingI t, WellTyped t, HasNoOp t, HasNoNestedBigMaps t) => ParameterScope t  -- | Set of constraints that Michelson applies to contract storage. -- -- Not just a type alias in order to be able to partially apply it-class (SingI t, HasNoOp t, HasNoNestedBigMaps t, HasNoContract t) => StorageScope t-instance (SingI t, HasNoOp t, HasNoNestedBigMaps t, HasNoContract t) => StorageScope t+class (SingI t, WellTyped t, HasNoOp t, HasNoNestedBigMaps t, HasNoContract t) => StorageScope t+instance (SingI t, WellTyped t, HasNoOp t, HasNoNestedBigMaps t, HasNoContract t) => StorageScope t  -- | Set of constraints that Michelson applies to pushed constants. -- -- Not just a type alias in order to be able to partially apply it-class (SingI t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t) => ConstantScope t-instance (SingI t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t) => ConstantScope t+class (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t, HasNoSaplingState t) => ConstantScope t+instance (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoContract t, HasNoTicket t, HasNoSaplingState t) => ConstantScope t  -- | Alias for constraints which Michelson requires in @DUP@ instruction. class (SingI t, HasNoTicket t) => DupableScope t instance (SingI t, HasNoTicket t) => DupableScope t +-- | Returns whether the type is dupable.+type family IsDupableScope (t :: T) :: Bool where+  IsDupableScope t = Not (ContainsTicket t)+ -- | Set of constraints that Michelson applies to packed values. -- -- Not just a type alias in order to be able to partially apply it-class (SingI t, HasNoOp t, HasNoBigMap t, HasNoTicket t) => PackedValScope t-instance (SingI t, HasNoOp t, HasNoBigMap t, HasNoTicket t) => PackedValScope t+class (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoTicket t, HasNoSaplingState t) => PackedValScope t+instance (SingI t, WellTyped t, HasNoOp t, HasNoBigMap t, HasNoTicket t, HasNoSaplingState t ) => PackedValScope t  -- | Set of constraints that Michelson applies to unpacked values. --@@ -783,8 +908,8 @@ -- in a value we unpack to. -- -- Not just a type alias in order to be able to partially apply it-class (PackedValScope t, ConstantScope t) => UnpackedValScope t-instance (PackedValScope t, ConstantScope t) => UnpackedValScope t+class (WellTyped t, PackedValScope t, ConstantScope t) => UnpackedValScope t+instance (WellTyped t, PackedValScope t, ConstantScope t) => UnpackedValScope t  -- | Set of constraints that Michelson applies to argument type and -- return type of views.@@ -807,6 +932,8 @@   -- | Check that constraint hold for a given type.   checkScope :: Either BadTypeForScope (Dict c) +instance SingI t => CheckScope (WellTyped t) where+  checkScope = first nwtCause $ getWTP @t instance SingI t => CheckScope (HasNoOp t) where   checkScope = maybeToRight BtIsOperation $ opAbsense sing instance SingI t => CheckScope (HasNoBigMap t) where@@ -817,27 +944,44 @@   checkScope = maybeToRight BtHasContract $ contractTypeAbsense sing instance SingI t => CheckScope (HasNoTicket t) where   checkScope = maybeToRight BtHasTicket $ ticketAbsense sing+instance SingI t => CheckScope (HasNoSaplingState t) where+  checkScope = maybeToRight BtHasSaplingState $ saplingStateAbsense sing+instance SingI t => CheckScope (Comparable t) where+  checkScope = maybeToRight BtNotComparable $ comparabilityPresence sing +-- | Alias for comparable types.+type ComparabilityScope t =+  (SingI t, Comparable t)++comparabilityPresence :: Sing t -> Maybe (Dict $ (Comparable t))+comparabilityPresence s = case checkComparability s of+  CanBeCompared -> Just Dict+  CannotBeCompared -> Nothing+ instance SingI t => CheckScope (ParameterScope t) where   checkScope =-    (\Dict Dict -> Dict)-      <$> checkScope @(HasNoOp t)+    (\Dict Dict Dict -> Dict)+      <$> checkScope @(WellTyped t)+      <*> checkScope @(HasNoOp t)       <*> checkScope @(HasNoNestedBigMaps t)  instance SingI t => CheckScope (StorageScope t) where   checkScope =-    (\Dict Dict Dict -> Dict)-      <$> checkScope @(HasNoOp t)+    (\Dict Dict Dict Dict -> Dict)+      <$> checkScope @(WellTyped t)+      <*> checkScope @(HasNoOp t)       <*> checkScope @(HasNoNestedBigMaps t)       <*> checkScope @(HasNoContract t)  instance SingI t => CheckScope (ConstantScope t) where   checkScope =-    (\Dict Dict Dict Dict -> Dict)-      <$> checkScope @(HasNoOp t)+    (\Dict Dict Dict Dict Dict Dict -> Dict)+      <$> checkScope @(WellTyped t)+      <*> checkScope @(HasNoOp t)       <*> checkScope @(HasNoBigMap t)       <*> checkScope @(HasNoContract t)       <*> checkScope @(HasNoTicket t)+      <*> checkScope @(HasNoSaplingState t)  instance SingI t => CheckScope (DupableScope t) where   checkScope =@@ -846,15 +990,18 @@  instance SingI t => CheckScope (PackedValScope t) where   checkScope =-    (\Dict Dict Dict -> Dict)-      <$> checkScope @(HasNoOp t)+    (\Dict Dict Dict Dict Dict -> Dict)+      <$> checkScope @(WellTyped t)+      <*> checkScope @(HasNoOp t)       <*> checkScope @(HasNoBigMap t)       <*> checkScope @(HasNoTicket t)+      <*> checkScope @(HasNoSaplingState t)  instance SingI t => CheckScope (UnpackedValScope t) where   checkScope =-    (\Dict Dict -> Dict)-      <$> checkScope @(PackedValScope t)+    (\Dict Dict Dict -> Dict)+      <$> checkScope @(WellTyped t)+      <*> checkScope @(PackedValScope t)       <*> checkScope @(ConstantScope t)  instance SingI t => CheckScope (ViewableScope t) where@@ -864,6 +1011,10 @@       <*> checkScope @(HasNoBigMap t)       <*> checkScope @(HasNoTicket t) +instance SingI t => CheckScope (ComparabilityScope t) where+  checkScope =+    (\Dict -> Dict) <$> checkScope @(Comparable t)+ -- | Allows using a scope that can be proven true with a De Morgan law. -- -- Many scopes are defined as @not a@ (or rather @a ~ 'False@) where @a@ is a@@ -934,6 +1085,7 @@   ( WithDeMorganScope HasNoOp t a b   , WithDeMorganScope HasNoNestedBigMaps t a b   , SingI a, SingI b+  , WellTyped a, WellTyped b   ) => WithDeMorganScope ParameterScope t a b where   withDeMorganScope f =     withDeMorganScope @HasNoOp @t @a @b $@@ -944,6 +1096,7 @@   , WithDeMorganScope HasNoNestedBigMaps t a b   , WithDeMorganScope HasNoContract t a b   , SingI a, SingI b+  , WellTyped a, WellTyped b   ) => WithDeMorganScope StorageScope t a b where   withDeMorganScope f =     withDeMorganScope @HasNoOp @t @a @b $@@ -955,29 +1108,36 @@   , WithDeMorganScope HasNoBigMap t a b   , WithDeMorganScope HasNoContract t a b   , WithDeMorganScope HasNoTicket t a b+  , WithDeMorganScope HasNoSaplingState t a b   , SingI a, SingI b+  , WellTyped a, WellTyped b   ) => WithDeMorganScope ConstantScope t a b where   withDeMorganScope f =     withDeMorganScope @HasNoOp @t @a @b $     withDeMorganScope @HasNoBigMap @t @a @b $     withDeMorganScope @HasNoContract @t @a @b $-    withDeMorganScope @HasNoTicket @t @a @b f+    withDeMorganScope @HasNoTicket @t @a @b $+    withDeMorganScope @HasNoSaplingState @t @a @b f  instance   ( WithDeMorganScope HasNoOp t a b   , WithDeMorganScope HasNoBigMap t a b   , WithDeMorganScope HasNoTicket t a b+  , WithDeMorganScope HasNoSaplingState t a b   , SingI a, SingI b+  , WellTyped a, WellTyped b   ) => WithDeMorganScope PackedValScope t a b where   withDeMorganScope f =     withDeMorganScope @HasNoOp @t @a @b $     withDeMorganScope @HasNoBigMap @t @a @b $-    withDeMorganScope @HasNoTicket @t @a @b f+    withDeMorganScope @HasNoTicket @t @a @b $+    withDeMorganScope @HasNoSaplingState @t @a @b f  instance   ( WithDeMorganScope PackedValScope t a b   , WithDeMorganScope ConstantScope t a b   , SingI a, SingI b+  , WellTyped a, WellTyped b   ) => WithDeMorganScope UnpackedValScope t a b where   withDeMorganScope f =     withDeMorganScope @PackedValScope @t @a @b $@@ -991,19 +1151,19 @@ -}  type ProperParameterBetterErrors t =-  (SingI t, ForbidOp t, ForbidNestedBigMaps t)+  (SingI t, WellTyped t, ForbidOp t, ForbidNestedBigMaps t)  type ProperStorageBetterErrors t =-  (SingI t, ForbidOp t, ForbidNestedBigMaps t, ForbidContract t)+  (SingI t, WellTyped t, ForbidOp t, ForbidNestedBigMaps t, ForbidContract t)  type ProperConstantBetterErrors t =-  (SingI t, ForbidOp t, ForbidBigMap t, ForbidContract t, ForbidTicket t)+  (SingI t, WellTyped t, ForbidOp t, ForbidBigMap t, ForbidContract t, ForbidTicket t, ForbidSaplingState t)  type ProperDupableBetterErrors t =   (SingI t, ForbidTicket t)  type ProperPackedValBetterErrors t =-  (SingI t, ForbidOp t, ForbidBigMap t, ForbidTicket t)+  (SingI t, WellTyped t, ForbidOp t, ForbidBigMap t, ForbidTicket t, ForbidSaplingState t)  type ProperUnpackedValBetterErrors t =   (ProperPackedValBetterErrors t, ProperConstantBetterErrors t)@@ -1034,6 +1194,7 @@        \\ forbiddenBigMapEvi @t        \\ forbiddenContractTypeEvi @t        \\ forbiddenTicketTypeEvi @t+       \\ forbiddenSaplingStateTypeEvi @t  properDupableEvi :: forall t. ProperDupableBetterErrors t :- DupableScope t properDupableEvi = Sub $@@ -1044,6 +1205,7 @@   Dict \\ forbiddenOpEvi @t        \\ forbiddenBigMapEvi @t        \\ forbiddenTicketTypeEvi @t+       \\ forbiddenSaplingStateTypeEvi @t  properUnpackedValEvi :: forall t. ProperUnpackedValBetterErrors t :- UnpackedValScope t properUnpackedValEvi = Sub $@@ -1059,3 +1221,248 @@ properUntypedValEvi :: forall t. ProperUntypedValBetterErrors t :- UntypedValScope t properUntypedValEvi = Sub $   Dict \\ forbiddenOpEvi @t++class (IsComparable t ~ 'True, SingI t, ComparableSuperC t) => Comparable t where+  -- | Constraints required for instance of a given type.+  type ComparableSuperC t :: Constraint+  type ComparableSuperC _ = ()++instance ComparableSuperC ('TPair t1 t2) => Comparable ('TPair t1 t2) where+  type ComparableSuperC ('TPair t1 t2) =+    (Comparable t1, Comparable t2, FailOnNonComparableFound (IsComparable t1 && IsComparable t2))++instance ComparableSuperC ('TOr t1 t2) => Comparable ('TOr t1 t2) where+  type ComparableSuperC ('TOr t1 t2) =+    (Comparable t1, Comparable t2, FailOnNonComparableFound (IsComparable t1 && IsComparable t2))++instance ComparableSuperC ('TOption t) => Comparable ('TOption t) where+  type ComparableSuperC ('TOption t) = (Comparable t, ForbidNonComparable t)++instance Comparable 'TUnit+instance Comparable 'TInt+instance Comparable 'TNat+instance Comparable 'TString+instance Comparable 'TBytes+instance Comparable 'TMutez+instance Comparable 'TBool+instance Comparable 'TKeyHash+instance Comparable 'TTimestamp+instance Comparable 'TAddress+instance Comparable 'TNever+instance Comparable 'TChainId+instance Comparable 'TSignature+instance Comparable 'TKey++-- | This class encodes Michelson rules w.r.t where it requires comparable+-- types. Earlier we had a dedicated type for representing comparable types @CT@.+-- But then we integreated those types into @T@. This meant that some of the+-- types that could be formed with various combinations of @T@ would be+-- illegal as per Michelson typing rule. Using this class, we inductively+-- enforce that a type and all types it contains are well typed as per+-- Michelson's rules.+class (SingI t, WellTypedSuperC t) => WellTyped (t :: T) where+  -- | Constraints required for instance of a given type.+  type WellTypedSuperC t :: Constraint+  type WellTypedSuperC _ = ()++instance WellTyped 'TKey+instance WellTyped 'TUnit+instance WellTyped 'TNever+instance WellTyped 'TSignature+instance WellTyped 'TChainId+instance WellTyped 'TChest where+instance WellTyped 'TChestKey where++instance WellTypedSuperC ('TOption t) => WellTyped ('TOption t) where+  type WellTypedSuperC ('TOption t) = WellTyped t++instance WellTypedSuperC ('TList t) => WellTyped ('TList t) where+  type WellTypedSuperC ('TList t) = WellTyped t++instance WellTypedSuperC ('TSet t) => WellTyped ('TSet t) where+  type WellTypedSuperC ('TSet t) = (Comparable t, WellTyped t)++instance WellTyped 'TOperation++instance WellTypedSuperC ('TContract t) => WellTyped ('TContract t) where+  type WellTypedSuperC ('TContract t) = (WellTyped t, HasNoOp t)++instance WellTypedSuperC ('TTicket t) => WellTyped ('TTicket t) where+  type WellTypedSuperC ('TTicket t) = (WellTyped t, Comparable t)++instance WellTypedSuperC ('TPair t1 t2) => WellTyped ('TPair t1 t2) where+  type WellTypedSuperC ('TPair t1 t2) = (WellTyped t1, WellTyped t2)++instance WellTypedSuperC ('TOr t1 t2) => WellTyped ('TOr t1 t2) where+  type WellTypedSuperC ('TOr t1 t2) = (WellTyped t1, WellTyped t2)++instance WellTypedSuperC ('TLambda t1 t2) => WellTyped ('TLambda t1 t2) where+  type WellTypedSuperC ('TLambda t1 t2) = (WellTyped t1, WellTyped t2)++instance WellTypedSuperC ('TMap k v) => WellTyped ('TMap k v) where+  type WellTypedSuperC ('TMap k v) = (Comparable k, WellTyped k, WellTyped v)++instance WellTypedSuperC ('TBigMap k v) => WellTyped ('TBigMap k v) where+  type WellTypedSuperC ('TBigMap k v) = ( Comparable k, WellTyped k, WellTyped v+                                        , HasNoBigMap v, HasNoOp v)++instance WellTyped 'TInt+instance WellTyped 'TNat+instance WellTyped 'TString+instance WellTyped 'TBytes+instance WellTyped 'TMutez+instance WellTyped 'TBool+instance WellTyped 'TKeyHash+instance WellTyped 'TBls12381Fr+instance WellTyped 'TBls12381G1+instance WellTyped 'TBls12381G2+instance WellTyped 'TTimestamp+instance WellTyped 'TAddress++instance (SingI n) => WellTyped ('TSaplingState n) where+  type WellTypedSuperC ('TSaplingState n) = (SingI n)++instance (SingI n) => WellTyped ('TSaplingTransaction n) where+  type WellTypedSuperC ('TSaplingTransaction n) = (SingI n)++-- | Error type for when a value is not well-typed.+data NotWellTyped = NotWellTyped+  { nwtBadType :: T+  , nwtCause :: BadTypeForScope+  }++instance Buildable NotWellTyped where+  build (NotWellTyped t c) =+    "Given type is not well typed because '" <> (build t) <> "' " <> (build c)++data Comparability t where+  CanBeCompared :: (Comparable t) => Comparability t+  CannotBeCompared :: (IsComparable t ~ 'False) => Comparability t++-- | Given a type, provide evidence that it is well typed w.r.t to the+--  Michelson rules regarding where comparable types are required.+getWTP :: forall t. (SingI t) => Either NotWellTyped (Dict (WellTyped t))+getWTP = getWTP' sing++-- | Version of 'getWTP' that accepts 'Sing' at term-level.+getWTP' :: Sing t -> Either NotWellTyped (Dict (WellTyped t))+getWTP' = \case+  STKey -> Right Dict+  STUnit -> Right Dict+  STSignature -> Right Dict+  STChainId -> Right Dict+  STOption s -> do+    Dict <- getWTP' s+    pure Dict+  STList s -> do+    Dict <- getWTP' s+    pure Dict+  STSet s -> do+    Dict <- getWTP' s+    Dict <- eitherWellTyped BtNotComparable getComparableProofS s+    pure Dict+  STOperation -> Right Dict+  STContract s -> do+    Dict <- getWTP' s+    Dict <- eitherWellTyped BtIsOperation opAbsense s+    pure Dict+  STTicket s -> do+    Dict <- getWTP' s+    Dict <- eitherWellTyped BtNotComparable getComparableProofS s+    pure Dict+  STPair s1 s2 -> do+    Dict <- getWTP' s1+    Dict <- getWTP' s2+    pure Dict+  STOr s1 s2 -> do+    Dict <- getWTP' s1+    Dict <- getWTP' s2+    pure Dict+  STLambda s1 s2 -> do+    Dict <- getWTP' s1+    Dict <- getWTP' s2+    pure Dict+  STMap s1 s2 -> do+    Dict <- getWTP' s1+    Dict <- getWTP' s2+    Dict <- eitherWellTyped BtNotComparable getComparableProofS s1+    pure Dict+  STBigMap s1 s2 -> do+    Dict <- getWTP' s1+    Dict <- getWTP' s2+    Dict <- eitherWellTyped BtNotComparable getComparableProofS s1+    Dict <- eitherWellTyped BtIsOperation opAbsense s2+    Dict <- eitherWellTyped BtHasBigMap bigMapAbsense s2+    pure Dict+  STInt -> Right Dict+  STNat -> Right Dict+  STString -> Right Dict+  STBytes -> Right Dict+  STMutez -> Right Dict+  STBool -> Right Dict+  STKeyHash -> Right Dict+  STBls12381Fr -> Right Dict+  STBls12381G1 -> Right Dict+  STBls12381G2 -> Right Dict+  STTimestamp -> Right Dict+  STAddress -> Right Dict+  STChest -> Right Dict+  STChestKey -> Right Dict+  STNever -> Right Dict+  STSaplingState s -> withSingI s $ Right Dict+  STSaplingTransaction s -> withSingI s $ Right Dict+  where+    eitherWellTyped+      :: BadTypeForScope+      -> (Sing (ty :: T) -> Maybe a)+      -> Sing (ty :: T)+      -> Either NotWellTyped a+    eitherWellTyped bt sf sng = maybeToRight (NotWellTyped (fromSing sng) bt) $ sf sng++getComparableProofS :: Sing (a :: T) -> Maybe (Dict (Comparable a))+getComparableProofS s = case checkComparability s of+  CanBeCompared -> Just Dict+  CannotBeCompared -> Nothing++checkComparability :: Sing t -> Comparability t+checkComparability = \case+  STPair a b -> case (checkComparability a, checkComparability b) of+    (CanBeCompared, CanBeCompared) -> CanBeCompared+    (CannotBeCompared, _) -> CannotBeCompared+    (_, CannotBeCompared) -> CannotBeCompared+  STOr a b -> case (checkComparability a, checkComparability b) of+    (CanBeCompared, CanBeCompared) -> CanBeCompared+    (CannotBeCompared, _) -> CannotBeCompared+    (_, CannotBeCompared) -> CannotBeCompared+  STOption t -> case checkComparability t of+    CanBeCompared -> CanBeCompared+    CannotBeCompared -> CannotBeCompared+  STList _ -> CannotBeCompared+  STSet _ -> CannotBeCompared+  STOperation -> CannotBeCompared+  STContract _ -> CannotBeCompared+  STTicket _ -> CannotBeCompared+  STLambda _ _ -> CannotBeCompared+  STMap _ _ -> CannotBeCompared+  STBigMap _ _ -> CannotBeCompared+  STNever -> CanBeCompared+  STUnit -> CanBeCompared+  STInt -> CanBeCompared+  STNat -> CanBeCompared+  STString -> CanBeCompared+  STBytes -> CanBeCompared+  STMutez -> CanBeCompared+  STBool -> CanBeCompared+  STKeyHash -> CanBeCompared+  STBls12381Fr -> CannotBeCompared+  STBls12381G1 -> CannotBeCompared+  STBls12381G2 -> CannotBeCompared+  STTimestamp -> CanBeCompared+  STAddress -> CanBeCompared+  STKey -> CanBeCompared+  STSignature -> CanBeCompared+  STChainId -> CanBeCompared+  STChest -> CannotBeCompared+  STChestKey -> CannotBeCompared+  STSaplingState _ -> CannotBeCompared+  STSaplingTransaction _ -> CannotBeCompared
src/Morley/Michelson/Typed/Sing.hs view
@@ -1,8 +1,6 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA -{-# LANGUAGE StandaloneKindSignatures #-} {-# OPTIONS_GHC -Wno-unused-top-binds #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-}@@ -20,24 +18,16 @@   , requireEq   ) where -import Data.Singletons (Demote, KindOf, SingI(..), demote)-import Data.Singletons.TH (genSingletons, singDecideInstance)-import Data.Singletons.TH.Options (Options(..), defaultOptions, withOptions)+import Data.Singletons (SingI(..), demote) import Data.Type.Equality ((:~:)(..))-import Language.Haskell.TH (Name, mkName, nameBase)+import Fmt ((+|), (|+)) -import Fmt ((+||), (||+)) import Morley.Michelson.Typed.T (T(..))-import Morley.Util.Sing (SingI1(..), castSing, eqI)+import Morley.Util.MismatchError+import Morley.Util.Sing (SingI1(..), castSing, eqI, genSingletonsType)  -- | 'SingI' and 'Data.Singletons.TH.SDecide' instances for the 'T' kind.-$(let singPrefix, sPrefix :: Name -> Name-      singPrefix nm = mkName ("Sing" ++ nameBase nm)-      sPrefix nm = mkName ("S" ++ nameBase nm) in--  withOptions defaultOptions{singledDataConName = sPrefix, singledDataTypeName = singPrefix} $-  concat <$> sequence [genSingletons [''T], singDecideInstance ''T]-  )+$(genSingletonsType ''T)  --------------------------------------------- -- 'Data.Singletons.withSingI' usage@@ -56,6 +46,9 @@ instance SingI1 'TList where   withSingI1 x = x +instance SingI1 'TOption where+  withSingI1 x = x+ instance SingI k => SingI1 ('TMap k) where   withSingI1 x = x @@ -64,15 +57,15 @@   => t a -> Either Text (t b) castSingE = maybeToRight errMsg . castSing   where-    errMsg = "Type mismatch: expected " +|| demote @a ||+-                               ", got " +|| demote @b ||+ ""+    errMsg = "Type mismatch: expected '" +| demote @a |++                          "', but got '" +| demote @b |+ "'"  -- | Monadic version of 'castSing'. -- Throws an error using the given function if the cast fails. castM   :: forall (a :: T) (b :: T) t m. (SingI a, SingI b, Monad m)   => t a-  -> (forall x. Demote (KindOf a) -> Demote (KindOf b) -> m x)+  -> (forall x. MismatchError T -> m x)   -> m (t b) castM a throwErr =   requireEq @a @b throwErr <&> \Refl -> a@@ -81,12 +74,15 @@ -- Throws an error using the given function if the two types are not equal. requireEq   :: forall (a :: T) (b :: T) m. (SingI a, SingI b, Monad m)-  => (forall x. Demote (KindOf a) -> Demote (KindOf b) -> m x)+  => (forall x. MismatchError T -> m x)   -> m (a :~: b) requireEq throwErr =   case eqI @a @b of     Just p -> pure p-    Nothing -> throwErr (demote @a) (demote @b)+    Nothing -> throwErr MkMismatchError+      { meActual = demote @a+      , meExpected = demote @b+      }  -- | Version of 'eqI' that uses 'Proxy' eqP :: forall (a :: T) (b :: T). (SingI a, SingI b) => Proxy a -> Proxy b -> Maybe (a :~: b)
src/Morley/Michelson/Typed/T.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Module, providing 'T' data type, representing Michelson -- language types without annotations.@@ -11,10 +10,13 @@   ) where  import Fmt (Buildable(..), Builder, listF)-import Morley.Michelson.Printer.Util (RenderDoc(..))-import qualified Morley.Michelson.Untyped.Annotation as Un-import qualified Morley.Michelson.Untyped.Type as Un +import Morley.Michelson.Printer.Util (Prettier(..), RenderDoc(..), buildRenderDocExtended)+import Morley.Michelson.Untyped.Annotation qualified as Un+import Morley.Michelson.Untyped.Type qualified as Un+import Morley.Util.MismatchError+import Morley.Util.Peano qualified as Peano+ -- | Michelson language type with annotations stripped off. data T =     TKey@@ -46,6 +48,8 @@   | TAddress   | TChest   | TChestKey+  | TSaplingState Peano.Peano+  | TSaplingTransaction Peano.Peano   | TNever   deriving stock (Eq, Show, Generic) @@ -75,6 +79,8 @@     convert TChest = Un.TChest     convert TChestKey = Un.TChestKey     convert TNever = Un.TNever+    convert (TSaplingState n) = Un.TSaplingState (Peano.toNatural n)+    convert (TSaplingTransaction n) = Un.TSaplingTransaction (Peano.toNatural n)     convert (TOption a) = Un.TOption (toUType a)     convert (TList a) = Un.TList (toUType a)     convert (TSet a) = Un.TSet $ Un.Ty (Un.unwrapT $ toUType a) Un.noAnn@@ -95,8 +101,23 @@ instance Buildable T where   build = build . toUType +instance Buildable (MismatchError T) where+  build = buildRenderDocExtended++instance Buildable (MismatchError [T]) where+  build = buildRenderDocExtended+ instance RenderDoc T where   renderDoc context = renderDoc context . toUType++instance RenderDoc (Prettier T) where+  renderDoc context = renderDoc context . fmap toUType++instance RenderDoc (MismatchError T) where+  renderDoc ctx = renderDocDiff ctx . fmap Prettier++instance RenderDoc (MismatchError [T]) where+  renderDoc ctx = renderDocDiffList ctx . (fmap . fmap) Prettier  -- | Format type stack in a pretty way. buildStack :: [T] -> Builder
src/Morley/Michelson/Typed/TypeLevel.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | A collection of type families and other type-level machinery -- for working with Michelson types.@@ -15,7 +14,7 @@   where  import Morley.Michelson.Typed.T (T(TPair))-import Morley.Util.Peano (Nat(S, Z), Peano, ToPeano)+import Morley.Util.Peano (Peano, ToPeano, pattern S, pattern Z)  ---------------------------------------------------------------------------- -- Right-combed pairs
src/Morley/Michelson/Typed/Util.hs view
@@ -1,17 +1,23 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA +-- TODO [#712]: Remove this next major release+{-# OPTIONS_GHC -Wno-deprecations #-}+ -- | General-purpose utility functions for typed types.  module Morley.Michelson.Typed.Util-  ( DfsSettings (..)+  ( -- * Instruction analysis+    DfsSettings (..)   , CtorEffectsApp (..)   , ceaBottomToTop+  , dfsTraverseInstr   , dfsInstr   , dfsFoldInstr   , dfsModifyInstr +  , isMichelsonInstr+   -- * Changing instruction tree structure   , linearizeLeft   , linearizeLeftDeep@@ -28,59 +34,69 @@   -- * Instruction generation   , PushableStorageSplit (..)   , splitPushableStorage++  -- * Working with 'RemFail'+  , analyzeInstrFailure   ) where +import Debug qualified (show) import Prelude hiding (Ordering(..)) -import Control.Monad.Writer.Strict (execWriterT, runWriter, tell, writer)+import Control.Monad.Writer.Strict (Writer, execWriterT, runWriter, tell, writer) import Data.Constraint (Dict(..)) import Data.Default (Default(..))-import qualified Data.Map as M-import qualified Data.Set as S+import Data.Map qualified as M+import Data.Set qualified as S+import Data.Text.Internal.Builder (fromText)+import Fmt (Buildable(..)) import GHC.Exts (fromList)-import qualified Text.Show  import Morley.Michelson.Text (MText) import Morley.Michelson.Typed.Aliases import Morley.Michelson.Typed.Contract import Morley.Michelson.Typed.Instr import Morley.Michelson.Typed.Scope-import qualified Morley.Michelson.Typed.T as T+import Morley.Michelson.Typed.T qualified as T import Morley.Michelson.Typed.Value import Morley.Michelson.Typed.View --- | Options for 'dfsInstr'.-data DfsSettings x = DfsSettings+-- $setup+-- >>> :m + Morley.Michelson.Typed.Instr++-- | Options for 'dfsTraverseInstr' family of functions.+data DfsSettings m = DfsSettings   { dsGoToValues :: Bool-    -- ^ Whether 'dfsInstr' function should go into values which contain other+    -- ^ Whether @dfsTraverseInstr@ function should go into values which contain other     -- instructions: lambdas and constant contracts     -- (which can be passed to @CREATE_CONTRACT@).-  , dsCtorEffectsApp :: CtorEffectsApp x+  , dsCtorEffectsApp :: CtorEffectsApp m     -- ^ How do we handle intermediate nodes in instruction tree.-  } deriving stock (Show)+  }  -- | Describes how intermediate nodes in instruction tree are accounted.-data CtorEffectsApp x = CtorEffectsApp+data CtorEffectsApp m = CtorEffectsApp   { ceaName :: Text     -- ^ Name of this way.-  , ceaApplyEffects-      :: forall i o. Semigroup x => x -> x -> Instr i o -> (Instr i o, x)-    -- ^ This function accepts:-    -- 1. Effects gathered after applying @step@ to node's children, but-    -- before applying it to the node itself.-    -- 2. Effects gathered after applying @step@ to the given intermediate node.-    -- 3. Instruction resulting after all modifications produced by @step@.+  , ceaPostStep+      :: forall i o. Monad m+      => Instr i o+      -> m (Instr i o)+      -> m (Instr i o)+    -- ^ This transformation is applied after the step.+    -- It will be provided with the old instruction and the action gathered+    -- with the recursive traversal for the instruction subtree,+    -- and the result will go to the parent node.   } -instance Show (CtorEffectsApp x) where-  show CtorEffectsApp{..} = show ceaName+instance Buildable (CtorEffectsApp x) where+  build CtorEffectsApp{..} = fromText ceaName  -- | Gather effects first for children nodes, then for their parents.+{-# DEPRECATED ceaBottomToTop "\"Bottom to top\" is the only available behaviour now." #-} ceaBottomToTop :: CtorEffectsApp x ceaBottomToTop = CtorEffectsApp-  { ceaName = "Apply after"-  , ceaApplyEffects =-      \effBefore effAfter instr -> (instr, effBefore <> effAfter)+  { ceaName = "Do nothing"+  , ceaPostStep = const id   }  instance Default (DfsSettings x) where@@ -90,16 +106,17 @@     }  -- | Traverse a typed instruction in depth-first order.--- '<>' is used to concatenate intermediate results.--- Each instructions can be changed using the supplied @step@ function.--- It does not consider extra instructions (not present in Michelson).-dfsInstr ::-     forall x inp out. Semigroup x-  => DfsSettings x-  -> (forall i o. Instr i o -> (Instr i o, x))+--+-- The step action will be applied in bottom-to-top order, i.e.+-- first to the children of a node, then to the node itself.+dfsTraverseInstr ::+     forall m inp out.+     (Monad m)+  => DfsSettings m+  -> (forall i o. Instr i o -> m (Instr i o))   -> Instr inp out-  -> (Instr inp out, x)-dfsInstr settings@DfsSettings{..} step i =+  -> m (Instr inp out)+dfsTraverseInstr settings@DfsSettings{..} step i =   case i of     Seq i1 i2 -> recursion2 Seq i1 i2     WithLoc loc i1 -> recursion1 (WithLoc loc) i1@@ -125,181 +142,195 @@     -- This case is more complex so we duplicate @recursion1@ a bit.     -- We have to traverse the pushed value because a lambda can be     -- somewhere inside of it (e. g. one item of a pair).-    PUSH v -> fromMaybe (step i) do-        guard dsGoToValues+    PUSH v+      | dsGoToValues -> ceaPostStep dsCtorEffectsApp i do         let-          valueStep :: forall t . Value t -> (Value t, Maybe x)+          valueStep :: forall t . Value t -> m (Value t)           valueStep = \case             -- Using 'analyzeInstrFailure' here (and in case below) is cheap             -- (O(n) in total) because we never make it run over the same code twice-            VLam lambda -> bimap (VLam . analyzeInstrFailure) Just $-              dfsInstr settings step (rfAnyInstr lambda)-            otherV -> (otherV, Nothing)-        -- Note that @dfsTraverseValue@ does not respect 'CtorEffectsApp',-        -- so if we encounter a value that contains more than one lambda-        -- this function may misbehave.-        -- That's very unlikely in practice.-        -- In #264 we will support this feature in @dfsTraverseValue@.-        let-          (innerV, innerXMaybe) = runWriter $ dfsTraverseValue (writer . valueStep) v--        innerX <- innerXMaybe-        let (outerI, outerX) = step $ PUSH innerV-        pure $ ceaApplyEffects dsCtorEffectsApp innerX outerX outerI+            VLam lambda -> fmap (VLam . analyzeInstrFailure) $+              dfsTraverseInstr settings step (rfAnyInstr lambda)+            otherV -> pure otherV+        innerV <- dfsTraverseValue valueStep v+        step $ PUSH innerV+     | otherwise -> recursion0 i      LAMBDA (VLam i1)       | dsGoToValues ->           recursion1 (LAMBDA . VLam . analyzeInstrFailure) (rfAnyInstr i1)-      | otherwise -> step i+      | otherwise -> recursion0 i     CREATE_CONTRACT contract       | dsGoToValues ->-        let-          (codeI, codeX) = dfsInstr settings step (cCode contract)-          (viewsI, viewsX) = unzip $ toList (cViews contract) <&> \(SomeView v) ->-            first (\c -> SomeView v{ vCode = c }) $ dfsInstr settings step $ vCode v-          (i', x) = step $ CREATE_CONTRACT $ contract-            { cCode = codeI-            , cViews = UnsafeViewsSet $ fromList viewsI-            }-        in ceaApplyEffects dsCtorEffectsApp (sconcat $ codeX :| viewsX) x i'-      | otherwise -> step i+          ceaPostStep dsCtorEffectsApp i do+            codeI <- dfsTraverseInstr settings step (cCode contract)+            viewsI <- forM (toList $ cViews contract) \(SomeView v) -> do+                code <- dfsTraverseInstr settings step $ vCode v+                return $ SomeView v{ vCode = code }+            step $ CREATE_CONTRACT $ contract+              { cCode = codeI+              , cViews = UnsafeViewsSet $ fromList viewsI+              }+      | otherwise -> recursion0 i -    Nop{} -> step i+    Nop{} -> recursion0 i     Ext (TEST_ASSERT (TestAssert nm pc i1)) ->       recursion1 (Ext . TEST_ASSERT . TestAssert nm pc) i1-    Ext{} -> step i-    AnnCAR{} -> step i-    AnnCDR{} -> step i-    DROP{} -> step i-    DROPN{} -> step i-    DUP{} -> step i-    DUPN{} -> step i-    SWAP{} -> step i-    DIG{} -> step i-    DUG{} -> step i-    SOME{} -> step i-    NONE{} -> step i-    UNIT{} -> step i-    AnnPAIR{} -> step i-    AnnUNPAIR{} -> step i-    PAIRN{} -> step i-    UNPAIRN{} -> step i-    AnnLEFT{} -> step i-    AnnRIGHT{} -> step i-    NIL{} -> step i-    CONS{} -> step i-    SIZE{} -> step i-    EMPTY_SET{} -> step i-    EMPTY_MAP{} -> step i-    EMPTY_BIG_MAP{} -> step i-    MEM{} -> step i-    GET{} -> step i-    GETN{} -> step i-    UPDATE{} -> step i-    UPDATEN{} -> step i-    GET_AND_UPDATE{} -> step i-    EXEC{} -> step i-    APPLY{} -> step i-    FAILWITH{} -> step i-    CAST{} -> step i-    RENAME{} -> step i-    PACK{} -> step i-    UNPACK{} -> step i-    CONCAT{} -> step i-    CONCAT'{} -> step i-    SLICE{} -> step i-    ISNAT{} -> step i-    ADD{} -> step i-    SUB{} -> step i-    MUL{} -> step i-    EDIV{} -> step i-    ABS{} -> step i-    NEG{} -> step i-    LSL{} -> step i-    LSR{} -> step i-    OR{} -> step i-    AND{} -> step i-    XOR{} -> step i-    NOT{} -> step i-    COMPARE{} -> step i-    EQ{} -> step i-    NEQ{} -> step i-    LT{} -> step i-    GT{} -> step i-    LE{} -> step i-    GE{} -> step i-    INT{} -> step i-    VIEW{} -> step i-    SELF{} -> step i-    CONTRACT{} -> step i-    TRANSFER_TOKENS{} -> step i-    SET_DELEGATE{} -> step i-    IMPLICIT_ACCOUNT{} -> step i-    NOW{} -> step i-    AMOUNT{} -> step i-    BALANCE{} -> step i-    VOTING_POWER{} -> step i-    TOTAL_VOTING_POWER{} -> step i-    CHECK_SIGNATURE{} -> step i-    SHA256{} -> step i-    SHA512{} -> step i-    BLAKE2B{} -> step i-    SHA3{} -> step i-    KECCAK{} -> step i-    HASH_KEY{} -> step i-    PAIRING_CHECK{} -> step i-    SOURCE{} -> step i-    SENDER{} -> step i-    ADDRESS{} -> step i-    CHAIN_ID{} -> step i-    LEVEL{} -> step i-    SELF_ADDRESS{} -> step i-    NEVER{} -> step i-    TICKET{} -> step i-    READ_TICKET{} -> step i-    SPLIT_TICKET{} -> step i-    JOIN_TICKETS{} -> step i-    OPEN_CHEST{} -> step i+    Ext{} -> recursion0 i+    AnnCAR{} -> recursion0 i+    AnnCDR{} -> recursion0 i+    DROP{} -> recursion0 i+    DROPN{} -> recursion0 i+    DUP{} -> recursion0 i+    DUPN{} -> recursion0 i+    SWAP{} -> recursion0 i+    DIG{} -> recursion0 i+    DUG{} -> recursion0 i+    SOME{} -> recursion0 i+    NONE{} -> recursion0 i+    UNIT{} -> recursion0 i+    AnnPAIR{} -> recursion0 i+    AnnUNPAIR{} -> recursion0 i+    PAIRN{} -> recursion0 i+    UNPAIRN{} -> recursion0 i+    AnnLEFT{} -> recursion0 i+    AnnRIGHT{} -> recursion0 i+    NIL{} -> recursion0 i+    CONS{} -> recursion0 i+    SIZE{} -> recursion0 i+    EMPTY_SET{} -> recursion0 i+    EMPTY_MAP{} -> recursion0 i+    EMPTY_BIG_MAP{} -> recursion0 i+    MEM{} -> recursion0 i+    GET{} -> recursion0 i+    GETN{} -> recursion0 i+    UPDATE{} -> recursion0 i+    UPDATEN{} -> recursion0 i+    GET_AND_UPDATE{} -> recursion0 i+    EXEC{} -> recursion0 i+    APPLY{} -> recursion0 i+    FAILWITH{} -> recursion0 i+    CAST{} -> recursion0 i+    RENAME{} -> recursion0 i+    PACK{} -> recursion0 i+    UNPACK{} -> recursion0 i+    CONCAT{} -> recursion0 i+    CONCAT'{} -> recursion0 i+    SLICE{} -> recursion0 i+    ISNAT{} -> recursion0 i+    ADD{} -> recursion0 i+    SUB{} -> recursion0 i+    SUB_MUTEZ{} -> recursion0 i+    MUL{} -> recursion0 i+    EDIV{} -> recursion0 i+    ABS{} -> recursion0 i+    NEG{} -> recursion0 i+    LSL{} -> recursion0 i+    LSR{} -> recursion0 i+    OR{} -> recursion0 i+    AND{} -> recursion0 i+    XOR{} -> recursion0 i+    NOT{} -> recursion0 i+    COMPARE{} -> recursion0 i+    EQ{} -> recursion0 i+    NEQ{} -> recursion0 i+    LT{} -> recursion0 i+    GT{} -> recursion0 i+    LE{} -> recursion0 i+    GE{} -> recursion0 i+    INT{} -> recursion0 i+    VIEW{} -> recursion0 i+    SELF{} -> recursion0 i+    CONTRACT{} -> recursion0 i+    TRANSFER_TOKENS{} -> recursion0 i+    SET_DELEGATE{} -> recursion0 i+    IMPLICIT_ACCOUNT{} -> recursion0 i+    NOW{} -> recursion0 i+    AMOUNT{} -> recursion0 i+    BALANCE{} -> recursion0 i+    VOTING_POWER{} -> recursion0 i+    TOTAL_VOTING_POWER{} -> recursion0 i+    CHECK_SIGNATURE{} -> recursion0 i+    SHA256{} -> recursion0 i+    SHA512{} -> recursion0 i+    BLAKE2B{} -> recursion0 i+    SHA3{} -> recursion0 i+    KECCAK{} -> recursion0 i+    HASH_KEY{} -> recursion0 i+    PAIRING_CHECK{} -> recursion0 i+    SOURCE{} -> recursion0 i+    SENDER{} -> recursion0 i+    ADDRESS{} -> recursion0 i+    CHAIN_ID{} -> recursion0 i+    LEVEL{} -> recursion0 i+    SELF_ADDRESS{} -> recursion0 i+    NEVER{} -> recursion0 i+    TICKET{} -> recursion0 i+    READ_TICKET{} -> recursion0 i+    SPLIT_TICKET{} -> recursion0 i+    JOIN_TICKETS{} -> recursion0 i+    OPEN_CHEST{} -> recursion0 i+    SAPLING_EMPTY_STATE{} -> recursion0 i+    SAPLING_VERIFY_UPDATE{} -> recursion0 i   where+    recursion0 ::+      forall a b. Instr a b -> m (Instr a b)+    recursion0 i0 =+      ceaPostStep dsCtorEffectsApp i0 $+      step i0+     recursion1 ::-      forall a b c d. (Instr a b -> Instr c d) -> Instr a b -> (Instr c d, x)+      forall a b c d. (Instr a b -> Instr c d) -> Instr a b -> m (Instr c d)     recursion1 constructor i0 =-      let-        (innerI, innerX) = dfsInstr settings step i0-        (outerI, outerX) = step $ constructor innerI-      in ceaApplyEffects dsCtorEffectsApp innerX outerX outerI+      ceaPostStep dsCtorEffectsApp (constructor i0) do+        innerI <- dfsTraverseInstr settings step i0+        step $ constructor innerI      recursion2 ::       forall i o i1 o1 i2 o2.       (Instr i1 o1 -> Instr i2 o2 -> Instr i o) ->-      Instr i1 o1 -> Instr i2 o2 -> (Instr i o, x)+      Instr i1 o1 -> Instr i2 o2 -> m (Instr i o)     recursion2 constructor i1 i2 =-      let-        (i1', x1) = dfsInstr settings step i1-        (i2', x2) = dfsInstr settings step i2-        (i', x) = step $ constructor i1' i2'-      in ceaApplyEffects dsCtorEffectsApp (x1 <> x2) x i'+      ceaPostStep dsCtorEffectsApp (constructor i1 i2) do+        i1' <- dfsTraverseInstr settings step i1+        i2' <- dfsTraverseInstr settings step i2+        step $ constructor i1' i2' --- | Specialization of 'dfsInstr' for case when changing the instruction is+-- | Traverse a typed instruction in depth-first order.+-- '<>' is used to concatenate intermediate results.+-- Each instructions can be changed using the supplied @step@ function.+-- It does not consider extra instructions (not present in Michelson).+{-# DEPRECATED dfsInstr "Use `dfsModifyInstr`, `dfsFoldInstr` or `dfsTraverseInstr` instead." #-}+dfsInstr ::+     forall x inp out.+     (Monoid x)+  => DfsSettings (Writer x)+  -> (forall i o. Instr i o -> (Instr i o, x))+  -> Instr inp out+  -> (Instr inp out, x)+dfsInstr settings step i =+  runWriter $ dfsTraverseInstr settings (writer . step) i++-- | Specialization of 'dfsTraverseInstr' for case when changing the instruction is -- not required. dfsFoldInstr   :: forall x inp out.-      (Semigroup x)-  => DfsSettings x+      (Monoid x)+  => DfsSettings (Writer x)   -> (forall i o. Instr i o -> x)   -> Instr inp out   -> x dfsFoldInstr settings step instr =   snd $ dfsInstr settings (\i -> (i, step i)) instr --- | Specialization of 'dfsInstr' which only modifies given instruction.+-- | Specialization of 'dfsTraverseInstr' which only modifies given instruction. dfsModifyInstr-  :: DfsSettings ()+  :: DfsSettings Identity   -> (forall i o. Instr i o -> Instr i o)   -> Instr inp out   -> Instr inp out dfsModifyInstr settings step instr =-  fst $ dfsInstr settings (\i -> (step i, ())) instr+  runIdentity $ dfsTraverseInstr settings (pure . step) instr  -- | Check whether instruction fails at each execution path or have at least one -- non-failing path.@@ -331,22 +362,22 @@       RfNormal i0 ->         RfNormal (InstrWithNotes p pn i0)       RfAlwaysFails i0 ->-        error $ "InstrWithNotes wraps always-failing instruction: " <> show i0+        error $ "InstrWithNotes wraps always-failing instruction: " <> Debug.show i0     InstrWithVarNotes vn i -> case go i of       RfNormal i0 ->         RfNormal (InstrWithVarNotes vn i0)       RfAlwaysFails i0 ->-        error $ "InstrWithVarNotes wraps always-failing instruction: " <> show i0+        error $ "InstrWithVarNotes wraps always-failing instruction: " <> Debug.show i0     InstrWithVarAnns vn i -> case go i of       RfNormal i0 ->         RfNormal (InstrWithVarAnns vn i0)       RfAlwaysFails i0 ->-        error $ "InstrWithVarAnns wraps always-failing instruction: " <> show i0+        error $ "InstrWithVarAnns wraps always-failing instruction: " <> Debug.show i0     FrameInstr s i -> case go i of       RfNormal i0 ->         RfNormal (FrameInstr s i0)       RfAlwaysFails i0 ->-        error $ "FrameInstr wraps always-failing instruction: " <> show i0+        error $ "FrameInstr wraps always-failing instruction: " <> Debug.show i0     Seq a b -> Seq a `rfMapAnyInstr` go b     Nop -> RfNormal Nop     Ext e -> RfNormal (Ext e)@@ -411,6 +442,7 @@     i@ISNAT -> RfNormal i     i@ADD -> RfNormal i     i@SUB -> RfNormal i+    i@SUB_MUTEZ -> RfNormal i     i@MUL -> RfNormal i     i@EDIV -> RfNormal i     i@ABS -> RfNormal i@@ -461,6 +493,8 @@     i@SPLIT_TICKET -> RfNormal i     i@JOIN_TICKETS -> RfNormal i     i@OPEN_CHEST -> RfNormal i+    i@SAPLING_EMPTY_STATE{} -> RfNormal i+    i@SAPLING_VERIFY_UPDATE{} -> RfNormal i  -- | There are many ways to represent a sequence of more than 2 instructions. -- E. g. for @i1; i2; i3@ it can be @Seq i1 $ Seq i2 i3@ or @Seq (Seq i1 i2) i3@.@@ -808,3 +842,138 @@               foldM handleMap EMPTY_MAP $ M.toList vMap    VBigMap _ _ -> PartlyPushableStorage v Nop++-- | Whether this instruction is a real Michelson instruction.+--+-- Only the root is in question, children in the instruction tree are not+-- accounted for.+--+-- >>> isMichelsonInstr (Seq Nop Nop)+-- True+--+-- >>> isMichelsonInstr (Ext $ COMMENT_ITEM "comment")+-- False+--+-- This function is helpful e.g. in debugger.+isMichelsonInstr :: Instr i o -> Bool+isMichelsonInstr = \case+  WithLoc{} -> False+  Meta{} -> False+  InstrWithNotes{} -> False+  InstrWithVarNotes{} -> False+  InstrWithVarAnns{} -> False+  FrameInstr{} -> False+  Seq{} -> True+  Nop -> False+  Ext{} -> False+  Nested{} -> True+  DocGroup{} -> False+  Fn{} -> False+  AnnCAR{} -> True+  AnnCDR{} -> True+  DROP{} -> True+  DROPN{} -> True+  DUP{} -> True+  DUPN{} -> True+  SWAP{} -> True+  DIG{} -> True+  DUG{} -> True+  PUSH{} -> True+  SOME{} -> True+  NONE{} -> True+  UNIT{} -> True+  IF_NONE{} -> True+  AnnPAIR{} -> True+  AnnUNPAIR{} -> True+  PAIRN{} -> True+  UNPAIRN{} -> True+  AnnLEFT{} -> True+  AnnRIGHT{} -> True+  IF_LEFT{} -> True+  NIL{} -> True+  CONS{} -> True+  IF_CONS{} -> True+  SIZE{} -> True+  EMPTY_SET{} -> True+  EMPTY_MAP{} -> True+  EMPTY_BIG_MAP{} -> True+  MAP{} -> True+  ITER{} -> True+  MEM{} -> True+  GET{} -> True+  GETN{} -> True+  UPDATE{} -> True+  UPDATEN{} -> True+  GET_AND_UPDATE{} -> True+  IF{} -> True+  LOOP{} -> True+  LOOP_LEFT{} -> True+  LAMBDA{} -> True+  EXEC{} -> True+  APPLY{} -> True+  DIP{} -> True+  DIPN{} -> True+  FAILWITH{} -> True+  CAST{} -> True+  RENAME{} -> True+  PACK{} -> True+  UNPACK{} -> True+  CONCAT{} -> True+  CONCAT'{} -> True+  SLICE{} -> True+  ISNAT{} -> True+  ADD{} -> True+  SUB{} -> True+  SUB_MUTEZ{} -> True+  MUL{} -> True+  EDIV{} -> True+  ABS{} -> True+  NEG{} -> True+  LSL{} -> True+  LSR{} -> True+  OR{} -> True+  AND{} -> True+  XOR{} -> True+  NOT{} -> True+  COMPARE{} -> True+  EQ{} -> True+  NEQ{} -> True+  LT{} -> True+  GT{} -> True+  LE{} -> True+  GE{} -> True+  INT{} -> True+  VIEW{} -> True+  SELF{} -> True+  CONTRACT{} -> True+  TRANSFER_TOKENS{} -> True+  SET_DELEGATE{} -> True+  CREATE_CONTRACT{} -> True+  IMPLICIT_ACCOUNT{} -> True+  NOW{} -> True+  AMOUNT{} -> True+  BALANCE{} -> True+  VOTING_POWER{} -> True+  TOTAL_VOTING_POWER{} -> True+  CHECK_SIGNATURE{} -> True+  SHA256{} -> True+  SHA512{} -> True+  BLAKE2B{} -> True+  SHA3{} -> True+  KECCAK{} -> True+  HASH_KEY{} -> True+  PAIRING_CHECK{} -> True+  SOURCE{} -> True+  SENDER{} -> True+  ADDRESS{} -> True+  CHAIN_ID{} -> True+  LEVEL{} -> True+  SELF_ADDRESS{} -> True+  NEVER{} -> True+  TICKET{} -> True+  READ_TICKET{} -> True+  SPLIT_TICKET{} -> True+  JOIN_TICKETS{} -> True+  OPEN_CHEST{} -> True+  SAPLING_EMPTY_STATE{} -> True+  SAPLING_VERIFY_UPDATE{} -> True
src/Morley/Michelson/Typed/Value.hs view
@@ -1,13 +1,10 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Module, containing data types for Michelson value.  module Morley.Michelson.Typed.Value   ( Comparability (..)-  , Comparable-  , ComparabilityScope   , CreateContract (..)   , Operation' (..)   , SetDelegate (..)@@ -21,7 +18,6 @@   , buildVContract   , checkComparability   , compileEpLiftSequence-  , comparabilityPresence   , getComparableProofS   , liftCallArg   , valueTypeSanity@@ -31,15 +27,12 @@  import Control.Lens (At(..), Index, IxValue, Ixed(..)) import Data.Constraint (Dict(..), (\\))-import Data.Singletons (Sing)-import Data.Type.Bool (type (&&)) import Fmt (Buildable(build), Builder, (+|), (|+))  import Morley.Michelson.Text (MText) import Morley.Michelson.Typed.Contract import Morley.Michelson.Typed.Entrypoints import Morley.Michelson.Typed.Scope-import Morley.Michelson.Typed.Sing import Morley.Michelson.Typed.T (T(..)) import Morley.Tezos.Address (Address, GlobalCounter(..)) import Morley.Tezos.Core (ChainId, Mutez, Timestamp)@@ -177,114 +170,26 @@   RfNormal i -> RfNormal $ f i   RfAlwaysFails i -> RfAlwaysFails $ f i -getComparableProofS :: Sing (a :: T) -> Maybe (Dict (Comparable a))-getComparableProofS s = case checkComparability s of-  CanBeCompared -> Just Dict-  CannotBeCompared -> Nothing--class (IsComparable t ~ 'True) => Comparable t where-  tcompare :: (Value' instr t) -> (Value' instr t) -> Ordering--instance (Comparable e1, Comparable e2, FailOnNonComparableFound (IsComparable e1 && IsComparable e2))-  => Comparable ('TPair e1 e2) where-  tcompare (VPair a) (VPair b) = compare a b-instance (Comparable e1, Comparable e2, FailOnNonComparableFound (IsComparable e1 && IsComparable e2))-  => Comparable ('TOr e1 e2) where-  tcompare (VOr a) (VOr b) = compare a b-instance (Comparable e, ForbidNonComparable e) => Comparable ('TOption e) where-  tcompare (VOption a) (VOption b) = compare a b-instance Comparable 'TUnit where-  tcompare VUnit VUnit = EQ-instance Comparable 'TInt where-  tcompare (VInt a) (VInt b) = compare a b-instance Comparable 'TNat where-  tcompare (VNat a) (VNat b) = compare a b-instance Comparable 'TString where-  tcompare (VString a) (VString b) = compare a b-instance Comparable 'TBytes where-  tcompare (VBytes a) (VBytes b) = compare a b-instance Comparable 'TMutez where-  tcompare (VMutez a) (VMutez b) = compare a b-instance Comparable 'TBool where-  tcompare (VBool a) (VBool b) = compare a b-instance Comparable 'TKeyHash where-  tcompare (VKeyHash a) (VKeyHash b) = compare a b-instance Comparable 'TTimestamp where-  tcompare (VTimestamp a) (VTimestamp b) = compare a b-instance Comparable 'TAddress where-  tcompare (VAddress a) (VAddress b) = compare a b-instance Comparable 'TNever where-  tcompare = \case-instance Comparable 'TChainId where-  tcompare (VChainId a) (VChainId b) = compare a b-instance Comparable 'TSignature where-  tcompare (VSignature a) (VSignature b) = compare a b-instance Comparable 'TKey where-  tcompare (VKey a) (VKey b) = compare a b--instance (Comparable e) => Ord (Value' instr e) where-  compare = tcompare @e---- | Alias for comparable types.-type ComparabilityScope t =-  (SingI t, Comparable t)--data Comparability t where-  CanBeCompared :: (Comparable t) => Comparability t-  CannotBeCompared :: (IsComparable t ~ 'False) => Comparability t--checkComparability :: Sing t -> Comparability t-checkComparability = \case-  STPair a b -> case (checkComparability a, checkComparability b) of-    (CanBeCompared, CanBeCompared) -> CanBeCompared-    (CannotBeCompared, _) -> CannotBeCompared-    (_, CannotBeCompared) -> CannotBeCompared-  STOr a b -> case (checkComparability a, checkComparability b) of-    (CanBeCompared, CanBeCompared) -> CanBeCompared-    (CannotBeCompared, _) -> CannotBeCompared-    (_, CannotBeCompared) -> CannotBeCompared-  STOption t -> case checkComparability t of-    CanBeCompared -> CanBeCompared-    CannotBeCompared -> CannotBeCompared-  STList _ -> CannotBeCompared-  STSet _ -> CannotBeCompared-  STOperation -> CannotBeCompared-  STContract _ -> CannotBeCompared-  STTicket _ -> CannotBeCompared-  STLambda _ _ -> CannotBeCompared-  STMap _ _ -> CannotBeCompared-  STBigMap _ _ -> CannotBeCompared-  STChest -> CannotBeCompared-  STChestKey -> CannotBeCompared-  STNever -> CanBeCompared-  STUnit -> CanBeCompared-  STInt -> CanBeCompared-  STNat -> CanBeCompared-  STString -> CanBeCompared-  STBytes -> CanBeCompared-  STMutez -> CanBeCompared-  STBool -> CanBeCompared-  STKeyHash -> CanBeCompared-  STBls12381Fr -> CannotBeCompared-  STBls12381G1 -> CannotBeCompared-  STBls12381G2 -> CannotBeCompared-  STTimestamp -> CanBeCompared-  STAddress -> CanBeCompared-  STKey -> CanBeCompared-  STSignature -> CanBeCompared-  STChainId -> CanBeCompared--comparabilityPresence :: Sing t -> Maybe (Dict $ (Comparable t))-comparabilityPresence s = case checkComparability s of-  CanBeCompared -> Just Dict-  CannotBeCompared -> Nothing--instance SingI t => CheckScope (Comparable t) where-  checkScope = maybeToRight BtNotComparable $ comparabilityPresence sing+tcompare :: forall t instr. Comparable t => (Value' instr t) -> (Value' instr t) -> Ordering+tcompare (VPair a) (VPair b) = compare a b+tcompare (VOr a) (VOr b) = compare a b+tcompare (VOption a) (VOption b) = compare a b+tcompare VUnit VUnit = EQ+tcompare (VInt a) (VInt b) = compare a b+tcompare (VNat a) (VNat b) = compare a b+tcompare (VString a) (VString b) = compare a b+tcompare (VBytes a) (VBytes b) = compare a b+tcompare (VMutez a) (VMutez b) = compare a b+tcompare (VBool a) (VBool b) = compare a b+tcompare (VKeyHash a) (VKeyHash b) = compare a b+tcompare (VTimestamp a) (VTimestamp b) = compare a b+tcompare (VAddress a) (VAddress b) = compare a b+tcompare (VChainId a) (VChainId b) = compare a b+tcompare (VSignature a) (VSignature b) = compare a b+tcompare (VKey a) (VKey b) = compare a b -instance (SingI t) => CheckScope (ComparabilityScope t) where-  checkScope =-    (\Dict -> Dict) <$> checkScope @(Comparable t)+instance (Comparable t) => Ord (Value' instr t) where+  compare = tcompare @t  -- | Representation of Michelson value. --
src/Morley/Michelson/Typed/View.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- 'newtype Container' deriving produced some fake warnings {-# OPTIONS_GHC -Wno-redundant-constraints #-}@@ -10,7 +9,6 @@   ( -- * View     ViewName (..)   , mkViewName-  , unsafeMkViewName   , viewNameToMText   , ViewCode'   , View' (..)@@ -30,14 +28,14 @@  import Control.Monad.Except (throwError) import Data.Default (Default(..))-import qualified Data.Sequence as Seq+import Data.Sequence qualified as Seq import Fmt (Buildable(..), (+|), (|+)) import GHC.Exts (fromList)  import Morley.Michelson.Typed.Annotation import Morley.Michelson.Typed.Scope import Morley.Michelson.Typed.T (T(..))-import Morley.Michelson.Untyped.View (ViewName(..), mkViewName, unsafeMkViewName, viewNameToMText)+import Morley.Michelson.Untyped.View (ViewName(..), mkViewName, viewNameToMText) import Morley.Util.Sing  
src/Morley/Michelson/Untyped.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Untyped   ( module Exports
src/Morley/Michelson/Untyped/Aliases.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Some simple aliases for Michelson types. @@ -11,10 +10,10 @@   , ExpandedExtInstr   ) where -import qualified Morley.Michelson.Untyped.Contract as Untyped-import qualified Morley.Michelson.Untyped.Ext as Untyped-import qualified Morley.Michelson.Untyped.Instr as Untyped-import qualified Morley.Michelson.Untyped.Value as Untyped+import Morley.Michelson.Untyped.Contract qualified as Untyped+import Morley.Michelson.Untyped.Ext qualified as Untyped+import Morley.Michelson.Untyped.Instr qualified as Untyped+import Morley.Michelson.Untyped.Value qualified as Untyped  type Value = Untyped.Value' Untyped.ExpandedOp type View = Untyped.View' Untyped.ExpandedOp
src/Morley/Michelson/Untyped/Annotation.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Michelson annotations in untyped model. @@ -40,7 +39,6 @@   , varAnnQ   , fieldAnnQ   , typeAnnQ-  , unsafeMkAnnotation   , mkAnnotation   , specialVarAnns   , specialFieldAnn@@ -58,17 +56,18 @@ import Data.Char (isAlpha, isAscii, isDigit, isNumber) import Data.Data (Data(..)) import Data.Default (Default(..))-import qualified Data.Text as T+import Data.Text qualified as T import Data.Typeable (eqT, (:~:)(..)) import Fmt (Buildable(build)) import Instances.TH.Lift ()-import qualified Language.Haskell.TH as TH+import Language.Haskell.TH qualified as TH import Language.Haskell.TH.Lift (deriveLift)-import qualified Language.Haskell.TH.Quote as TH+import Language.Haskell.TH.Quote qualified as TH import Text.PrettyPrint.Leijen.Text (Doc, hsep, textStrict, (<+>))-import qualified Text.Show+import Text.Show qualified as T+import Type.Reflection (tyConName, typeRep, typeRepTyCon) -import Morley.Michelson.Printer.Util (RenderDoc(..), buildRenderDoc, doesntNeedParens, printDocS)+import Morley.Michelson.Printer.Util (RenderDoc(..), buildRenderDoc) import Morley.Util.Aeson  -- | Generic Type/Field/Variable Annotation@@ -120,7 +119,7 @@   { asTypes  :: [TypeAnn]   , asFields :: [FieldAnn]   , asVars   :: [VarAnn]-  } deriving stock Eq+  } deriving stock (Eq, Show)  instance Semigroup AnnotationSet where   (AnnotationSet ts1 fs1 vs1) <> (AnnotationSet ts2 fs2 vs2) = AnnotationSet {..}@@ -215,8 +214,13 @@   -- ^ What prefix is used for the given annotation type (identified by @tag@) in Michelson code,   -- i.e. @%@ for field annotations, @\@@ for variable annotations, @:@ for type annotations -instance KnownAnnTag tag => Show (Annotation tag) where-  show = printDocS True . renderDoc doesntNeedParens+instance Typeable tag => Show (Annotation tag) where+  showsPrec d (Annotation text) =+    T.showParen (d > app_prec) $ T.showString $ toString $+      "UnsafeAnnotation @" <> tag <> " \"" <> text <> "\""+    where+      app_prec = 10+      tag = toText . tyConName . typeRepTyCon $ typeRep @tag  -- | Type-level tag for type annotations data TypeTag@@ -252,9 +256,6 @@ instance KnownAnnTag tag => Buildable (Annotation tag) where   build = buildRenderDoc -instance Show AnnotationSet where-  show = printDocS True . renderDoc doesntNeedParens- instance RenderDoc AnnotationSet where   renderDoc _ (AnnotationSet {..}) =     renderAnnGroup asTypes <+> renderAnnGroup asFields <+> renderAnnGroup asVars@@ -283,11 +284,6 @@ noAnn = UnsafeAnnotation ""  -- | Makes an t'Annotation' from its textual value, prefix (%/@/:) excluded--- Throws an error if the given 'Text' contains invalid characters-unsafeMkAnnotation :: HasCallStack => Text -> Annotation a-unsafeMkAnnotation = either error id . mkAnnotation---- | Makes an t'Annotation' from its textual value, prefix (%/@/:) excluded -- Returns a 'Text' error message if the given 'Text' contains invalid characters mkAnnotation :: Text -> Either Text (Annotation a) mkAnnotation text@@ -303,28 +299,37 @@       T.find (not . isValidAnnBodyChar) suffix  -- |+-- >>> :t [annQ||]+-- ... :: forall k (tag :: k). Annotation tag+-- -- >>> :t [annQ|abc|] -- ... :: forall k (tag :: k). Annotation tag annQ :: TH.QuasiQuoter annQ = annQImpl Nothing  -- |+-- >>> :t [typeAnnQ||]+-- ... :: TypeAnn+-- -- >>> :t [typeAnnQ|abc|]--- ... -- ... :: TypeAnn typeAnnQ :: TH.QuasiQuoter typeAnnQ = annQImpl (Just [t|TypeAnn|])  -- |+-- >>> :t [fieldAnnQ||]+-- ... :: FieldAnn+-- -- >>> :t [fieldAnnQ|abc|]--- ... -- ... :: FieldAnn fieldAnnQ :: TH.QuasiQuoter fieldAnnQ = annQImpl (Just [t|FieldAnn|])  -- |+-- >>> :t [varAnnQ||]+-- ... :: VarAnn+-- -- >>> :t [varAnnQ|abc|]--- ... -- ... :: VarAnn varAnnQ :: TH.QuasiQuoter varAnnQ = annQImpl (Just [t|VarAnn|])@@ -336,8 +341,8 @@       case (mkAnnotation $ toText @String s) of         Left err -> fail $ toString err         Right _ -> case annTypeMb of-          Nothing -> [e| (UnsafeAnnotation s) |]-          Just annType -> [e| (UnsafeAnnotation s :: $(annType)) |]+          Nothing -> [e| (UnsafeAnnotation $ fromString s) |]+          Just annType -> [e| (UnsafeAnnotation $ fromString s :: $(annType)) |]   , TH.quotePat = \s ->        case (mkAnnotation $ toText @String s) of          Left err -> fail $ toString err
src/Morley/Michelson/Untyped/Contract.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Michelson contract in untyped model. @@ -97,6 +96,12 @@   [CBCode    c, CBStorage s, CBParam   p] -> Just $ Contract p s c CSP vs   [CBCode    c, CBParam   p, CBStorage s] -> Just $ Contract p s c CPS vs   _                                       -> Nothing++instance Buildable (ContractBlock op) where+  build (CBParam{}) = "parameter"+  build (CBStorage{}) = "storage"+  build (CBCode{}) = "code"+  build (CBView{}) = "view"  -- | Map each contract fields by the given function and sort the output -- based on the 'EntriesOrder'.
src/Morley/Michelson/Untyped/Entrypoints.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Michelson.Untyped.Entrypoints   ( EpName (..)@@ -13,12 +12,11 @@   , epNameToRefAnn   , EpNameFromRefAnnError (..)   , buildEpName-  , unsafeBuildEpName   , mkEntrypointsMap   ) where  import Data.Aeson.TH (deriveJSON)-import qualified Data.Map as Map+import Data.Map qualified as Map import Fmt (Buildable(..), pretty)  import Morley.Michelson.Printer.Util (RenderDoc(..), buildRenderDoc, renderAnyBuildable)@@ -101,7 +99,7 @@ epNameToParamAnn :: EpName -> FieldAnn epNameToParamAnn (UnsafeEpName name)   | name == "" = [annQ|default|]-  | otherwise = unsafeMkAnnotation name+  | otherwise = unsafe . mkAnnotation $ name  data EpNameFromRefAnnError   = InEpNameBadAnnotation FieldAnn@@ -138,7 +136,7 @@  -- | Turn entrypoint name into annotation used as reference to entrypoint. epNameToRefAnn :: EpName -> FieldAnn-epNameToRefAnn (UnsafeEpName name) = unsafeMkAnnotation name+epNameToRefAnn (UnsafeEpName name) = unsafe . mkAnnotation $ name  -- | Make a valid entrypoint name from an arbitrary text. This -- function prohibits explicit @default@ entrypoint name which is@@ -152,10 +150,6 @@     & first (mappend "Failed to parse entrypoint: " . pretty)   epNameFromRefAnn annotation     & first pretty---- | Partial version of 'buildEpName'.-unsafeBuildEpName :: HasCallStack => Text -> EpName-unsafeBuildEpName = either (error . pretty) id . buildEpName  instance HasCLReader EpName where   getReader = eitherReader (buildEpName . toText)
src/Morley/Michelson/Untyped/Ext.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Morley extensions to the Michelson language module Morley.Michelson.Untyped.Ext@@ -18,8 +17,8 @@  import Data.Aeson.TH (deriveJSON) import Data.Data (Data(..))-import qualified Data.Set as Set-import qualified Data.Text as T+import Data.Set qualified as Set+import Data.Text qualified as T import Fmt (Buildable(build), Builder, GenericBuildable(..), listF) import Text.PrettyPrint.Leijen.Text (textStrict) @@ -44,6 +43,8 @@   | UPRINT PrintComment         -- ^ Print a comment with optional embedded @StackRef@s   | UCOMMENT Text        -- ^ A comment in Michelson code   deriving stock (Eq, Show, Data, Generic, Functor)++{-# DEPRECATED FN "Morley let macros are deprecated" #-}  deriving via GenericBuildable (ExtInstrAbstract op) instance Buildable op => Buildable (ExtInstrAbstract op) 
src/Morley/Michelson/Untyped/Instr.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Michelson instructions in untyped model. @@ -18,12 +17,11 @@ import Fmt (Buildable(build), (+|), (|+)) import Generics.SYB (everywhere, mkT) import Text.PrettyPrint.Leijen.Text-  (Doc, align, braces, enclose, indent, line, nest, space, text, (<$$>), (<+>))-import qualified Text.Show+  (Doc, align, braces, enclose, indent, integer, line, nest, space, text, (<$$>), (<+>))  import Morley.Michelson.ErrorPos (InstrCallStack) import Morley.Michelson.Printer.Util-  (RenderDoc(..), buildRenderDoc, doesntNeedParens, needsParens, printDocS, renderOpsList, spaces)+  (RenderDoc(..), buildRenderDoc, doesntNeedParens, needsParens, renderOpsList, spaces) import Morley.Michelson.Untyped.Annotation   (Annotation, FieldAnn, KnownAnnTag, TypeAnn, VarAnn, fullAnnSet, singleAnnSet) import Morley.Michelson.Untyped.Contract (Contract'(..))@@ -159,6 +157,7 @@   | ISNAT             VarAnn   | ADD               VarAnn   | SUB               VarAnn+  | SUB_MUTEZ         VarAnn   | MUL               VarAnn   | EDIV              VarAnn   | ABS               VarAnn@@ -209,10 +208,9 @@   | SPLIT_TICKET      VarAnn   | JOIN_TICKETS      VarAnn   | OPEN_CHEST        VarAnn-  deriving stock (Eq, Functor, Data, Generic)--instance RenderDoc (InstrAbstract op) => Show (InstrAbstract op) where-  show = printDocS True . renderDoc doesntNeedParens+  | SAPLING_EMPTY_STATE VarAnn Natural+  | SAPLING_VERIFY_UPDATE VarAnn+  deriving stock (Eq, Functor, Data, Generic, Show)  instance NFData op => NFData (InstrAbstract op) @@ -287,6 +285,7 @@     ISNAT va                -> "ISNAT" <+> renderAnnot va     ADD va                  -> "ADD" <+> renderAnnot va     SUB va                  -> "SUB" <+> renderAnnot va+    SUB_MUTEZ va            -> "SUB_MUTEZ" <+> renderAnnot va     MUL va                  -> "MUL" <+> renderAnnot va     EDIV va                 -> "EDIV" <+> renderAnnot va     ABS va                  -> "ABS" <+> renderAnnot va@@ -339,6 +338,8 @@     SPLIT_TICKET va         -> "SPLIT_TICKET" <+> renderAnnot va     JOIN_TICKETS va         -> "JOIN_TICKETS" <+> renderAnnot va     OPEN_CHEST va           -> "OPEN_CHEST" <+> renderAnnot va+    SAPLING_EMPTY_STATE va n -> "SAPLING_EMPTY_STATE" <+> renderAnnot va <+> (integer $ toInteger n)+    SAPLING_VERIFY_UPDATE va -> "SAPLING_VERIFY_UPDATE" <+> renderAnnot va     where       renderTy = renderDoc @Ty needsParens       renderComp = renderDoc @Ty needsParens
src/Morley/Michelson/Untyped/OpSize.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Measuring operation size. --@@ -30,7 +29,7 @@  import Fmt (Buildable(..)) import Prelude hiding (Ordering(..))-import qualified Unsafe (fromIntegral)+import Unsafe qualified (fromIntegral)  import Morley.Michelson.Interpret.Utils import Morley.Michelson.Untyped.Aliases@@ -123,6 +122,7 @@   ISNAT va -> annsOpSize va   ADD va -> annsOpSize va   SUB va -> annsOpSize va+  SUB_MUTEZ va -> annsOpSize va   MUL va -> annsOpSize va   EDIV va -> annsOpSize va   ABS va -> annsOpSize va@@ -173,6 +173,8 @@   SPLIT_TICKET va -> annsOpSize va   JOIN_TICKETS va -> annsOpSize va   OPEN_CHEST va -> annsOpSize va+  SAPLING_EMPTY_STATE va n -> annsOpSize va <> numOpSize n+  SAPLING_VERIFY_UPDATE va -> annsOpSize va   where     subcodeOpSize is = expandedInstrOpSize (SeqEx is)     ifOpSize l r = expandedInstrOpSize (SeqEx l) <> expandedInstrOpSize (SeqEx r)@@ -270,6 +272,8 @@     TChest -> mempty     TChestKey -> mempty     TNever -> mempty+    TSaplingState _ -> mempty+    TSaplingTransaction _ -> mempty  innerOpSize :: Ty -> OpSize innerOpSize (Ty _ a) =
src/Morley/Michelson/Untyped/Type.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Michelson types represented in untyped model. @@ -41,15 +40,16 @@ import Fmt (Buildable(build)) import Language.Haskell.TH.Lift (deriveLift) import Prelude hiding ((<$>))-import Text.PrettyPrint.Leijen.Text (Doc, align, softbreak, (<$>), (<+>))+import Text.PrettyPrint.Leijen.Text (Doc, align, integer, softbreak, (<$>), (<+>))  import Morley.Michelson.Printer.Util-  (Prettier(..), RenderContext, RenderDoc(..), addParens, buildRenderDoc, doesntNeedParens,-  needsParens, wrapInParens)+  (Prettier(..), RenderContext, RenderDoc(..), addParens, buildRenderDoc, buildRenderDocExtended,+  doesntNeedParens, needsParens, wrapInParens) import Morley.Michelson.Untyped.Annotation   (AnnotationSet, FieldAnn, RootAnn, TypeAnn, VarAnn, emptyAnnSet, fullAnnSet, noAnn,   pattern Annotation, singleAnnSet) import Morley.Util.Aeson+import Morley.Util.MismatchError  -- | Annotated Michelson type. -- We don't name it 'Type' to avoid conflicts with 'Data.Kind.Type'.@@ -70,6 +70,9 @@ instance RenderDoc Ty where   renderDoc pn (Ty t ta) = renderType t True pn (singleAnnSet ta) +instance RenderDoc (MismatchError Ty) where+  renderDoc ctx = renderDocDiff ctx . fmap Prettier+ instance RenderDoc T where   renderDoc pn t = renderType t True pn emptyAnnSet @@ -142,6 +145,8 @@     TChest            -> wrapInParens pn $ "chest" :| [annDoc]     TChestKey         -> wrapInParens pn $ "chest_key" :| [annDoc]     TNever            -> wrapInParens pn $ "never" :| [annDoc]+    TSaplingState n   -> addParens pn $ "sapling_state" <+> annDoc <+> (integer $ toInteger n)+    TSaplingTransaction n -> addParens pn $ "sapling_transaction" <+> annDoc <+> (integer $ toInteger n)      TOption (Ty t1 ta1) ->       addParens pn $@@ -215,6 +220,9 @@ instance Buildable Ty where   build = buildRenderDoc +instance Buildable (MismatchError Ty) where+  build = buildRenderDocExtended+ instance Buildable ParameterType where   build = buildRenderDoc @@ -249,6 +257,8 @@   | TAddress   | TChest   | TChestKey+  | TSaplingState Natural+  | TSaplingTransaction Natural   | TNever   deriving stock (Eq, Show, Data, Generic) 
src/Morley/Michelson/Untyped/Value.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Untyped Michelson values (i. e. type of a value is not statically known). 
src/Morley/Michelson/Untyped/View.hs view
@@ -1,12 +1,10 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Michelson view. module Morley.Michelson.Untyped.View   ( ViewName (.., ViewName)   , mkViewName-  , unsafeMkViewName   , BadViewNameError (..)   , isValidViewNameChar   , viewNameMaxLength@@ -19,8 +17,8 @@ import Control.Monad.Except (throwError) import Data.Aeson.TH (deriveJSON) import Data.Data (Data)-import qualified Data.Text as Text-import Fmt (Buildable(..), pretty, (+|), (|+))+import Data.Text qualified as Text+import Fmt (Buildable(..), (+|), (|+)) import Text.PrettyPrint.Leijen.Text (Doc, dquotes, textStrict)  import Morley.Michelson.Printer.Util@@ -77,10 +75,6 @@     throwError (BadViewIllegalChars txt)   return (UnsafeViewName txt) --- | Unsafe constructor for t'ViewName'.-unsafeMkViewName :: HasCallStack => Text -> ViewName-unsafeMkViewName = either (error . pretty) id . mkViewName- renderViewName :: ViewName -> Doc renderViewName = dquotes . textStrict . unViewName @@ -89,7 +83,7 @@  -- | Valid view names form a subset of valid Michelson texts. viewNameToMText :: ViewName -> MText-viewNameToMText = unsafeMkMText . unViewName+viewNameToMText = unsafe . mkMText . unViewName  -- | Untyped view in a contract. data View' op = View
src/Morley/Tezos/Address.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Address in Tezos. @@ -26,22 +25,19 @@   , parseContractHash   , parseAddress   , ta-  , unsafeParseAddressRaw-  , unsafeParseAddress-  , unsafeParseContractHash   ) where  import Data.Aeson (FromJSON(..), FromJSONKey, ToJSON(..), ToJSONKey)-import qualified Data.Aeson as Aeson-import qualified Data.Aeson.Encoding as Aeson-import qualified Data.Aeson.Types as AesonTypes-import qualified Data.ByteString as BS+import Data.Aeson qualified as Aeson+import Data.Aeson.Encoding qualified as Aeson+import Data.Aeson.Types qualified as AesonTypes+import Data.ByteString qualified as BS import Data.Text (strip) import Fmt (Buildable(build), hexF, pretty) import Instances.TH.Lift ()-import qualified Language.Haskell.TH.Quote as TH+import Language.Haskell.TH.Quote qualified as TH import Language.Haskell.TH.Syntax (Lift)-import qualified Language.Haskell.TH.Syntax as TH+import Language.Haskell.TH.Syntax qualified as TH import Text.PrettyPrint.Leijen.Text (backslash, dquotes, int, parens, (<+>))  import Morley.Michelson.Printer.Util (RenderDoc(..), buildRenderDoc, renderAnyBuildable)@@ -136,7 +132,7 @@     ContractAddress h -> formatContractHash h  mformatAddress :: Address -> MText-mformatAddress = unsafeMkMText . formatAddress+mformatAddress = unsafe . mkMText . formatAddress  instance Buildable Address where   build = build . formatAddress@@ -292,21 +288,6 @@ ---------------------------------------------------------------------------- -- Unsafe -------------------------------------------------------------------------------- | Parse a @KT1@ contract address, fail if address does not match--- the expected format.-unsafeParseContractHash :: HasCallStack => Text -> ContractHash-unsafeParseContractHash = either (error . pretty) id . parseContractHash---- | Partial version of 'parseAddress' which assumes that the address--- is correct. Can be used in tests.-unsafeParseAddress :: HasCallStack => Text -> Address-unsafeParseAddress = either (error . pretty) id . parseAddress---- | Partially parse raw bytes representation of an address and assume that--- it is correct from the beginning. Can be used in tests.-unsafeParseAddressRaw :: ByteString -> Address-unsafeParseAddressRaw = either (error . pretty) id . parseAddressRaw  instance HasCLReader Address where   getReader = eitherReader parseAddrDo
src/Morley/Tezos/Core.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Core primitive Tezos types. @@ -8,8 +7,8 @@   (     -- * Mutez     Mutez (..)+  , tz   , mkMutez-  , unsafeMkMutez   , toMutez   , addMutez   , unsafeAddMutez@@ -40,7 +39,6 @@     -- * ChainId   , ChainId (..)   , mkChainId-  , unsafeMkChainId   , dummyChainId   , formatChainId   , mformatChainId@@ -49,21 +47,25 @@   ) where  import Data.Aeson (FromJSON(..), ToJSON(..))-import qualified Data.Aeson as Aeson+import Data.Aeson qualified as Aeson import Data.Aeson.TH (deriveJSON)-import Data.Bits (Bits) import Data.Data (Data(..)) import Data.Scientific-import qualified Data.Text as T+  (FPFormat(Fixed), Scientific, floatingOrInteger, formatScientific, isFloating, scientificP,+  toBoundedInteger)+import Data.Text qualified as T import Data.Time.Clock (UTCTime) import Data.Time.Clock.POSIX (POSIXTime, getPOSIXTime, posixSecondsToUTCTime, utcTimeToPOSIXSeconds) import Data.Time.Format (defaultTimeLocale, parseTimeM) import Data.Time.LocalTime (utc, utcToZonedTime) import Data.Time.RFC3339 (formatTimeRFC3339) import Fmt (Buildable(build), fmt, hexF, pretty)-import qualified Language.Haskell.TH.Quote as TH+import Language.Haskell.TH qualified as TH+import Language.Haskell.TH.Quote qualified as TH import Language.Haskell.TH.Syntax (liftData)-import qualified Options.Applicative as Opt+import Options.Applicative qualified as Opt+import Text.ParserCombinators.ReadP (ReadP, eof, readP_to_S, skipSpaces, string, (+++))+import Unsafe qualified (unsafeM)  import Morley.Michelson.Text import Morley.Tezos.Crypto@@ -75,58 +77,166 @@ ----------------------------------------------------------------------------  -- | Mutez is a wrapper over integer data type. 1 mutez is 1 token (μTz).+--+-- The constructor is marked "Unsafe" since GHC does not warn on overflowing+-- literals (exceeding custom 'Word63' type bounds), thus the resultant+-- 'Mutez' value may get truncated silently.+--+-- >>> UnsafeMutez 9223372036854775809+-- UnsafeMutez {unMutez = 1} newtype Mutez = UnsafeMutez-  { unMutez :: Word64-  } deriving stock (Show, Eq, Ord, Data, Generic)-    deriving newtype Enum+  { unMutez :: Word63+  } deriving stock (Show, Eq, Ord, Generic)+    deriving newtype (Enum, Bounded)  instance Buildable Mutez where-  build (UnsafeMutez w) = build w <> " μꜩ"+  build (UnsafeMutez w) = show w <> " μꜩ" -instance Bounded Mutez where-  minBound = UnsafeMutez 0-  -- 2⁶³ - 1-  -- This value was checked against the reference implementation.-  maxBound = UnsafeMutez 9223372036854775807+instance NFData Mutez where+  rnf (UnsafeMutez !_) = ()  instance HasCLReader Mutez where   getReader = either (readerError . toString) pure . mkMutez @Word64 =<< Opt.auto   getMetavar = "MUTEZ" -instance NFData Mutez+{- | Quotes a 'Mutez' value. +The value is in XTZ, i.e. 1e6 'Mutez', with optional suffix representing+a unit:++* @k@, @kilo@ -- 1000 XTZ+* @M@, @Mega@, @mega@ -- 1000000 XTZ+* @m@, @milli@ -- 0.001 XTZ+* @u@, @μ@, @micro@ -- 0.000001 XTZ++This is the safest and recommended way to create 'Mutez' from a numeric literal.++The suffix can be separated from the number by whitespace.+You can also use underscores as a delimiter (those will be ignored), and+scientific notation, e.g. @123.456e6@. Note that if the scientific notation+represents a mutez fraction, that is a compile-time error.++>>> [tz|123|]+UnsafeMutez {unMutez = 123000000}++>>> [tz|123k|]+UnsafeMutez {unMutez = 123000000000}++>>> [tz|123 kilo|]+UnsafeMutez {unMutez = 123000000000}++>>> [tz|123M|]+UnsafeMutez {unMutez = 123000000000000}++>>> [tz|123 Mega|]+UnsafeMutez {unMutez = 123000000000000}++>>> [tz|123 mega|]+UnsafeMutez {unMutez = 123000000000000}++>>> [tz|123e6|]+UnsafeMutez {unMutez = 123000000000000}++>>> [tz|123m|]+UnsafeMutez {unMutez = 123000}++>>> [tz|123 milli|]+UnsafeMutez {unMutez = 123000}++>>> [tz|123u|]+UnsafeMutez {unMutez = 123}++>>> [tz|123μ|]+UnsafeMutez {unMutez = 123}++>>> [tz|123 micro|]+UnsafeMutez {unMutez = 123}++>>> [tz| 123.456_789 |]+UnsafeMutez {unMutez = 123456789}++>>> [tz|123.456u|]+...+... error:+...  • The number is a mutez fraction. The smallest possible subdivision is 0.000001 XTZ+...++>>> [tz|0.012_345_6|]+...+... error:+...  • The number is a mutez fraction. The smallest possible subdivision is 0.000001 XTZ+...++>>> [tz| 9223372.036854775807 M |]+UnsafeMutez {unMutez = 9223372036854775807}++>>> [tz| 9223372.036854775808 M |]+...+... error:+...  • The number is out of mutez bounds. It must be between 0 and 9223372036854.775807 XTZ (inclusive).+...++>>> [tz| -1 |]+...+... error:+...  • The number is out of mutez bounds. It must be between 0 and 9223372036854.775807 XTZ (inclusive).+...+-}+tz :: TH.QuasiQuoter+tz = TH.QuasiQuoter+  { quoteExp = \inp -> do+      val <- parseTez @Word64 inp+      [| UnsafeMutez val |]+  , quotePat = \inp -> do+      val <- parseTez @Integer inp+      [p| UnsafeMutez $(pure $ TH.LitP $ TH.IntegerL val) |]+  , quoteType = const $ fail "Cannot be used as type"+  , quoteDec = const $ fail "Cannot be used as dec"+  }+  where+    parseTez :: forall t m. (CheckIntSubType Word63 t, Integral t, MonadFail m) => String -> m t+    parseTez inp = fromIntegral <$>+      case readP_to_S (skipSpaces *> parser) $ filter (/='_') inp of+        [(val, "")] -> unsafeM . maybeToRight (oobErr val) $ toBoundedInteger @Word63 val+        _ -> fail "no parse"+    parser = (*) <$> (scientificP <* skipSpaces) <*> (unit <* skipSpaces) <* eof+    oobErr :: Scientific -> String+    oobErr val+      | isFloating val = "The number is a mutez fraction. \+          \The smallest possible subdivision is 0.000001 XTZ"+      | otherwise = "The number is out of mutez bounds. \+          \It must be between 0 and 9223372036854.775807 XTZ (inclusive)."+    unit :: ReadP Scientific+    unit = (string "M" +++ string "Mega" +++ string "mega" $> 1e12)+       +++ (string "k" +++ string "kilo" $> 1e9)+       +++ (string "m" +++ string "milli" $> 1e3)+       +++ (string "u" +++ string "μ" +++ string "micro" $> 1)+       +++ (pure 1e6)+ -- | Safely creates 'Mutez' checking for -- overflow and underflow. Accepts a number of any type.-mkMutez :: (Integral i, Bits i) => i -> Either Text Mutez-mkMutez i = case fromIntegralMaybe i of-  Just n | n <= unMutez maxBound -> Right (UnsafeMutez n)-  _ | i < 0 -> Left "Mutez underflow"-  _ -> Left "Mutez overflow"---- | Partial function for 'Mutez' creation, it's pre-condition is that--- the argument must not exceed bounds of the 'Mutez'.-unsafeMkMutez :: HasCallStack => Word64 -> Mutez-unsafeMkMutez n =-  either (error . ("mkMutez: " <>)) id $ mkMutez n-{-# INLINE unsafeMkMutez #-}+mkMutez :: Integral i => i -> Either Text Mutez+mkMutez = bimap (fromString . displayException) UnsafeMutez . fromIntegralNoOverflow  -- | Safely create 'Mutez'. ----- This is recommended way to create @Mutez@ from a numeric literal;--- you can't construct all valid @Mutez@ values using this function--- but for small values it works neat.+-- When constructing literals, you'll need to specify the type of the literal.+-- GHC will check for literal overflow on builtin types like 'Word16' and+-- 'Word32', but not on 'Word62' or 'Word63', so those can overflow silently. ----- Warnings displayed when trying to construct invalid 'Natural' or 'Word'--- literal are hardcoded for these types in GHC implementation, so we can only--- exploit these existing rules.-toMutez :: Word32 -> Mutez-toMutez = unsafeMkMutez . fromIntegral+-- It's recommended to use 'tz' quasiquote for literals instead.+toMutez :: (Integral a, CheckIntSubType a Word63) => a -> Mutez+toMutez = UnsafeMutez . fromIntegral {-# INLINE toMutez #-}  -- | Addition of 'Mutez' values. Returns 'Nothing' in case of overflow. addMutez :: Mutez -> Mutez -> Maybe Mutez addMutez (unMutez -> a) (unMutez -> b) =-  rightToMaybe $ mkMutez (a + b) -- (a + b) can't overflow if 'Mutez' values are valid+  rightToMaybe $ mkMutez @Word64 $+    -- NB: plain @a + b@ might overflow and+    -- thus we widen the operands (and the sum)+    -- to 'Word64'+    fromIntegral a + fromIntegral b {-# INLINE addMutez #-}  -- | Partial addition of 'Mutez', should be used only if you're@@ -163,7 +273,7 @@ unsafeMulMutez = fromMaybe (error "unsafeMulMutez: overflow") ... mulMutez  -- | Euclidian division of two 'Mutez' values.-divModMutez :: Mutez -> Mutez -> Maybe (Word64, Mutez)+divModMutez :: Mutez -> Mutez -> Maybe (Word63, Mutez) divModMutez a (unMutez -> b) = first unMutez <$> divModMutezInt a b  -- | Euclidian division of  'Mutez' and a number.@@ -182,10 +292,10 @@ oneMutez = UnsafeMutez 1  -- |--- >>> putTextLn $ prettyTez (toMutez 420)+-- >>> putTextLn $ prettyTez [tz|420u|] -- 0.00042 ꜩ ----- >>> putTextLn $ prettyTez (toMutez 42000000)+-- >>> putTextLn $ prettyTez [tz|42|] -- 42 ꜩ prettyTez :: Mutez -> Text prettyTez ((/ 1000000) . fromIntegralToRealFrac . unMutez -> s) =@@ -306,14 +416,11 @@ instance NFData ChainId  -- | Construct chain ID from raw bytes.-mkChainId :: ByteString -> Maybe ChainId+mkChainId :: ByteString -> Either ParseChainIdError ChainId mkChainId bs =-  guard (length bs == chainIdLength) $> UnsafeChainId bs---- | Construct chain ID from raw bytes or fail otherwise.--- Expects exactly 4 bytes.-unsafeMkChainId :: HasCallStack => ByteString -> ChainId-unsafeMkChainId = fromMaybe (error "Bad chain id") . mkChainId+  if length bs == chainIdLength+  then Right $ UnsafeChainId bs+  else Left . ParseChainIdWrongSize $ length bs  -- | Identifier of a pseudo network. dummyChainId :: ChainId@@ -327,7 +434,7 @@ formatChainId (unChainId -> bs) = encodeBase58Check (chainIdPrefix <> bs)  mformatChainId :: ChainId -> MText-mformatChainId = unsafeMkMText . formatChainId+mformatChainId = unsafe . mkMText . formatChainId  instance Buildable ChainId where   build = build . formatChainId@@ -358,9 +465,7 @@       Left (ParseChainIdWrongTag prefix)     Left B58CheckWithPrefixWrongEncoding ->       Left ParseChainIdWrongBase58Check-    Right bs -> case mkChainId bs of-      Just ci -> Right ci-      Nothing -> Left $ ParseChainIdWrongSize (length bs)+    Right bs -> mkChainId bs  chainIdLength :: Int chainIdLength = 4@@ -374,7 +479,14 @@ -- JSON ---------------------------------------------------------------------------- -deriveJSON morleyAesonOptions ''Mutez+instance FromJSON Mutez where+  parseJSON v = do+    i <- parseJSON @Int64 v+    Unsafe.unsafeM $ mkMutez i++instance ToJSON Mutez where+  toJSON (UnsafeMutez a) = toJSON $ fromIntegral @Word63 @Word64 a+ deriveJSON morleyAesonOptions ''Timestamp  instance ToJSON ChainId where
src/Morley/Tezos/Crypto.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Cryptographic primitives used in Tezos. --@@ -69,7 +68,6 @@   , formatKeyHash   , mformatKeyHash   , parseKeyHash-  , unsafeParseKeyHash   , parseKeyHashRaw   , keyHashLengthBytes   , formatSecretKey@@ -91,7 +89,7 @@   , TLTime(..)   , openChest   , mkTLTime-  , unsafeMkTLTime+  , toTLTime    -- * Utilities   , encodeBase58Check@@ -104,26 +102,26 @@  import Crypto.Random (MonadRandom) import Data.Aeson (FromJSON(..), FromJSONKey, ToJSON(..), ToJSONKey)-import qualified Data.Aeson as Aeson-import qualified Data.Aeson.Encoding as Aeson-import qualified Data.Aeson.Types as AesonTypes-import qualified Data.Binary.Get as Get-import qualified Data.ByteArray as BA-import qualified Data.ByteString as BS-import qualified Data.ByteString.Lazy as LBS-import qualified Data.Text as T+import Data.Aeson qualified as Aeson+import Data.Aeson.Encoding qualified as Aeson+import Data.Aeson.Types qualified as AesonTypes+import Data.Binary.Get qualified as Get+import Data.ByteArray qualified as BA+import Data.ByteString qualified as BS+import Data.ByteString.Lazy qualified as LBS+import Data.Text qualified as T import Fmt (Buildable, build, hexF, pretty) import Instances.TH.Lift () import Language.Haskell.TH.Syntax (Lift)  import Morley.Michelson.Text-import qualified Morley.Tezos.Crypto.BLS12381 as BLS12381-import qualified Morley.Tezos.Crypto.Ed25519 as Ed25519+import Morley.Tezos.Crypto.BLS12381 qualified as BLS12381+import Morley.Tezos.Crypto.Ed25519 qualified as Ed25519 import Morley.Tezos.Crypto.Hash-import qualified Morley.Tezos.Crypto.P256 as P256-import qualified Morley.Tezos.Crypto.Secp256k1 as Secp256k1+import Morley.Tezos.Crypto.P256 qualified as P256+import Morley.Tezos.Crypto.Secp256k1 qualified as Secp256k1 import Morley.Tezos.Crypto.Timelock-  (Chest, ChestKey, OpeningResult(..), TLTime(..), mkTLTime, openChest, unsafeMkTLTime)+  (Chest, ChestKey, OpeningResult(..), TLTime(..), mkTLTime, openChest, toTLTime) import Morley.Tezos.Crypto.Util import Morley.Util.Binary import Morley.Util.CLI@@ -328,7 +326,7 @@   PublicKeyP256 pk -> P256.formatPublicKey pk  mformatPublicKey :: PublicKey -> MText-mformatPublicKey = unsafeMkMText . formatPublicKey+mformatPublicKey = unsafe . mkMText . formatPublicKey  instance Buildable PublicKey where   build = build . formatPublicKey@@ -355,7 +353,7 @@   SignatureGeneric sig -> formatImpl genericSignatureTag sig  mformatSignature :: Signature -> MText-mformatSignature = unsafeMkMText . formatSignature+mformatSignature = unsafe . mkMText . formatSignature  instance Buildable Signature where   build = build . formatSignature@@ -482,7 +480,7 @@ formatKeyHash (KeyHash tag bytes) = formatImpl (keyHashTagBytes tag) bytes  mformatKeyHash :: KeyHash -> MText-mformatKeyHash = unsafeMkMText . formatKeyHash+mformatKeyHash = unsafe . mkMText . formatKeyHash  instance Buildable KeyHash where   build = build . formatKeyHash@@ -499,9 +497,6 @@     parse tag = mkKeyHash tag =<< parseImpl (keyHashTagBytes tag) pure txt    in firstRight $ map parse $ minBound :| [succ minBound ..]--unsafeParseKeyHash :: HasCallStack => Text -> KeyHash-unsafeParseKeyHash = either (error . pretty) id . parseKeyHash  parseKeyHashRaw :: ByteString -> Either CryptoParseError KeyHash parseKeyHashRaw ba =
src/Morley/Tezos/Crypto/BLS12381.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Support for BLS12-381 elliptic curve. --@@ -13,7 +12,6 @@   , Bls12381G1   , Bls12381G2   , CurveObject (..)-  , unsafeFromMichelsonBytes   , MultiplyPoint (..)   , DeserializationError (..)   , checkPairing@@ -26,24 +24,24 @@   ) where  import Prelude hiding (negate, one)-import qualified Prelude+import Prelude qualified+import Unsafe qualified (fromIntegral)  import Control.Exception (assert) import Control.Lens (each, toListOf) import Control.Monad.Random (MonadRandom, evalRand, getRandom, mkStdGen) import Data.Bits (bit, complement, setBit, testBit, (.&.))-import qualified Data.ByteString as BS-import qualified Data.Curve as C-import qualified Data.Curve.Weierstrass as CW-import qualified Data.Curve.Weierstrass.BLS12381 as CW.BLS-import qualified Data.Field.Galois as GF-import qualified Data.Pairing.BLS12381 as BLS-import Fmt (Buildable(..), pretty)+import Data.ByteString qualified as BS+import Data.Curve qualified as C+import Data.Curve.Weierstrass qualified as CW+import Data.Curve.Weierstrass.BLS12381 qualified as CW.BLS+import Data.Field.Galois qualified as GF+import Data.Pairing.BLS12381 qualified as BLS+import Fmt (Buildable(..)) import Morley.Util.Instances () import Morley.Util.Named import Text.Hex (decodeHex, encodeHex) import Text.PrettyPrint.Leijen.Text (int, integer, (<+>))-import qualified Unsafe (fromIntegral)  import Morley.Michelson.Printer.Util (RenderDoc(..), buildRenderDoc, renderAnyBuildable) @@ -74,17 +72,13 @@ generateFrom :: (CurveObject a) => Int -> a generateFrom = evalRand generate . mkStdGen --- | Read a value from Michelson's bytes form assuming that it is correct.-unsafeFromMichelsonBytes :: (CurveObject a, HasCallStack) => ByteString -> a-unsafeFromMichelsonBytes = either (error . pretty) id . fromMichelsonBytes- -- | Reads an object from hex string. -- -- To be used only in playground and tests. unsafeReadFromHex :: (CurveObject a, HasCallStack) => String -> a unsafeReadFromHex hex =   let bs = decodeHex (toText hex) ?: error "bad hex"-  in unsafeFromMichelsonBytes bs+  in unsafe $ fromMichelsonBytes bs  -- | Multiplication operations on BLS12-381 objects. class MultiplyPoint scalar point where@@ -196,10 +190,10 @@   renderDoc _ = \case     CompressedFormIsNotSupported ->       "Compressed form of BLS12-381 point is not supported by Tezos"-    UnexpectedLength (N expected) (N given) ->+    UnexpectedLength (arg #expected -> expected) (arg #given -> given) ->       "Unexpected length of BLS12-381 primitive: \       \expected" <+> (int expected) <> ", but given" <+> (int given)-    TooLargeLength (N limit) (N given) ->+    TooLargeLength (arg #limit -> limit) (arg #given -> given) ->       "Too large length of BLS12-381 primitive: \       \limit is" <+> (int limit) <+> ", but given" <+> (int given)     ValueOutsideOfField v ->
src/Morley/Tezos/Crypto/Ed25519.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Ed25519 cryptographic primitives. @@ -10,6 +9,7 @@   , SecretKey   , Signature (..)   , detSecretKey+  , randomSecretKey   , toPublic    -- * Raw bytes (no checksums, tags or anything)@@ -36,7 +36,8 @@   ) where  import Crypto.Error (onCryptoFailure)-import qualified Crypto.PubKey.Ed25519 as Ed25519+import Crypto.PubKey.Ed25519 qualified as Ed25519+import Crypto.Random (MonadRandom(getRandomBytes)) import Data.ByteArray (ByteArray, ByteArrayAccess, convert) import Fmt (Buildable, build) @@ -69,6 +70,10 @@ detSecretKey :: ByteString -> SecretKey detSecretKey seed = SecretKey $ deterministic seed Ed25519.generateSecretKey +-- | Generate a random secret key.+randomSecretKey :: MonadRandom m => m SecretKey+randomSecretKey = detSecretKey <$> getRandomBytes 32+ -- | Create a public key from a secret key. toPublic :: SecretKey -> PublicKey toPublic = PublicKey . Ed25519.toPublic . unSecretKey@@ -94,7 +99,7 @@   onCryptoFailure (Left . CryptoParseCryptoError) (Right . PublicKey) .   Ed25519.publicKey -publicKeyLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n+publicKeyLengthBytes :: (Integral n, CheckIntSubType Int n) => n publicKeyLengthBytes = fromIntegral Ed25519.publicKeySize  -- | Convert a 'Signature' to raw bytes.@@ -107,7 +112,7 @@   onCryptoFailure (Left . CryptoParseCryptoError) (Right . Signature) .   Ed25519.signature -signatureLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n+signatureLengthBytes :: (Integral n, CheckIntSubType Int n) => n signatureLengthBytes = fromIntegral Ed25519.signatureSize  mkSecretKey :: ByteArrayAccess ba => ba -> Either CryptoParseError SecretKey@@ -135,7 +140,7 @@ formatPublicKey = formatImpl publicKeyTag . unPublicKey  mformatPublicKey :: PublicKey -> MText-mformatPublicKey = unsafeMkMText . formatPublicKey+mformatPublicKey = unsafe . mkMText . formatPublicKey  instance Buildable PublicKey where   build = build . formatPublicKey@@ -156,7 +161,7 @@ formatSignature = formatImpl signatureTag . unSignature  mformatSignature :: Signature -> MText-mformatSignature = unsafeMkMText . formatSignature+mformatSignature = unsafe . mkMText . formatSignature  instance Buildable Signature where   build = build . formatSignature
src/Morley/Tezos/Crypto/Hash.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Cryptographic primitives related to hashing. @@ -14,7 +13,7 @@   ) where  import Crypto.Hash (Blake2b_160, Blake2b_256, Digest, Keccak_256, SHA256, SHA3_256, SHA512, hash)-import qualified Data.ByteArray as ByteArray+import Data.ByteArray qualified as ByteArray  -- | Compute a cryptographic hash of a bytestring using the -- Blake2b_256 cryptographic hash function. It's used by the BLAKE2B
src/Morley/Tezos/Crypto/P256.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | P256 cryptographic primitives. @@ -37,8 +36,8 @@   ) where  import Crypto.Hash (Blake2b_256(..))-import qualified Crypto.PubKey.ECC.ECDSA as ECDSA-import qualified Crypto.PubKey.ECC.Generate as ECC.Generate+import Crypto.PubKey.ECC.ECDSA qualified as ECDSA+import Crypto.PubKey.ECC.Generate qualified as ECC.Generate import Crypto.PubKey.ECC.Types (Curve(..), CurveName(..), getCurveByName) import Crypto.Random (MonadRandom) import Data.ByteArray (ByteArray, ByteArrayAccess)@@ -112,7 +111,7 @@ mkPublicKey :: ByteArrayAccess ba => ba -> Either CryptoParseError PublicKey mkPublicKey ba = PublicKey <$> mkPublicKey_ curve ba -publicKeyLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n+publicKeyLengthBytes :: (Integral n, CheckIntSubType Int n) => n publicKeyLengthBytes = publicKeyLengthBytes_ curve  -- | Convert a 'PublicKey' to raw bytes.@@ -124,7 +123,7 @@ mkSignature :: ByteArray ba => ba -> Either CryptoParseError Signature mkSignature ba = Signature <$> mkSignature_ curve ba -signatureLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n+signatureLengthBytes :: (Integral n, CheckIntSubType Int n) => n signatureLengthBytes = signatureLengthBytes_ curve  mkSecretKey :: ByteArray ba => ba -> Either CryptoParseError SecretKey@@ -157,7 +156,7 @@ formatPublicKey = formatImpl @ByteString publicKeyTag . publicKeyToBytes  mformatPublicKey :: PublicKey -> MText-mformatPublicKey = unsafeMkMText . formatPublicKey+mformatPublicKey = unsafe . mkMText . formatPublicKey  instance Buildable PublicKey where   build = build . formatPublicKey@@ -169,7 +168,7 @@ formatSignature = formatImpl @ByteString signatureTag . signatureToBytes  mformatSignature :: Signature -> MText-mformatSignature = unsafeMkMText . formatSignature+mformatSignature = unsafe . mkMText . formatSignature  instance Buildable Signature where   build = build . formatSignature
src/Morley/Tezos/Crypto/Secp256k1.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Secp256k1 cryptographic primitives. @@ -37,8 +36,8 @@   ) where  import Crypto.Hash (Blake2b_256(..))-import qualified Crypto.PubKey.ECC.ECDSA as ECDSA-import qualified Crypto.PubKey.ECC.Generate as ECC.Generate+import Crypto.PubKey.ECC.ECDSA qualified as ECDSA+import Crypto.PubKey.ECC.Generate qualified as ECC.Generate import Crypto.PubKey.ECC.Types (Curve(..), CurveName(..), getCurveByName) import Crypto.Random (MonadRandom) import Data.ByteArray (ByteArray, ByteArrayAccess)@@ -112,7 +111,7 @@ mkPublicKey :: ByteArrayAccess ba => ba -> Either CryptoParseError PublicKey mkPublicKey ba = PublicKey <$> mkPublicKey_ curve ba -publicKeyLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n+publicKeyLengthBytes :: (Integral n, CheckIntSubType Int n) => n publicKeyLengthBytes = publicKeyLengthBytes_ curve  -- | Convert a 'PublicKey' to raw bytes.@@ -124,7 +123,7 @@ mkSignature :: ByteArray ba => ba -> Either CryptoParseError Signature mkSignature ba = Signature <$> mkSignature_ curve ba -signatureLengthBytes :: (Integral n, IsIntSubType Int n ~ 'True) => n+signatureLengthBytes :: (Integral n, CheckIntSubType Int n) => n signatureLengthBytes = signatureLengthBytes_ curve  mkSecretKey :: ByteArray ba => ba -> Either CryptoParseError SecretKey@@ -157,7 +156,7 @@ formatPublicKey = formatImpl @ByteString publicKeyTag . publicKeyToBytes  mformatPublicKey :: PublicKey -> MText-mformatPublicKey = unsafeMkMText . formatPublicKey+mformatPublicKey = unsafe . mkMText . formatPublicKey  instance Buildable PublicKey where   build = build . formatPublicKey@@ -169,7 +168,7 @@ formatSignature = formatImpl @ByteString signatureTag . signatureToBytes  mformatSignature :: Signature -> MText-mformatSignature = unsafeMkMText . formatSignature+mformatSignature = unsafe . mkMText . formatSignature  instance Buildable Signature where   build = build . formatSignature
src/Morley/Tezos/Crypto/Timelock.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {- | Timelock puzzle algorithms implementation. @@ -44,7 +43,7 @@   , chestKeyFromBytes   , openChest   , mkTLTime-  , unsafeMkTLTime+  , toTLTime   -- * Internal, not safe for cryptography   , createChestAndChestKeyFromSeed   ) where@@ -53,20 +52,20 @@ import Crypto.Number.ModArithmetic (expFast) import Crypto.Number.Prime (findPrimeFrom) import Crypto.Number.Serialize.LE (i2osp, os2ip)-import qualified Crypto.Sodium.Encrypt.Symmetric as Box (Key, Nonce, decrypt, encrypt)+import Crypto.Sodium.Encrypt.Symmetric qualified as Box (Key, Nonce, decrypt, encrypt) import Crypto.Sodium.Hash (blake2bWithKey)-import qualified Crypto.Sodium.Nonce as Nonce (generate)-import qualified Crypto.Sodium.Random as Random (generate)-import qualified Data.Binary as Bi (Binary(..), decodeOrFail, encode)-import qualified Data.Binary.Get as Bi (getByteString)-import qualified Data.Binary.Put as Bi (putBuilder)-import Data.Bits (Bits, shiftL)+import Crypto.Sodium.Nonce qualified as Nonce (generate)+import Crypto.Sodium.Random qualified as Random (generate)+import Data.Binary qualified as Bi (Binary(..), decodeOrFail, encode)+import Data.Binary.Get qualified as Bi (getByteString)+import Data.Binary.Put qualified as Bi (putBuilder)+import Data.Bits (shiftL) import Data.ByteArray.Sized (SizedByteArray, sizedByteArray, unSizedByteArray)-import qualified Data.ByteString as BS (intercalate, length, replicate)-import qualified Data.ByteString.Lazy as LBS (fromStrict, toStrict)+import Data.ByteString qualified as BS (intercalate, length, replicate)+import Data.ByteString.Lazy qualified as LBS (fromStrict, toStrict) import Fmt (Buildable(..)) import GHC.TypeNats (Div, type (+))-import qualified Options.Applicative as Opt+import Options.Applicative qualified as Opt  import Morley.Micheline.Binary.Internal import Morley.Util.CLI@@ -142,43 +141,50 @@ -- i.e. modulo factorization. -- -- The reference implementation uses OCaml @int@, and it can only be positive,--- so on 64-bit architecture it's actually a 62-bit natural. We use 'Word64'+-- so on 64-bit architecture it's actually a 62-bit natural. We use 'Word62' -- to represent it.-newtype TLTime = UnsafeTLTime { unTLTime :: Word64 }+--+-- The constructor is marked "Unsafe" since GHC does not warn on overflowing+-- literals (exceeding custom 'Word62' type bounds), thus the resultant+-- t'TLTime' value may get truncated silently.+--+-- >>> UnsafeTLTime 4611686018427387906+-- UnsafeTLTime {unTLTime = 2}+newtype TLTime = UnsafeTLTime { unTLTime :: Word62 }   deriving stock (Show, Eq)-  deriving newtype Num+  deriving newtype Bounded -pattern TLTime :: Word64 -> TLTime+pattern TLTime :: Word62 -> TLTime pattern TLTime x <- UnsafeTLTime x {-# COMPLETE TLTime #-} -instance Bounded TLTime where-  minBound = UnsafeTLTime 0-  -- 2⁶² - 1-  -- This value was checked against the reference implementation.-  maxBound = UnsafeTLTime 4611686018427387903- instance HasCLReader TLTime where   getReader = either (readerError . toString) pure . mkTLTime @Word64 =<< Opt.auto   getMetavar = "TIME"  instance Buildable TLTime where-  build = build . unTLTime+  build = show . unTLTime  -- | Safely creates t'TLTime' checking for -- overflow and underflow. Accepts a number of any type.-mkTLTime :: (Integral i, Bits i) => i -> Either Text TLTime-mkTLTime i = case fromIntegralMaybe i of-  Just n | n <= unTLTime maxBound -> Right (UnsafeTLTime n)-  _ | i < 0 -> Left "TLTime underflow"-  _ -> Left "TLTime overflow"+mkTLTime :: Integral i => i -> Either Text TLTime+mkTLTime = bimap (fromString . displayException) UnsafeTLTime . fromIntegralNoOverflow --- | Partial function for t'TLTime' creation, it's pre-condition is that--- the argument must not exceed bounds of the t'TLTime'.-unsafeMkTLTime :: HasCallStack => Word64 -> TLTime-unsafeMkTLTime n =-  either (error . ("unsafeMkTLTime: " <>)) id $ mkTLTime n-{-# INLINE unsafeMkTLTime #-}+-- | Safely creates t'TLTime'.+--+-- This is the recommended way to create t'TLTime' values.+--+-- When constructing literals, you'll need to specify the type of the literal.+-- Bear in mind that GHC will check for literal overflow on builtin types like+-- 'Word16' and 'Word32', but not on 'Word62', so be aware that 'toTLTime' from+-- 'Word62' will overflow silently. Prefer using builtin types when possible.+--+-- >>> unTLTime $ toTLTime (4611686018427387903 :: Word62)+-- 4611686018427387903+-- >>> unTLTime $ toTLTime (4611686018427387904 :: Word62)+-- 0+toTLTime :: (Integral a, CheckIntSubType a Word62) => a -> TLTime+toTLTime = UnsafeTLTime . fromIntegral  -- | A nonce for symmetric encryption. newtype Nonce = Nonce { unNonce :: Box.Nonce ByteString }
src/Morley/Tezos/Crypto/Util.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Utilities shared by multiple cryptographic primitives. @@ -27,19 +26,21 @@   , signatureLengthBytes_   ) where +import Debug qualified (show)+ import Crypto.Error (CryptoError) import Crypto.Number.ModArithmetic (squareRoot) import Crypto.Number.Serialize (i2ospOf_, os2ip)-import qualified Crypto.PubKey.ECC.ECDSA as ECDSA-import qualified Crypto.PubKey.ECC.Generate as ECC.Generate+import Crypto.PubKey.ECC.ECDSA qualified as ECDSA+import Crypto.PubKey.ECC.Generate qualified as ECC.Generate import Crypto.PubKey.ECC.Types   (Curve(..), CurveCommon(..), CurvePrime(..), Point(..), curveSizeBits) import Crypto.Random (ChaChaDRG, MonadPseudoRandom, drgNewSeed, seedFromInteger, withDRG)-import qualified Data.Binary.Get as Get-import qualified Data.ByteArray as BA-import qualified Data.ByteString as BS-import qualified Data.ByteString.Base58 as Base58-import qualified Data.ByteString.Lazy as LBS+import Data.Binary.Get qualified as Get+import Data.ByteArray qualified as BA+import Data.ByteString qualified as BS+import Data.ByteString.Base58 qualified as Base58+import Data.ByteString.Lazy qualified as LBS import Fmt (Buildable, Builder, build, hexF) import Text.PrettyPrint.Leijen.Text (int, textStrict, (<+>)) @@ -58,7 +59,7 @@   deriving stock (Show, Eq)  instance NFData CryptoParseError where-  rnf = rnf @String . show+  rnf = rnf @String . Debug.show  instance Buildable CryptoParseError where   build = buildRenderDocExtended@@ -161,13 +162,13 @@ curveSizeBytes :: Curve -> Int curveSizeBytes curve = curveSizeBits curve `div` 8 -signatureLengthBytes_ :: (Integral n, IsIntSubType Int n ~ 'True) => Curve -> n+signatureLengthBytes_ :: (Integral n, CheckIntSubType Int n) => Curve -> n signatureLengthBytes_ curve = fromIntegral $ 2 * (curveSizeBytes curve)  coordToBytes :: BA.ByteArray ba => Curve -> Integer -> ba coordToBytes curve = i2ospOf_ (curveSizeBytes curve) -publicKeyLengthBytes_ :: (Integral n, IsIntSubType Int n ~ 'True) => Curve -> n+publicKeyLengthBytes_ :: (Integral n, CheckIntSubType Int n) => Curve -> n publicKeyLengthBytes_ curve = fromIntegral $ 1 + (curveSizeBytes curve)  -- | Make a 'ECDSA.PublicKey' from raw bytes.
src/Morley/Util/Aeson.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Utilities related to the @aeson@ package. 
src/Morley/Util/Binary.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | This module contains helper functions to deal with encoding -- and decoding of binary data.@@ -20,11 +19,11 @@ import Prelude hiding (EQ, Ordering(..), get)  import Data.Binary (Get)-import qualified Data.Binary.Get as Get-import qualified Data.ByteString as BS-import qualified Data.ByteString.Lazy as LBS-import qualified Data.List as List-import Fmt (Buildable, build, fmt, hexF, pretty, (+|), (+||), (|+), (||+))+import Data.Binary.Get qualified as Get+import Data.ByteString qualified as BS+import Data.ByteString.Lazy qualified as LBS+import Data.List qualified as List+import Fmt (Buildable, build, fmt, hexF, pretty, (+|), (|+)) import Text.Hex (encodeHex)  ----------------------------------------------------------------------------@@ -46,8 +45,8 @@   unlessM Get.isEmpty $ do     remainder <- Get.getRemainingLazyByteString     fail $ "Expected end of entry, unconsumed bytes \-           \(" +| length remainder |+ "): "-           +|| encodeHex (LBS.toStrict remainder) ||+ ""+           \(" +| length remainder |+ "): \""+           +| encodeHex (LBS.toStrict remainder) |+ "\""  launchGet :: Get a -> LByteString -> Either UnpackError a launchGet decoder bs =
src/Morley/Util/ByteString.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Util.ByteString   ( HexJSONByteString(..)
src/Morley/Util/CLI.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Utilities for command line options parsing -- (we use @optparse-applicative@).@@ -35,7 +34,7 @@ import GHC.TypeLits (KnownSymbol, Symbol, symbolVal) import Options.Applicative   (eitherReader, help, long, metavar, option, readerError, showDefaultWith, strOption, value)-import qualified Options.Applicative as Opt+import Options.Applicative qualified as Opt  import Morley.Util.Instances () import Morley.Util.Named@@ -169,7 +168,7 @@   -> "help" :! String   -> [Opt.Mod Opt.OptionFields a]   -> Opt.Parser a-mkCLOptionParserExt defValue (N name) (N hInfo) mods =+mkCLOptionParserExt defValue (arg #name -> name) (arg #help -> hInfo) mods =   option getReader $ mconcat $     metavar (getMetavar @a) :     long name :@@ -192,7 +191,7 @@   -> "help" :! String   -> [Opt.Mod Opt.ArgumentFields a]   -> Opt.Parser a-mkCLArgumentParserExt defValue (N hInfo) mods =+mkCLArgumentParserExt defValue (arg #help -> hInfo) mods =   Opt.argument getReader $ mconcat $     metavar (getMetavar @a) :     help hInfo :@@ -217,12 +216,12 @@   -> String   -> Opt.Parser (name :! a) namedParser defValue hInfo =-  option ((Name @name) <:!> getReader) $+  option (fromLabel @name <:!> getReader) $     mconcat     [ long (toString . toSpinal . toText $ name)     , metavar (getMetavar @a)     , help hInfo-    , maybeAddDefault pretty (Name @name <:!> defValue)+    , maybeAddDefault pretty (fromLabel @name <:!> defValue)     ]   where     name = symbolVal (Proxy @name)
src/Morley/Util/CustomGeneric.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA -- -- | Generic deriving with unbalanced trees. @@ -28,22 +27,25 @@      -- * Helpers   , fromDepthsStrategy+  , fromDepthsStrategy'      -- * Internals   , reifyDataType   , deriveFullType   , customGeneric'+  , makeRightBalDepths   ) where  import Prelude hiding (Type)  import Control.Lens (traversed)-import qualified GHC.Generics as G+import Fmt (pretty)+import GHC.Generics qualified as G import Generics.Deriving.TH (makeRep0Inline) import Language.Haskell.TH import Morley.Util.Generic (mkGenericTree) import Morley.Util.TH (lookupTypeNameOrFail)-import qualified Unsafe (fromIntegral)+import Unsafe qualified (fromIntegral)  ---------------------------------------------------------------------------- -- Simple type synonyms@@ -234,9 +236,15 @@ -- * @length (f n) ≡ n@ -- * @sum $ (\x -> 2 ^^ (-x)) \<$\> f n ≡ 1@ (unless @n = 0@) fromDepthsStrategy :: (Int -> [Natural]) -> GenericStrategy-fromDepthsStrategy dStrategy = simpleGenericStrategy $ \cShapes -> return $-  zip (dStrategy $ length cShapes) $ map (dStrategy . view _2) cShapes+fromDepthsStrategy = join fromDepthsStrategy' +-- | Like 'fromDepthsStrategy', but allows specifying different strategies for+-- constructors and fields.+fromDepthsStrategy' :: (Int -> [Natural]) -> (Int -> [Natural]) -> GenericStrategy+fromDepthsStrategy' dCtorStrategy dFieldStrategy =+  simpleGenericStrategy $ \cShapes -> return $+    zip (dCtorStrategy $ length cShapes) $ map (dFieldStrategy . view _2) cShapes+ makeRightBalDepths :: Int -> [Natural] makeRightBalDepths n = foldr (const addRightBalDepth) [] [1..n]   where@@ -412,7 +420,7 @@       return (typeName', decCxt, mKind, vars, [constr])     _ -> fail $       "Only plain datatypes are supported for derivation, but '" <>-      show typeName <> "' instead reifies to:\n" <> show typeInfo+      show typeName <> "' instead reifies to:\n" <> show (ppr typeInfo)  -- | Derives, as well as possible, a type definition from its name, its kind -- (where known) and its variables.@@ -433,7 +441,7 @@   NormalC name lst -> return (name, length lst, Nothing)   RecC name lst    -> return (name, length lst, Just $ lst ^.. traversed . _1)   InfixC _ name _  -> return (name, 2, Nothing)-  constr           -> fail $ "Unsupported constructor: " <> show constr+  constr           -> fail $ "Unsupported constructor: " <> show (ppr constr)  -- | Combines depths with constructors, 'fail'ing in case of mismatches, and -- generates 'Name's for the constructors' arguments.@@ -501,7 +509,7 @@           _ -> []   return (meta, collectLeafsTypes nodes) dismantleGenericTree _ x = fail $-  "Unexpected lack of Generic Metadata: " <> show x+  "Unexpected lack of Generic Metadata: " <> show (ppr x)  -- | Create the unbalanced 'G.from' fuction declaration for a type starting from -- its list of weighted constructors.@@ -561,7 +569,7 @@     "Resulting unbalanced tree has a single root, but of depth " <> show n <>     " instead of 0. Check your depths definitions."   _ -> fail $-    "Cannot create a tree from nodes of depths: " <> show (map fst lst) <>+    "Cannot create a tree from nodes of depths: " <> pretty (map (show @Text . fst) lst) <>     ". Check your depths definitions."   where     unbalancedFoldRec :: [(Natural, a)] -> Q [(Natural, a)]
src/Morley/Util/Default.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Util.Default   ( permute2Def , permute3Def
src/Morley/Util/Exception.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Util.Exception   ( -- * General simple helpers
src/Morley/Util/Fcf.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Util.Fcf   ( Over2@@ -11,7 +10,7 @@   ) where  import Data.Singletons.Prelude.Eq (DefaultEq)-import Fcf+import Fcf (type Eval, type Exp, type LiftM2)  data Over2 :: (a -> b -> Exp r) -> (x -> Exp a) -> (x -> Exp b) -> x -> Exp r type instance Eval (Over2 f g h x) = Eval (LiftM2 f (g x) (h x))@@ -20,7 +19,7 @@ type instance Eval ('Nothing <|> m) = m type instance Eval ('Just x <|> _) = 'Just x --- | Similar to 'TyEq', but compares types via @DefaultEq@ used in singletons+-- | Similar to 'Fcf.TyEq', but compares types via @DefaultEq@ used in singletons -- comparisons (see "Data.Singletons.Prelude.Eq" module). data TyEqSing :: a -> b -> Exp Bool type instance Eval (TyEqSing a b) = DefaultEq a b
src/Morley/Util/Generic.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Generic-related utils. module Morley.Util.Generic@@ -11,10 +10,10 @@   ) where  import Control.Exception (assert)-import qualified Data.Vector as V-import qualified GHC.Generics as G+import Data.Vector qualified as V+import GHC.Generics qualified as G import GHC.TypeLits (Symbol)-import qualified Unsafe (fromIntegral)+import Unsafe qualified (fromIntegral)  -- | Rebuild a list into a binary tree of exactly the same form which -- "Data.Generics" uses to represent datatypes.
src/Morley/Util/Instances.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-orphans #-} 
src/Morley/Util/Interpolate.hs view
@@ -1,14 +1,13 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {- | String interpolation quasi-quoters. The most basic version is 'i', it returns anything that-has a 'Fmt.FromBuilder' instance: 'Text', 'ByteString', 'String', 'Builder'.+has a 'Fmt.FromBuilder' instance: 'Text', 'ByteString', 'String', @Builder@. -In some cases, it is more convenient to return a lazy @Text@ 'Builder', in that case 'ib', which+In some cases, it is more convenient to return a lazy @Text@ @Builder@, in that case 'ib', which returns a non-polymorphic result, can be helpful, for instance, if you want to use one interpolated-string inside another one. Using 'Builder' is also more efficient in this case.+string inside another one. Using @Builder@ is also more efficient in this case.  >>> let splice = [i|some text|] >>> [i|larger text with #{splice}|] :: Text@@ -26,7 +25,7 @@ those that remove whitespace-only lines from beginning and end of the quote.  The mnemonic is @i@nterpolate @t@rimming @u@nindenting returning @b@uilder, i.e. 'itub' is-the trimming, unindenting version returning 'Builder'.+the trimming, unindenting version returning @Builder@.  Versions not interpreting Haskell escape sequences additionally start with @l@, e.g. 'litu' is @l@iteral @i@nterpolation @t@trimming @u@nindenting.@@ -38,10 +37,10 @@ \955\x1F600\\  Splices are specified in the form @#{variableName}@. Note that expressions are not supported.-You can add @\@ before @#@, e.g. @\#{variableName}@, to interpret it as literal text. All the usual+You can add @\\@ before @#@, e.g. @\\#{variableName}@, to interpret it as literal text. All the usual Haskell string escapes also work, unless using "literal" versions. A warning will be issued if an escape is not recognized, however the code will still compile, ignoring the backslash, e.g.-@\{@ will be treated as @{@.+@\\{@ will be treated as @{@.  All splices will be indented exactly to their column position in the original text, e.g. @@ -146,170 +145,17 @@   , litub   ) where -import Prelude hiding (lift)--import Data.Char (isSpace)-import qualified Data.List as List-import qualified Data.Set as S-import Data.Text.Internal.Builder (Builder, fromLazyText, toLazyText)-import qualified Data.Text.Lazy as TL-import Fmt (build, fmt)-import Language.Haskell.TH (Exp, Q, lookupValueName, reportWarning, varE)-import Language.Haskell.TH.Quote (QuasiQuoter(..))-import Text.ParserCombinators.ReadP (readP_to_S)-import Text.Read.Lex (lexChar)---- | Datatype encoding transformations we apply to a quoter input and output.--- Note the order is important! We first unescape, then unindent, then trim.-data Transformation-  = Unescaping-  | Unindenting-  | Trimming-  | Polymorphic-  deriving stock (Eq, Ord, Enum, Bounded)---- | A 'Set' of 'Transformation'-type Transformations = Set Transformation---- | Actual quasi-quoters-i, ib, iu, iub, it, itb, itu, itub, li, lib, liu, liub, lit, litb, litu, litub :: QuasiQuoter---- | 'Transformations' singletons-trimming, unindenting, unescaping, polymorphic :: Transformations-trimming = S.singleton Trimming-unindenting = S.singleton Unindenting-unescaping = S.singleton Unescaping-polymorphic = S.singleton Polymorphic--lib = mkQuoter mempty-liub = mkQuoter unindenting-litb = mkQuoter trimming-litub = mkQuoter $ trimming <> unindenting--ib = mkQuoter unescaping-iub = mkQuoter $ unindenting <> unescaping-itb = mkQuoter $ trimming <> unescaping-itub = mkQuoter $ trimming <> unindenting <> unescaping--li = mkQuoter polymorphic-liu = mkQuoter $ unindenting <> polymorphic-lit = mkQuoter $ trimming <> polymorphic-litu = mkQuoter $ trimming <> unindenting <> polymorphic--i = mkQuoter $ unescaping <> polymorphic-iu = mkQuoter $ unindenting <> unescaping <> polymorphic-it = mkQuoter $ trimming <> unescaping <> polymorphic-itu = mkQuoter $ trimming <> unindenting <> unescaping <> polymorphic--mkQuoter :: Transformations -> QuasiQuoter-mkQuoter ts = QuasiQuoter-  { quoteExp = foldr go makeBuilder $ toList ts-  , quotePat = \_ -> fail "Cannot be used at pattern position"-  , quoteType = \_ -> fail "Cannot be used at type position"-  , quoteDec = \_ -> fail "Cannot be used as declaration"-  }-  where-    go Unescaping  f = f <=< unescape-    go Unindenting f = f . unindent . dropLeadingNewline-    go Trimming    f = f . trim-    go Polymorphic f = \s -> [| fmt $(f s) |]--unescape :: String -> Q String-unescape ('\\':'#':xs) = ('\\':) . ('#':) <$> unescape xs-unescape xs@('\\':c:cs) = case readP_to_S lexChar xs of-  (ch, rest):_ -> (ch :) <$> unescape rest-  [] -> do-    reportWarning $ "Unrecognized escape sequence near '" <> takeWhile (not . isSpace) xs <> "'"-    (c :) <$> unescape cs-unescape (c:cs) = (c :) <$> unescape cs-unescape [] = pure []--makeBuilder :: String -> Q Exp-makeBuilder = go mempty-  where-    go tacc ('\\':'#':xs) = go (tacc <> "#") xs-    go tacc ('#':'{':xs)-      | (expr, '}':ys) <- List.span (/='}') xs-      = lookupValueName expr >>= \case-          Just valueName ->-            let txt = fmt tacc-                ls = splitTextLazy (=='\n') txt-                indent = length . last $ ls-            in [| build txt <> indentF'' indent (build $(varE valueName)) <> $(go mempty ys) |]-          Nothing -> fail $ "Variable '" ++ expr ++ "' is not in scope"-    go tacc (c:cs) = case List.span (`notElem` ['\\', '#']) cs of-      (str, rest) -> go (tacc <> build (c:str)) rest-    go tacc [] = let txt = fmt @Text tacc in [| build txt |]---- | A version of @Fmt.indentF'@ that doesn't indent the first line, and keeps the final line break--- intact.-indentF'' :: Int -> Builder -> Builder-indentF'' indent bld = case splitTextLazy (=='\n') $ toLazyText bld of-  (x :| xs) -> fromLazyText . TL.intercalate "\n" $ x : map addIndent xs-  where-    addIndent str | null str = str-                  | otherwise = spaces <> str-    spaces = TL.replicate (fromIntegral indent) " "--splitTextLazy :: (Char -> Bool) -> TL.Text -> NonEmpty TL.Text-splitTextLazy p t = case nonEmpty $ TL.split p t of-  Just ne -> ne-  Nothing -> error "Morley.Util.Interpolate.splitTextLazy: the impossible happened"--dropLeadingNewline :: String -> String-dropLeadingNewline ('\n':xs) = xs-dropLeadingNewline xs = xs--unindent :: String -> String-unindent s =-  case nonEmpty (filter (not . null) ls) of-    Just ne ->-      let minIndent = minimum $ indentOf <$> ne-      -- See Note [lines/unlines] below about the use of 'intercalate'-      in intercalate "\n" $ drop minIndent <$> ls-    Nothing -> s-  where-    ls = split (=='\n') s-    indentOf = length . takeWhile (== ' ')---- See Note [lines/unlines] below about the use of this function-split :: (Char -> Bool) -> String -> [String]-split cond s = case break cond s of-  (pfx, _:suf) -> pfx : split cond suf-  (pfx, "") -> [pfx]--trim :: String -> String-trim = intercalate "\n" . List.dropWhileEnd (all (== ' '))-     -- See Note [lines/unlines] below about the use of 'intercalate'-     . dropWhile (all (== ' ')) . split (=='\n')--{- Note [lines/unlines]-   ~~~~~~~~~~~~~~~~~~~~--lines/unlines don't actually satisfy our requirements here due to-some edge case behaviour.--First of all, `lines` and `unlines` aren't strictly speaking inverse-of each other: `unlines` always adds a trailing newline. Consider:-->>> unlines . lines $ "hello\nworld"-"hello\nworld\n"--Furthermore, `lines` itself does "gobble" the trailing empty line, consider:-->>> lines $ "hello\nworld\n"-["hello","world"]--We actually need this to be `["hello","world",""]` for the unindenting-algorithm to work correctly (i.e. not unindent anything if the last indent is 0),-but that doesn't work with `lines` (also we either lose a trailing newline-or get an extra one with `unlines`). I could use `lines` with `trim`,-but for consistency chose not to.--Long story short, I use `split (=='\n')` and `Text.Lazy.split (=='\n')`-to get a list of lines, and `intercalate "\n"` to glue them back.-This has the behaviour we need.+import Language.Haskell.TH (Dec(SigD), Pat(VarP))+import Language.Haskell.TH.Quote (QuasiQuoter) -- @lierdakil+import Morley.Util.Interpolate.Internal+import Morley.Util.SizedList qualified as SL+import Morley.Util.SizedList.Types --}+$(+  let names = generateName <$> transformationsPowerSet+      infixp l r = [p| $l ::< $r |]+      pat = foldr infixp [p|Nil'|] (pure . VarP <$> names)+      sigs = traverse ((<$> [t|QuasiQuoter|]) . SigD) names+  in liftA2 (<>) sigs [d|$pat = mkQuoter <$> SL.unsafeFromList transformationsPowerSet|]+  )
+ src/Morley/Util/Interpolate/Internal.hs view
@@ -0,0 +1,161 @@+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA++-- | Internal module exporting utilities for making string interpolation quasiquoters+module Morley.Util.Interpolate.Internal+  ( Transformation(..)+  , Transformations+  , transformationsPowerSet+  , mkQuoter+  , generateName+  ) where++import Prelude hiding (lift)++import Data.Char (isSpace)+import Data.List qualified as List+import Data.Set qualified as S+import Data.Text.Internal.Builder (Builder, fromLazyText, toLazyText)+import Data.Text.Lazy qualified as TL+import Fmt (build, fmt)+import Language.Haskell.TH (Exp, Name, Q, lookupValueName, mkName, reportWarning, varE)+import Language.Haskell.TH.Quote (QuasiQuoter(..))+import Text.ParserCombinators.ReadP (readP_to_S)+import Text.Read.Lex (lexChar)++-- | Datatype encoding transformations we apply to a quoter input and output.+-- Note the order is important! We first unescape, then unindent, then trim.+data Transformation+  = Unescaping+  | Unindenting+  | Trimming+  | Polymorphic+  deriving stock (Eq, Ord, Enum, Bounded)++-- | A 'Set' of 'Transformation'+type Transformations = Set Transformation++-- | Used to generate quasi-quoters+transformationsPowerSet :: [Transformations]+transformationsPowerSet = toList $ S.powerSet $ S.fromAscList [minBound..maxBound]++-- | Generate TH 'Name' for a quoter based on a set of transformations+generateName :: Transformations -> Name+generateName ls = mkName $+     t Unescaping "" "l" <> "i" <> t Trimming "t" ""+  <> t Unindenting "u" "" <> t Polymorphic "" "b"+  where t el tru fls = if S.member el ls then tru else fls++-- | Make a 'QuasiQuoter' using a given set of transformaions+mkQuoter :: Transformations -> QuasiQuoter+mkQuoter ts = QuasiQuoter+  { quoteExp = foldr go makeBuilder $ toList ts+  , quotePat = \_ -> fail "Cannot be used at pattern position"+  , quoteType = \_ -> fail "Cannot be used at type position"+  , quoteDec = \_ -> fail "Cannot be used as declaration"+  }+  where+    go Unescaping  f = f <=< unescape+    go Unindenting f = f . unindent . dropLeadingNewline+    go Trimming    f = f . trim+    go Polymorphic f = \s -> [| fmt $(f s) |]++unescape :: String -> Q String+unescape ('\\':'#':xs) = ('\\':) . ('#':) <$> unescape xs+unescape xs@('\\':c:cs) = case readP_to_S lexChar xs of+  (ch, rest):_ -> (ch :) <$> unescape rest+  [] -> do+    reportWarning $ "Unrecognized escape sequence near '" <> takeWhile (not . isSpace) xs <> "'"+    (c :) <$> unescape cs+unescape (c:cs) = (c :) <$> unescape cs+unescape [] = pure []++makeBuilder :: String -> Q Exp+makeBuilder = go mempty+  where+    go tacc ('\\':'#':xs) = go (tacc <> "#") xs+    go tacc ('#':'{':xs)+      | (expr, '}':ys) <- List.span (/='}') xs+      = lookupValueName expr >>= \case+          Just valueName ->+            let txt = fmt tacc+                ls = splitTextLazy (=='\n') txt+                indent = length . last $ ls+            in [| build txt <> indentF'' indent (build $(varE valueName)) <> $(go mempty ys) |]+          Nothing -> fail $ "Variable '" ++ expr ++ "' is not in scope"+    go tacc (c:cs) = case List.span (`notElem` ['\\', '#']) cs of+      (str, rest) -> go (tacc <> build (c:str)) rest+    go tacc [] = let txt = fmt @Text tacc in [| build txt |]++-- | A version of @Fmt.indentF'@ that doesn't indent the first line, and keeps the final line break+-- intact.+indentF'' :: Int -> Builder -> Builder+indentF'' indent bld = case splitTextLazy (=='\n') $ toLazyText bld of+  (x :| xs) -> fromLazyText . TL.intercalate "\n" $ x : map addIndent xs+  where+    addIndent str | null str = str+                  | otherwise = spaces <> str+    spaces = TL.replicate (fromIntegral indent) " "++splitTextLazy :: (Char -> Bool) -> TL.Text -> NonEmpty TL.Text+splitTextLazy p t = case nonEmpty $ TL.split p t of+  Just ne -> ne+  Nothing -> error "Morley.Util.Interpolate.splitTextLazy: the impossible happened"++dropLeadingNewline :: String -> String+dropLeadingNewline ('\n':xs) = xs+dropLeadingNewline xs = xs++unindent :: String -> String+unindent s =+  case nonEmpty (filter (not . null) ls) of+    Just ne ->+      let minIndent = minimum $ indentOf <$> ne+      -- See Note [lines/unlines] below about the use of 'intercalate'+      in intercalate "\n" $ drop minIndent <$> ls+    Nothing -> s+  where+    ls = split (=='\n') s+    indentOf = length . takeWhile (== ' ')++-- See Note [lines/unlines] below about the use of this function+split :: (Char -> Bool) -> String -> [String]+split cond s = case break cond s of+  (pfx, _:suf) -> pfx : split cond suf+  (pfx, "") -> [pfx]++trim :: String -> String+trim = intercalate "\n" . List.dropWhileEnd (all (== ' '))+     -- See Note [lines/unlines] below about the use of 'intercalate'+     . dropWhile (all (== ' ')) . split (=='\n')++{- Note [lines/unlines]+   ~~~~~~~~~~~~~~~~~~~~++lines/unlines don't actually satisfy our requirements here due to+some edge case behaviour.++First of all, `lines` and `unlines` aren't strictly speaking inverse+of each other: `unlines` always adds a trailing newline. Consider:++>>> unlines . lines $ "hello\nworld"+"hello\nworld\n"++Furthermore, `lines` itself does "gobble" the trailing empty line, consider:++>>> lines $ "hello\nworld\n"+["hello","world"]++We actually need this to be `["hello","world",""]` for the unindenting+algorithm to work correctly (i.e. not unindent anything if the last indent is 0),+but that doesn't work with `lines` (also we either lose a trailing newline+or get an extra one with `unlines`). I could use `lines` with `trim`,+but for consistency chose not to.++Long story short, I use `split (=='\n')` and `Text.Lazy.split (=='\n')`+to get a list of lines, and `intercalate "\n"` to glue them back.+This has the behaviour we need.++- @lierdakil++-}
src/Morley/Util/Label.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Definition of the Label type and utilities module Morley.Util.Label
src/Morley/Util/Lens.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-redundant-constraints #-} 
src/Morley/Util/Main.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Functions supposed to be used in the @Main@ module. 
src/Morley/Util/Markdown.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | A small Markdown eDSL. module Morley.Util.Markdown
+ src/Morley/Util/MismatchError.hs view
@@ -0,0 +1,121 @@+-- SPDX-FileCopyrightText: 2022 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA++{- | Helper utilities for rendering mismatch-type errors.++For cases where it's useful to get a diff-style mismatch report, i.e. where+types can be rendered multi-line, a few override instances are needed.++The diff is produced by printing the types in a multiline format, then computing+the line diff with the standard algorithm (as implemented by the @Diff@+package).++In general, assuming the type in question is @T@, those instances+can look like this:++@+instance Buildable (MismatchError T) where+  build = buildRenderDocExtended++instance RenderDoc (MismatchError T) where+  renderDoc ctx = renderDocDiff ctx . fmap Prettier+@++The @fmap Prettier@ part is only required to enable multi-line rendering.++Additionally, if there's a need to show mismatch errors for lists, the following+instance can be used:++@+instance RenderDoc (MismatchError [T]) where+  renderDoc ctx = renderDocDiffList ctx . (fmap . fmap) Prettier+@+-}+module Morley.Util.MismatchError+  ( MismatchError(..)+  , renderDocDiff+  , renderDocDiffList+  ) where++import Prelude hiding (First, (<$>))++import Data.Algorithm.Diff (PolyDiff(..), getDiffBy)+import Data.Text.Lazy as LT (lines, strip)+import Fmt (Buildable(..), nameF)+import Text.PrettyPrint.Leijen.Text (Doc, align, fill, indent, text, vcat, (<$>), (<+>))++import Morley.Michelson.Printer.Util++-- | A helper record datatype representing a mismatch between two values of+-- some type. One is assumed to be in some sense the "expected" value, the other+-- one is assumed to be the "actual" value.+data MismatchError a = MkMismatchError+  { meExpected :: a -- ^ Expected value+  , meActual :: a -- ^ Actual value+  } deriving stock (Show, Eq, Generic, Functor, Foldable)+    deriving anyclass (NFData, Container)++instance {-# OVERLAPPABLE #-} Buildable a => Buildable (MismatchError a) where+  build MkMismatchError{..} =+    nameF "Expected" (build meExpected) <> nameF "Actual" (build meActual)++instance {-# OVERLAPPABLE #-} RenderDoc a => RenderDoc (MismatchError a) where+  renderDoc = renderDocStandard++renderDocStandard :: RenderDoc a => RenderContext -> MismatchError a -> Doc+renderDocStandard _ (fmap (align . renderDoc doesntNeedParens) -> MkMismatchError{..})+  =   fill 9 "Expected:" <+> meExpected+  <$> fill 9 "Actual:"   <+> meActual++renderDocStandardList :: RenderDoc a => RenderContext -> MismatchError [a] -> Doc+renderDocStandardList _ (fmap (align . renderDocList doesntNeedParens) -> MkMismatchError{..})+  =   fill 9 "Expected:" <+> meExpected+  <$> fill 9 "Actual:"   <+> meActual++-- | Render a mismatch error with a diff.+--+-- This is intended to be used with types for which 'RenderDoc' outputs+-- multiline 'Doc'. Generally those are types wrapped in 'Prettier'.+renderDocDiff :: RenderDoc a => RenderContext -> MismatchError a -> Doc+renderDocDiff ctx err = renderDocStandard ctx err+  <$> if expectedAndActualBothSingleLine+      then mempty+      else "Mismatch:"+       <$> indent 2 "--- expected +++ actual"+       <$> align (diff errText)+  where+    errText = fmap (renderDoc doesntNeedParens) err+    expectedAndActualBothSingleLine = all (null . drop 1 . LT.lines . printDoc False) errText++-- | Render a mismatch error of lists with a diff.+--+-- This is intended to be used with types for which 'RenderDoc' outputs+-- multiline 'Doc'. Generally those are types wrapped in 'Prettier'.+renderDocDiffList :: RenderDoc a => RenderContext -> MismatchError [a] -> Doc+renderDocDiffList ctx err = renderDocStandardList ctx err+  <$> if simple+      then mempty+      else "Mismatch:"+       <$> indent 2 "--- expected +++ actual"+       <$> align (diff errText)+  where+    errText = fmap (renderList' . map (align . renderDoc doesntNeedParens)) err+    -- "simple" here means that at least one is true:+    --+    -- * one of the lists is empty+    -- * rendered representation for both expected and actual types are single-line+    simple = any null err || all (null . drop 1 . LT.lines . printDoc False) errText+    renderList' ds+      = case ds of+          []  -> "[]"+          [d] -> align $ "[ " <> d <> " ]"+          _   -> align $ vcat (zipWith (<>) ("[ " : repeat ", ") ds) <$> "]"++diff :: MismatchError Doc -> Doc+diff (fmap $ LT.lines . printDoc False -> MkMismatchError{..}) = vcat $+  showLine `fmap` getDiffBy ((==) `on` LT.strip) meExpected meActual+  where+    showLine = \case+      (Both _ b) -> indent 2 $ text b+      (First x) -> "-" <+> text x+      (Second x) -> "+" <+> text x
src/Morley/Util/Named.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-orphans #-} @@ -15,40 +14,61 @@   , NamedInner   , KnownNamedFunctor (..)   , NamedF (.., (:!), (:?), N, M, SomeArg, NoArg)-  , Name (..)+  , Name+  , arg+  , argF   , argDef   ) where +import Debug qualified (show)+ import Control.Lens (Iso', Wrapped(..), iso) import Data.Aeson (FromJSON, ToJSON) import Data.Data (Data) import Fmt (Buildable(..)) import GHC.TypeLits (KnownSymbol, symbolVal)-import Named (Name(..), NamedF(..), argDef, (!), (:!), (:?))-import qualified Text.Show+import Named (Name(..), NamedF(..), arg, argDef, argF, (!), (:!), (:?))+import Text.Show qualified  import Morley.Util.Label (Label) --- | Convenience pattern synonym, use this instead of 'Named.arg' with @ViewPatterns@.+{- | Convenience pattern synonym. Use to construct a named value.++To pattern-match on a named value, use 'arg' in a view pattern:++>>> :{+let someFunc (arg #arg1 -> arg1) (arg #arg2 -> arg2) = arg1 + arg2+in someFunc ! #arg1 1 ! #arg2 2+:}+3+-} pattern (:!) :: Name name -> a -> NamedF Identity a name-pattern (:!) n v <- (decomposeNamedF -> (n, Identity v))+pattern (:!) n v <- ((Name,) -> (n, ArgF (Identity v)))   where (:!) _ v = ArgF (Identity v) {-# COMPLETE (:!) #-} --- | Convenience pattern synonym, use this instead of 'Named.argF' with @ViewPatterns@.+{- | Convenience pattern synonym. Use to construct an optional named value.++To pattern-match on an optional named value, use 'argDef' or 'argF' in a view+pattern:++>>> :{+let someFunc (argDef #arg1 "" ->arg1) (argDef #arg2 "" -> arg2) = arg1 <> arg2+in someFunc ! #arg1 "asd" ! #arg2 "efg"+:}+"asdefg"+-} pattern (:?) :: Name name -> Maybe a -> NamedF Maybe a name-pattern (:?) n v <- (decomposeNamedF -> (n, v))+pattern (:?) n v <- ((Name,) -> (n, ArgF v))   where (:?) _ v = ArgF v {-# COMPLETE (:?) #-} -decomposeNamedF :: NamedF f a name -> (Name name, f a)-decomposeNamedF (ArgF fa) = (Name, fa)- -- | Convenience pattern synonym, use this instead of 'Named.arg' with @ViewPatterns@ -- when the @name@ can be inferred. pattern N :: a -> NamedF Identity a name pattern N a = ArgF (Identity a) {-# COMPLETE N #-}+{-# DEPRECATED N "Please use view patterns with 'arg' instead." #-}  -- | Convenience pattern synonym, use this instead of 'Named.argF' with @ViewPatterns@ -- when the @name@ can be inferred. Matches only on @Just@ values@@ -66,6 +86,7 @@ pattern M :: Maybe a -> NamedF Maybe a name pattern M a = ArgF a {-# COMPLETE M #-}+{-# DEPRECATED M, SomeArg, NoArg "Please use view patterns with 'argF' instead." #-}  -- | Special version of 'Morley.Util.Named.(:!)' for monadic operations (<:!>) :: Functor m => Name name -> m a -> m (NamedF Identity a name)@@ -107,7 +128,7 @@ deriving stock instance Ord (f a) => Ord (NamedF f a name)  instance (Show a, KnownSymbol name) => Show (NamedF Identity a name) where-  show (ArgF a) = symbolVal (Proxy @name) <> " :! " <> show a+  show (ArgF a) = symbolVal (Proxy @name) <> " :! " <> Debug.show a  instance (KnownSymbol name, Buildable (f a)) => Buildable (NamedF f a name) where   build (ArgF a) = build (symbolVal (Proxy @name)) <> ": " <> build a
src/Morley/Util/Peano.hs view
@@ -1,10 +1,13 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-orphans #-}-{-# LANGUAGE UndecidableSuperClasses #-}+{-# OPTIONS_GHC -Wno-unused-top-binds #-}+-- This is needed because `singletons-th` generates redundant constraints.+-- GHC may not throw the warning always, see #791. {-# OPTIONS_GHC -Wno-redundant-constraints #-}+{-# LANGUAGE UndecidableSuperClasses #-}+{-# LANGUAGE DeriveLift #-}  -- | Type-nat utilities. --@@ -19,21 +22,31 @@ module Morley.Util.Peano   ( -- * General     Peano-    -- @gromak: I think we should not export Nat, but we want to-    -- export `Z` and `S` and I do not know how to do it without-    -- exporting `Nat`.-  , Nat (Z, S)+  , pattern S+  , pattern Z   , ToPeano   , FromPeano   , SingNat (SZ, SS) -  , Decrement-  , type (>)   , peanoSing+  , peanoSing'+  , withPeanoSingI+  , withSomePeano +  -- * Utility type synonyms+  , IsoNatPeano+  , SingIPeano+   -- * Peano Arithmetic+  , type (>)   , type (>=)   , peanoSingDecrement+  , peanoSingAdd+  , Decrement+  , AddPeano+  , SubPeano+  , MinPeano+  , MaxPeano    -- * Lists   , Length@@ -56,19 +69,38 @@   -- * Length constraints 'Dict'ionaries   , isGreaterThan   , isGreaterEqualThan++  -- * Inductive proofs+  , additivity+  , associativity+  , minIdempotency+  , commutativity+  , transitivity+  , (|-)++  -- * Helpers+  , toNatural+  , someSingNat   ) where -import Data.Constraint (Dict(..))-import Data.Singletons (Sing, SingI(..))+import Data.Constraint (Dict(..), (\\))+import Data.Singletons (Sing, SingI(..), SomeSing(..))+import Data.Type.Equality (gcastWith, type (:~:)(..)) import Data.Vinyl (Rec(..)) import Data.Vinyl.TypeLevel (Nat(..), RLength) import GHC.TypeLits (ErrorMessage(..), TypeError) import GHC.TypeNats (type (+), type (-))-import qualified GHC.TypeNats as GHC+import GHC.TypeNats qualified as GHC+import Language.Haskell.TH.Lift (Lift) import Unsafe.Coerce (unsafeCoerce) -import Morley.Util.Type+import Morley.Util.Sing (genSingletonsType)+import Morley.Util.Type (If, MockableConstraint(..)) +-- This is very obviously a false positive.+{-# ANN module ("HLint: ignore Use 'natVal' from Universum" :: Text) #-}+{-# ANN module ("HLint: ignore Use 'someNatVal' from Universum" :: Text) #-}+ ---------------------------------------------------------------------------- -- General ----------------------------------------------------------------------------@@ -79,6 +111,29 @@ -- normal 'Nat's in user API, need to distinguish them somehow. type Peano = Nat +deriving stock instance Eq Nat+deriving stock instance Show Nat+deriving stock instance Generic Nat+deriving anyclass instance NFData Nat++$(genSingletonsType ''Nat)++deriving stock instance Show (SingNat (n :: Nat))+deriving stock instance Eq (SingNat (n :: Nat))+deriving stock instance Lift (SingNat (n :: Nat))+instance NFData (SingNat (n :: Nat)) where+  rnf SZ = ()+  rnf (SS n) = rnf n+++-- | A constraint asserting that GHC's @Nat@ @n@ and @Peano@ @p@ are the same (up to an+-- isomorphism)+type IsoNatPeano (n :: GHC.Nat) (p :: Peano) = (n ~ FromPeano p, ToPeano n ~ p)++-- | A synonym for @SingI (ToPeano n)@. Essentialy requires that we can construct a 'Peano'+-- singleton for a given 'Nat'+type SingIPeano (n :: GHC.Nat) = SingI (ToPeano n)+ type family ToPeano (n :: GHC.Nat) :: Peano where   ToPeano 0 = 'Z   ToPeano a = 'S (ToPeano (a - 1))@@ -91,25 +146,40 @@ -- -- >>> peanoSing @2 -- SS (SS SZ)-peanoSing :: forall (n :: GHC.Nat). SingI (ToPeano n) => SingNat (ToPeano n)+peanoSing :: forall (n :: GHC.Nat). SingIPeano n => SingNat (ToPeano n) peanoSing = sing @(ToPeano n) -data SingNat (n :: Nat) where-  SZ :: SingNat 'Z-  SS :: !(SingNat n) -> SingNat ('S n)+-- | Same as 'peanoSing', but only requires 'KnownNat' instance.+--+-- Witnesses half the equivalence between @KnownNat n@ and @SingI (ToPeano n)@+peanoSing' :: forall (n :: GHC.Nat). KnownNat n => SingNat (ToPeano n)+peanoSing' = go (natVal @n Proxy)+  where+  go :: forall m. Natural -> SingNat m+  go = \case+    0 -> (unsafeCoerce Refl :: m :~: 'Z) |- SZ+    n -> (unsafeCoerce Refl :: m :~: 'S (Decrement m)) |-+      SS $ go @(Decrement m) (n - 1) -deriving stock instance Show (SingNat (n :: Nat))-deriving stock instance Eq (SingNat (n :: Nat))-instance NFData (SingNat (n :: Nat)) where-  rnf SZ = ()-  rnf (SS n) = rnf n+-- | Run a computation requiring @SingI (ToPeano n)@ in a context which only has+-- @KnownNat n@. Mostly useful when used with 'SomeNat'+withPeanoSingI :: forall (n :: GHC.Nat) r. KnownNat n => (SingIPeano n => r) -> r+withPeanoSingI act = act \\ go @(ToPeano n) (natVal @n Proxy)+  where+  go :: forall (m :: Peano). Natural -> Dict (SingI m)+  go = \case+    0 -> (unsafeCoerce Refl :: m :~: 'Z) |- Dict+    n -> (unsafeCoerce Refl :: m :~: 'S (Decrement m)) |- (Dict \\ go @(Decrement m) (n - 1)) -type instance Sing = SingNat+-- | Lift a given term-level 'Natural' to the type level for a given computation. The computation is+-- expected to accept a 'Proxy' for the sake of convenience: it's easier to get at the type-level+-- natural with @ScopedTypeVariables@ when pattern-matching on the proxy, e.g.+--+-- > (x :: Natural) `withSomePeano` \(_ :: Proxy n) -> doSomeNatComputation @n+withSomePeano :: Natural -> (forall n. (KnownNat n, SingIPeano n) => Proxy n -> r) -> r+withSomePeano n f = case someNatVal n of+  SomeNat (pn :: Proxy n) -> withPeanoSingI @n $ f pn -instance SingI 'Z where-  sing = SZ-instance SingI n => SingI ('S n) where-  sing = SS (sing @n)  ---------------------------------------------------------------------------- -- Peano Arithmetic@@ -127,16 +197,48 @@   SZ -> Nothing   SS n -> pure n +-- | 'Peano' naturals comparisson type family (>) (x :: Peano) (y :: Peano) :: Bool where   'Z   > _    = 'False   'S _ > 'Z   = 'True   'S x > 'S y = x > y +-- | 'Peano' naturals comparisson type family (>=) (x :: Peano) (y :: Peano) :: Bool where   _      >= 'Z     = 'True   'Z     >= _      = 'False   ('S x) >= ('S y) = x >= y +-- | 'Peano' naturals addition+type family AddPeano (n :: Peano) (m :: Peano) :: Peano where+  AddPeano 'Z x = x+  AddPeano ('S x) y = 'S (AddPeano x y)++-- | 'Peano' naturals subtraction+type family SubPeano (n :: Peano) (m :: Peano) :: Peano where+  SubPeano 'Z ('S m) = TypeError ('Text "Subtracting " ':<>: 'ShowType (FromPeano ('S m))+    ':<>: 'Text " from zero")+  SubPeano n 'Z = n+  SubPeano ('S n) ('S m) = SubPeano n m++-- | Out of two 'Peano' naturals, return the smaller one+type family MinPeano (n :: Peano) (m :: Peano) :: Peano where+  MinPeano _ 'Z = 'Z+  MinPeano 'Z _ = 'Z+  MinPeano ('S n) ('S m) = 'S (MinPeano n m)++-- | Out of two 'Peano' naturals, return the larger one+type family MaxPeano (n :: Peano) (m :: Peano) :: Peano where+  MaxPeano n 'Z = n+  MaxPeano 'Z m = m+  MaxPeano ('S n) ('S m) = 'S (MaxPeano n m)++-- | Singleton addition+peanoSingAdd :: SingNat n -> SingNat m -> SingNat (AddPeano n m)+peanoSingAdd (SS n) (SS m) = associativity n m |- SS $ SS $ peanoSingAdd n m+peanoSingAdd SZ m = m+peanoSingAdd n SZ = commutativity n SZ |- n+ ---------------------------------------------------------------------------- -- Lists ----------------------------------------------------------------------------@@ -314,3 +416,72 @@ isGreaterEqualThan _ SZ          = pure Dict isGreaterEqualThan SZ _          = Nothing isGreaterEqualThan (SS a) (SS b) = isGreaterEqualThan a b++----------------------------------------------------------------------------+-- Inductive proofs+----------------------------------------------------------------------------++-- | Convenience synonym for 'gcastWith'+(|-) :: forall k (a :: k) (b :: k) r. (a :~: b) -> ((a ~ b) => r) -> r+(|-) = gcastWith+infixr 1 |-++-- | Proof that for naturals, @k + (m + 1) = n@ entails @n > k@+{-# RULES "additivity" forall k m n. additivity k m n = unsafeCoerce Refl #-}+{-# INLINE[1] additivity #-}+additivity :: forall k m n. AddPeano k ('S m) ~ n+           => SingNat m -> SingNat n -> SingNat k -> n > k :~: 'True+additivity _ (SS _) SZ = Refl+additivity m (SS _) k = associativity k m |- lemma2 @_ @m k |- lemma k |- Refl+  where++  lemma2 :: forall k' m'. SingNat k' -> 'S (AddPeano k' m') > k' :~: 'True+  lemma2 SZ = Refl+  lemma2 (SS k') = lemma2 @_ @m' k' |- Refl++  lemma :: SingNat k' -> 'S k' > k' :~: 'True+  lemma SZ = Refl+  lemma (SS n) = lemma n |- Refl++-- | Proof that for naturals, @x + (y + 1) = (x + y) + 1@+{-# RULES "associativity" forall x y. associativity x y = unsafeCoerce Refl #-}+{-# INLINE[1] associativity #-}+associativity :: SingNat x -> SingNat y -> AddPeano x ('S y) :~: 'S (AddPeano x y)+associativity SZ _ = Refl+associativity (SS x) y = associativity x y |- Refl++-- | Proof that @x + y = y + x@+{-# RULES "commutativity" forall x y. commutativity x y = unsafeCoerce Refl #-}+{-# INLINE[1] commutativity #-}+commutativity :: SingNat x -> SingNat y -> AddPeano x y :~: AddPeano y x+commutativity SZ SZ = Refl+commutativity SZ (SS y) = commutativity SZ y |- Refl+commutativity (SS x) y = commutativity x y |- associativity y x |- Refl++-- | Proof that for naturals, @min(n, n) = n@+{-# RULES "minIdempotency" forall x. minIdempotency x = unsafeCoerce Refl #-}+{-# INLINE[1] minIdempotency #-}+minIdempotency :: SingNat n -> MinPeano n n :~: n+minIdempotency SZ = Refl+minIdempotency (SS n) = minIdempotency n |- Refl++-- | Proof that for naturals, @x >= y > z@ implies @x > z@+{-# RULES "transitivity" forall x y z. transitivity x y z = unsafeCoerce Refl #-}+{-# INLINE[1] transitivity #-}+transitivity :: (x >= y ~ 'True, y > z ~ 'True)+             => SingNat x -> SingNat y -> SingNat z -> x > z :~: 'True+transitivity (SS _) (SS _) SZ = Refl+transitivity (SS x) (SS y) (SS z) = transitivity x y z |- Refl++----------------------------------------------------------------------------+-- Helpers+----------------------------------------------------------------------------++toNatural :: Peano -> Natural+toNatural Z = 0+toNatural (S x) = 1 + toNatural x++someSingNat :: Natural -> SomeSing Peano+someSingNat 0 = SomeSing SZ+someSingNat n = case someSingNat (n - 1) of+  SomeSing sn -> SomeSing (SS sn)
src/Morley/Util/PeanoNatural.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Utility for 'PeanoNatural' --@@ -15,11 +14,14 @@   , toPeanoNatural'   , fromPeanoNatural   , singPeanoVal+  , eqPeanoNat+  , singPeanoNat   ) where  import Data.Singletons (SingI(..))-import qualified GHC.TypeNats as GHC (Nat)-import Morley.Util.Peano (Nat(S, Z), SingNat(..), ToPeano)+import Data.Type.Equality (TestEquality(..), (:~:))+import GHC.TypeNats (Nat)+import Morley.Util.Peano (Peano, SingIPeano, SingNat(..), ToPeano, pattern S, pattern Z) import Text.PrettyPrint.Leijen.Text (integer)  import Morley.Michelson.Printer.Util@@ -31,7 +33,7 @@ -- if @PN s k :: PeanoNatural n@, then @k == n@. -- This definition allows extracting values of Natural -- without O(n) conversion from @SingNat n@.-data PeanoNatural (n :: Nat) = PN !(SingNat n) !Natural+data PeanoNatural (n :: Peano) = PN !(SingNat n) !Natural  deriving stock instance Show (PeanoNatural n) deriving stock instance Eq (PeanoNatural n)@@ -76,7 +78,7 @@  -- | toPeanoNatural and toPeanoNatural' connect PeanoNatural with -- natural numbers known at run-time.-singPeanoVal :: forall (n :: Nat). SingNat n -> Natural+singPeanoVal :: forall (n :: Peano). SingNat n -> Natural singPeanoVal = \case   SZ   -> 0   SS a -> 1 + singPeanoVal a@@ -86,5 +88,14 @@   PN pSing $ singPeanoVal pSing  toPeanoNatural'-  :: forall (n :: GHC.Nat). SingI (ToPeano n) => PeanoNatural (ToPeano n)+  :: forall (n :: Nat). SingIPeano n => PeanoNatural (ToPeano n) toPeanoNatural' = toPeanoNatural @(ToPeano n)++-- | Check if two 'PeanoNatural's are equal, and return evidence of type equality+-- between the corresponding 'Nat's.+eqPeanoNat :: PeanoNatural a -> PeanoNatural b -> Maybe (a :~: b)+eqPeanoNat (PN a _) (PN b _) = testEquality a b++-- | Get a corresponding 'SingNat' from a 'PeanoNatural'.+singPeanoNat :: PeanoNatural a -> SingNat a+singPeanoNat (PN n _) = n
src/Morley/Util/Positive.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Definition of 'Positive' type and related utilities. module Morley.Util.Positive@@ -13,7 +12,7 @@ import Data.Aeson (FromJSON, ToJSON) import Data.Data (Data) import Fmt (Buildable, pretty)-import qualified Unsafe (fromIntegral)+import Unsafe qualified (fromIntegral)  import Morley.Util.Instances () 
src/Morley/Util/Sing.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2021 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Util.Sing   ( eqI@@ -10,12 +9,16 @@   , eqParamMixed3   , castSing   , SingI1(..)+  , genSingletonsType   ) where  import Data.Singletons (KindOf, Sing, SingI, sing) import Data.Singletons.Decide (SDecide, decideEquality)+import Data.Singletons.TH (genSingletons, singDecideInstance)+import Data.Singletons.TH.Options (Options(..), OptionsMonad, defaultOptions, withOptions) import Data.Type.Equality (TestEquality(..), (:~:)(..)) import Data.Typeable (eqT)+import Language.Haskell.TH (Dec, Name, mkName, nameBase)  -- | Version of 'testEquality' that uses 'SingI' eqI :: forall a b. (SingI a, SingI b, TestEquality (Sing @(KindOf a))) => Maybe (a :~: b)@@ -115,3 +118,16 @@ -- Second-order analogue of 'SingI' class SingI1 f where   withSingI1 :: forall x r. SingI x => (SingI (f x) => r) -> r++-- | Helper function to generate 'SingI' and 'Data.Singletons.TH.SDecide' instances+-- using @Sing@ as prefix for the type names and @S@ for constructors'.+genSingletonsType :: OptionsMonad q => Name -> q [Dec]+genSingletonsType name =+  let+    singPrefix, sPrefix :: Name -> Name+    singPrefix nm = mkName ("Sing" ++ nameBase nm)+    sPrefix nm = mkName ("S" ++ nameBase nm)+  in+    withOptions defaultOptions{singledDataConName = sPrefix, singledDataTypeName = singPrefix} $+    concat <$> sequence+      [ genSingletons [name], singDecideInstance name]
+ src/Morley/Util/SizedList.hs view
@@ -0,0 +1,402 @@+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA++-- | Defines lists with length fixed on the type level+module Morley.Util.SizedList+  ( -- * Base types+    SizedList+  , SizedList'(.., (::<), Nil')+  , SomeSizedList(..)++  -- * Utility type synonyms (re-exports)+  , SingIPeano+  , IsoNatPeano++  -- * Basic+  , append+  , reverse+  , head+  , tail++  -- * Construction+  , fromList+  , withNonEmpty+  , withList+  , fromListMaybe+  , fromListMaybe'+  , unsafeFromList+  , generate+  , generate'+  , replicate+  , replicate'+  , replicateT+  , singleton++  -- * Conversion+  , toNonEmpty++  -- * Zips+  , zipWith+  , unzipWith+  , zip+  , unzip++  -- * Index access+  , index'+  , index+  , indexMaybe+  , length'++  -- * Sublists+  , take+  , drop+  , splitAt+  ) where++import Prelude hiding (drop, head, replicate, reverse, splitAt, tail, take, unzip, zip, zipWith)++import Data.List qualified as List+import Data.Singletons (SingI(..))+import Fmt (Buildable(..))+import GHC.TypeNats (Nat)+import Text.Show (Show(..), showParen, showString)++import Morley.Util.Peano++-- $setup+--+-- >>> import Prelude hiding (drop, head, replicate, reverse, splitAt, tail, take, unzip, zip, zipWith)+-- >>> import Morley.Util.Peano++-- | The primary fixed-size list type. Parametrized by a type-level 'Nat' as length and type+-- as element type.+--+-- Internally powered by 'Peano' numbers+type SizedList (n :: Nat) a = SizedList' (ToPeano n) a++-- | Actual fixed-size list GADT, parametrized by 'Peano' natural. You generally don't want to+-- use this directly, since 'Peano' is not very ergonomic. Prefer using 'SizedList' unless+-- writing utility functions that need to do type-level arithmetic.+--+-- Note that while this has the usual instances, 'Applicative' and 'Monad' are not the same+-- as for regular lists: they implement "zipper" semantics, i.e. @f \<*\> x@ is the same as+-- @zipWith ($) f x@+data SizedList' (n :: Peano) a where+  Nil :: SizedList' 'Z a -- ^ Empty list+  (:<) :: a -> SizedList' n a -> SizedList' ('S n) a -- ^ Cons+infixr 5 :<++-- | Sized list cons pattern. Unlike ':<' this pattern can be used to auto-deduce the type of+-- the result, e.g.+--+-- >>> a ::< b ::< c ::< Nil' = pure 'a'+-- >>> (a, b, c)+-- ('a','a','a')+infixr 5 ::<+pattern (::<) :: a -> SizedList' n a -> SizedList' ('S n) a+pattern a ::< l <- a :< l+{-# COMPLETE (::<) #-}++-- | Sized list Nil pattern. Unlike 'Nil' this pattern can be used to auto-deduce the type of+-- the result, see '::<'.+pattern Nil' :: SizedList' 'Z a+pattern Nil' <- Nil+{-# COMPLETE Nil' #-}++deriving stock instance Eq a => Eq (SizedList' n a)+deriving stock instance Foldable (SizedList' n)+deriving stock instance Traversable (SizedList' n)+deriving stock instance Functor (SizedList' n)+instance Show a => Show (SizedList' n a) where+  showsPrec d (x :< xs) = showParen (d > prec) $+    showsPrec (prec+1) x . showString " :< " . showsPrec prec xs+    where prec = 5+  showsPrec _ Nil = showString "Nil"+deriving stock instance Ord a => Ord (SizedList' n a)++instance Buildable a => Buildable (SizedList' n a) where+  build = build . toList++instance Container (SizedList' n a)++instance SingI n => Applicative (SizedList' n) where+  pure = replicate' (sing @n)+  (<*>) = minIdempotency (sing @n) |- zipWith ($)++instance SingI n => Monad (SizedList' n) where+  f >>= k = generate' (sing @n) $ \(r, _) -> index' r $ k (index' r f)++-- | Existential capturing a fixed-size list whose length is only known at runtime.+--+-- In most cases, it's probably better to use regular lists, but this can be occasionally+-- useful.+--+-- We do not provide the 'Applicative' and 'Monad' instances, since "zipper" applicative is+-- ill-defined for lists of different length, and having inconsistent instances between+-- this and 'SizedList' is more confusing than useful.+--+-- Unlike regular sized list, @SomeSizedList@ is a 'Semigroup' and a 'Monoid':+--+-- >>> fromList "ab" <> fromList "de" <> mempty+-- SomeSizedList (SS (SS (SS (SS SZ)))) ('a' :< 'b' :< 'd' :< 'e' :< Nil)+data SomeSizedList a where+  SomeSizedList :: SingNat n -> SizedList' n a -> SomeSizedList a++deriving stock instance Foldable SomeSizedList+deriving stock instance Traversable SomeSizedList+deriving stock instance Functor SomeSizedList+deriving stock instance Show a => Show (SomeSizedList a)++instance Semigroup (SomeSizedList a) where+  (SomeSizedList sl l) <> (SomeSizedList sr r) = SomeSizedList (peanoSingAdd sl sr) $ l `append` r++instance Monoid (SomeSizedList a) where+  mempty = SomeSizedList SZ Nil++instance Buildable a => Buildable (SomeSizedList a) where+  build = build . toList++instance Container (SomeSizedList a)++instance (n ~ 'S 'Z) => One (SizedList' n a) where+  type OneItem (SizedList' n a) = a+  one = singleton++-- | Try to make a fixed-size list from a regular list, given a 'Nat'. Returns 'Nothing' if+-- the regular list has incorrect length.+--+-- >>> fromListMaybe @3 [1, 2, 3]+-- Just (1 :< 2 :< 3 :< Nil)+--+-- >>> fromListMaybe @4 [1, 2, 3]+-- Nothing+fromListMaybe :: forall n n' a. (SingIPeano n, IsoNatPeano n n') => [a] -> Maybe (SizedList n a)+fromListMaybe = fromListMaybe' $ sing @n'++-- | Same as 'fromListMaybe', but accepts an explicit 'Peano' singleton.+fromListMaybe' :: SingNat m -> [a] -> Maybe (SizedList' m a)+fromListMaybe' SZ [] = Just Nil+fromListMaybe' (SS n) (x:xs) = (x :<) <$> fromListMaybe' n xs+fromListMaybe' _ _ = Nothing++-- | Construct 'SomeSizedList' from a regular list+fromList :: forall a. [a] -> SomeSizedList a+fromList [] = SomeSizedList SZ Nil+fromList (x:xs) = case fromList xs of+  SomeSizedList n xs' -> SomeSizedList (SS n) (x :< xs')++-- | Run some computation with a 'NonEmpty' list converted to 'SizedList'. Similar+-- to pattern-matching on 'SomeSizedList', but asserts on the type level that list is+-- in fact not empty.+withNonEmpty+  :: forall a r. NonEmpty a+  -> (forall n. SingNat ('S n) -> SizedList' ('S n) a -> r)+  -> r+withNonEmpty (x :| xs) f = case fromList xs of+  SomeSizedList n xs' -> f (SS n) $ x :< xs'++-- | Run some computation with a list converted to 'SizedList'. The same as+-- pattern-matching on 'SomeSizedList'.+withList :: forall a r. [a] -> (forall n. SingNat n -> SizedList' n a -> r) -> r+withList xs f = case fromList xs of+  SomeSizedList n xs' -> f n xs'++-- | Construct a list of given length from a regular list. Raise error+-- if length is inconsistent.+--+-- >>> unsafeFromList @3 [1, 2, 3]+-- 1 :< 2 :< 3 :< Nil+--+-- >>> unsafeFromList @1 [1, 2, 3]+-- *** Exception: Invalid list size in Morley.Util.SizedList.unsafeFromList+-- ...+unsafeFromList+  :: forall n n' a. (SingIPeano n, IsoNatPeano n n', HasCallStack)+  => [a] -> SizedList n a+unsafeFromList = unsafeFromList' $ sing @n'++-- | Same as 'unsafeFromList', but accepts explicit 'Peano' singleton+unsafeFromList' :: forall n a. HasCallStack => SingNat n -> [a] -> SizedList' n a+unsafeFromList' sg xs =+  fromMaybe (error "Invalid list size in Morley.Util.SizedList.unsafeFromList") $+  fromListMaybe' sg xs++-- | Convert a 'SizedList' to 'NonEmpty'+toNonEmpty :: SizedList' ('S n) a -> NonEmpty a+toNonEmpty (x :< xs) = x :| toList xs++-- | Replicate a value @n@ times. This is a version+-- returning an existential. You probably want+-- 'replicateT' or `replicate'`.+replicate :: Natural -> a -> SomeSizedList a+replicate 0 _ = SomeSizedList SZ Nil+replicate n x = case replicate (n - 1) x of+  SomeSizedList m xs -> SomeSizedList (SS m) (x :< xs)++-- | Replicate a value @n@ times, where @n@ is passed as a type-level natural.+-- This is essentially a synonym for 'pure'.+--+-- >>> replicateT @5 'a'+-- 'a' :< 'a' :< 'a' :< 'a' :< 'a' :< Nil+replicateT :: forall n n' a. (SingIPeano n, IsoNatPeano n n') => a -> SizedList n a+replicateT = pure++-- | As 'replicateT', but accepts an explicit 'Peano' singleton.+replicate' :: SingNat n -> a -> SizedList' n a+replicate' SZ _ = Nil+replicate' (SS n) x = x :< replicate' n x++-- | Zip two lists of potentially different lengths. If one list is+-- longer, extraneous elements will be ignored.+--+-- >>> zip (unsafeFromList @3 "abc") (unsafeFromList @4 "defg")+-- ('a','d') :< ('b','e') :< ('c','f') :< Nil+zip :: SizedList' n a -> SizedList' m b -> SizedList' (MinPeano n m) (a, b)+zip = zipWith (,)++-- | Zip using a binary operation.+zipWith :: (a -> b -> c) -> SizedList' n a -> SizedList' m b -> SizedList' (MinPeano n m) c+zipWith _ Nil _ = Nil+zipWith _ _ Nil = Nil+zipWith f (x :< xs) (y :< ys) = f x y :< zipWith f xs ys++-- | Given a type-level 'Nat' and a generator function, make a 'SizedList'+--+-- Indexing starts at @0@+--+-- >>> generate @3 (+1)+-- 1 :< 2 :< 3 :< Nil+generate :: forall n n' a. (SingIPeano n, IsoNatPeano n n') => (Natural -> a) -> SizedList n a+generate f = generate' (sing @n') (f . snd)++-- | Same as 'generate', but accepts an explicit 'Peano' singleton, and passes an explicit+-- singleton as index to the generator function+generate' :: forall n a. SingNat n+          -> (forall m. (n > m ~ 'True) => (SingNat m, Natural) -> a)+          -> SizedList' n a+generate' n f = go 0 SZ n+  where+  go :: forall k m. (AddPeano k m ~ n)+     => Natural -> SingNat k -> SingNat m -> SizedList' m a+  go _ _ SZ = Nil+  go i k (SS m) = additivity m n k |- associativity k m |-+    f (k, i) :< go (i + 1) (SS k) m++-- | Reverse a 'SizedList'+--+-- >>> reverse $ generate @3 (+1)+-- 3 :< 2 :< 1 :< Nil+reverse :: forall n a. SingI n => SizedList' n a -> SizedList' n a+reverse = unsafeFromList' (sing @n) . List.reverse . toList++-- | Append two sized lists.+--+-- >>> generate @3 (+1) `append` generate @3 (+11)+-- 1 :< 2 :< 3 :< 11 :< 12 :< 13 :< Nil+append :: SizedList' n a -> SizedList' m a -> SizedList' (AddPeano n m) a+append Nil ys = ys+append (x :< xs) ys = x :< append xs ys+infixr 5 `append`++-- | Unzip a sized list using a function+unzipWith :: (a -> (b, c)) -> SizedList' n a -> (SizedList' n b, SizedList' n c)+unzipWith _ Nil = (Nil, Nil)+unzipWith f (a :< as) =+  let (b, c) = f a+      (bs, cs) = unzipWith f as+  in (b :< bs, c :< cs)++-- | Unzip a sized list of pairs+unzip :: SizedList' n (b, c) -> (SizedList' n b, SizedList' n c)+unzip = unzipWith id++-- | Index into a list using a type-level constant+--+-- >>> index @2 $ unsafeFromList @5 [1..5]+-- 3+index+  :: forall i m a. (m > ToPeano i ~ 'True, SingIPeano i)+  => SizedList' m a -> a+index = index' $ peanoSing @i++-- | Same as 'index', but accepts an explicit 'Peano' singleton+--+-- Note, that if you wish to use this with `generate'`, indexing into some+-- other list, for one, you may want to rethink your approach, since it's+-- pretty inefficient.+-- For two, you may run into arcane compiler error messages, e.g.+--+-- >>> let someList = 'a' :< 'b' :< 'c' :< Nil+-- >>> generate' @_ @Char (peanoSing @2) $ \(sg, _) -> index' sg someList+-- ...+--     • Could not deduce: ('S ('S ('S 'Z)) > m) ~ 'True+-- ...+--+-- To make this work, use 'transitivity' proof:+--+-- >>> let slLen = length' someList+-- >>> let len = peanoSing @2+-- >>> generate' @_ @Char len $ \(sg, _) -> transitivity slLen len sg |- index' sg someList+-- 'a' :< 'b' :< Nil+index' :: (m > n ~ 'True) => SingNat n -> SizedList' m a -> a+index' SZ (x :< _)= x+index' (SS n) (_ :< xs) = index' n xs++-- | Use a term-level 'Natural' to index into a list. Since the natural can+-- be larger than the length of the list, returns a 'Maybe'.+indexMaybe :: Natural -> SizedList' m a -> Maybe a+indexMaybe _ Nil = Nothing+indexMaybe 0 (x :< _) = Just x+indexMaybe n (_ :< xs) = indexMaybe (n - 1) xs++-- | Get the first element of a non-empty list+head :: SizedList' ('S n) a -> a+head (x :< _) = x++-- | Get elements after the first+tail :: SizedList' ('S n) a -> SizedList' n a+tail (_ :< xs) = xs++-- | Construct a list of one element+singleton :: a -> SizedList 1 a+singleton x = x :< Nil++-- | Take a fixed number of elements, given by a type-level 'Nat'. Must be+-- smaller than the size of the list+--+-- >>> take @3 $ unsafeFromList @5 [1..5]+-- 1 :< 2 :< 3 :< Nil+take+  :: forall n n' m a. (m >= ToPeano n ~ 'True, SingIPeano n, IsoNatPeano n n')+  => SizedList' m a -> SizedList n a+take = fst . splitAt @n++-- | Drop a fixed number of elements, given by a type-level 'Nat'. Must be+-- smaller than the size of the list+--+-- >>> drop @3 $ unsafeFromList @5 [1..5]+-- 4 :< 5 :< Nil+drop+  :: forall n n' m a. (m >= ToPeano n ~ 'True, SingIPeano n, IsoNatPeano n n')+  => SizedList' m a -> SizedList' (SubPeano m (ToPeano n)) a+drop = snd . splitAt @n++-- | @splitAt \@n xs = (take \@n xs, drop \@n xs)@, but traverses the list only+-- once+--+-- >>> splitAt @3 $ unsafeFromList @5 [1..5]+-- (1 :< 2 :< 3 :< Nil,4 :< 5 :< Nil)+splitAt+  :: forall n n' m a. (m >= ToPeano n ~ 'True, SingIPeano n, IsoNatPeano n n')+  => SizedList' m a -> (SizedList n a, SizedList' (SubPeano m n') a)+splitAt = go $ sing @n'+  where+  go :: (l >= k ~ 'True)+     => SingNat k -> SizedList' l a+     -> (SizedList' k a, SizedList' (SubPeano l k) a)+  go SZ xs = (Nil, xs)+  go (SS n) (x :< xs) = first (x :<) $ go n xs++-- | Return a Peano singleton representing the list length+length' :: forall n a. (SingI n) => SizedList' n a -> SingNat n+length' _ = sing @n
+ src/Morley/Util/SizedList/Types.hs view
@@ -0,0 +1,19 @@+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA++-- | This module re-exports types from "Morley.Util.SizedList"+--+-- Since "Morley.Util.SizedList" is intended to be imported qualified, this module provides+-- a convenient way to import only types, which are unlinkely to be ambiguous.+module Morley.Util.SizedList.Types+  ( -- * Base types+    SizedList+  , SizedList'(..)+  , SomeSizedList(..)++  -- * Utility type synonyms+  , SingIPeano+  , IsoNatPeano+  ) where++import Morley.Util.SizedList
src/Morley/Util/TH.hs view
@@ -1,14 +1,14 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Util.TH   ( deriveGADTNFData   , lookupTypeNameOrFail   , isTypeAlias+  , addTypeVariables   ) where -import Language.Haskell.TH+import Language.Haskell.TH as TH  -- | Generates an NFData instance for a GADT. /Note:/ This will not generate -- additional constraints to the generated instance if those are required.@@ -62,3 +62,16 @@ isTypeAlias typeName = reify typeName <&> \case   TyConI (TySynD {}) -> True   _ -> False++-- | Accepts a type constructor and fills it with variables until+-- getting a type of kind @*@.+addTypeVariables :: Name -> Q TH.Type+addTypeVariables tyCtor = do+  tyVarBindrs <- reify tyCtor >>= \case+    TyConI (DataD _ _ tyVarBindrs _ _ _) -> pure tyVarBindrs+    TyConI (NewtypeD _ _ tyVarBindrs _ _ _) -> pure tyVarBindrs+    _ -> fail "Expected a plain datatype"+  let vars = tyVarBindrs <&> \case+        PlainTV vName -> vName+        KindedTV vName _ -> vName+  return $ foldl (\acc var -> acc `AppT` VarT var) (ConT tyCtor) vars
src/Morley/Util/Text.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Util.Text   ( headToLower@@ -9,7 +8,7 @@   ) where  import Data.Char (toLower)-import qualified Data.Text as T+import Data.Text qualified as T  -- | Leads first character of text to lower case. --
src/Morley/Util/Type.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-redundant-constraints #-} @@ -37,13 +36,16 @@   , MockableConstraint (..)    , onFirst+  , knownListFromSingI   ) where  import Data.Constraint (Dict(..), (:-)(..), (\\))+import Data.Singletons (SingI(sing))+import Data.Singletons.Prelude.List (SList(..)) import Data.Type.Bool (If, Not, type (&&)) import Data.Type.Equality (type (==)) import Data.Vinyl.Core (Rec(..))-import qualified Data.Vinyl.Functor as Vinyl+import Data.Vinyl.Functor qualified as Vinyl import Data.Vinyl.Recursive (recordToList, rmap) import Data.Vinyl.TypeLevel (type (++)) import GHC.TypeLits (ErrorMessage(..), Symbol, TypeError)@@ -135,6 +137,17 @@   klist = KNil instance KnownList xs => KnownList (x ': xs) where   klist = KCons Proxy Proxy++-- | Given a type-level list that is 'SingI', construct evidence that it is also+-- a 'KnownList'. Note that 'KnownList' is weaker, hence this construction+-- is always possible.+knownListFromSingI :: forall xs. SingI xs => Dict (KnownList xs)+knownListFromSingI = go (sing @xs)+  where+    go :: forall ys. SList ys -> Dict (KnownList ys)+    go = \case+      SNil -> Dict+      SCons _ ys -> Dict \\ go ys  -- | @Data.List.Singletons.SList@ analogue for 'KnownList'. data KList (l :: [k]) where
src/Morley/Util/TypeLits.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-redundant-constraints #-} @@ -20,8 +19,8 @@   , AssertTypesEqual   ) where -import Data.Type.Equality-import GHC.TypeLits+import Data.Type.Equality (type (==))+import GHC.TypeLits (AppendSymbol, ErrorMessage(..), KnownSymbol, Symbol, TypeError, symbolVal)  symbolValT :: forall s. KnownSymbol s => Proxy s -> Text symbolValT = toText . symbolVal
src/Morley/Util/TypeTuple.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Conversions between tuples and list-like types. module Morley.Util.TypeTuple
src/Morley/Util/TypeTuple/Class.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  module Morley.Util.TypeTuple.Class   ( RecFromTuple (..)
src/Morley/Util/TypeTuple/Instances.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# OPTIONS_GHC -Wno-orphans #-} 
src/Morley/Util/TypeTuple/TH.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  {-# LANGUAGE QuasiQuotes #-} @@ -11,7 +10,7 @@   ) where  import Data.Vinyl.Core (Rec(..))-import qualified Language.Haskell.TH as TH+import Language.Haskell.TH qualified as TH  import Morley.Util.TypeTuple.Class 
src/Morley/Util/Typeable.hs view
@@ -1,6 +1,5 @@--- SPDX-FileCopyrightText: 2020 Tocqueville Group------ SPDX-License-Identifier: LicenseRef-MIT-TQ+-- SPDX-FileCopyrightText: 2021 Oxhead Alpha+-- SPDX-License-Identifier: LicenseRef-MIT-OA  -- | Utility for 'Typeable'. module Morley.Util.Typeable@@ -18,7 +17,7 @@  import Data.Coerce (coerce) import Data.Typeable (eqT, typeRep, (:~:)(..))-import qualified Type.Reflection as Refl+import Type.Reflection qualified as Refl  -- | Suppose you have a data type @X@ with parameter @a@ and you have -- two values: @x1 :: X a1@ and @x2 :: X a2@. You can't compare them