morley 1.2.0 → 1.3.0
raw patch · 166 files changed
+2017/−1090 lines, 166 filessetup-changed
Files
- CHANGES.md +28/−0
- LICENSE +16/−659
- README.md +6/−0
- Setup.hs +4/−0
- app/Main.hs +6/−2
- bench/Main.hs +8/−4
- morley.cabal +10/−8
- src/Michelson/Analyzer.hs +4/−0
- src/Michelson/Doc.hs +5/−1
- src/Michelson/Doc/Test.hs +14/−0
- src/Michelson/ErrorPos.hs +4/−0
- src/Michelson/FailPattern.hs +4/−0
- src/Michelson/Interpret.hs +7/−3
- src/Michelson/Interpret/Pack.hs +19/−15
- src/Michelson/Interpret/Unpack.hs +4/−0
- src/Michelson/Let.hs +4/−0
- src/Michelson/Macro.hs +4/−0
- src/Michelson/OpSize.hs +4/−0
- src/Michelson/Optimizer.hs +4/−0
- src/Michelson/Parser.hs +6/−0
- src/Michelson/Parser/Annotations.hs +4/−0
- src/Michelson/Parser/Error.hs +4/−0
- src/Michelson/Parser/Ext.hs +4/−0
- src/Michelson/Parser/Helpers.hs +4/−0
- src/Michelson/Parser/Instr.hs +4/−0
- src/Michelson/Parser/Let.hs +21/−10
- src/Michelson/Parser/Lexer.hs +4/−0
- src/Michelson/Parser/Macro.hs +4/−0
- src/Michelson/Parser/Type.hs +4/−0
- src/Michelson/Parser/Types.hs +4/−0
- src/Michelson/Parser/Value.hs +4/−0
- src/Michelson/Preprocess.hs +13/−27
- src/Michelson/Printer.hs +9/−5
- src/Michelson/Printer/Util.hs +4/−0
- src/Michelson/Runtime.hs +6/−2
- src/Michelson/Runtime/GState.hs +14/−2
- src/Michelson/Runtime/TxData.hs +4/−0
- src/Michelson/Test.hs +4/−0
- src/Michelson/Test/Dummy.hs +4/−0
- src/Michelson/Test/Gen.hs +4/−0
- src/Michelson/Test/Import.hs +12/−8
- src/Michelson/Test/Integrational.hs +9/−2
- src/Michelson/Test/Unit.hs +8/−4
- src/Michelson/Test/Util.hs +4/−0
- src/Michelson/Text.hs +4/−0
- src/Michelson/TypeCheck.hs +4/−0
- src/Michelson/TypeCheck/Error.hs +85/−18
- src/Michelson/TypeCheck/Ext.hs +4/−0
- src/Michelson/TypeCheck/Helpers.hs +59/−33
- src/Michelson/TypeCheck/Instr.hs +357/−59
- src/Michelson/TypeCheck/TypeCheck.hs +4/−0
- src/Michelson/TypeCheck/Types.hs +6/−2
- src/Michelson/TypeCheck/Value.hs +4/−0
- src/Michelson/Typed.hs +4/−0
- src/Michelson/Typed/Aliases.hs +4/−0
- src/Michelson/Typed/Annotation.hs +16/−16
- src/Michelson/Typed/Arith.hs +4/−0
- src/Michelson/Typed/Convert.hs +20/−19
- src/Michelson/Typed/Doc.hs +4/−0
- src/Michelson/Typed/EntryPoints.hs +4/−0
- src/Michelson/Typed/Extract.hs +18/−15
- src/Michelson/Typed/Haskell.hs +4/−0
- src/Michelson/Typed/Haskell/Doc.hs +145/−72
- src/Michelson/Typed/Haskell/Instr.hs +4/−0
- src/Michelson/Typed/Haskell/Instr/Helpers.hs +4/−0
- src/Michelson/Typed/Haskell/Instr/Product.hs +114/−1
- src/Michelson/Typed/Haskell/Instr/Sum.hs +6/−1
- src/Michelson/Typed/Haskell/LooseSum.hs +4/−0
- src/Michelson/Typed/Haskell/ValidateDescription.hs +135/−0
- src/Michelson/Typed/Haskell/Value.hs +5/−0
- src/Michelson/Typed/Instr.hs +19/−16
- src/Michelson/Typed/Polymorphic.hs +4/−0
- src/Michelson/Typed/Scope.hs +4/−0
- src/Michelson/Typed/Sing.hs +4/−0
- src/Michelson/Typed/T.hs +4/−0
- src/Michelson/Typed/Util.hs +122/−22
- src/Michelson/Typed/Value.hs +4/−0
- src/Michelson/Untyped.hs +4/−0
- src/Michelson/Untyped/Aliases.hs +4/−0
- src/Michelson/Untyped/Annotation.hs +7/−3
- src/Michelson/Untyped/Contract.hs +4/−0
- src/Michelson/Untyped/EntryPoints.hs +4/−0
- src/Michelson/Untyped/Ext.hs +4/−0
- src/Michelson/Untyped/Instr.hs +4/−0
- src/Michelson/Untyped/Type.hs +4/−0
- src/Michelson/Untyped/Value.hs +4/−0
- src/Morley/CLI.hs +33/−3
- src/Morley/Micheline.hs +11/−7
- src/Tezos/Address.hs +4/−0
- src/Tezos/Core.hs +8/−1
- src/Tezos/Crypto.hs +5/−1
- src/Tezos/Crypto/Ed25519.hs +4/−0
- src/Tezos/Crypto/Hash.hs +4/−0
- src/Tezos/Crypto/P256.hs +4/−0
- src/Tezos/Crypto/Secp256k1.hs +4/−0
- src/Tezos/Crypto/Util.hs +4/−0
- src/Util/Aeson.hs +4/−0
- src/Util/Alternative.hs +4/−0
- src/Util/ByteString.hs +4/−0
- src/Util/CLI.hs +4/−0
- src/Util/Default.hs +4/−0
- src/Util/Exception.hs +16/−1
- src/Util/Fcf.hs +4/−0
- src/Util/Generic.hs +4/−0
- src/Util/IO.hs +8/−18
- src/Util/IO/GHC.hs +25/−0
- src/Util/Instances.hs +4/−0
- src/Util/Label.hs +4/−0
- src/Util/Lens.hs +4/−0
- src/Util/Markdown.hs +4/−0
- src/Util/Named.hs +4/−0
- src/Util/Peano.hs +4/−0
- src/Util/Positive.hs +4/−0
- src/Util/TH.hs +4/−0
- src/Util/Test/Arbitrary.hs +4/−0
- src/Util/Test/Ingredients.hs +7/−3
- src/Util/Text.hs +4/−0
- src/Util/Type.hs +4/−0
- src/Util/TypeLits.hs +4/−0
- src/Util/TypeTuple.hs +4/−0
- src/Util/TypeTuple/Class.hs +4/−0
- src/Util/TypeTuple/Instances.hs +4/−0
- src/Util/TypeTuple/TH.hs +4/−0
- src/Util/Typeable.hs +4/−0
- test/Main.hs +4/−0
- test/Test/Analyzer.hs +4/−0
- test/Test/EntryPoints.hs +4/−0
- test/Test/Ext.hs +5/−1
- test/Test/Integrational.hs +8/−4
- test/Test/Interpreter.hs +6/−2
- test/Test/Interpreter/Apply.hs +4/−0
- test/Test/Interpreter/Auction.hs +4/−0
- test/Test/Interpreter/Balance.hs +3/−0
- test/Test/Interpreter/CallSelf.hs +5/−1
- test/Test/Interpreter/ComparableSet.hs +4/−0
- test/Test/Interpreter/Compare.hs +4/−0
- test/Test/Interpreter/ComparePairs.hs +4/−0
- test/Test/Interpreter/Conditionals.hs +4/−0
- test/Test/Interpreter/ContractOp.hs +6/−2
- test/Test/Interpreter/EnvironmentSpec.hs +6/−2
- test/Test/Interpreter/StackRef.hs +10/−6
- test/Test/Interpreter/StringCaller.hs +6/−2
- test/Test/Macro.hs +4/−0
- test/Test/Michelson/Runtime.hs +4/−0
- test/Test/Michelson/Text.hs +4/−0
- test/Test/Michelson/Typed/Util.hs +4/−0
- test/Test/OpSize.hs +4/−0
- test/Test/Optimizer.hs +4/−0
- test/Test/Parser.hs +25/−2
- test/Test/Preprocess.hs +4/−0
- test/Test/Printer/Michelson.hs +4/−0
- test/Test/Serialization/Aeson.hs +4/−0
- test/Test/Serialization/Michelson.hs +4/−0
- test/Test/Tezos/Address.hs +4/−0
- test/Test/Tezos/Core.hs +4/−0
- test/Test/Tezos/Crypto.hs +4/−0
- test/Test/Tezos/Crypto/Hash.hs +4/−0
- test/Test/Typeable.hs +4/−0
- test/Test/Typecheck.hs +41/−5
- test/Test/Untyped/Instr.hs +4/−0
- test/Test/Util/Contracts.hs +4/−0
- test/Test/Util/HUnit.hs +4/−0
- test/Test/Util/Parser.hs +4/−0
- test/Test/Util/QuickCheck.hs +4/−0
- test/Test/ValConversion.hs +4/−0
- test/Tree.hs +4/−0
CHANGES.md view
@@ -1,6 +1,34 @@+<!--+SPDX-FileCopyrightText: 2020 Tocqueville Group++SPDX-License-Identifier: LicenseRef-MIT-TQ+-->+ Unreleased ========== <!-- Append new entries here -->++1.3.0+=====+* [!417](https://gitlab.com/morley-framework/morley/-/merge_requests/417)+Change the license to MIT.+* [!386](https://gitlab.com/morley-framework/morley/-/merge_requests/386)+ + Add a way to describe constructors and fields of ADTs in Markdown documentation.+ + Require that all contracts include documentation for the storage type.+* [!396](https://gitlab.com/morley-framework/morley/merge_requests/396) Fixed+ typed `Notes` to permit pair annotations for container keys.+* [!359](https://gitlab.com/morley-framework/morley/merge_requests/359) Renamed+ 'FullContract' to 'Contract', removed the prefix `f` from its record fields+ and removed "Full" from the names of the functions:+ `convertFullContract`, `printTypedFullContract` and `mapFullContractCode`.+* [!354](https://gitlab.com/morley-framework/morley/-/merge_requests/354)+ + Fix bug: add `ChainId` to `IsPrimitiveValue` type family.+ + Add `GInstrDeconstruct` type class and related functions+ which serve to deconstruct datatype into its fields on the stack.+ + Add `gInstrConstructStack` to `GInstrConstruct` type class that serves+ to construct a datatype from its fields on the stack.+ + Add `GFieldNames` type family returning list of `Symbol`s:+ the names of direct fields of datatype. 1.2.0 =====
LICENSE view
@@ -1,662 +1,19 @@- GNU AFFERO GENERAL PUBLIC LICENSE- Version 3, 19 November 2007-- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>- Everyone is permitted to copy and distribute verbatim copies- of this license document, but changing it is not allowed.-- Preamble-- The GNU Affero General Public License is a free, copyleft license for-software and other kinds of works, specifically designed to ensure-cooperation with the community in the case of network server software.-- The licenses for most software and other practical works are designed-to take away your freedom to share and change the works. By contrast,-our General Public Licenses are intended to guarantee your freedom to-share and change all versions of a program--to make sure it remains free-software for all its users.-- When we speak of free software, we are referring to freedom, not-price. Our General Public Licenses are designed to make sure that you-have the freedom to distribute copies of free software (and charge for-them if you wish), that you receive source code or can get it if you-want it, that you can change the software or use pieces of it in new-free programs, and that you know you can do these things.-- Developers that use our General Public Licenses protect your rights-with two steps: (1) assert copyright on the software, and (2) offer-you this License which gives you legal permission to copy, distribute-and/or modify the software.-- A secondary benefit of defending all users' freedom is that-improvements made in alternate versions of the program, if they-receive widespread use, become available for other developers to-incorporate. Many developers of free software are heartened and-encouraged by the resulting cooperation. However, in the case of-software used on network servers, this result may fail to come about.-The GNU General Public License permits making a modified version and-letting the public access it on a server without ever releasing its-source code to the public.-- The GNU Affero General Public License is designed specifically to-ensure that, in such cases, the modified source code becomes available-to the community. It requires the operator of a network server to-provide the source code of the modified version running there to the-users of that server. Therefore, public use of a modified version, on-a publicly accessible server, gives the public access to the source-code of the modified version.-- An older license, called the Affero General Public License and-published by Affero, was designed to accomplish similar goals. This is-a different license, not a version of the Affero GPL, but Affero has-released a new version of the Affero GPL which permits relicensing under-this license.-- The precise terms and conditions for copying, distribution and-modification follow.-- TERMS AND CONDITIONS-- 0. Definitions.-- "This License" refers to version 3 of the GNU Affero General Public License.-- "Copyright" also means copyright-like laws that apply to other kinds of-works, such as semiconductor masks.-- "The Program" refers to any copyrightable work licensed under this-License. Each licensee is addressed as "you". "Licensees" and-"recipients" may be individuals or organizations.-- To "modify" a work means to copy from or adapt all or part of the work-in a fashion requiring copyright permission, other than the making of an-exact copy. The resulting work is called a "modified version" of the-earlier work or a work "based on" the earlier work.-- A "covered work" means either the unmodified Program or a work based-on the Program.-- To "propagate" a work means to do anything with it that, without-permission, would make you directly or secondarily liable for-infringement under applicable copyright law, except executing it on a-computer or modifying a private copy. Propagation includes copying,-distribution (with or without modification), making available to the-public, and in some countries other activities as well.-- To "convey" a work means any kind of propagation that enables other-parties to make or receive copies. Mere interaction with a user through-a computer network, with no transfer of a copy, is not conveying.-- An interactive user interface displays "Appropriate Legal Notices"-to the extent that it includes a convenient and prominently visible-feature that (1) displays an appropriate copyright notice, and (2)-tells the user that there is no warranty for the work (except to the-extent that warranties are provided), that licensees may convey the-work under this License, and how to view a copy of this License. If-the interface presents a list of user commands or options, such as a-menu, a prominent item in the list meets this criterion.-- 1. Source Code.-- The "source code" for a work means the preferred form of the work-for making modifications to it. "Object code" means any non-source-form of a work.-- A "Standard Interface" means an interface that either is an official-standard defined by a recognized standards body, or, in the case of-interfaces specified for a particular programming language, one that-is widely used among developers working in that language.-- The "System Libraries" of an executable work include anything, other-than the work as a whole, that (a) is included in the normal form of-packaging a Major Component, but which is not part of that Major-Component, and (b) serves only to enable use of the work with that-Major Component, or to implement a Standard Interface for which an-implementation is available to the public in source code form. A-"Major Component", in this context, means a major essential component-(kernel, window system, and so on) of the specific operating system-(if any) on which the executable work runs, or a compiler used to-produce the work, or an object code interpreter used to run it.-- The "Corresponding Source" for a work in object code form means all-the source code needed to generate, install, and (for an executable-work) run the object code and to modify the work, including scripts to-control those activities. However, it does not include the work's-System Libraries, or general-purpose tools or generally available free-programs which are used unmodified in performing those activities but-which are not part of the work. For example, Corresponding Source-includes interface definition files associated with source files for-the work, and the source code for shared libraries and dynamically-linked subprograms that the work is specifically designed to require,-such as by intimate data communication or control flow between those-subprograms and other parts of the work.-- The Corresponding Source need not include anything that users-can regenerate automatically from other parts of the Corresponding-Source.-- The Corresponding Source for a work in source code form is that-same work.-- 2. Basic Permissions.-- All rights granted under this License are granted for the term of-copyright on the Program, and are irrevocable provided the stated-conditions are met. This License explicitly affirms your unlimited-permission to run the unmodified Program. The output from running a-covered work is covered by this License only if the output, given its-content, constitutes a covered work. This License acknowledges your-rights of fair use or other equivalent, as provided by copyright law.-- You may make, run and propagate covered works that you do not-convey, without conditions so long as your license otherwise remains-in force. You may convey covered works to others for the sole purpose-of having them make modifications exclusively for you, or provide you-with facilities for running those works, provided that you comply with-the terms of this License in conveying all material for which you do-not control copyright. Those thus making or running the covered works-for you must do so exclusively on your behalf, under your direction-and control, on terms that prohibit them from making any copies of-your copyrighted material outside their relationship with you.-- Conveying under any other circumstances is permitted solely under-the conditions stated below. Sublicensing is not allowed; section 10-makes it unnecessary.-- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.-- No covered work shall be deemed part of an effective technological-measure under any applicable law fulfilling obligations under article-11 of the WIPO copyright treaty adopted on 20 December 1996, or-similar laws prohibiting or restricting circumvention of such-measures.-- When you convey a covered work, you waive any legal power to forbid-circumvention of technological measures to the extent such circumvention-is effected by exercising rights under this License with respect to-the covered work, and you disclaim any intention to limit operation or-modification of the work as a means of enforcing, against the work's-users, your or third parties' legal rights to forbid circumvention of-technological measures.-- 4. Conveying Verbatim Copies.-- You may convey verbatim copies of the Program's source code as you-receive it, in any medium, provided that you conspicuously and-appropriately publish on each copy an appropriate copyright notice;-keep intact all notices stating that this License and any-non-permissive terms added in accord with section 7 apply to the code;-keep intact all notices of the absence of any warranty; and give all-recipients a copy of this License along with the Program.-- You may charge any price or no price for each copy that you convey,-and you may offer support or warranty protection for a fee.-- 5. Conveying Modified Source Versions.-- You may convey a work based on the Program, or the modifications to-produce it from the Program, in the form of source code under the-terms of section 4, provided that you also meet all of these conditions:-- a) The work must carry prominent notices stating that you modified- it, and giving a relevant date.-- b) The work must carry prominent notices stating that it is- released under this License and any conditions added under section- 7. This requirement modifies the requirement in section 4 to- "keep intact all notices".-- c) You must license the entire work, as a whole, under this- License to anyone who comes into possession of a copy. This- License will therefore apply, along with any applicable section 7- additional terms, to the whole of the work, and all its parts,- regardless of how they are packaged. This License gives no- permission to license the work in any other way, but it does not- invalidate such permission if you have separately received it.-- d) If the work has interactive user interfaces, each must display- Appropriate Legal Notices; however, if the Program has interactive- interfaces that do not display Appropriate Legal Notices, your- work need not make them do so.-- A compilation of a covered work with other separate and independent-works, which are not by their nature extensions of the covered work,-and which are not combined with it such as to form a larger program,-in or on a volume of a storage or distribution medium, is called an-"aggregate" if the compilation and its resulting copyright are not-used to limit the access or legal rights of the compilation's users-beyond what the individual works permit. Inclusion of a covered work-in an aggregate does not cause this License to apply to the other-parts of the aggregate.-- 6. Conveying Non-Source Forms.-- You may convey a covered work in object code form under the terms-of sections 4 and 5, provided that you also convey the-machine-readable Corresponding Source under the terms of this License,-in one of these ways:-- a) Convey the object code in, or embodied in, a physical product- (including a physical distribution medium), accompanied by the- Corresponding Source fixed on a durable physical medium- customarily used for software interchange.-- b) Convey the object code in, or embodied in, a physical product- (including a physical distribution medium), accompanied by a- written offer, valid for at least three years and valid for as- long as you offer spare parts or customer support for that product- model, to give anyone who possesses the object code either (1) a- copy of the Corresponding Source for all the software in the- product that is covered by this License, on a durable physical- medium customarily used for software interchange, for a price no- more than your reasonable cost of physically performing this- conveying of source, or (2) access to copy the- Corresponding Source from a network server at no charge.-- c) Convey individual copies of the object code with a copy of the- written offer to provide the Corresponding Source. This- alternative is allowed only occasionally and noncommercially, and- only if you received the object code with such an offer, in accord- with subsection 6b.-- d) Convey the object code by offering access from a designated- place (gratis or for a charge), and offer equivalent access to the- Corresponding Source in the same way through the same place at no- further charge. You need not require recipients to copy the- Corresponding Source along with the object code. If the place to- copy the object code is a network server, the Corresponding Source- may be on a different server (operated by you or a third party)- that supports equivalent copying facilities, provided you maintain- clear directions next to the object code saying where to find the- Corresponding Source. Regardless of what server hosts the- Corresponding Source, you remain obligated to ensure that it is- available for as long as needed to satisfy these requirements.-- e) Convey the object code using peer-to-peer transmission, provided- you inform other peers where the object code and Corresponding- Source of the work are being offered to the general public at no- charge under subsection 6d.-- A separable portion of the object code, whose source code is excluded-from the Corresponding Source as a System Library, need not be-included in conveying the object code work.-- A "User Product" is either (1) a "consumer product", which means any-tangible personal property which is normally used for personal, family,-or household purposes, or (2) anything designed or sold for incorporation-into a dwelling. In determining whether a product is a consumer product,-doubtful cases shall be resolved in favor of coverage. For a particular-product received by a particular user, "normally used" refers to a-typical or common use of that class of product, regardless of the status-of the particular user or of the way in which the particular user-actually uses, or expects or is expected to use, the product. A product-is a consumer product regardless of whether the product has substantial-commercial, industrial or non-consumer uses, unless such uses represent-the only significant mode of use of the product.-- "Installation Information" for a User Product means any methods,-procedures, authorization keys, or other information required to install-and execute modified versions of a covered work in that User Product from-a modified version of its Corresponding Source. The information must-suffice to ensure that the continued functioning of the modified object-code is in no case prevented or interfered with solely because-modification has been made.-- If you convey an object code work under this section in, or with, or-specifically for use in, a User Product, and the conveying occurs as-part of a transaction in which the right of possession and use of the-User Product is transferred to the recipient in perpetuity or for a-fixed term (regardless of how the transaction is characterized), the-Corresponding Source conveyed under this section must be accompanied-by the Installation Information. But this requirement does not apply-if neither you nor any third party retains the ability to install-modified object code on the User Product (for example, the work has-been installed in ROM).-- The requirement to provide Installation Information does not include a-requirement to continue to provide support service, warranty, or updates-for a work that has been modified or installed by the recipient, or for-the User Product in which it has been modified or installed. Access to a-network may be denied when the modification itself materially and-adversely affects the operation of the network or violates the rules and-protocols for communication across the network.-- Corresponding Source conveyed, and Installation Information provided,-in accord with this section must be in a format that is publicly-documented (and with an implementation available to the public in-source code form), and must require no special password or key for-unpacking, reading or copying.-- 7. Additional Terms.-- "Additional permissions" are terms that supplement the terms of this-License by making exceptions from one or more of its conditions.-Additional permissions that are applicable to the entire Program shall-be treated as though they were included in this License, to the extent-that they are valid under applicable law. If additional permissions-apply only to part of the Program, that part may be used separately-under those permissions, but the entire Program remains governed by-this License without regard to the additional permissions.-- When you convey a copy of a covered work, you may at your option-remove any additional permissions from that copy, or from any part of-it. (Additional permissions may be written to require their own-removal in certain cases when you modify the work.) You may place-additional permissions on material, added by you to a covered work,-for which you have or can give appropriate copyright permission.-- Notwithstanding any other provision of this License, for material you-add to a covered work, you may (if authorized by the copyright holders of-that material) supplement the terms of this License with terms:-- a) Disclaiming warranty or limiting liability differently from the- terms of sections 15 and 16 of this License; or-- b) Requiring preservation of specified reasonable legal notices or- author attributions in that material or in the Appropriate Legal- Notices displayed by works containing it; or-- c) Prohibiting misrepresentation of the origin of that material, or- requiring that modified versions of such material be marked in- reasonable ways as different from the original version; or-- d) Limiting the use for publicity purposes of names of licensors or- authors of the material; or-- e) Declining to grant rights under trademark law for use of some- trade names, trademarks, or service marks; or-- f) Requiring indemnification of licensors and authors of that- material by anyone who conveys the material (or modified versions of- it) with contractual assumptions of liability to the recipient, for- any liability that these contractual assumptions directly impose on- those licensors and authors.-- All other non-permissive additional terms are considered "further-restrictions" within the meaning of section 10. If the Program as you-received it, or any part of it, contains a notice stating that it is-governed by this License along with a term that is a further-restriction, you may remove that term. If a license document contains-a further restriction but permits relicensing or conveying under this-License, you may add to a covered work material governed by the terms-of that license document, provided that the further restriction does-not survive such relicensing or conveying.-- If you add terms to a covered work in accord with this section, you-must place, in the relevant source files, a statement of the-additional terms that apply to those files, or a notice indicating-where to find the applicable terms.-- Additional terms, permissive or non-permissive, may be stated in the-form of a separately written license, or stated as exceptions;-the above requirements apply either way.-- 8. Termination.-- You may not propagate or modify a covered work except as expressly-provided under this License. Any attempt otherwise to propagate or-modify it is void, and will automatically terminate your rights under-this License (including any patent licenses granted under the third-paragraph of section 11).-- However, if you cease all violation of this License, then your-license from a particular copyright holder is reinstated (a)-provisionally, unless and until the copyright holder explicitly and-finally terminates your license, and (b) permanently, if the copyright-holder fails to notify you of the violation by some reasonable means-prior to 60 days after the cessation.-- Moreover, your license from a particular copyright holder is-reinstated permanently if the copyright holder notifies you of the-violation by some reasonable means, this is the first time you have-received notice of violation of this License (for any work) from that-copyright holder, and you cure the violation prior to 30 days after-your receipt of the notice.-- Termination of your rights under this section does not terminate the-licenses of parties who have received copies or rights from you under-this License. If your rights have been terminated and not permanently-reinstated, you do not qualify to receive new licenses for the same-material under section 10.-- 9. Acceptance Not Required for Having Copies.-- You are not required to accept this License in order to receive or-run a copy of the Program. Ancillary propagation of a covered work-occurring solely as a consequence of using peer-to-peer transmission-to receive a copy likewise does not require acceptance. However,-nothing other than this License grants you permission to propagate or-modify any covered work. These actions infringe copyright if you do-not accept this License. Therefore, by modifying or propagating a-covered work, you indicate your acceptance of this License to do so.-- 10. Automatic Licensing of Downstream Recipients.-- Each time you convey a covered work, the recipient automatically-receives a license from the original licensors, to run, modify and-propagate that work, subject to this License. You are not responsible-for enforcing compliance by third parties with this License.-- An "entity transaction" is a transaction transferring control of an-organization, or substantially all assets of one, or subdividing an-organization, or merging organizations. If propagation of a covered-work results from an entity transaction, each party to that-transaction who receives a copy of the work also receives whatever-licenses to the work the party's predecessor in interest had or could-give under the previous paragraph, plus a right to possession of the-Corresponding Source of the work from the predecessor in interest, if-the predecessor has it or can get it with reasonable efforts.-- You may not impose any further restrictions on the exercise of the-rights granted or affirmed under this License. For example, you may-not impose a license fee, royalty, or other charge for exercise of-rights granted under this License, and you may not initiate litigation-(including a cross-claim or counterclaim in a lawsuit) alleging that-any patent claim is infringed by making, using, selling, offering for-sale, or importing the Program or any portion of it.-- 11. Patents.-- A "contributor" is a copyright holder who authorizes use under this-License of the Program or a work on which the Program is based. The-work thus licensed is called the contributor's "contributor version".-- A contributor's "essential patent claims" are all patent claims-owned or controlled by the contributor, whether already acquired or-hereafter acquired, that would be infringed by some manner, permitted-by this License, of making, using, or selling its contributor version,-but do not include claims that would be infringed only as a-consequence of further modification of the contributor version. For-purposes of this definition, "control" includes the right to grant-patent sublicenses in a manner consistent with the requirements of-this License.-- Each contributor grants you a non-exclusive, worldwide, royalty-free-patent license under the contributor's essential patent claims, to-make, use, sell, offer for sale, import and otherwise run, modify and-propagate the contents of its contributor version.-- In the following three paragraphs, a "patent license" is any express-agreement or commitment, however denominated, not to enforce a patent-(such as an express permission to practice a patent or covenant not to-sue for patent infringement). To "grant" such a patent license to a-party means to make such an agreement or commitment not to enforce a-patent against the party.-- If you convey a covered work, knowingly relying on a patent license,-and the Corresponding Source of the work is not available for anyone-to copy, free of charge and under the terms of this License, through a-publicly available network server or other readily accessible means,-then you must either (1) cause the Corresponding Source to be so-available, or (2) arrange to deprive yourself of the benefit of the-patent license for this particular work, or (3) arrange, in a manner-consistent with the requirements of this License, to extend the patent-license to downstream recipients. "Knowingly relying" means you have-actual knowledge that, but for the patent license, your conveying the-covered work in a country, or your recipient's use of the covered work-in a country, would infringe one or more identifiable patents in that-country that you have reason to believe are valid.-- If, pursuant to or in connection with a single transaction or-arrangement, you convey, or propagate by procuring conveyance of, a-covered work, and grant a patent license to some of the parties-receiving the covered work authorizing them to use, propagate, modify-or convey a specific copy of the covered work, then the patent license-you grant is automatically extended to all recipients of the covered-work and works based on it.-- A patent license is "discriminatory" if it does not include within-the scope of its coverage, prohibits the exercise of, or is-conditioned on the non-exercise of one or more of the rights that are-specifically granted under this License. You may not convey a covered-work if you are a party to an arrangement with a third party that is-in the business of distributing software, under which you make payment-to the third party based on the extent of your activity of conveying-the work, and under which the third party grants, to any of the-parties who would receive the covered work from you, a discriminatory-patent license (a) in connection with copies of the covered work-conveyed by you (or copies made from those copies), or (b) primarily-for and in connection with specific products or compilations that-contain the covered work, unless you entered into that arrangement,-or that patent license was granted, prior to 28 March 2007.-- Nothing in this License shall be construed as excluding or limiting-any implied license or other defenses to infringement that may-otherwise be available to you under applicable patent law.-- 12. No Surrender of Others' Freedom.-- If conditions are imposed on you (whether by court order, agreement or-otherwise) that contradict the conditions of this License, they do not-excuse you from the conditions of this License. If you cannot convey a-covered work so as to satisfy simultaneously your obligations under this-License and any other pertinent obligations, then as a consequence you may-not convey it at all. For example, if you agree to terms that obligate you-to collect a royalty for further conveying from those to whom you convey-the Program, the only way you could satisfy both those terms and this-License would be to refrain entirely from conveying the Program.-- 13. Remote Network Interaction; Use with the GNU General Public License.-- Notwithstanding any other provision of this License, if you modify the-Program, your modified version must prominently offer all users-interacting with it remotely through a computer network (if your version-supports such interaction) an opportunity to receive the Corresponding-Source of your version by providing access to the Corresponding Source-from a network server at no charge, through some standard or customary-means of facilitating copying of software. This Corresponding Source-shall include the Corresponding Source for any work covered by version 3-of the GNU General Public License that is incorporated pursuant to the-following paragraph.-- Notwithstanding any other provision of this License, you have-permission to link or combine any covered work with a work licensed-under version 3 of the GNU General Public License into a single-combined work, and to convey the resulting work. The terms of this-License will continue to apply to the part which is the covered work,-but the work with which it is combined will remain governed by version-3 of the GNU General Public License.-- 14. Revised Versions of this License.-- The Free Software Foundation may publish revised and/or new versions of-the GNU Affero General Public License from time to time. Such new versions-will be similar in spirit to the present version, but may differ in detail to-address new problems or concerns.-- Each version is given a distinguishing version number. If the-Program specifies that a certain numbered version of the GNU Affero General-Public License "or any later version" applies to it, you have the-option of following the terms and conditions either of that numbered-version or of any later version published by the Free Software-Foundation. If the Program does not specify a version number of the-GNU Affero General Public License, you may choose any version ever published-by the Free Software Foundation.-- If the Program specifies that a proxy can decide which future-versions of the GNU Affero General Public License can be used, that proxy's-public statement of acceptance of a version permanently authorizes you-to choose that version for the Program.-- Later license versions may give you additional or different-permissions. However, no additional obligations are imposed on any-author or copyright holder as a result of your choosing to follow a-later version.-- 15. Disclaimer of Warranty.-- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.-- 16. Limitation of Liability.-- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF-SUCH DAMAGES.-- 17. Interpretation of Sections 15 and 16.-- If the disclaimer of warranty and limitation of liability provided-above cannot be given local legal effect according to their terms,-reviewing courts shall apply local law that most closely approximates-an absolute waiver of all civil liability in connection with the-Program, unless a warranty or assumption of liability accompanies a-copy of the Program in return for a fee.-- END OF TERMS AND CONDITIONS-- How to Apply These Terms to Your New Programs-- If you develop a new program, and you want it to be of the greatest-possible use to the public, the best way to achieve this is to make it-free software which everyone can redistribute and change under these terms.-- To do so, attach the following notices to the program. It is safest-to attach them to the start of each source file to most effectively-state the exclusion of warranty; and each file should have at least-the "copyright" line and a pointer to where the full notice is found.-- <one line to give the program's name and a brief idea of what it does.>- Copyright (C) <year> <name of author>-- This program is free software: you can redistribute it and/or modify- it under the terms of the GNU Affero General Public License as published by- the Free Software Foundation, either version 3 of the License, or- (at your option) any later version.-- This program is distributed in the hope that it will be useful,- but WITHOUT ANY WARRANTY; without even the implied warranty of- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- GNU Affero General Public License for more details.-- You should have received a copy of the GNU Affero General Public License- along with this program. If not, see <https://www.gnu.org/licenses/>.--Also add information on how to contact you by electronic and paper mail.+MIT License Copyright (c) 2020 Tocqueville Group - If your software can interact with users remotely through a computer-network, you should also make sure that it provides a way for users to-get its source. For example, if your program is a web application, its-interface could display a "Source" link that leads users to an archive-of the code. There are many ways you could offer source, and different-solutions will be better for different programs; see section 13 for the-specific requirements.+Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is furnished+to do so, subject to the following conditions: - You should also get your employer (if you work as a programmer) or school,-if any, to sign a "copyright disclaimer" for the program, if necessary.-For more information on this, and how to apply and follow the GNU AGPL, see-<https://www.gnu.org/licenses/>.+The above copyright notice and this permission notice (including the next+paragraph) shall be included in all copies or substantial portions of the+Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS+OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF+OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
README.md view
@@ -1,3 +1,9 @@+<!--+SPDX-FileCopyrightText: 2020 Tocqueville Group++SPDX-License-Identifier: LicenseRef-MIT-TQ+-->+ # Morley: Developer tools for the Michelson Language [](https://hackage.haskell.org/package/morley)
Setup.hs view
@@ -1,2 +1,6 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ import Distribution.Simple main = defaultMain
app/Main.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Main ( main ) where@@ -23,7 +27,7 @@ typeCheckWithDb) import Michelson.Runtime.GState (genesisAddress) import Michelson.TypeCheck.Types (SomeContract(..), mapSomeContract)-import Michelson.Typed (FullContract(..))+import Michelson.Typed (Contract(..)) import qualified Michelson.Untyped as U import Morley.CLI import Tezos.Address (Address)@@ -293,7 +297,7 @@ untypedContract <- prepareContract aoContractFile SomeContract contract <- either throwM pure =<< typeCheckWithDb aoDBPath untypedContract- putTextLn $ pretty $ analyze (fcCode contract)+ putTextLn $ pretty $ analyze (cCode contract) TypeCheck TypeCheckOptions{..} -> do morleyContract <- prepareContract tcoContractFile either throwM (const pass) =<< typeCheckWithDb tcoDBPath morleyContract
bench/Main.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Main (main) where import qualified Data.Map as M@@ -38,7 +42,7 @@ let basicBench = bench basicFp (nf- (interpret (T.fcCode basicC) T.epcPrimitive T.VUnit (T.VList [T.VInt 0]))+ (interpret (T.cCode basicC) T.epcPrimitive T.VUnit (T.VList [T.VInt 0])) dummyContractEnv ) @@ -46,18 +50,18 @@ dummyString = mkMTextUnsafe "TGAP" stringCallerBench = bench stringCallerFp (nf- (interpret (T.fcCode stringCallerC) T.epcPrimitive (T.toVal dummyString) (T.toVal dummyAddress))+ (interpret (T.cCode stringCallerC) T.epcPrimitive (T.toVal dummyString) (T.toVal dummyAddress)) dummyContractEnv ) callSelfBench = bench callSelfFp (nf- (interpret (T.fcCode callSelfC) T.epcPrimitive (T.toVal (100 :: Integer)) (T.toVal (0 :: Natural)))+ (interpret (T.cCode callSelfC) T.epcPrimitive (T.toVal (100 :: Integer)) (T.toVal (0 :: Natural))) dummyContractEnv ) sq2Bench = bench sq2Fp (nf- (interpret (T.fcCode sq2C) T.epcPrimitive (T.toVal (100 :: Integer, 200 :: Integer)) T.VUnit)+ (interpret (T.cCode sq2C) T.epcPrimitive (T.toVal (100 :: Integer, 200 :: Integer)) T.VUnit) dummyContractEnv )
morley.cabal view
@@ -4,19 +4,19 @@ -- -- see: https://github.com/sol/hpack ----- hash: 987d0620d3775b492e6130748d155b4aa4f41a8fc5e517837f3d0de73f0b85ed+-- hash: 71cfcdcc615797d3a54aa8f14a7cc29b27deb7ba4b9c6c464091aec8fdd56a45 name: morley-version: 1.2.0+version: 1.3.0 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 homepage: https://gitlab.com/morley-framework/morley-bug-reports: https://gitlab.com/morley-framework/morley/issues+bug-reports: https://gitlab.com/morley-framework/morley/-/issues author: camlCase, Serokell, Tocqueville Group maintainer: Serokell <hi@serokell.io> copyright: 2018 camlCase, 2019-2020 Tocqueville Group-license: AGPL-3.0-or-later+license: MIT license-file: LICENSE build-type: Simple extra-source-files:@@ -90,6 +90,7 @@ Michelson.Typed.Haskell.Instr.Product Michelson.Typed.Haskell.Instr.Sum Michelson.Typed.Haskell.LooseSum+ Michelson.Typed.Haskell.ValidateDescription Michelson.Typed.Haskell.Value Michelson.Typed.Instr Michelson.Typed.Polymorphic@@ -127,6 +128,7 @@ Util.Generic Util.Instances Util.IO+ Util.IO.GHC Util.Label Util.Lens Util.Markdown@@ -148,7 +150,7 @@ Paths_morley hs-source-dirs: src- default-extensions: ApplicativeDo AllowAmbiguousTypes BangPatterns BlockArguments ConstraintKinds DataKinds DefaultSignatures DeriveAnyClass DeriveDataTypeable DeriveFoldable DeriveFunctor DeriveGeneric DeriveTraversable DerivingStrategies EmptyCase FlexibleContexts FlexibleInstances GADTs GeneralizedNewtypeDeriving LambdaCase MultiParamTypeClasses MultiWayIf NamedFieldPuns NegativeLiterals NumDecimals OverloadedLabels OverloadedStrings PatternSynonyms PolyKinds QuasiQuotes RankNTypes RecordWildCards RecursiveDo ScopedTypeVariables StandaloneDeriving StrictData TemplateHaskell TupleSections TypeApplications TypeFamilies TypeOperators UndecidableInstances ViewPatterns+ default-extensions: ApplicativeDo AllowAmbiguousTypes BangPatterns BlockArguments ConstraintKinds DataKinds DefaultSignatures DeriveAnyClass DeriveDataTypeable DeriveFoldable DeriveFunctor DeriveGeneric DeriveTraversable DerivingStrategies EmptyCase FlexibleContexts FlexibleInstances GADTs GeneralizedNewtypeDeriving LambdaCase MultiParamTypeClasses MultiWayIf NamedFieldPuns NegativeLiterals NumDecimals OverloadedLabels OverloadedStrings PatternSynonyms PolyKinds QuasiQuotes RankNTypes RecordWildCards RecursiveDo ScopedTypeVariables StandaloneDeriving StrictData TemplateHaskell TupleSections TypeApplications TypeFamilies TypeOperators UndecidableInstances UndecidableSuperClasses 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 build-depends: HUnit@@ -213,7 +215,7 @@ Paths_morley hs-source-dirs: app- default-extensions: ApplicativeDo AllowAmbiguousTypes BangPatterns BlockArguments ConstraintKinds DataKinds DefaultSignatures DeriveAnyClass DeriveDataTypeable DeriveFoldable DeriveFunctor DeriveGeneric DeriveTraversable DerivingStrategies EmptyCase FlexibleContexts FlexibleInstances GADTs GeneralizedNewtypeDeriving LambdaCase MultiParamTypeClasses MultiWayIf NamedFieldPuns NegativeLiterals NumDecimals OverloadedLabels OverloadedStrings PatternSynonyms PolyKinds QuasiQuotes RankNTypes RecordWildCards RecursiveDo ScopedTypeVariables StandaloneDeriving StrictData TemplateHaskell TupleSections TypeApplications TypeFamilies TypeOperators UndecidableInstances ViewPatterns+ default-extensions: ApplicativeDo AllowAmbiguousTypes BangPatterns BlockArguments ConstraintKinds DataKinds DefaultSignatures DeriveAnyClass DeriveDataTypeable DeriveFoldable DeriveFunctor DeriveGeneric DeriveTraversable DerivingStrategies EmptyCase FlexibleContexts FlexibleInstances GADTs GeneralizedNewtypeDeriving LambdaCase MultiParamTypeClasses MultiWayIf NamedFieldPuns NegativeLiterals NumDecimals OverloadedLabels OverloadedStrings PatternSynonyms PolyKinds QuasiQuotes RankNTypes RecordWildCards RecursiveDo ScopedTypeVariables StandaloneDeriving StrictData TemplateHaskell TupleSections TypeApplications TypeFamilies TypeOperators UndecidableInstances UndecidableSuperClasses 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 build-depends: base-noprelude >=4.7 && <5@@ -273,7 +275,7 @@ Paths_morley hs-source-dirs: test- default-extensions: ApplicativeDo AllowAmbiguousTypes BangPatterns BlockArguments ConstraintKinds DataKinds DefaultSignatures DeriveAnyClass DeriveDataTypeable DeriveFoldable DeriveFunctor DeriveGeneric DeriveTraversable DerivingStrategies EmptyCase FlexibleContexts FlexibleInstances GADTs GeneralizedNewtypeDeriving LambdaCase MultiParamTypeClasses MultiWayIf NamedFieldPuns NegativeLiterals NumDecimals OverloadedLabels OverloadedStrings PatternSynonyms PolyKinds QuasiQuotes RankNTypes RecordWildCards RecursiveDo ScopedTypeVariables StandaloneDeriving StrictData TemplateHaskell TupleSections TypeApplications TypeFamilies TypeOperators UndecidableInstances ViewPatterns DerivingStrategies+ default-extensions: ApplicativeDo AllowAmbiguousTypes BangPatterns BlockArguments ConstraintKinds DataKinds DefaultSignatures DeriveAnyClass DeriveDataTypeable DeriveFoldable DeriveFunctor DeriveGeneric DeriveTraversable DerivingStrategies EmptyCase FlexibleContexts FlexibleInstances GADTs GeneralizedNewtypeDeriving LambdaCase MultiParamTypeClasses MultiWayIf NamedFieldPuns NegativeLiterals NumDecimals OverloadedLabels OverloadedStrings PatternSynonyms PolyKinds QuasiQuotes RankNTypes RecordWildCards RecursiveDo ScopedTypeVariables StandaloneDeriving StrictData TemplateHaskell TupleSections TypeApplications TypeFamilies TypeOperators UndecidableInstances UndecidableSuperClasses ViewPatterns DerivingStrategies 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 -threaded -with-rtsopts=-N build-tool-depends: tasty-discover:tasty-discover@@ -315,7 +317,7 @@ Paths_morley hs-source-dirs: bench- default-extensions: ApplicativeDo AllowAmbiguousTypes BangPatterns BlockArguments ConstraintKinds DataKinds DefaultSignatures DeriveAnyClass DeriveDataTypeable DeriveFoldable DeriveFunctor DeriveGeneric DeriveTraversable DerivingStrategies EmptyCase FlexibleContexts FlexibleInstances GADTs GeneralizedNewtypeDeriving LambdaCase MultiParamTypeClasses MultiWayIf NamedFieldPuns NegativeLiterals NumDecimals OverloadedLabels OverloadedStrings PatternSynonyms PolyKinds QuasiQuotes RankNTypes RecordWildCards RecursiveDo ScopedTypeVariables StandaloneDeriving StrictData TemplateHaskell TupleSections TypeApplications TypeFamilies TypeOperators UndecidableInstances ViewPatterns+ default-extensions: ApplicativeDo AllowAmbiguousTypes BangPatterns BlockArguments ConstraintKinds DataKinds DefaultSignatures DeriveAnyClass DeriveDataTypeable DeriveFoldable DeriveFunctor DeriveGeneric DeriveTraversable DerivingStrategies EmptyCase FlexibleContexts FlexibleInstances GADTs GeneralizedNewtypeDeriving LambdaCase MultiParamTypeClasses MultiWayIf NamedFieldPuns NegativeLiterals NumDecimals OverloadedLabels OverloadedStrings PatternSynonyms PolyKinds QuasiQuotes RankNTypes RecordWildCards RecursiveDo ScopedTypeVariables StandaloneDeriving StrictData TemplateHaskell TupleSections TypeApplications TypeFamilies TypeOperators UndecidableInstances UndecidableSuperClasses 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 build-depends: base-noprelude >=4.7 && <5
src/Michelson/Analyzer.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Static analysis of Michelson code. module Michelson.Analyzer
src/Michelson/Doc.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE TypeFamilyDependencies, UndecidableSuperClasses #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-} @@ -511,7 +515,7 @@ morleyRepoSettings :: GitRepoSettings morleyRepoSettings = GitRepoSettings $ \commit ->- "https://gitlab.com/morley-framework/morley/blob/" <> commit+ "https://gitlab.com/morley-framework/morley/-/tree/" <> commit -- | Make 'DGitRevision'. --
src/Michelson/Doc/Test.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utilities for testing documentations sanity. -- -- These tests serve to ensure that documentation generation is not broken and@@ -19,6 +23,7 @@ , testNoGitInfo , testDocNotEmpty , testNoAdjacentDescriptions+ , testStorageIsDocumented -- * Utilities , forEachContractLayer@@ -37,6 +42,7 @@ import qualified Text.Show import Michelson.Doc+import Michelson.Typed.Haskell.Doc ---------------------------------------------------------------------------- -- Framework@@ -218,6 +224,13 @@ toString desc <> "\"" | otherwise = pass +-- | Test whether storage documentation is included in the contract's documentation.+testStorageIsDocumented :: DocTest+testStorageIsDocumented =+ mkDocTest "Storage documentation is included" $+ \contractDoc -> assertBool "No documentation for storage in the contract." $+ or $ forEachContractDocItem contractDoc $ \(DStorageType _) -> True+ -- | Base properties which should comply for all documentations. testDocBasic :: [DocTest] testDocBasic =@@ -226,4 +239,5 @@ , testDocNotEmpty , testNoAdjacentDescriptions , testDescriptionsAreWellFormatted+ , testStorageIsDocumented ]
src/Michelson/ErrorPos.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.ErrorPos ( mkPos , Pos (..)
src/Michelson/FailPattern.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Typical usages of FAILWITH instruction. module Michelson.FailPattern
src/Michelson/Interpret.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing function to interpret Michelson -- instructions against given context and input stack. module Michelson.Interpret@@ -180,7 +184,7 @@ -> ContractEnv -> Either InterpretError InterpretResult interpretUntyped uContract@U.Contract{..} paramU initStU env = do- SomeContract (FullContract (instr :: ContractCode cp st) _ _)+ SomeContract (Contract (instr :: ContractCode cp st) _ _) <- first IllTypedContract $ typeCheckContract (ceContracts env) uContract -- Do creates dummy scope to somehow overcome this: -- GHC internal error: ‘st’ is not in scope during type checking, but it passed the renamer.@@ -511,10 +515,10 @@ case mbKeyHash of Just (VKeyHash k) -> pure $ VOp (OpSetDelegate $ SetDelegate $ Just k) :& r Nothing -> pure $ VOp (OpSetDelegate $ SetDelegate $ Nothing) :& r-runInstrImpl _ (CREATE_CONTRACT fullContract)+runInstrImpl _ (CREATE_CONTRACT contract) (VOption mbKeyHash :& VMutez m :& g :& r) = do originator <- ceSelf <$> ask- let ops = fcCode fullContract+ let ops = cCode contract let resAddr = U.mkContractAddress $ createOrigOp originator mbKeyHash m ops g let resEpAddr = EpAddress resAddr def let resOp = CreateContract originator (unwrapMbKeyHash mbKeyHash) m g ops
src/Michelson/Interpret/Pack.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, carrying logic of @PACK@ instruction. -- -- This is nearly symmetric to adjacent Unpack.hs module.@@ -347,7 +351,7 @@ "\x03\x4d" SET_DELEGATE -> "\x03\x4e"- CREATE_CONTRACT (FullContract instr np ng)+ CREATE_CONTRACT (Contract instr np ng) | _ :: Instr '[ 'TPair p g ] '[ 'TPair ('TList 'TOperation) g ] <- instr -> let contents = [ "\x05\x00" <> encodeParamNotes' @p np@@ -420,14 +424,14 @@ encodeWithAnns [tn] [fn1, fn2] vns $ "\x05\x44" <> encodeNotedT' @l ns1 (NIL, _ :: Proxy ('TList t ': s), NTList tn ns) -> encodeWithAnns [tn] [] vns $ "\x05\x3d" <> encodeNotedT' @t ns- (EMPTY_SET, _ :: Proxy ('TSet t ': s), NTSet tn1 tn2) ->- encodeWithAnns [tn1] [] vns $ "\x05\x24" <> encodeNotedT' @t (insertTypeAnn tn2 starNotes)- (EMPTY_MAP, _ :: Proxy ('TMap k v ': s), NTMap tn1 tn2 ns) ->+ (EMPTY_SET, _ :: Proxy ('TSet t ': s), NTSet tn ns) ->+ encodeWithAnns [tn] [] vns $ "\x05\x24" <> encodeNotedT' @t ns+ (EMPTY_MAP, _ :: Proxy ('TMap k v ': s), NTMap tn1 nk ns) -> encodeWithAnns [tn1] [] vns $- "\x07\x23" <> encodeNotedT' @k (insertTypeAnn tn2 starNotes) <> encodeNotedT' @v ns- (EMPTY_BIG_MAP, _ :: Proxy ('TBigMap k v ': s), NTBigMap tn1 tn2 ns) ->+ "\x07\x23" <> encodeNotedT' @k nk <> encodeNotedT' @v ns+ (EMPTY_BIG_MAP, _ :: Proxy ('TBigMap k v ': s), NTBigMap tn1 nk ns) -> encodeWithAnns [tn1] [] vns $- "\x07\x72" <> encodeNotedT' @k (insertTypeAnn tn2 starNotes) <> encodeNotedT' @v ns+ "\x07\x72" <> encodeNotedT' @k nk <> encodeNotedT' @v ns (PUSH (v :: Value t), _, tn) -> "\x07\x43" <> encodeNotedT' @t tn <> encodeValue v (LAMBDA (v :: Value ('TLambda i o)), _, NTLambda _tn ns1 ns2) ->@@ -487,8 +491,8 @@ encodeWithAnns [tn] [fn] [] $ "\x05\x63" <> encodeNotedST a noAnn ns (STList a, NTList tn ns) -> encodeWithAnns [tn] [fn] [] $ "\x05\x5f" <> encodeNotedST a noAnn ns- (STSet a, NTSet tn1 tn2) ->- encodeWithAnns [tn1] [fn] [] $ "\x05\x66" <> encodeWithAnns [tn2] [] [] (encodeT (fromSingT a))+ (STSet a, NTSet tn ns) ->+ encodeWithAnns [tn] [fn] [] $ "\x05\x66" <> encodeNotedST a noAnn ns (STOperation, NTOperation tn) -> encodeWithAnns [tn] [fn] [] $ "\x03\x6d" (STContract a, NTContract tn ns) ->@@ -502,12 +506,12 @@ (STLambda a r, NTLambda tn ns1 ns2) -> encodeWithAnns [tn] [fn] [] $ "\x07\x5e" <> encodeNotedST a noAnn ns1 <> encodeNotedST r noAnn ns2- (STMap k v, NTMap tn1 tn2 ns) ->- encodeWithAnns [tn1] [fn] [] $- "\x07\x60" <> encodeWithAnns [tn2] [] [] (encodeT (fromSingT k)) <> encodeNotedST v noAnn ns- (STBigMap k v, NTBigMap tn1 tn2 ns) ->- encodeWithAnns [tn1] [fn] [] $- "\x07\x61" <> encodeWithAnns [tn2] [] [] (encodeT (fromSingT k)) <> encodeNotedST v noAnn ns+ (STMap k v, NTMap tn nk nv) ->+ encodeWithAnns [tn] [fn] [] $+ "\x07\x60" <> encodeNotedST k noAnn nk <> encodeNotedST v noAnn nv+ (STBigMap k v, NTBigMap tn nk nv) ->+ encodeWithAnns [tn] [fn] [] $+ "\x07\x61" <> encodeNotedST k noAnn nk <> encodeNotedST v noAnn nv encodeT :: T -> LByteString encodeT = \case
src/Michelson/Interpret/Unpack.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {- | Module, carrying logic of @UNPACK@ instruction. This is nearly symmetric to adjacent Pack.hs module.
src/Michelson/Let.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Let ( LetType (..) , LetValue (..)
src/Michelson/Macro.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Macro ( -- * Macros types
src/Michelson/OpSize.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Measuring operation size. -- -- When originating a contract or making a transfer, tezos node forms operation
src/Michelson/Optimizer.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Optimizer for typed instructions. -- -- It's quite experimental and incomplete.
src/Michelson/Parser.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Parser ( -- * Main parser type Parser@@ -20,10 +24,12 @@ -- * For tests , codeEntry , type_+ , letInner , letType , stringLiteral , bytesLiteral , intLiteral+ , parsedOp , printComment -- * Quoters
src/Michelson/Parser/Annotations.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Parser.Annotations ( note , noteF
src/Michelson/Parser/Error.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Custom exceptions that can happen during parsing. module Michelson.Parser.Error
src/Michelson/Parser/Ext.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Parsing logic for extra instructions (Morley extensions) module Michelson.Parser.Ext
src/Michelson/Parser/Helpers.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Parser.Helpers ( mkParser , sepEndBy1
src/Michelson/Parser/Instr.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Parsing of Michelson instructions. module Michelson.Parser.Instr
src/Michelson/Parser/Let.hs view
@@ -1,9 +1,14 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Parsing of let blocks module Michelson.Parser.Let ( letBlock , mkLetMac -- * For tests+ , letInner , letType ) where @@ -57,9 +62,9 @@ lets :: Parser ParsedOp -> Parser Let lets opParser = choice- [ (LetM <$> (try $ letMacro opParser))- , (LetV <$> (try $ letValue opParser))- , (LetT <$> (try letType))+ [ (LetM <$> letMacro opParser)+ , (LetV <$> letValue opParser)+ , (LetT <$> letType) ] -- | build a let name parser from a leading character parser@@ -72,8 +77,10 @@ letMacro :: Parser ParsedOp -> Parser LetMacro letMacro opParser = lexeme $ do- n <- letName lowerChar- symbol "::"+ n <- try $ do+ n <- letName lowerChar+ symbol "::"+ return n s <- stackFn symbol "=" o <- ops' opParser@@ -81,9 +88,11 @@ letType :: Parser LetType letType = lexeme $ do- symbol "type"- n <- letName upperChar <|> letName lowerChar- symbol "="+ n <- try $ do+ symbol "type"+ n <- letName upperChar <|> letName lowerChar+ symbol "="+ return n t@(Type t' a) <- type_ return $ if a == noAnn then LetType n (Type t' (ann n))@@ -91,8 +100,10 @@ letValue :: Parser ParsedOp -> Parser LetValue letValue opParser = lexeme $ do- n <- letName upperChar- symbol "::"+ n <- try $ do+ n <- letName upperChar+ symbol "::"+ return n t <- type_ symbol "=" v <- value' opParser
src/Michelson/Parser/Lexer.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Parser.Lexer ( lexeme , mSpace
src/Michelson/Parser/Macro.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Parsing of built-in Michelson macros. module Michelson.Parser.Macro
src/Michelson/Parser/Type.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Parsing of Michelson types. module Michelson.Parser.Type
src/Michelson/Parser/Types.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Core parser types module Michelson.Parser.Types
src/Michelson/Parser/Value.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Parsing of untyped Michelson values. module Michelson.Parser.Value
src/Michelson/Preprocess.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Apply some transformations to Michelson code. module Michelson.Preprocess@@ -6,8 +10,6 @@ ) where import Data.Default (def)-import qualified Data.Map.Strict as Map-import qualified Data.Set as Set import Michelson.Text (MText) import Michelson.Typed@@ -20,48 +22,32 @@ -- function. The first argument specifies whether we should go into -- arguments that contain instructions. transformStrings :: Bool -> (MText -> MText) -> Instr inp out -> Instr inp out-transformStrings goToValues f = transformConstants goToValues valF+transformStrings goToValues f = transformConstants goToValues mapStr where- valF :: Value t -> Value t- valF = \case+ mapStr :: Value t -> Value t+ mapStr = \case VString str -> VString $ f str- VOption mv -> VOption (valF <$> mv)- VList vs -> VList (valF <$> vs)- VSet vSet -> VSet (Set.map valF vSet)- VPair (v1, v2) -> VPair (valF v1, valF v2)- VOr eith -> VOr (bimap valF valF eith)- VMap m -> VMap . fmap valF . Map.mapKeys valF $ m- VBigMap m -> VBigMap . fmap valF . Map.mapKeys valF $ m- -- We do not handle 'VLam' here, because 'dfsInstr' takes care of that. v -> v -- | Similar to 'transformStrings' but for bytes.--- TODO [TM-375]: deduplicate transformBytes :: Bool -> (ByteString -> ByteString) -> Instr inp out -> Instr inp out-transformBytes goToValues f = transformConstants goToValues valF+transformBytes goToValues f = transformConstants goToValues mapBytes where- valF :: Value t -> Value t- valF = \case- VBytes str -> VBytes $ f str- VOption mv -> VOption (valF <$> mv)- VList vs -> VList (valF <$> vs)- VSet vSet -> VSet (Set.map valF vSet)- VPair (v1, v2) -> VPair (valF v1, valF v2)- VOr eith -> VOr (bimap valF valF eith)- VMap m -> VMap . fmap valF . Map.mapKeys valF $ m- VBigMap m -> VBigMap . fmap valF . Map.mapKeys valF $ m- -- We do not handle 'VLam' here, because 'dfsInstr' takes care of that.+ mapBytes :: Value t -> Value t+ mapBytes = \case+ VBytes bytes -> VBytes $ f bytes v -> v transformConstants :: forall inp out. Bool -> (forall t. Value t -> Value t)+ -- ^ Should transform only atomic values, 'dfsValue' will be applied to it. -> Instr inp out -> Instr inp out transformConstants dsGoToValues f = fst . dfsInstr def{ dsGoToValues } step where step :: forall i o. Instr i o -> (Instr i o, ()) step = (,()) . \case- PUSH v -> PUSH (f v)+ PUSH v -> PUSH (dfsModifyValue f v) i -> i
src/Michelson/Printer.hs view
@@ -1,9 +1,13 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Printer ( RenderDoc(..) , printDoc , printUntypedContract , printTypedContractCode- , printTypedFullContract+ , printTypedContract , printSomeContract , printTypedValue , printUntypedValue@@ -31,9 +35,9 @@ -- | Convert typed contract into a textual representation which -- will be accepted by the OCaml reference client.-printTypedFullContract :: Bool -> T.FullContract p s -> TL.Text-printTypedFullContract forceSingleLine fc@T.FullContract{} =- printUntypedContract forceSingleLine $ T.convertFullContract fc+printTypedContract :: Bool -> T.Contract p s -> TL.Text+printTypedContract forceSingleLine fc@T.Contract{} =+ printUntypedContract forceSingleLine $ T.convertContract fc -- | Convert typed value into a textual representation which -- will be accepted by the OCaml reference client.@@ -55,4 +59,4 @@ -- will be accepted by the OCaml reference client. printSomeContract :: Bool -> SomeContract -> TL.Text printSomeContract forceSingleLine (SomeContract fc) =- printTypedFullContract forceSingleLine fc+ printTypedContract forceSingleLine fc
src/Michelson/Printer/Util.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Printer.Util ( RenderDoc(..) , Prettier(..)
src/Michelson/Runtime.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Executor and typechecker of a contract in Morley language. module Michelson.Runtime@@ -464,7 +468,7 @@ SomeContractAndStorage typedContract typedStorage <- getTypedContractAndStorage EEIllTypedContract EEIllTypedStorage gs cs T.MkEntryPointCallRes _ epc- <- T.mkEntryPointCall epName (T.fcParamNotes typedContract)+ <- T.mkEntryPointCall epName (T.cParamNotes typedContract) & maybe (throwError $ EEUnknownEntrypoint epName) pure typedParameter <- first EEIllTypedParameter $ typeVerifyTopLevelType existingContracts (tdParameter txData)@@ -475,7 +479,7 @@ } <- first (EEInterpreterFailed addr) $ handleContractReturn $- interpret (T.fcCode typedContract) epc+ interpret (T.cCode typedContract) epc typedParameter typedStorage contractEnv let newValueU = untypeValue newValue
src/Michelson/Runtime/GState.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Global blockchain state (emulated). module Michelson.Runtime.GState@@ -26,6 +30,10 @@ , genesisAddress5 , genesisAddress6 , genesisKeyHash+ -- * Genesis secret keys+ , genesisSecretKey+ , genesisSecrets+ , initGState , readGState , writeGState@@ -161,7 +169,7 @@ -- broader than it data SomeContractAndStorage = forall cp st. (ParameterScope cp, StorageScope st) => SomeContractAndStorage- { scsContract :: T.FullContract cp st+ { scsContract :: T.Contract cp st , scsStorage :: T.Value st } @@ -172,7 +180,7 @@ -> ContractState -> Either err SomeContractAndStorage getTypedContractAndStorage liftContractErr liftStorageErr gs cs = do- SomeContract (contract@T.FullContract{} :: T.FullContract cp st) <-+ SomeContract (contract@T.Contract{} :: T.Contract cp st) <- first liftContractErr $ getTypedContract gs cs SomeValue (storage :: T.Value st') <- first liftStorageErr $ getTypedStorage gs cs@@ -206,6 +214,10 @@ -- | One of genesis addresses. genesisAddress :: Address genesisAddress = head genesisAddresses++-- | Secret key assotiated with 'genesisAddress'.+genesisSecretKey :: SecretKey+genesisSecretKey = head genesisSecrets -- | More genesis addresses --
src/Michelson/Runtime/TxData.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | 'TxData' type and associated functionality. module Michelson.Runtime.TxData
src/Michelson/Test.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module containing some utilities for testing Michelson contracts using -- Haskell testing frameworks (hspec and QuickCheck in particular). -- It's Morley testing EDSL.
src/Michelson/Test/Dummy.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Dummy data to be used in tests where it's not essential. module Michelson.Test.Dummy
src/Michelson/Test/Gen.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-orphans #-} -- | Utilities for arbitrary data generation in property tests.
src/Michelson/Test/Import.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Functions to import contracts to be used in tests. module Michelson.Test.Import@@ -32,7 +36,7 @@ import Michelson.Parser.Error (ParserException(..)) import Michelson.Runtime (parseExpandContract, prepareContract) import Michelson.TypeCheck (SomeContract(..), TCError, typeCheckContract)-import Michelson.Typed (FullContract(..), toUType)+import Michelson.Typed (Contract(..), toUType) import qualified Michelson.Untyped as U import Util.IO @@ -48,7 +52,7 @@ -- result will notify about problem). testTreesWithContract :: (Each [Typeable, SingI] [cp, st], HasCallStack)- => FilePath -> ((U.Contract, FullContract cp st) -> IO [TestTree]) -> IO [TestTree]+ => FilePath -> ((U.Contract, Contract cp st) -> IO [TestTree]) -> IO [TestTree] testTreesWithContract = testTreesWithContractImpl importContract -- | Like 'testTreesWithContract' but supplies only untyped contract.@@ -61,7 +65,7 @@ -- | Like 'testTreesWithContract' but supplies only typed contract. testTreesWithTypedContract :: (Each [Typeable, SingI] [cp, st], HasCallStack)- => FilePath -> (FullContract cp st -> IO [TestTree]) -> IO [TestTree]+ => FilePath -> (Contract cp st -> IO [TestTree]) -> IO [TestTree] testTreesWithTypedContract = testTreesWithContractImpl (fmap snd . importContract) @@ -94,14 +98,14 @@ -- result will notify about problem). specWithContract :: (Each [Typeable, SingI] [cp, st], HasCallStack)- => FilePath -> ((U.Contract, FullContract cp st) -> Spec) -> Spec+ => FilePath -> ((U.Contract, Contract cp st) -> Spec) -> Spec specWithContract = specWithContractImpl importContract -- | A version of 'specWithContract' which passes only the typed -- representation of the contract. specWithTypedContract :: (Each [Typeable, SingI] [cp, st], HasCallStack)- => FilePath -> (FullContract cp st -> Spec) -> Spec+ => FilePath -> (Contract cp st -> Spec) -> Spec specWithTypedContract = specWithContractImpl (fmap snd . importContract) specWithUntypedContract :: FilePath -> (U.Contract -> Spec) -> Spec@@ -137,10 +141,10 @@ Each [Typeable, SingI] [cp, st] => FilePath -> Text- -> Either ImportContractError (U.Contract, FullContract cp st)+ -> Either ImportContractError (U.Contract, Contract cp st) readContract filePath txt = do contract <- first ICEParse $ parseExpandContract (Just filePath) txt- SomeContract (tContract@FullContract{} :: FullContract cp' st')+ SomeContract (tContract@Contract{} :: Contract cp' st') <- first ICETypeCheck $ typeCheckContract mempty contract case (eqT @cp @cp', eqT @st @st') of (Just Refl, Just Refl) -> pure (contract, tContract)@@ -158,7 +162,7 @@ importContract :: forall cp st . Each [Typeable, SingI] [cp, st]- => FilePath -> IO (U.Contract, FullContract cp st)+ => FilePath -> IO (U.Contract, Contract cp st) importContract file = either throwM pure =<< readContract file <$> readFileUtf8 file importUntypedContract :: FilePath -> IO U.Contract
src/Michelson/Test/Integrational.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utilities for integrational testing. -- Example tests can be found in the 'morley-test' test suite. @@ -52,6 +56,9 @@ , tExpectStorageConst , expectGasExhaustion , expectMichelsonFailed++ -- * Lenses+ , isGState ) where import Control.Lens (assign, at, makeLenses, makeLensesFor, modifying, (%=), (.=), (<>=), (?=))@@ -251,13 +258,13 @@ -- | Like 'originate', but for typed contract and value. tOriginate :: (ParameterScope cp, StorageScope st)- => Typed.FullContract cp st+ => Typed.Contract cp st -> Text -> Typed.Value st -> Mutez -> IntegrationalScenarioM Address tOriginate contract name value balance =- originate (Typed.convertFullContract contract) name+ originate (Typed.convertContract contract) name (Typed.untypeValue value) balance -- | Transfer tokens to a given address.
src/Michelson/Test/Unit.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utility functions for unit testing. module Michelson.Test.Unit@@ -24,7 +28,7 @@ import Michelson.Interpret (ContractEnv, ContractReturn, MichelsonFailed(..), interpret) import Michelson.Printer (printUntypedContract) import Michelson.Runtime (parseExpandContract)-import Michelson.Typed (FullContract, IsoValue(..), ToT)+import Michelson.Typed (Contract, IsoValue(..), ToT) import qualified Michelson.Typed as T import Michelson.Untyped hiding (Contract) import qualified Michelson.Untyped as U@@ -47,7 +51,7 @@ , ToT param ~ cp, ToT storage ~ st , T.ParameterScope cp )- => FullContract cp st+ => Contract cp st -> ContractPropValidator st prop -> ContractEnv -> param@@ -65,14 +69,14 @@ -- by "Michelson.Test.Integrational" module. contractPropVal :: (T.ParameterScope cp)- => FullContract cp st+ => Contract cp st -> ContractPropValidator st prop -> ContractEnv -> T.Value cp -> T.Value st -> prop contractPropVal instr check env param initSt =- check $ interpret (T.fcCode instr) T.epcCallRootUnsafe param initSt env+ check $ interpret (T.cCode instr) T.epcCallRootUnsafe param initSt env -- | Check if entrypoint is present in `T`. hasEp :: T -> (EpName, U.Type) -> Bool
src/Michelson/Test/Util.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Testing utility functions used by testing framework itself or -- intended to be used by test writers.
src/Michelson/Text.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- deriving 'Container' automatically produces extra constraints. {-# OPTIONS_GHC -Wno-redundant-constraints #-}
src/Michelson/TypeCheck.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.TypeCheck ( typeCheckContract , typeCheckTopLevelType
src/Michelson/TypeCheck/Error.hs view
@@ -1,7 +1,11 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Errors that can occur when some code is being typechecked. module Michelson.TypeCheck.Error- ( NotEnoughItemsInstr (..)+ ( ExpectType (..) , TypeContext (..) , TCTypeError (..) , TCError (..)@@ -9,7 +13,7 @@ , StackSize (..) ) where -import Fmt (Buildable(..), pretty, (+|), (+||), (|+), (||+))+import Fmt (Buildable(..), listF, pretty, (+|), (+||), (|+), (||+)) import qualified Text.Show (show) import Michelson.ErrorPos (InstrCallStack)@@ -23,23 +27,76 @@ import Tezos.Address (Address) import Tezos.Crypto (CryptoParseError) --- | Description of the instruction which wants more items on stack--- than currently present.-data NotEnoughItemsInstr- = NotEnoughDrop- | NotEnoughDip- | NotEnoughDig- | NotEnoughDug+-- | Description of the type to be expected by certain instruction.+data ExpectType+ = ExpectTypeVar+ | ExpectStackVar+ | ExpectBool+ | ExpectInt+ | ExpectNat+ | ExpectByte+ | ExpectString+ | ExpectAddress+ | ExpectKey+ | ExpectKeyHash+ | ExpectSignature+ | ExpectContract+ | ExpectMutez+ | ExpectList (Maybe ExpectType)+ | ExpectSet (Maybe ExpectType)+ | ExpectMap+ | ExpectBigMap+ | ExpectOption (Maybe ExpectType)+ | ExpectPair (Maybe ExpectType) (Maybe ExpectType)+ | ExpectOr (Maybe ExpectType) (Maybe ExpectType)+ | ExpectLambda (Maybe ExpectType) (Maybe ExpectType) deriving stock (Show, Eq, Generic) -instance NFData NotEnoughItemsInstr+instance NFData ExpectType -instance Buildable NotEnoughItemsInstr where+instance Buildable ExpectType where build = \case- NotEnoughDrop -> "DROP"- NotEnoughDip -> "DIP"- NotEnoughDig -> "DIG"- NotEnoughDug -> "DUG"+ ExpectTypeVar -> "'a"+ ExpectStackVar -> "'A"+ ExpectBool -> "bool"+ ExpectInt -> "int"+ ExpectNat -> "nat"+ ExpectByte -> "byte"+ ExpectString -> "string"+ ExpectAddress -> "address"+ ExpectKey -> "key"+ ExpectKeyHash -> "key_hash"+ ExpectSignature -> "signature"+ ExpectMutez -> "mutez"+ ExpectContract -> "contract 'p"+ ExpectList expType ->+ "list "+ +| maybe "'a" build expType+ ExpectSet expType ->+ "set "+ +| maybe "'a" build expType+ ExpectMap -> "map 'key 'val"+ ExpectBigMap -> "big_map 'key 'val"+ ExpectOption expType ->+ "option "+ +| maybe "'a" build expType+ ExpectPair expType1 expType2 ->+ "pair "+ +| (maybe "'a" build expType1) +| " "+ +| (maybe "'b" build expType2) +| ""+ ExpectOr expType1 expType2 ->+ "or "+ +| (maybe "'a" build expType1) +| " "+ +| (maybe "'b" build expType2) +| ""+ ExpectLambda expType1 expType2 ->+ "lambda "+ +| (maybe "'a"+ (\case+ ExpectPair a b -> "(" +| ExpectPair a b |+ ")" -- bracket is needed for APPLY+ x -> build x+ ) expType1+ ) +| " "+ +| (maybe "'b" build expType2) +| "" -- | Contexts where type error can occur. data TypeContext@@ -100,12 +157,16 @@ | NotNumericTypes T.T T.T -- ^ Arithmetic operation is applied to types, at least one of which is not numeric -- (e.g. @timestamp@ and @timestamp@ passed to @MUL@ instruction).+ | UnexpectedType (NonEmpty (NonEmpty ExpectType))+ -- ^ 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. | InvalidInstruction U.ExpandedInstr -- ^ Some instruction can not be used in a specific context, like @SELF@ in @LAMBDA@. | InvalidValueType T.T -- ^ Error that happens when a `U.Value` is never a valid source for this type -- (e.g. @timestamp@ cannot be obtained from a `U.ValueTrue`)- | NotEnoughItemsOnStack Word NotEnoughItemsInstr+ | NotEnoughItemsOnStack -- ^ There are not enough items on stack to perform a certain instruction. | IllegalEntryPoint T.EpNameFromRefAnnError -- ^ Invalid entrypoint name provided@@ -147,12 +208,18 @@ NotNumericTypes t1 t2 -> "Some of the types in an arithmetic operation are not numeric: " +| t1 |+ " and " +| t2 |+ ""+ UnexpectedType (t :| ts) ->+ "Wrong stack type for instruction, expect stack type to begin with " +|+ ( intercalate " or "+ $ fmap (\(x :| xs) -> "" +| listF (x:xs) |+ "")+ $ (t:ts)+ ) |+ "" InvalidInstruction instr -> "Forbidden instruction " +| instr |+ "" InvalidValueType t -> "Value type is never a valid `" +| t |+ "`"- NotEnoughItemsOnStack n instr ->- "Not enough items on stack to " +| instr |+ " " +| n |+ ""+ NotEnoughItemsOnStack ->+ "Not enough items on stack" UnknownContract addr -> "Contract is not registered: " +| addr |+ "" IllegalEntryPoint err -> build err
src/Michelson/TypeCheck/Ext.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Type-checking of Morley extension. module Michelson.TypeCheck.Ext ( typeCheckExt
src/Michelson/TypeCheck/Helpers.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.TypeCheck.Helpers ( onLeft , deriveSpecialVN@@ -53,8 +57,8 @@ import Michelson.TypeCheck.TypeCheck import Michelson.TypeCheck.Types import Michelson.Typed- (BadTypeForScope(..), Comparable, Instr(..), Notes(..), PackedNotes(..),- SingT(..), T(..), WellTyped, converge , getComparableProofS, notesT, orAnn, starNotes)+ (BadTypeForScope(..), Comparable, Instr(..), Notes(..), PackedNotes(..), SingT(..), T(..),+ WellTyped, converge, getComparableProofS, notesT, orAnn, starNotes) import Michelson.Typed.Annotation (AnnConvergeError, isStar) import Michelson.Typed.Arith (Add, ArithOp(..), Mul, Sub, UnaryArithOp(..)) import Michelson.Typed.Polymorphic@@ -328,44 +332,57 @@ -- | Generic implementation for MEMeration memImpl- :: forall (q :: T) (c :: T) ts inp m .- ( MonadReader InstrCallStack m, MonadError TCError m, Typeable ts- , Typeable (MemOpKey c), SingI (MemOpKey c), MemOp c- , inp ~ (q : c : ts)+ :: forall c memKey rs inp m .+ ( MemOp c+ , Typeable (MemOpKey c), SingI (MemOpKey c)+ , inp ~ (memKey : c : rs)+ , MonadReader InstrCallStack m+ , MonadError TCError m )- => Un.ExpandedInstr+ => Notes (MemOpKey c) -> HST inp -> VarAnn -> m (SomeInstr inp)-memImpl instr i@(_ ::& _ ::& rs) vn = do- pos <- ask- case eqType @q @(MemOpKey c) of- Right Refl -> pure $ i :/ MEM ::: ((starNotes, Dict, vn) ::& rs)- Left m -> throwError $- TCFailedOnInstr instr (SomeHST i) pos (Just ContainerKeyType) (Just m)+memImpl cKeyNotes inputHST@(hst0 ::& _ ::& hstTail) varAnn =+ case eqType @memKey @(MemOpKey c) of+ Right Refl -> do+ _ <- onTypeCheckInstrAnnErr uInstr inputHST+ (Just ContainerKeyType) (converge memKeyNotes cKeyNotes)+ pure $ inputHST :/+ MEM ::: ((starNotes, Dict, varAnn) ::& hstTail)+ Left m ->+ typeCheckInstrErr' uInstr (SomeHST inputHST) (Just ContainerKeyType) m+ where+ (memKeyNotes, Dict, _) = hst0+ uInstr = Un.MEM varAnn getImpl :: forall c getKey rs inp m .- ( GetOp c, Typeable (GetOpKey c)- , Typeable (GetOpVal c)- , SingI (GetOpVal c), SingI (GetOpKey c)+ ( GetOp c+ , Typeable (GetOpKey c), SingI (GetOpKey c)+ , Typeable (GetOpVal c), SingI (GetOpVal c) , WellTyped (GetOpVal c) , inp ~ (getKey : c : rs) , MonadReader InstrCallStack m , MonadError TCError m )- => Un.ExpandedInstr- -> HST (getKey ': c ': rs)+ => Notes (GetOpKey c)+ -> HST inp -> Notes (GetOpVal c) -> VarAnn -> m (SomeInstr inp)-getImpl instr i@(_ ::& _ ::& rs) vns vn = do- pos <- ask+getImpl notesKeyC inputHST@(hst0 ::& _ ::& hstTail) valueNotes varAnn = case eqType @getKey @(GetOpKey c) of Right Refl -> do- let rn = NTOption def vns- pure $ i :/ GET ::: ((rn, Dict, vn) ::& rs)- Left m -> throwError $ TCFailedOnInstr instr (SomeHST i) pos (Just ContainerKeyType) (Just m)+ _ <- onTypeCheckInstrAnnErr uInstr inputHST+ (Just ContainerKeyType) (converge getKeyNotes notesKeyC)+ pure $ inputHST :/+ GET ::: ((NTOption def valueNotes, Dict, varAnn) ::& hstTail)+ Left m ->+ typeCheckInstrErr' uInstr (SomeHST inputHST) (Just ContainerKeyType) m+ where+ (getKeyNotes, Dict, _) = hst0+ uInstr = Un.GET varAnn updImpl :: forall c updKey updParams rs inp m .@@ -376,19 +393,28 @@ , MonadReader InstrCallStack m , MonadError TCError m )- => Un.ExpandedInstr- -> HST (updKey ': updParams ': c ': rs)+ => Notes (UpdOpKey c)+ -> HST inp+ -> Notes (UpdOpParams c) -> VarAnn -> m (SomeInstr inp)-updImpl instr i@(_ ::& _ ::& cTuple ::& rest) vn = do- pos <- ask+updImpl cKeyNotes inputHST@(hst0 ::& hst1 ::& cTuple ::& hstTail) cValueNotes varAnn = case (eqType @updKey @(UpdOpKey c), eqType @updParams @(UpdOpParams c)) of- (Right Refl, Right Refl) ->- pure $ i :/ UPDATE ::: ((cTuple & _3 .~ vn) ::& rest)- (Left m, _) -> throwError $ TCFailedOnInstr instr (SomeHST i)- pos (Just ContainerKeyType) (Just m)- (_, Left m) -> throwError $ TCFailedOnInstr instr (SomeHST i)- pos (Just ContainerValueType) (Just m)+ (Right Refl, Right Refl) -> do+ _ <- onTypeCheckInstrAnnErr uInstr inputHST+ (Just ContainerKeyType) (converge updKeyNotes cKeyNotes)+ _ <- onTypeCheckInstrAnnErr uInstr inputHST+ (Just ContainerValueType) (converge updValueNotes cValueNotes)+ pure $ inputHST :/+ UPDATE ::: ((cTuple & _3 .~ varAnn) ::& hstTail)+ (Left m, _) ->+ typeCheckInstrErr' uInstr (SomeHST inputHST) (Just ContainerKeyType) m+ (_, Left m) ->+ typeCheckInstrErr' uInstr (SomeHST inputHST) (Just ContainerValueType) m+ where+ (updKeyNotes, Dict, _) = hst0+ (updValueNotes, Dict, _) = hst1+ uInstr = Un.UPDATE varAnn sizeImpl :: (SizeOp c, inp ~ (c ': rs), Monad m)
src/Michelson/TypeCheck/Instr.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, providing functions for conversion from -- instruction and value representation from @Michelson.Type@ module -- to strictly-typed GADT-based representation from @Michelson.Value@ module.@@ -72,7 +76,7 @@ Just Dict -> fn Nothing -> do loc <- ask- throwError $ TCFailedOnInstr v t loc Nothing Nothing+ throwError $ TCFailedOnInstr v t loc Nothing (Just $ UnsupportedTypeForScope (demote @t) BtNotComparable) typeCheckContractImpl :: U.Contract@@ -91,9 +95,9 @@ let inpNote = NTPair def def def paramNote storageNote let inp = (inpNote, Dict, def) ::& SNil inp' :/ instrOut <- usingReaderT def $ typeCheckImpl typeCheckInstr pCode inp- let (paramNotesRaw, fcStoreNotes) = case inp' of+ let (paramNotesRaw, cStoreNotes) = case inp' of (NTPair _ _ _ cpNotes stNotes, _, _) ::& SNil -> (cpNotes, stNotes)- fcParamNotes <-+ cParamNotes <- liftEither $ mkParamNotes paramNotesRaw rootAnn `onLeft` (TCContractError "invalid parameter declaration: " . Just . IllegalParamDecl)@@ -105,17 +109,17 @@ _ <- converge outN (NTPair def def def starNotes storageNote) `onLeft` ((TCContractError "contract output type violates convention:") . Just . AnnError)- pure $ SomeContract FullContract- { fcCode = instr- , fcParamNotes- , fcStoreNotes+ pure $ SomeContract Contract+ { cCode = instr+ , cParamNotes+ , cStoreNotes } Left err -> Left $ TCContractError "contract output type violates convention:" $ Just err AnyOutInstr instr ->- pure $ SomeContract FullContract- { fcCode = instr- , fcParamNotes- , fcStoreNotes+ pure $ SomeContract Contract+ { cCode = instr+ , cParamNotes+ , cStoreNotes } where hasTypeError :: forall (t :: T) a. SingI t => Text -> BadTypeForScope -> TypeCheck a@@ -214,6 +218,8 @@ (U.DROP, _ ::& rs) -> pure (inp :/ DROP ::: rs) + (U.DROP, SNil) -> notEnoughItemsOnStack+ (U.DROPN nTotal, inputHST) -> go nTotal inputHST <&> \case TCDropHelper s out -> inputHST :/ DROPN s ::: out@@ -225,8 +231,7 @@ go n i = case (n, i) of (0, _) -> pure (TCDropHelper SZ i) - (_, SNil) -> typeCheckInstrErr' uInstr (SomeHST SNil) Nothing- $ NotEnoughItemsOnStack nTotal NotEnoughDrop+ (_, SNil) -> notEnoughItemsOnStack (_, (_ ::& iTail)) -> do go (n - 1) iTail <&> \case TCDropHelper s out -> TCDropHelper (SS s) out@@ -234,9 +239,13 @@ (U.DUP _vn, a ::& rs) -> pure (inp :/ DUP ::: (a ::& a::& rs)) + (U.DUP _vn, SNil) -> notEnoughItemsOnStack+ (U.SWAP, a ::& b ::& rs) -> pure (inp :/ SWAP ::: (b ::& a ::& rs)) + (U.SWAP, _) -> notEnoughItemsOnStack+ (U.DIG nTotal, inputHST) -> go nTotal inputHST <&> \case TCDigHelper s out -> inputHST :/ DIG s ::: out@@ -247,8 +256,7 @@ -> TypeCheckInstr (TCDigHelper inp) go n i = case (n, i) of -- Even 'DIG 0' is invalid on empty stack (so it is not strictly `Nop`).- (_, SNil) -> typeCheckInstrErr' uInstr (SomeHST SNil) Nothing- $ NotEnoughItemsOnStack nTotal NotEnoughDig+ (_, SNil) -> notEnoughItemsOnStack (0, (_ ::& _)) -> pure (TCDigHelper SZ i) @@ -274,8 +282,7 @@ -- Two cases: -- 1. Input stack is empty. -- 2. n > 0 and input stack has exactly 1 item.- _ -> typeCheckInstrErr' uInstr (SomeHST i) Nothing- $ NotEnoughItemsOnStack nTotal NotEnoughDug+ _ -> notEnoughItemsOnStack (U.PUSH vn mt mval, i) -> withUType mt $ \(nt :: Notes t) -> do@@ -288,6 +295,8 @@ (U.SOME tn vn, (an, Dict, _) ::& rs) -> do pure (inp :/ SOME ::: ((NTOption tn an, Dict, vn) ::& rs)) + (U.SOME _ _, SNil) -> notEnoughItemsOnStack+ (U.NONE tn vn elMt, _) -> withUType elMt $ \(elNotes :: Notes t) -> withWTPInstr @t $@@ -301,11 +310,18 @@ withWTPInstr @a $ genericIf IF_NONE U.IF_NONE mp mq rs ((an, Dict, avn) ::& rs) inp + (U.IF_NONE _ _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectOption Nothing :| []) :| []++ (U.IF_NONE _ _, SNil) -> notEnoughItemsOnStack+ (U.PAIR tn vn pfn qfn, (an, _, avn) ::& (bn, _, bvn) ::& rs) -> do let (vn', pfn', qfn') = deriveSpecialFNs pfn qfn avn bvn case NTPair tn pfn' qfn' an bn of (ns :: Notes ('TPair a b)) -> withWTPInstr @('TPair a b) $ pure (inp :/ PAIR ::: ((ns, Dict, vn `orAnn` vn') ::& rs)) + (U.PAIR {}, _) -> notEnoughItemsOnStack+ (U.CAR vn fn, (STPair{}, NTPair pairTN pfn qfn (pns :: Notes p) (qns :: Notes q), _, pairVN) ::&+ rs) -> do pfn' <- onTypeCheckInstrAnnErr uInstr inp (Just CarArgument) (convergeAnns fn pfn) withWTPInstr @p $@@ -314,6 +330,11 @@ i' = (NTPair pairTN pfn' qfn pns qns, Dict, pairVN) ::& rs pure $ i' :/ AnnCAR fn ::: ((pns, Dict, vn') ::& rs) + (U.CAR _ _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectPair Nothing Nothing :| []) :| []++ (U.CAR _ _, SNil) -> notEnoughItemsOnStack+ (U.CDR vn fn, (STPair{}, NTPair pairTN pfn qfn (pns :: Notes p) (qns :: Notes q), _, pairVN) ::&+ rs) -> do qfn' <- onTypeCheckInstrAnnErr uInstr inp (Just CdrArgument) (convergeAnns fn qfn) @@ -323,18 +344,27 @@ i' = (NTPair pairTN pfn qfn' pns qns, Dict, pairVN) ::& rs pure $ i' :/ AnnCDR fn ::: ((qns, Dict, vn') ::& rs) + (U.CDR _ _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectPair Nothing Nothing :| []) :| []++ (U.CDR _ _, SNil) -> notEnoughItemsOnStack+ (U.LEFT tn vn pfn qfn bMt, (an :: Notes l, Dict, _) ::& rs) -> withUType bMt $ \(bn :: Notes r) -> do withWTPInstr @r $ do let ns = NTOr tn pfn qfn an bn pure (inp :/ LEFT ::: ((ns, Dict, vn) ::& rs)) + (U.LEFT {}, SNil) -> notEnoughItemsOnStack+ (U.RIGHT tn vn pfn qfn aMt, (bn :: Notes r, Dict, _) ::& rs) -> withUType aMt $ \(an :: Notes l) -> do withWTPInstr @l $ do let ns = NTOr tn pfn qfn an bn pure (inp :/ RIGHT ::: ((ns, Dict, vn) ::& rs)) + ( U.RIGHT {}, SNil) -> notEnoughItemsOnStack+ (U.IF_LEFT mp mq, (STOr{}, ons, _, ovn) ::&+ rs) -> do case deriveNsOr ons ovn of (an :: Notes a, bn :: Notes b, avn, bvn) ->@@ -345,6 +375,11 @@ bit = (bn, Dict, bvn) ::& rs genericIf IF_LEFT U.IF_LEFT mp mq ait bit inp + (U.IF_LEFT _ _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectOr Nothing Nothing :| []) :| []++ (U.IF_LEFT _ _, SNil) -> notEnoughItemsOnStack+ (U.NIL tn vn elMt, i) -> withUType elMt $ \(elNotes :: Notes t) -> withWTPInstr @('TList t) $@@ -359,84 +394,155 @@ pure $ inp :/ CONS ::: ((n, Dict, vn) ::& rs) Left m -> typeCheckInstrErr' uInstr (SomeHST inp) (Just ConsArgument) m + (U.CONS _, _) -> notEnoughItemsOnStack+ (U.IF_CONS mp mq, (STList{}, ns, Dict, vn) ::&+ rs) -> do case ns of NTList _ (an :: Notes t1) -> do ait <- withWTPInstr @t1 $ pure $ (an, Dict, vn <> "hd") ::& (ns, Dict, vn <> "tl") ::& rs genericIf IF_CONS U.IF_CONS mp mq ait rs inp + (U.IF_CONS _ _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectList Nothing :| []) :| []++ (U.IF_CONS _ _, SNil)-> notEnoughItemsOnStack+ (U.SIZE vn, (NTList{}, _, _) ::& _) -> sizeImpl inp vn (U.SIZE vn, (NTSet{}, _, _) ::& _) -> sizeImpl inp vn (U.SIZE vn, (NTMap{}, _, _) ::& _) -> sizeImpl inp vn (U.SIZE vn, (NTString{}, _, _) ::& _) -> sizeImpl inp vn (U.SIZE vn, (NTBytes{}, _, _) ::& _) -> sizeImpl inp vn- (U.EMPTY_SET tn vn (U.Type mk ktn), i) ->- withSomeSingT (fromUType $ U.Type mk U.noAnn) $ \(k :: Sing k) -> do- withWTPInstr @('TSet k) $- withCompareableCheck k uInstr inp $ i :/ EMPTY_SET ::: ((STSet k, NTSet tn ktn, Dict, vn) ::&+ inp)+ (U.SIZE _, _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectList Nothing :| []) :|+ [ (ExpectSet Nothing :| [])+ , (ExpectMap :| [])+ , (ExpectString :| [])+ , (ExpectByte :| [])+ ] - (U.EMPTY_MAP tn vn (U.Type mk ktn) mv, i) ->- withUType mv $ \(vns :: Notes v) ->- withSomeSingT (fromUType $ U.Type mk U.noAnn) $ \(k :: Sing k) ->do- withWTPInstr @('TMap k v) $- withCompareableCheck k uInstr inp $ i :/ EMPTY_MAP ::: ((STMap k sing, NTMap tn ktn vns, Dict, vn) ::&+ i)+ (U.SIZE _, SNil) -> notEnoughItemsOnStack - (U.EMPTY_BIG_MAP tn vn (U.Type mk ktn) mv, i) ->+ (U.EMPTY_SET tn vn mv, i) -> withUType mv $ \(vns :: Notes v) ->- withSomeSingT (fromUType $ U.Type mk U.noAnn) $ \(k :: Sing k) -> do- withWTPInstr @('TBigMap k v) $- withCompareableCheck k uInstr inp $ i :/ EMPTY_BIG_MAP ::: ((STBigMap k sing, NTBigMap tn ktn vns, Dict, vn) ::&+ i)+ withWTPInstr @('TSet v) $+ withCompareableCheck (notesSing vns) uInstr inp $ i :/ EMPTY_SET ::: ((STSet sing, NTSet tn vns, Dict, vn) ::&+ i) + (U.EMPTY_MAP tn vn mk mv, i) -> do+ withUType mv $ \(vns :: Notes v) ->+ withUType mk $ \(ktn :: Notes k) ->+ withWTPInstr @('TMap k v) $+ withCompareableCheck (notesSing ktn) uInstr inp $ i :/ EMPTY_MAP ::: ((STMap sing sing, NTMap tn ktn vns, Dict, vn) ::&+ i)++ (U.EMPTY_BIG_MAP tn vn mk mv, i) ->+ withUType mv $ \(vns :: Notes v) ->+ withUType mk $ \(ktn :: Notes k) ->+ withWTPInstr @('TBigMap k v) $+ withCompareableCheck (notesSing ktn) uInstr inp $ i :/ EMPTY_BIG_MAP ::: ((STBigMap sing sing, NTBigMap tn ktn vns, Dict, vn) ::&+ i)+ (U.MAP vn mp, (STList _, NTList _ (vns :: Notes t1), Dict, _vn) ::&+ _) -> do withWTPInstr @t1 $ mapImpl vns uInstr mp inp (\(rn :: Notes t) hst -> withWTPInstr @t $ pure $ (NTList def rn, Dict, vn) ::& hst) (U.MAP vn mp, (STMap{}, NTMap _ kns vns, Dict, _vn) ::&+ _) -> do- case NTPair def def def (insertTypeAnn kns starNotes) vns of+ case NTPair def def def kns vns of (pns :: Notes ('TPair k v1)) -> withWTPInstr @('TPair k v1) $ mapImpl pns uInstr mp inp (\(rn :: Notes v) hst -> withWTPInstr @('TMap k v) $ pure $ (NTMap def kns rn, Dict, vn) ::& hst) --- case `U.HSTER []` is wrongly typed by definition--- (as it is required to at least drop an element), so we don't consider it+ (U.MAP _ _, _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectList Nothing :| []) :|+ [ (ExpectMap :| [])+ ] + (U.MAP _ _, SNil) -> notEnoughItemsOnStack+ (U.ITER is, (STSet (_ :: Sing t1), NTSet _ en, _, _) ::&+ _) -> do withWTPInstr @t1 $- iterImpl (insertTypeAnn en starNotes) uInstr is inp+ iterImpl en uInstr is inp (U.ITER is, (STList (_ :: Sing t1), NTList _ en, _, _) ::&+ _) -> do withWTPInstr @t1 $ iterImpl en uInstr is inp (U.ITER is, (STMap _ _, NTMap _ kns vns, _, _) ::&+ _) -> do- case NTPair def def def (insertTypeAnn kns starNotes) vns of+ case NTPair def def def kns vns of (en :: Notes ('TPair a b)) -> withWTPInstr @('TPair a b) $ iterImpl en uInstr is inp - (U.MEM vn, _ ::& (STSet{}, NTSet{}, _, _) ::&+ _) ->- memImpl uInstr inp vn- (U.MEM vn, _ ::& (STMap{}, NTMap{}, _, _) ::&+ _) ->- memImpl uInstr inp vn- (U.MEM vn, _ ::& (STBigMap{}, NTBigMap{}, _, _) ::&+ _) ->- memImpl uInstr inp vn+ (U.ITER _, _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectSet Nothing :| []) :|+ [ (ExpectList Nothing :| [])+ , (ExpectMap :| [])+ ] - (U.GET vn, _ ::& (STMap{}, NTMap _ _ (v :: Notes v), _, _) ::&+ _) ->- withWTPInstr @v $ getImpl uInstr inp v vn- (U.GET vn, _ ::& (STBigMap{}, NTBigMap _ _ (v :: Notes v), _, _) ::&+ _) ->- withWTPInstr @v $ getImpl uInstr inp v vn+ (U.ITER _, SNil) -> notEnoughItemsOnStack - (U.UPDATE vn, _ ::& _ ::& (STMap _ _, _, _, _) ::&+ _) ->- updImpl uInstr inp vn- (U.UPDATE vn, _ ::& _ ::& (STBigMap _ _, _, _, _) ::&+ _) ->- updImpl uInstr inp vn- (U.UPDATE vn, _ ::& _ ::& (STSet _, _, _, _) ::&+ _) ->- updImpl uInstr inp vn+ (U.MEM varNotes,+ _ ::& (STSet{}, NTSet _ notesK, _, _) ::&+ _) ->+ memImpl notesK inp varNotes+ (U.MEM varNotes,+ _ ::& (STMap{}, NTMap _ notesK _, _, _) ::&+ _) ->+ memImpl notesK inp varNotes+ (U.MEM varNotes,+ _ ::& (STBigMap{}, NTBigMap _ notesK _, _, _) ::&+ _) ->+ memImpl notesK inp varNotes+ (U.MEM _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectTypeVar :| [ExpectSet Nothing]) :|+ [ (ExpectTypeVar :| [ExpectMap])+ , (ExpectTypeVar :| [ExpectBigMap])+ ] + (U.MEM _, _) -> notEnoughItemsOnStack+++ (U.GET varNotes,+ _ ::& (STMap{}, NTMap _ notesK (notesV :: Notes v), _, _) ::&+ _) ->+ withWTPInstr @v $ getImpl notesK inp notesV varNotes+ (U.GET varNotes,+ _ ::& (STBigMap{}, NTBigMap _ notesK (notesV :: Notes v), _, _) ::&+ _) ->+ withWTPInstr @v $ getImpl notesK inp notesV varNotes++ (U.GET _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectTypeVar :| [ExpectMap]) :|+ [ (ExpectTypeVar :| [ExpectBigMap])+ ]++ (U.GET _, _) -> notEnoughItemsOnStack++ (U.UPDATE varNotes,+ _ ::& _ ::& (STMap{}, (NTMap _ notesK (notesV :: Notes v)), _, _) ::&+ _) ->+ updImpl notesK inp (NTOption U.noAnn notesV) varNotes+ (U.UPDATE varNotes,+ _ ::& _ ::& (STBigMap{}, NTBigMap _ notesK (notesV :: Notes v), _, _) ::&+ _) ->+ updImpl notesK inp (NTOption U.noAnn notesV) varNotes+ (U.UPDATE varNotes,+ _ ::& _ ::& (STSet{}, NTSet _ (notesK :: Notes k), _, _) ::&+ _) ->+ updImpl notesK inp (NTBool U.noAnn) varNotes++ (U.UPDATE _, _ ::& _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectTypeVar :| [ExpectTypeVar, ExpectMap]) :|+ [ (ExpectTypeVar :| [ExpectTypeVar, ExpectBigMap])+ , (ExpectTypeVar :| [ExpectTypeVar, ExpectSet Nothing])+ ]++ (U.UPDATE _, _) -> notEnoughItemsOnStack+ (U.IF mp mq, (NTBool{}, _, _) ::& rs) -> genericIf IF U.IF mp mq rs rs inp + (U.IF _ _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectBool :| []) :| []++ (U.IF _ _, SNil) -> notEnoughItemsOnStack+ (U.LOOP is, (NTBool{}, _, _) ::& (rs :: HST rs)) -> do _ :/ tp <- lift $ typeCheckList is rs case tp of@@ -449,6 +555,12 @@ AnyOutInstr subI -> pure $ inp :/ LOOP subI ::: rs + (U.LOOP _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectBool :| [ExpectStackVar]) :| []++ (U.LOOP _, _) -> notEnoughItemsOnStack+ (U.LOOP_LEFT is, (os@STOr{}, ons, Dict, ovn) ::&+ rs) -> do case deriveNsOr ons ovn of (an :: Notes t, bn :: Notes b, avn, bvn) -> do@@ -469,6 +581,12 @@ let br = (bn, Dict, bvn) pure $ inp :/ LOOP_LEFT subI ::: (br ::& rs) + (U.LOOP_LEFT _, _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectOr Nothing Nothing :| [ExpectStackVar]) :| []++ (U.LOOP_LEFT _, _) -> notEnoughItemsOnStack+ (U.LAMBDA vn (AsUType (ins :: Notes t)) (AsUType (ons :: Notes u)) is, i) -> do -- further processing is extracted into another function just not to -- litter our main typechecking logic@@ -487,6 +605,12 @@ (eqType @t1 @t1') withWTPInstr @t2' $ pure $ inp :/ EXEC ::: ((t2n, Dict, vn) ::& rs) + (U.EXEC _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectTypeVar :| [ExpectLambda Nothing Nothing]) :| []++ (U.EXEC _, _) -> notEnoughItemsOnStack+ (U.APPLY vn, ((_ :: Notes a'), _, _) ::& ( STLambda (STPair _ _) _ , NTLambda vann (NTPair _ _ _ (_ :: Notes a) (nb :: Notes b)) sc@@ -504,10 +628,18 @@ (Refl, Dict) -> pure $ inp :/ (APPLY @a) ::: ((l2n, Dict, vn) ::& rs) + (U.APPLY _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectTypeVar :| [ExpectLambda (Just $ ExpectPair Nothing Nothing) Nothing]) :| []++ (U.APPLY _, _) -> notEnoughItemsOnStack+ (U.DIP is, a ::& s) -> do typeCheckDipBody uInstr is s $ \subI t -> pure $ inp :/ DIP subI ::: (a ::& t) + (U.DIP _is, SNil) -> notEnoughItemsOnStack+ (U.DIPN nTotal instructions, inputHST) -> go nTotal inputHST <&> \case TCDipHelper s subI out -> inputHST :/ DIPN s subI ::: out@@ -519,8 +651,7 @@ go n curHST = case (n, curHST) of (0, _) -> typeCheckDipBody uInstr instructions curHST $ \subI t -> pure (TCDipHelper SZ subI t)- (_, SNil) -> typeCheckInstrErr' uInstr (SomeHST SNil) Nothing- $ NotEnoughItemsOnStack nTotal NotEnoughDip+ (_, SNil) -> notEnoughItemsOnStack (_, hstHead ::& hstTail) -> go (n - 1) hstTail <&> \case TCDipHelper s subI out -> TCDipHelper (SS s) subI (hstHead ::& out)@@ -528,6 +659,8 @@ (U.FAILWITH, (_ ::& _)) -> pure $ inp :/ AnyOutInstr FAILWITH + (U.FAILWITH, _) -> notEnoughItemsOnStack+ (U.CAST vn (AsUType (castToNotes :: Notes t)), (en, _, evn) ::& rs) -> do (Refl, _) <- errM $ matchTypes en castToNotes withWTPInstr @t $@@ -536,9 +669,13 @@ errM :: (MonadReader InstrCallStack m, MonadError TCError m) => Either TCTypeError a -> m a errM = onTypeCheckInstrErr uInstr (SomeHST inp) (Just Cast) + (U.CAST _ _, _) -> notEnoughItemsOnStack+ (U.RENAME vn, (an, Dict, _) ::& rs) -> pure $ inp :/ RENAME ::: ((an, Dict, vn) ::& rs) + (U.RENAME _, SNil) -> notEnoughItemsOnStack+ (U.UNPACK tn vn mt, (NTBytes{}, _, _) ::& rs) -> withUType mt $ \(tns :: Notes tn) -> do case NTOption tn tns of@@ -547,11 +684,18 @@ $ checkScope @(UnpackedValScope tn) pure $ inp :/ UNPACK ::: ((ns, Dict, vn) ::& rs) + (U.UNPACK {}, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectByte :| []) :| []++ (U.UNPACK {}, SNil) -> notEnoughItemsOnStack+ (U.PACK vn, (_ :: Notes a, _, _) ::& rs) -> do Dict <- onScopeCheckInstrErr @a uInstr (SomeHST inp) Nothing $ checkScope @(PackedValScope a) pure $ inp :/ PACK ::: ((starNotes, Dict, vn) ::& rs) + (U.PACK _, SNil) -> notEnoughItemsOnStack+ (U.CONCAT vn, (NTBytes{}, _, _) ::& (NTBytes{}, _, _) ::& _) -> concatImpl inp vn (U.CONCAT vn, (NTString{}, _, _) ::& (NTString{}, _, _) ::& _) ->@@ -560,6 +704,18 @@ concatImpl' inp vn (U.CONCAT vn, (STList STString, _, _, _) ::&+ _) -> concatImpl' inp vn+ (U.CONCAT _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectByte :| [ExpectByte]) :|+ [ (ExpectString :| [ExpectString])+ ]+ (U.CONCAT _, _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectList (Just ExpectByte) :| [ExpectList (Just ExpectByte)]) :|+ [ (ExpectList (Just ExpectString) :| [ExpectList (Just ExpectString)])+ ]+ (U.CONCAT _, SNil) -> notEnoughItemsOnStack+ (U.SLICE vn, (NTNat{}, _, _) ::& (NTNat{}, _, _) ::& (NTString{}, _, _) ::& _) -> sliceImpl inp vn@@ -567,30 +723,76 @@ (NTNat{}, _, _) ::& (NTBytes{}, _, _) ::& _) -> sliceImpl inp vn + (U.SLICE _, _ ::& _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectNat :| [ExpectNat, ExpectString]) :|+ [ (ExpectNat :| [ExpectNat, ExpectByte])+ ]+ (U.SLICE _, _) -> notEnoughItemsOnStack+ (U.ISNAT vn', (NTInt{}, _, oldVn) ::& rs) -> do let vn = vn' `orAnn` oldVn pure $ inp :/ ISNAT ::: ((starNotes, Dict, vn) ::& rs) + (U.ISNAT _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectInt :| []) :| []++ (U.ISNAT _, SNil)-> notEnoughItemsOnStack++ -- Type checking is already done inside `addImpl`. (U.ADD vn, (a, _, _, _) ::&+ (b, _, _, _) ::&+ _) -> addImpl a b inp vn++ (U.ADD _, _) -> notEnoughItemsOnStack+ (U.SUB vn, (a, _, _, _) ::&+ (b, _, _, _) ::&+ _) -> subImpl a b inp vn++ (U.SUB _, _) -> notEnoughItemsOnStack+ (U.MUL vn, (a, _, _, _) ::&+ (b, _, _, _) ::&+ _) -> mulImpl a b inp vn++ (U.MUL _, _) -> notEnoughItemsOnStack+ (U.EDIV vn, (a, _, _, _) ::&+ (b, _, _, _) ::&+ _) -> edivImpl a b inp vn + (U.EDIV _, _) -> notEnoughItemsOnStack+ (U.ABS vn, (STInt, _, _, _) ::&+ _) -> unaryArithImpl @Abs ABS inp vn+ (U.ABS _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectInt :| []) :| [] + (U.ABS _, SNil) -> notEnoughItemsOnStack+ (U.NEG vn, (STInt, _, _, _) ::&+ _) -> unaryArithImpl @Neg NEG inp vn (U.NEG vn, (STNat, _, _, _) ::&+ _) -> unaryArithImpl @Neg NEG inp vn+ (U.NEG _, _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectInt :| []) :|+ [ (ExpectNat :| [])+ ]+ (U.NEG _, SNil) -> notEnoughItemsOnStack (U.LSL vn, (STNat, _, _, _) ::&+ (STNat, _, _, _) ::&+ _) -> arithImpl @Lsl LSL inp vn+ (U.LSL _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectNat :| [ExpectNat]) :| []+ (U.LSL _, _) -> notEnoughItemsOnStack (U.LSR vn, (STNat, _, _, _) ::&+ (STNat, _, _, _) ::&+ _) -> arithImpl @Lsr LSR inp vn+ (U.LSR _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectNat :| [ExpectNat]) :| []+ (U.LSR _, _) -> notEnoughItemsOnStack (U.OR vn, (STBool, _, _, _) ::&+ (STBool, _, _, _) ::&+ _) -> arithImpl @Or OR inp vn (U.OR vn, (STNat, _, _, _) ::&+ (STNat, _, _, _) ::&+ _) -> arithImpl @Or OR inp vn+ (U.OR _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectBool :| [ExpectBool]) :|+ [ (ExpectNat :| [ExpectNat])+ ]+ (U.OR _, _) -> notEnoughItemsOnStack (U.AND vn, (STInt, _, _, _) ::&+ (STNat, _, _, _) ::&+ _) -> arithImpl @And AND inp vn@@ -598,15 +800,35 @@ (STNat, _, _, _) ::&+ _) -> arithImpl @And AND inp vn (U.AND vn, (STBool, _, _, _) ::&+ (STBool, _, _, _) ::&+ _) -> arithImpl @And AND inp vn+ (U.AND _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectInt :| [ExpectNat]) :|+ [ (ExpectNat :| [ExpectNat])+ , (ExpectBool :| [ExpectBool])+ ]+ (U.AND _, _) -> notEnoughItemsOnStack (U.XOR vn, (STBool, _, _, _) ::&+ (STBool, _, _, _) ::&+ _) -> arithImpl @Xor XOR inp vn (U.XOR vn, (STNat, _, _, _) ::&+ (STNat, _, _, _) ::&+ _) -> arithImpl @Xor XOR inp vn+ (U.XOR _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectBool :| [ExpectBool]) :|+ [ (ExpectNat :| [ExpectNat])+ ]+ (U.XOR _, _) -> notEnoughItemsOnStack (U.NOT vn, (STNat, _, _, _) ::&+ _) -> unaryArithImpl @Not NOT inp vn (U.NOT vn, (STBool, _, _, _) ::&+ _) -> unaryArithImpl @Not NOT inp vn (U.NOT vn, (STInt, _, _, _) ::&+ _) -> unaryArithImpl @Not NOT inp vn+ (U.NOT _, _ ::& _) ->+ failWithErr $ UnexpectedType+ $ (ExpectNat :| []) :|+ [ (ExpectBool :| [])+ , (ExpectInt :| [])+ ]+ (U.NOT _, SNil) -> notEnoughItemsOnStack (U.COMPARE vn, (an :: Notes aT, _, _)@@ -629,20 +851,43 @@ errConv :: (MonadReader InstrCallStack m, MonadError TCError m) => Either AnnConvergeError a -> m a errConv = onTypeCheckInstrAnnErr uInstr inp (Just ComparisonArguments) + (U.COMPARE _, _) -> notEnoughItemsOnStack+ (U.EQ vn, (NTInt{}, _, _) ::& _) -> unaryArithImpl @Eq' EQ inp vn+ (U.EQ _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectInt :| []) :| []+ (U.EQ _, SNil) -> notEnoughItemsOnStack (U.NEQ vn, (NTInt{}, _, _) ::& _) -> unaryArithImpl @Neq NEQ inp vn+ (U.NEQ _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectInt :| []) :| []+ (U.NEQ _, SNil) -> notEnoughItemsOnStack (U.LT vn, (NTInt{}, _, _) ::& _) -> unaryArithImpl @Lt LT inp vn+ (U.LT _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectInt :| []) :| []+ (U.LT _, SNil) -> notEnoughItemsOnStack (U.GT vn, (NTInt{}, _, _) ::& _) -> unaryArithImpl @Gt GT inp vn+ (U.GT _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectInt :| []) :| []+ (U.GT _, SNil) -> notEnoughItemsOnStack (U.LE vn, (NTInt{}, _, _) ::& _) -> unaryArithImpl @Le LE inp vn+ (U.LE _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectInt :| []) :| []+ (U.LE _, SNil) -> notEnoughItemsOnStack (U.GE vn, (NTInt{}, _, _) ::& _) -> unaryArithImpl @Ge GE inp vn+ (U.GE _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectInt :| []) :| []+ (U.GE _, SNil) -> notEnoughItemsOnStack (U.INT vn, (NTNat{}, _, _) ::& rs) -> pure $ inp :/ INT ::: ((starNotes, Dict, vn) ::& rs)+ (U.INT _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectNat :| []) :| []+ (U.INT _, SNil) -> notEnoughItemsOnStack (U.SELF vn fn, _) -> do (U.ParameterType cpType rootAnn) <- gets tcContractParam@@ -676,6 +921,10 @@ Dict -> withWTPInstr @t $ pure $ inp :/ CONTRACT tns epName ::: ((ns, Dict, vn) ::& rs) + (U.CONTRACT {}, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectAddress :| []) :| []+ (U.CONTRACT {}, SNil) -> notEnoughItemsOnStack+ (U.TRANSFER_TOKENS vn, ((_ :: Notes p'), _, _) ::& (NTMutez{}, _, _) ::& (STContract (_ :: Sing p), _, _, _) ::&+ rs) -> do@@ -687,17 +936,27 @@ (Left m, _) -> typeCheckInstrErr' uInstr (SomeHST inp) (Just ContractParameter) m + (U.TRANSFER_TOKENS _, _ ::& _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectTypeVar :| [ExpectMutez, ExpectContract]) :| []++ (U.TRANSFER_TOKENS _, _) -> notEnoughItemsOnStack+ (U.SET_DELEGATE vn, (STOption STKeyHash, NTOption _ NTKeyHash{}, _, _) ::&+ rs) -> do pure $ inp :/ SET_DELEGATE ::: ((starNotes, Dict, vn) ::& rs) + (U.SET_DELEGATE _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectOption (Just ExpectKeyHash) :| []) :| []++ (U.SET_DELEGATE _, _) -> notEnoughItemsOnStack+ (U.CREATE_CONTRACT ovn avn contract, (STOption STKeyHash, NTOption _ (_ :: Notes ('TKeyHash)), _, _) ::&+ (NTMutez{}, _, _) ::& (gn :: Notes g, Dict, _) ::& rs) -> do (SomeContract- (FullContract+ (Contract (contr :: ContractCode p' g') paramNotes storeNotes))@@ -706,12 +965,21 @@ $ eqType @g @g' void $ onTypeCheckInstrAnnErr uInstr inp (Just ContractStorage) (converge gn storeNotes) pure- $ inp :/ CREATE_CONTRACT (FullContract contr paramNotes storeNotes)+ $ inp :/ CREATE_CONTRACT (Contract contr paramNotes storeNotes) ::: ((starNotes, Dict, ovn) ::& (starNotes, Dict, avn) ::& rs) + (U.CREATE_CONTRACT {}, _ ::& _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectOption Nothing :| [ExpectMutez, ExpectTypeVar]) :| []++ (U.CREATE_CONTRACT {}, _) -> notEnoughItemsOnStack+ (U.IMPLICIT_ACCOUNT vn, (NTKeyHash{}, _, _) ::& rs) -> pure $ inp :/ IMPLICIT_ACCOUNT ::: ((starNotes, Dict, vn) ::& rs) + (U.IMPLICIT_ACCOUNT _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectKeyHash :| []) :| []+ (U.IMPLICIT_ACCOUNT _, SNil) -> notEnoughItemsOnStack+ (U.NOW vn, _) -> pure $ inp :/ NOW ::: ((starNotes, Dict, vn) ::& inp) @@ -726,17 +994,33 @@ ::& (NTSignature _, _, _) ::& (NTBytes{}, _, _) ::& rs) -> pure $ inp :/ CHECK_SIGNATURE ::: ((starNotes, Dict, vn) ::& rs) + (U.CHECK_SIGNATURE _, _ ::& _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectKey :| [ExpectSignature]) :| []+ (U.CHECK_SIGNATURE _, _) -> notEnoughItemsOnStack+ (U.SHA256 vn, (NTBytes{}, _, _) ::& rs) -> pure $ inp :/ SHA256 ::: ((starNotes, Dict, vn) ::& rs)+ (U.SHA256 _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectByte :| []) :| []+ (U.SHA256 _, SNil) -> notEnoughItemsOnStack (U.SHA512 vn, (NTBytes{}, _, _) ::& rs) -> pure $ inp :/ SHA512 ::: ((starNotes, Dict, vn) ::& rs)+ (U.SHA512 _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectByte :| []) :| []+ (U.SHA512 _, SNil) -> notEnoughItemsOnStack (U.BLAKE2B vn, (NTBytes{}, _, _) ::& rs) -> pure $ inp :/ BLAKE2B ::: ((starNotes, Dict, vn) ::& rs)+ (U.BLAKE2B _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectByte :| []) :| []+ (U.BLAKE2B _, SNil) -> notEnoughItemsOnStack (U.HASH_KEY vn, (NTKey{}, _, _) ::& rs) -> pure $ inp :/ HASH_KEY ::: ((starNotes, Dict, vn) ::& rs)+ (U.HASH_KEY _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectKey :| []) :| []+ (U.HASH_KEY _, SNil) -> notEnoughItemsOnStack (U.SOURCE vn, _) -> pure $ inp :/ SOURCE ::: ((starNotes, Dict, vn) ::& inp)@@ -747,16 +1031,30 @@ (U.ADDRESS vn, (NTContract{}, _, _) ::& rs) -> pure $ inp :/ ADDRESS ::: ((starNotes, Dict, vn) ::& rs) + (U.ADDRESS _, _ ::& _) ->+ failWithErr $ UnexpectedType $ (ExpectContract :| []) :| []+ (U.ADDRESS _, SNil) -> notEnoughItemsOnStack+ (U.CHAIN_ID vn, _) -> pure $ inp :/ CHAIN_ID ::: ((starNotes, Dict, vn) ::& inp) - _ ->- -- TODO #154 maksbotan: get rid of this clause, by explicitly matching all possible- -- instructions and generating relevant errors.- typeCheckInstrErr uInstr (SomeHST inp) Nothing+ -- Could not get rid of the catch all clause due to this warning:+ -- @+ -- Pattern match checker exceeded (2000000) iterations in+ -- a case alternative. (Use -fmax-pmcheck-iterations=n+ -- to set the maximum number of iterations to n)+ -- @+ i ->+ error $ "Pattern matches should be exhuastive, but instead got: " <> show i where withWTPInstr :: forall t a. SingI t => (WellTyped t => TypeCheckInstr a) -> TypeCheckInstr a withWTPInstr fn = withWTPInstr_ @t uInstr (SomeHST inp) fn++ failWithErr :: (MonadReader InstrCallStack m, MonadError TCError m) => TCTypeError -> m a+ failWithErr = typeCheckInstrErr' uInstr (SomeHST inp) Nothing++ notEnoughItemsOnStack :: (MonadReader InstrCallStack m, MonadError TCError m) => m a+ notEnoughItemsOnStack = failWithErr NotEnoughItemsOnStack -- | Helper function for two-branch if where each branch is given a single -- value.
src/Michelson/TypeCheck/TypeCheck.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.TypeCheck.TypeCheck ( TcInstrHandler , TcOriginatedContracts
src/Michelson/TypeCheck/Types.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.TypeCheck.Types ( HST (..) , (-:&)@@ -161,7 +165,7 @@ show (inp :/ out) = show inp <> " -> " <> show out data SomeContract where- SomeContract :: FullContract cp st -> SomeContract+ SomeContract :: Contract cp st -> SomeContract instance NFData SomeContract where rnf (SomeContract c) = rnf c@@ -170,7 +174,7 @@ (forall inp out. Instr inp out -> Instr inp out) -> SomeContract -> SomeContract-mapSomeContract f (SomeContract fc) = SomeContract $ mapFullContractCode f fc+mapSomeContract f (SomeContract fc) = SomeContract $ mapContractCode f fc deriving stock instance Show SomeContract
src/Michelson/TypeCheck/Value.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.TypeCheck.Value ( typeCheckValImpl ) where
src/Michelson/Typed.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Typed ( module Exports ) where
src/Michelson/Typed/Aliases.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Typed.Aliases ( Value , SomeValue
src/Michelson/Typed/Annotation.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE DataKinds, GADTs #-} -- | Module, providing @Notes t@ data type, which holds annotations for a@@ -55,7 +59,7 @@ NTChainId :: TypeAnn -> Notes 'TChainId NTOption :: TypeAnn -> Notes t -> Notes ('TOption t) NTList :: TypeAnn -> Notes t -> Notes ('TList t)- NTSet :: TypeAnn -> TypeAnn -> Notes ('TSet ct)+ NTSet :: TypeAnn -> Notes t -> Notes ('TSet t) NTOperation :: TypeAnn -> Notes 'TOperation NTContract :: TypeAnn -> Notes t -> Notes ('TContract t) NTPair :: TypeAnn -> FieldAnn -> FieldAnn@@ -63,8 +67,8 @@ NTOr :: TypeAnn -> FieldAnn -> FieldAnn -> Notes p -> Notes q -> Notes ('TOr p q) NTLambda :: TypeAnn -> Notes p -> Notes q -> Notes ('TLambda p q)- NTMap :: TypeAnn -> TypeAnn -> Notes v -> Notes ('TMap k v)- NTBigMap :: TypeAnn -> TypeAnn -> Notes v -> Notes ('TBigMap k v)+ NTMap :: TypeAnn -> Notes k -> Notes v -> Notes ('TMap k v)+ NTBigMap :: TypeAnn -> Notes k -> Notes v -> Notes ('TBigMap k v) NTInt :: TypeAnn -> Notes 'TInt NTNat :: TypeAnn -> Notes 'TNat NTString :: TypeAnn -> Notes 'TString@@ -102,14 +106,14 @@ NTChainId ta -> "NTChainId" <+> rendT ta NTOption ta nt -> "NTOption" <+> rendT ta <+> rendN nt NTList ta nt -> "NTList" <+> rendT ta <+> rendN nt- NTSet ta1 ta2 -> "NTSet" <+> rendT2 ta1 ta2+ NTSet ta nt -> "NTSet" <+> rendT ta <+> rendN nt NTOperation ta -> "NTOperation" <+> rendT ta NTContract ta nt -> "NTContract" <+> rendT ta <+> rendN nt NTPair ta fa1 fa2 np nq -> "NTPair" <+> rendTF2 ta fa1 fa2 <+> 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 ta1 ta2 nv -> "NTMap" <+> rendT2 ta1 ta2 <+> rendN nv- NTBigMap ta1 ta2 nv -> "NTBigMap" <+> rendT2 ta1 ta2 <+> rendN nv+ 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@@ -117,9 +121,6 @@ rendT :: TypeAnn -> Doc rendT = renderDoc doesntNeedParens . singleAnnSet - rendT2 :: TypeAnn -> TypeAnn -> Doc- rendT2 t1 t2 = renderDoc doesntNeedParens $ fullAnnSet [t1, t2] [] []- rendTF2 :: TypeAnn -> FieldAnn -> FieldAnn -> Doc rendTF2 t f1 f2 = renderDoc doesntNeedParens $ fullAnnSet [t] [f1, f2] [] @@ -152,12 +153,12 @@ STSignature -> NTSignature noAnn STChainId -> NTChainId noAnn STOperation -> NTOperation noAnn- STSet _ -> NTSet noAnn noAnn+ STSet _ -> NTSet noAnn starNotes STList _ -> NTList noAnn starNotes STOption _ -> NTOption noAnn starNotes STContract _ -> NTContract noAnn starNotes- STMap _ _ -> NTMap noAnn noAnn starNotes- STBigMap _ _ -> NTBigMap noAnn noAnn starNotes+ STMap _ _ -> NTMap noAnn starNotes starNotes+ STBigMap _ _ -> NTBigMap noAnn starNotes starNotes STPair _ _ -> NTPair noAnn noAnn noAnn starNotes starNotes STOr _ _ -> NTOr noAnn noAnn noAnn starNotes starNotes STLambda _ _ -> NTLambda noAnn starNotes starNotes@@ -194,7 +195,7 @@ (NTList a n, NTList b m) -> NTList <$> convergeAnns a b <*> converge n m (NTSet a n, NTSet b m) ->- NTSet <$> convergeAnns a b <*> convergeAnns n m+ NTSet <$> convergeAnns a b <*> converge n m (NTOperation a, NTOperation b) -> NTOperation <$> convergeAnns a b (NTContract a n, NTContract b m) ->@@ -208,9 +209,9 @@ (NTLambda a pN qN, NTLambda b pM qM) -> NTLambda <$> convergeAnns a b <*> converge pN pM <*> converge qN qM (NTMap a kN vN, NTMap b kM vM) ->- NTMap <$> convergeAnns a b <*> convergeAnns kN kM <*> converge vN vM+ NTMap <$> convergeAnns a b <*> converge kN kM <*> converge vN vM (NTBigMap a kN vN, NTBigMap b kM vM) ->- NTBigMap <$> convergeAnns a b <*> convergeAnns kN kM <*> converge vN vM+ NTBigMap <$> convergeAnns a b <*> converge kN kM <*> converge vN vM -- | Insert the provided type annotation into the provided notes. insertTypeAnn :: forall (b :: T). TypeAnn -> Notes b -> Notes b@@ -264,4 +265,3 @@ pure $ unifyAnn a b $(deriveGADTNFData ''AnnConvergeError)-
src/Michelson/Typed/Arith.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE DataKinds, MultiParamTypeClasses, TypeFamilies #-} -- | Module, containing some boilerplate for support of
src/Michelson/Typed/Convert.hs view
@@ -1,8 +1,12 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -fno-warn-orphans #-} module Michelson.Typed.Convert ( convertContractCode- , convertFullContract+ , convertContract , instrToOps , untypeValue ) where@@ -36,17 +40,14 @@ , contractCode = instrToOps contract } -addTNote :: U.TypeAnn -> U.Type -> U.Type-addTNote ta (U.Type ct _) = U.Type ct ta--convertFullContract+convertContract :: forall param store . (SingI param, SingI store)- => FullContract param store -> U.Contract-convertFullContract fc =- let c = convertContractCode (fcCode fc)- in c { U.contractParameter = U.ParameterType (mkUType (pnNotes $ fcParamNotes fc))- (pnRootAnn (fcParamNotes fc))- , U.contractStorage = mkUType (fcStoreNotes fc)+ => Contract param store -> U.Contract+convertContract fc =+ let c = convertContractCode (cCode fc)+ in c { U.contractParameter = U.ParameterType (mkUType (pnNotes $ cParamNotes fc))+ (pnRootAnn (cParamNotes fc))+ , U.contractStorage = mkUType (cStoreNotes fc) } -- | Convert a typed 'Val' to an untyped 'Value'.@@ -178,12 +179,12 @@ (STOr _ _, U.RIGHT _ va _ _ _, NTOr ta f1 f2 n1 _) -> U.RIGHT ta va f1 f2 (mkUType n1) (STList _, U.NIL _ va _, NTList ta n) -> U.NIL ta va (mkUType n)- (_, U.EMPTY_SET _ va ct, NTSet ta1 ta2) ->- U.EMPTY_SET ta1 va (addTNote ta2 ct)- (STMap _ _, U.EMPTY_MAP _ va ct _, NTMap ta1 ta2 n) ->- U.EMPTY_MAP ta1 va (addTNote ta2 ct) (mkUType n)- (STBigMap _ _, U.EMPTY_BIG_MAP _ va ct _, NTBigMap ta1 ta2 n) ->- U.EMPTY_BIG_MAP ta1 va (addTNote ta2 ct) (mkUType n)+ (STSet _, U.EMPTY_SET _ va _, NTSet ta1 n) ->+ U.EMPTY_SET ta1 va (mkUType n)+ (STMap _ _, U.EMPTY_MAP _ va _ _, NTMap ta1 k n) ->+ U.EMPTY_MAP ta1 va (mkUType k) (mkUType n)+ (STBigMap _ _, U.EMPTY_BIG_MAP _ va _ _, NTBigMap ta1 k n) ->+ U.EMPTY_BIG_MAP ta1 va (mkUType k) (mkUType n) (STLambda _ _, U.LAMBDA va _ _ ops, NTLambda _ n1 n2) -> U.LAMBDA va (mkUType n1) (mkUType n2) ops (_, U.CAST va _, n) -> U.CAST va (mkUType n)@@ -445,14 +446,14 @@ in U.CONTRACT U.noAnn fa (mkUType nt) TRANSFER_TOKENS -> U.TRANSFER_TOKENS U.noAnn SET_DELEGATE -> U.SET_DELEGATE U.noAnn- i@(CREATE_CONTRACT fullContract)+ i@(CREATE_CONTRACT contract) | _ :: Instr ( 'TOption ('TKeyHash) ': 'TMutez ': g ': s) ('TOperation ': 'TAddress ': s) <- i ->- U.CREATE_CONTRACT U.noAnn U.noAnn (convertFullContract fullContract)+ U.CREATE_CONTRACT U.noAnn U.noAnn (convertContract contract) IMPLICIT_ACCOUNT -> U.IMPLICIT_ACCOUNT U.noAnn NOW -> U.NOW U.noAnn AMOUNT -> U.AMOUNT U.noAnn
src/Michelson/Typed/Doc.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Extracting documentation from instructions set. module Michelson.Typed.Doc ( buildInstrDoc
src/Michelson/Typed/EntryPoints.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utilities for lightweight entrypoints support. module Michelson.Typed.EntryPoints ( EpAddress (..)
src/Michelson/Typed/Extract.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing functions to convert @Michelson.Untyped.Type@ to -- @Michelson.Typed.T.T@ Michelson type representation (type stripped off all -- annotations) and to @Michelson.Typed.Annotation.Notes@ value (which contains@@ -44,7 +48,7 @@ (STChainId, NTChainId tn) -> Un.Type Un.TChainId tn (STOption _, NTOption tn n) -> Un.Type (Un.TOption (mkUType n)) tn (STList _, NTList tn n) -> Un.Type (Un.TList (mkUType n)) tn- (STSet ct, NTSet tn n) -> Un.Type (Un.TSet $ mkComp ct n) tn+ (STSet _, NTSet tn n) -> Un.Type (Un.TSet (mkUType n)) tn (STOperation, NTOperation tn) -> Un.Type Un.TOperation tn (STContract _, NTContract tn n) -> Un.Type (Un.TContract (mkUType n)) tn@@ -54,12 +58,10 @@ Un.Type (Un.TOr fl fr (mkUType nl) (mkUType nr)) tn (STLambda _ _, NTLambda tn np nq) -> Un.Type (Un.TLambda (mkUType np) (mkUType nq)) tn- (STMap k _, NTMap tn nk nv) ->- Un.Type (Un.TMap (mkComp k nk) (mkUType nv)) tn- (STBigMap k _, NTBigMap tn nk nv) ->- Un.Type (Un.TBigMap (mkComp k nk) (mkUType nv)) tn- where- mkComp t a = Un.Type (Un.unwrapT $ toUType $ fromSingT t) a+ (STMap _ _, NTMap tn nk nv) ->+ Un.Type (Un.TMap (mkUType nk) (mkUType nv)) tn+ (STBigMap _ _, NTBigMap tn nk nv) ->+ Un.Type (Un.TBigMap (mkUType nk) (mkUType nv)) tn -- | Convert 'Un.Type' to the isomorphic set of information from typed world. withUType@@ -115,8 +117,9 @@ \(notesListT :: Notes listT) -> cont (NTList tn notesListT) - Un.TSet (Un.Type sT nsCT) -> withUType (Un.Type sT Un.noAnn) $- \(_ :: Notes sCT) -> cont @('TSet sCT) (NTSet tn nsCT)+ Un.TSet setT -> withUType setT $+ \(notesSetT :: Notes setT) ->+ cont (NTSet tn notesSetT) Un.TOperation -> cont (NTOperation tn)@@ -140,15 +143,15 @@ withUType rt $ \rn -> cont (NTLambda tn ln rn) - Un.TMap (Un.Type keyT notesT) valT ->- withUType (Un.Type keyT Un.noAnn) $ \(_ :: Notes keyT) ->+ Un.TMap keyT valT ->+ withUType keyT $ \keyN -> withUType valT $ \valN ->- cont @('TMap keyT _) (NTMap tn notesT valN)+ cont @('TMap _ _) (NTMap tn keyN valN) - Un.TBigMap (Un.Type keyT notesT) valT ->- withUType (Un.Type keyT Un.noAnn) $ \(_ :: Notes keyT) ->+ Un.TBigMap keyT valT ->+ withUType keyT $ \keyN -> withUType valT $ \valN ->- cont @('TBigMap keyT _) (NTBigMap tn notesT valN)+ cont @('TBigMap _ _) (NTBigMap tn keyN valN) -- Helper datatype for 'AsUType'. data SomeTypedInfo = forall t. (Typeable t, SingI t) => SomeTypedInfo (Notes t)
src/Michelson/Typed/Haskell.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Haskell-Michelson conversions. module Michelson.Typed.Haskell ( module Exports
src/Michelson/Typed/Haskell/Doc.hs view
@@ -1,13 +1,22 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- Dunno why it triggers {-# OPTIONS_GHC -Wno-redundant-constraints #-} -- | Documentation of types appearing in contracts. module Michelson.Typed.Haskell.Doc ( ADTRep+ , ConstructorRep (..)+ , crNameL, crDescriptionL, crFieldsL+ , FieldRep (..)+ , frNameL, frDescriptionL, frTypeRepL , WithinParens (..) , TypeHasDoc (..) , TypeDocHaskellRep , TypeDocMichelsonRep+ , FieldDescriptions , PolyTypeHasDocC , SomeTypeWithDoc (..) , typeDocDependencies'@@ -31,12 +40,15 @@ , DType (..) , DStorageType (..) , GTypeHasDoc+ , GProductHasDoc , buildADTRep , applyWithinParens ) where +import Control.Lens (each, to, _Just) import Data.Char (isLower, isUpper, toLower) import qualified Data.Kind as Kind+import Data.List (lookup) import Data.Singletons (SingI, demote) import qualified Data.Text as T import Data.Typeable (typeRep)@@ -52,12 +64,14 @@ import Michelson.Text import Michelson.Typed.Aliases import Michelson.Typed.EntryPoints+import Michelson.Typed.Haskell.ValidateDescription import Michelson.Typed.Haskell.Value import Michelson.Typed.T import Tezos.Address import Tezos.Core import Tezos.Crypto import Util.Generic+import Util.Lens import Util.Markdown import Util.Named import Util.Typeable@@ -66,38 +80,60 @@ -- Michelson value. Type parameter @a@ is what you put in place of -- each field of the datatype, e.g. information about field type. ----- Outer list layer corresponds to union, and the inner one corresponds--- to products within constructors. Constructors and fields names are present.-type ADTRep a = NonEmpty (Text, [(Maybe Text, a)])+-- This representation also includes descriptions of constructors and fields.+type ADTRep a = NonEmpty (ConstructorRep a) +-- | Representation of a constructor with an optional description.+data ConstructorRep a = ConstructorRep+ { crName :: Text+ , crDescription :: Maybe Text+ , crFields :: [FieldRep a]+ }++-- | Representation of a field with an optional description.+data FieldRep a = FieldRep+ { frName :: Maybe Text+ , frDescription :: Maybe Text+ , frTypeRep :: a+ }++makeLensesWith postfixLFields ''ConstructorRep+makeLensesWith postfixLFields ''FieldRep+ -- | Show given 'ADTRep' in a neat way. buildADTRep :: forall a. (WithinParens -> a -> Markdown) -> ADTRep a -> Markdown buildADTRep buildField = \case- p :| [] -> renderProduct (WithinParens False) (snd p)+ ConstructorRep{..} :| [] -> renderProduct (WithinParens False) crFields ps -> (mappend (mdItalic "one of" <> " \n")) $ mconcat . map (("+ " <> ) . (<> "\n")) $ map (renderNamedProduct (WithinParens True)) (toList ps) where- renderNamedProduct :: WithinParens -> (Text, [(Maybe Text, a)]) -> Markdown- renderNamedProduct wp (ctor, tys) =- mdBold (build ctor) <> " " <> renderProduct wp tys+ renderNamedProduct :: WithinParens -> ConstructorRep a -> Markdown+ renderNamedProduct wp ConstructorRep{..} =+ mdBold (build crName) <>+ if hasFieldNames+ then maybe "" (\d -> ": " <> build d <> " ") crDescription <> renderProduct wp crFields+ else renderProduct wp crFields <> maybe "" (\d -> ": " <> build d) crDescription+ where+ hasFieldNames = any (isJust . frName) crFields - renderProduct :: WithinParens -> [(Maybe Text, a)] -> Markdown+ renderProduct :: WithinParens -> [FieldRep a] -> Markdown renderProduct wp = \case [] -> "()"- [t] -> renderNamedField wp t- ts -> "(" <> (mconcat . intersperse ", " $ map (renderNamedField wp) ts) <> ")"+ [t] -> "\n" <> renderNamedField wp t+ ts -> "\n" <> (mconcat . intersperse "\n" $ map (renderNamedField wp) ts) - renderNamedField :: WithinParens -> (Maybe Text, a) -> Markdown- renderNamedField wp (mfieldName, ty) =- maybe "" buildFieldName mfieldName <>- buildField wp ty+ renderNamedField :: WithinParens -> FieldRep a -> Markdown+ renderNamedField wp FieldRep{frName = Just fieldName, ..} =+ " * " <> buildFieldName fieldName <> buildField wp frTypeRep <>+ maybe "" (mappend " " . mappend "\n" . build) frDescription --- | Remove fields names from 'ADTRep'.------ Sometimes there is no sense in showing them in the doc. Example: newtypes.+ renderNamedField wp FieldRep{frName = Nothing, ..} = buildField wp frTypeRep++-- | Map field names in a 'ADTRep', with the possibility to remove some names by+-- mapping them to 'Nothing'. mapADTRepFields :: (Maybe Text -> Maybe Text) -> ADTRep a -> ADTRep a-mapADTRepFields f = fmap . second . fmap $ first f+mapADTRepFields = over $ each . crFieldsL . each . frNameL -- | How field names should be displayed. --@@ -116,7 +152,10 @@ | otherwise = txt -- | Description for a Haskell type appearing in documentation.-class Typeable a => TypeHasDoc a where+class ( Typeable a+ , SingI (TypeDocFieldDescriptions a)+ , FieldDescriptionsValid (TypeDocFieldDescriptions a) a+ ) => TypeHasDoc a where -- | Name of type as it appears in definitions section. -- -- Each type must have its own unique name because it will be used@@ -138,11 +177,13 @@ -- | How reference to this type is rendered, in Markdown. -- -- Examples:- -- * @[Integer](#type-integer)@,- -- * @[Maybe](#type-Maybe) [()](#type-unit)@. --+ -- * @\[Integer](\#type-integer)@,+ -- * @\[Maybe](\#type-Maybe) \[()](\#type-unit)@.+ -- -- Consider using one of the following functions as default implementation; -- which one to use depends on number of type arguments in your type:+ -- -- * 'homomorphicTypeDocMdReference' -- * 'poly1TypeDocMdReference' -- * 'poly2TypeDocMdReference'@@ -183,6 +224,20 @@ => TypeDocHaskellRep a typeDocHaskellRep = haskellRepStripFieldPrefix homomorphicTypeDocHaskellRep + -- | Description of constructors and fields of @a@.+ --+ -- See 'FieldDescriptions' documentation for an example of usage.+ --+ -- Descriptions will be checked at compile time to make sure that only existing constructors+ -- and fields are referenced.+ --+ -- For that check to work @instance Generic a@ is required whenever @TypeDocFieldDescriptions@+ -- is not empty.+ --+ -- For implementation of the check see 'FieldDescriptionsValid' type family.+ type TypeDocFieldDescriptions a :: FieldDescriptions+ type TypeDocFieldDescriptions a = '[]+ -- | Final michelson representation of a type. -- -- For homomorphic types use 'homomorphicTypeDocMichelsonRep' implementation.@@ -196,6 +251,9 @@ -- | Signature of 'typeDocHaskellRep' function. --+-- A value of 'FieldDescriptionsV' is provided by the library to make sure that+-- instances won't replace it with an unchecked value.+-- -- When value is 'Just', it contains types which this type is built from. -- -- First element of provided pair may contain name a concrete type which has@@ -212,10 +270,11 @@ -- that it unfolds to @(Text, Integer)@. -- -- When rendered, values of this type look like:+-- -- * @(Integer, Natural)@ - for homomorphic type. -- * @MyError Integer = (Text, Integer)@ - concrete sample for polymorhpic type. type TypeDocHaskellRep a =- Proxy a -> Maybe (Maybe DocTypeRepLHS, ADTRep SomeTypeWithDoc)+ Proxy a -> FieldDescriptionsV -> Maybe (Maybe DocTypeRepLHS, ADTRep SomeTypeWithDoc) -- | Signature of 'typeDocMichelsonRep' function. --@@ -224,6 +283,7 @@ -- and its Michelson representation is given in the second element of the pair. -- -- Examples of rendered representation:+-- -- * @pair int nat@ - for homomorphic type. -- * @MyError Integer = pair string int@ - concrete sample for polymorhpic type. type TypeDocMichelsonRep a =@@ -279,8 +339,10 @@ [ Just mdSeparator , Just $ mdHeader lvl (mdTicked . build $ typeDocName ap') , Just $ typeDocMdDescription @a |+ "\n\n"- , typeDocHaskellRep ap' <&> \(mlhs, rep) ->+ , typeDocHaskellRep ap' (demote @(TypeDocFieldDescriptions a)) <&> \(mlhs, rep) -> let+ -- Without this signature type inference trips.+ buildField :: WithinParens -> SomeTypeWithDoc -> Markdown buildField wp (SomeTypeWithDoc di) = typeDocMdReference di wp renderedRep =@@ -393,24 +455,25 @@ (Generic a, GTypeHasDoc (G.Rep a)) => Proxy a -> [SomeTypeWithDoc] genericTypeDocDependencies _ = do- (_, products) <- toList $ gTypeDocHaskellRep @(G.Rep a)- (_, ty) <- products- return ty+ ConstructorRep{..} <- toList $ gTypeDocHaskellRep @(G.Rep a) []+ FieldRep{..} <- crFields+ return frTypeRep -- | Implement 'typeDocHaskellRep' for a homomorphic type. -- -- Note that it does not require your type to be of 'IsHomomorphic' instance, -- which can be useful for some polymorhpic types which, for documentation -- purposes, we want to consider homomorphic.+-- -- Example: 'Operation' is in fact polymorhpic, but we don't want this fact to -- be reflected in the documentation. homomorphicTypeDocHaskellRep :: forall a. (Generic a, GTypeHasDoc (G.Rep a)) => TypeDocHaskellRep a-homomorphicTypeDocHaskellRep _ = Just+homomorphicTypeDocHaskellRep _ descr = Just ( Nothing- , gTypeDocHaskellRep @(G.Rep a)+ , gTypeDocHaskellRep @(G.Rep a) descr ) -- | Implement 'typeDocHaskellRep' on example of given concrete type.@@ -434,9 +497,9 @@ ( Typeable a, GenericIsoValue a, GTypeHasDoc (G.Rep a) ) => TypeDocHaskellRep b-concreteTypeDocHaskellRepUnsafe _ = Just+concreteTypeDocHaskellRepUnsafe _ descr = Just ( Just (DocTypeRepLHS . toText . showtype $ Proxy @a)- , gTypeDocHaskellRep @(G.Rep a)+ , gTypeDocHaskellRep @(G.Rep a) descr ) -- | Erase fields from Haskell datatype representation.@@ -444,7 +507,7 @@ -- Use this when rendering fields names is undesired. haskellRepNoFields :: TypeDocHaskellRep a -> TypeDocHaskellRep a haskellRepNoFields mkRep =- \p -> second (mapADTRepFields (const Nothing)) <$> mkRep p+ \p descr -> second (mapADTRepFields (const Nothing)) <$> mkRep p descr -- | Cut fields prefixes which we use according to the style guide. --@@ -453,7 +516,7 @@ :: HasCallStack => TypeDocHaskellRep a -> TypeDocHaskellRep a haskellRepStripFieldPrefix mkRep =- \p -> second (mapADTRepFields (fmap stripPrefix)) <$> mkRep p+ \p descr -> second (mapADTRepFields (fmap stripPrefix)) <$> mkRep p descr where stripPrefix fieldName = case T.uncons $ T.dropWhile isLower fieldName of@@ -504,20 +567,23 @@ -- | Generic traversal for automatic deriving of some methods in 'TypeHasDoc'. class GTypeHasDoc (x :: Kind.Type -> Kind.Type) where- gTypeDocHaskellRep :: ADTRep SomeTypeWithDoc+ gTypeDocHaskellRep :: FieldDescriptionsV -> ADTRep SomeTypeWithDoc instance GTypeHasDoc x => GTypeHasDoc (G.D1 i x) where gTypeDocHaskellRep = gTypeDocHaskellRep @x instance (GTypeHasDoc x, GTypeHasDoc y) => GTypeHasDoc (x :+: y) where- gTypeDocHaskellRep = gTypeDocHaskellRep @x <> gTypeDocHaskellRep @y+ gTypeDocHaskellRep descr = gTypeDocHaskellRep @x descr <> gTypeDocHaskellRep @y descr instance (GProductHasDoc x, KnownSymbol ctor) => GTypeHasDoc (G.C1 ('G.MetaCons ctor _1 _2) x) where- gTypeDocHaskellRep = one $- ( toText $ symbolVal (Proxy @ctor)- , gProductDocHaskellRep @x- )+ gTypeDocHaskellRep descr = one $ ConstructorRep+ { crName = conName+ , crDescription = descr ^? to (lookup conName) . _Just . _1 . _Just+ , crFields = gProductDocHaskellRep @x $ descr ^. to (lookup conName) . _Just . _2+ }+ where+ conName = toText $ symbolVal (Proxy @ctor) instance TypeError ('Text "Cannot derive documentation for void-like type") => GTypeHasDoc G.V1 where@@ -525,21 +591,28 @@ -- | Product type traversal for 'TypeHasDoc'. class GProductHasDoc (x :: Kind.Type -> Kind.Type) where- gProductDocHaskellRep :: [(Maybe Text, SomeTypeWithDoc)]+ gProductDocHaskellRep :: [(Text, Text)] -> [FieldRep SomeTypeWithDoc] instance (GProductHasDoc x, GProductHasDoc y) => GProductHasDoc (x :*: y) where- gProductDocHaskellRep = gProductDocHaskellRep @x <> gProductDocHaskellRep @y+ gProductDocHaskellRep descr = gProductDocHaskellRep @x descr <> gProductDocHaskellRep @y descr instance TypeHasDoc a => GProductHasDoc (G.S1 ('G.MetaSel 'Nothing _1 _2 _3) (G.Rec0 a)) where- gProductDocHaskellRep = one (Nothing, SomeTypeWithDoc (Proxy @a))+ gProductDocHaskellRep _ = one $ FieldRep+ { frName = Nothing+ , frDescription = Nothing+ , frTypeRep = SomeTypeWithDoc (Proxy @a)+ } instance (TypeHasDoc a, KnownSymbol field) => GProductHasDoc (G.S1 ('G.MetaSel ('Just field) _1 _2 _3) (G.Rec0 a)) where- gProductDocHaskellRep = one- ( Just $ toText (symbolVal $ Proxy @field)- , SomeTypeWithDoc (Proxy @a)- )+ gProductDocHaskellRep descr = one $ FieldRep+ { frName = Just fieldName+ , frDescription = descr ^? to (lookup fieldName) . _Just+ , frTypeRep = SomeTypeWithDoc (Proxy @a)+ }+ where+ fieldName = toText (symbolVal $ Proxy @field) instance GProductHasDoc G.U1 where gProductDocHaskellRep = mempty@@ -558,13 +631,13 @@ typeDocName _ = "Integer" typeDocMdDescription = "Signed number." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc Natural where typeDocName _ = "Natural" typeDocMdDescription = "Unsigned number." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc MText where typeDocName _ = "Text"@@ -574,37 +647,37 @@ \This has to contain only ASCII characters with codes from [32; 126] range; \ \additionally, newline feed character is allowed." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc Bool where typeDocName _ = "Bool" typeDocMdDescription = "Bool primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc ByteString where typeDocName _ = "ByteString" typeDocMdDescription = "Bytes primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc Mutez where typeDocName _ = "Mutez" typeDocMdDescription = "Mutez primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc KeyHash where typeDocName _ = "KeyHash" typeDocMdDescription = "KeyHash primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc Timestamp where typeDocName _ = "Timestamp" typeDocMdDescription = "Timestamp primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc Address where typeDocName _ = "Address (no entrypoint)"@@ -612,25 +685,25 @@ "This is similar to Michelson Address, but does not retain entrypoint name \ \if it refers to a contract." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc EpAddress where typeDocName _ = "Address" typeDocMdDescription = "Address primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc PublicKey where typeDocName _ = "PublicKey" typeDocMdDescription = "PublicKey primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc Signature where typeDocName _ = "Signature" typeDocMdDescription = "Signature primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing instance TypeHasDoc () where typeDocName _ = "()"@@ -644,19 +717,19 @@ -- poly1TypeDocMdReference would produce text like @[] Integer@, we want -- to replace this @[]@ with @List@. customTypeDocMdReference ("List", DType (Proxy @[a])) [DType (Proxy @a)]- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @[Integer] instance PolyTypeHasDocC '[a] => TypeHasDoc (Maybe a) where typeDocMdDescription = "Option primitive." typeDocMdReference = poly1TypeDocMdReference- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @(Maybe Integer) instance PolyTypeHasDocC [l, r] => TypeHasDoc (Either l r) where typeDocMdDescription = "Or primitive." typeDocMdReference = poly2TypeDocMdReference- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @(Either Integer Natural) instance PolyTypeHasDocC [a, b] => TypeHasDoc (a, b) where@@ -666,7 +739,7 @@ , typeDocMdReference (Proxy @b) (WithinParens False) ] typeDocMdDescription = "Pair primitive."- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @(Integer, Natural) instance PolyCTypeHasDocC '[a] => TypeHasDoc (Set a) where@@ -674,7 +747,7 @@ typeDocMdReference = poly1TypeDocMdReference typeDocMdDescription = "Set primitive." typeDocDependencies _ = [SomeTypeWithDoc (Proxy @a)]- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @(Set Integer) instance TypeHasDoc Operation where@@ -682,7 +755,7 @@ typeDocMdReference tp = customTypeDocMdReference ("Operation", DType tp) [] typeDocMdDescription = "Operation primitive." typeDocDependencies _ = []- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = homomorphicTypeDocMichelsonRep instance PolyTypeHasDocC '[cp] => TypeHasDoc (ContractRef cp) where@@ -690,7 +763,7 @@ typeDocMdReference = poly1TypeDocMdReference typeDocMdDescription = "Contract primitive with given type of parameter." typeDocDependencies _ = [SomeTypeWithDoc (Proxy @cp)]- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @(ContractRef Integer) instance (PolyCTypeHasDocC '[k], PolyTypeHasDocC '[v], Ord k) =>@@ -699,7 +772,7 @@ typeDocMdReference = poly2TypeDocMdReference typeDocMdDescription = "Map primitive." typeDocDependencies _ = [SomeTypeWithDoc (Proxy @k), SomeTypeWithDoc (Proxy @v)]- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @(Map Integer Natural) instance (PolyCTypeHasDocC '[k], PolyTypeHasDocC '[v], Ord k) =>@@ -708,7 +781,7 @@ typeDocMdReference = poly2TypeDocMdReference typeDocMdDescription = "BigMap primitive." typeDocDependencies _ = [SomeTypeWithDoc (Proxy @k), SomeTypeWithDoc (Proxy @v)]- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @(BigMap Integer Natural) @@ -723,7 +796,7 @@ , typeDocMdReference (Proxy @c) (WithinParens False) ] typeDocMdDescription = "Tuple of size 3."- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @(Integer, Natural, MText) instance PolyTypeHasDocC [a, b, c, d] => TypeHasDoc (a, b, c, d) where@@ -735,7 +808,7 @@ , typeDocMdReference (Proxy @d) (WithinParens False) ] typeDocMdDescription = "Tuple of size 4."- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = -- Starting from tuple of size 4 the exact types should not matter to a reader, -- rather the resulting pairs tree.@@ -751,7 +824,7 @@ , typeDocMdReference (Proxy @d) (WithinParens False) , typeDocMdReference (Proxy @e) (WithinParens False) ]- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @((), (), (), (), ()) @@ -766,7 +839,7 @@ , typeDocMdReference (Proxy @f) (WithinParens False) ] typeDocMdDescription = "Tuple of size 6."- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @((), (), (), (), (), ()) @@ -782,7 +855,7 @@ , typeDocMdReference (Proxy @g) (WithinParens False) ] typeDocMdDescription = "Tuple of size 7."- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep = concreteTypeDocMichelsonRep @((), (), (), (), (), (), ()) @@ -800,7 +873,7 @@ typeDocMdReference (Proxy @(ApplyNamedFunctor f a)) (WithinParens False) |+ "" typeDocDependencies _ = [SomeTypeWithDoc (Proxy @(ApplyNamedFunctor f a)), SomeTypeWithDoc (Proxy @Integer)]- typeDocHaskellRep _ = Nothing+ typeDocHaskellRep _ _ = Nothing typeDocMichelsonRep _ = (Just "number: Integer", demote @(ToT (ApplyNamedFunctor f Integer))) typeDocMdDescription = "Some entries have names for clarity.\n\n\
src/Michelson/Typed/Haskell/Instr.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Typed.Haskell.Instr ( module Exports ) where
src/Michelson/Typed/Haskell/Instr/Helpers.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Typed.Haskell.Instr.Helpers ( Branch (..) , Path
src/Michelson/Typed/Haskell/Instr/Product.hs view
@@ -1,4 +1,9 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-redundant-constraints #-}+{-# LANGUAGE InstanceSigs #-} -- | Instructions working on product types derived from Haskell ones. module Michelson.Typed.Haskell.Instr.Product@@ -8,10 +13,15 @@ , instrGetField , instrSetField , instrConstruct+ , instrConstructStack+ , instrDeconstruct+ , InstrDeconstructC , GetFieldType , ConstructorFieldTypes+ , ConstructorFieldNames , FieldConstructor (..)+ , CastFieldConstructors (..) ) where import qualified Data.Kind as Kind@@ -243,6 +253,19 @@ newtype FieldConstructor (st :: [k]) (field :: Kind.Type) = FieldConstructor (Instr (ToTs' st) (ToT field ': ToTs' st)) +-- | Ability to pass list of fields with the same ToTs.+-- It may be useful if you don't want to work with NamedF in ConstructorFieldTypes.+class ToTs xs ~ ToTs ys => CastFieldConstructors xs ys where+ castFieldConstructorsImpl :: Rec (FieldConstructor st) xs -> Rec (FieldConstructor st) ys++instance CastFieldConstructors '[] '[] where+ castFieldConstructorsImpl RNil = RNil++instance (CastFieldConstructors xs ys, ToTs xs ~ ToTs ys, ToT x ~ ToT y)+ => CastFieldConstructors (x ': xs) (y ': ys) where+ castFieldConstructorsImpl (FieldConstructor fctr :& xs) =+ FieldConstructor fctr :& (castFieldConstructorsImpl @xs @ys xs)+ -- | For given complex type @dt@ and its field @fieldTy@ update the field value. instrConstruct :: forall dt st. InstrConstructC dt@@ -250,23 +273,52 @@ -> Instr st (ToT dt ': st) instrConstruct = gInstrConstruct @(G.Rep dt) +instrConstructStack+ :: forall dt stack st .+ ( InstrConstructC dt+ , stack ~ ToTs (ConstructorFieldTypes dt)+ , KnownList stack+ )+ => Instr (stack ++ st) (ToT dt ': st)+instrConstructStack =+ FrameInstr (Proxy @st) (gInstrConstructStack @(G.Rep dt))+ -- | Types of all fields in a datatype. type ConstructorFieldTypes dt = GFieldTypes (G.Rep dt) --- | Constraint for 'instrConstruct'.+-- | Names of all fields in a datatype.+type ConstructorFieldNames dt = GFieldNames (G.Rep dt)++-- | Constraint for 'instrConstruct' and 'gInstrConstructStack'. type InstrConstructC dt = (GenericIsoValue dt, GInstrConstruct (G.Rep dt)) +-- | Retrieve field names of a constructor.+type family GFieldNames x :: [Symbol] where+ GFieldNames (G.D1 _ x) = GFieldNames x+ GFieldNames (G.C1 _ x) = GFieldNames x+ GFieldNames (x :*: y) = GFieldNames x ++ GFieldNames y+ GFieldNames (G.S1 ('G.MetaSel ('Just fieldName) _ _ _) _) = '[fieldName]+ GFieldNames (G.S1 _ (G.Rec0 (NamedF _ _ fieldName))) = '[fieldName]++ GFieldNames (G.S1 ('G.MetaSel _ _ _ _) _) = TypeError ('Text "All fields have to be named")+ GFieldNames (_ :+: _) = TypeError ('Text "Cannot get field names of sum type")+ GFieldNames G.V1 = TypeError ('Text "Must be at least one constructor")+ -- | Generic traversal for 'instrConstruct'. class GIsoValue x => GInstrConstruct (x :: Kind.Type -> Kind.Type) where type GFieldTypes x :: [Kind.Type] gInstrConstruct :: Rec (FieldConstructor st) (GFieldTypes x) -> Instr st (GValueType x ': st)+ gInstrConstructStack :: Instr (ToTs (GFieldTypes x)) '[GValueType x] instance GInstrConstruct x => GInstrConstruct (G.M1 t i x) where type GFieldTypes (G.M1 t i x) = GFieldTypes x gInstrConstruct = gInstrConstruct @x+ gInstrConstructStack = gInstrConstructStack @x instance ( GInstrConstruct x, GInstrConstruct y , RSplit (GFieldTypes x) (GFieldTypes y)+ , KnownList (ToTs (GFieldTypes x)), KnownList (ToTs (GFieldTypes y))+ , ToTs (GFieldTypes x) ++ ToTs (GFieldTypes y) ~ ToTs (GFieldTypes x ++ GFieldTypes y) ) => GInstrConstruct (x :*: y) where type GFieldTypes (x :*: y) = GFieldTypes x ++ GFieldTypes y gInstrConstruct fs =@@ -275,19 +327,27 @@ rinstr = gInstrConstruct @y rfs in linstr `Seq` DIP rinstr `Seq` PAIR + gInstrConstructStack =+ let linstr = gInstrConstructStack @x+ rinstr = gInstrConstructStack @y+ in FrameInstr (Proxy @(ToTs (GFieldTypes y))) linstr `Seq` DIP rinstr `Seq` PAIR+ instance GInstrConstruct G.U1 where type GFieldTypes G.U1 = '[] gInstrConstruct RNil = UNIT+ gInstrConstructStack = UNIT instance ( TypeError ('Text "Cannot construct sum type") , GIsoValue x, GIsoValue y ) => GInstrConstruct (x :+: y) where type GFieldTypes (x :+: y) = '[] gInstrConstruct = error "impossible"+ gInstrConstructStack = error "impossible" instance IsoValue a => GInstrConstruct (G.Rec0 a) where type GFieldTypes (G.Rec0 a) = '[a] gInstrConstruct (FieldConstructor i :& RNil) = i+ gInstrConstructStack = Nop -- Examples ----------------------------------------------------------------------------@@ -300,3 +360,56 @@ FieldConstructor UNIT :& FieldConstructor DUP :& RNil++_constructInstr2 :: Instr s (ToT MyType1 ': s)+_constructInstr2 =+ instrConstruct @MyType1 $+ FieldConstructor (PUSH (toVal @Integer 5)) :&+ FieldConstructor (PUSH (toVal @ByteString "bytestring1")) :&+ FieldConstructor (PUSH (toVal @(Maybe ByteString) (Just "bytestring2"))) :&+ RNil++----------------------------------------------------------------------------+-- Value deconstruction+----------------------------------------------------------------------------++-- | Constraint for 'instrConstruct'.+type InstrDeconstructC dt = (GenericIsoValue dt, GInstrDeconstruct (G.Rep dt))++-- | For given complex type @dt@ deconstruct it to its field types.+instrDeconstruct+ :: forall dt stack st .+ (InstrDeconstructC dt+ , stack ~ ToTs (ConstructorFieldTypes dt)+ , KnownList stack+ )+ => Instr (ToT dt ': st) (stack ++ st)+instrDeconstruct = FrameInstr (Proxy @st) $ gInstrDeconstruct @(G.Rep dt)++-- | Generic traversal for 'instrDeconstruct'.+class GIsoValue x => GInstrDeconstruct (x :: Kind.Type -> Kind.Type) where+ gInstrDeconstruct :: Instr '[GValueType x] (ToTs (GFieldTypes x))++instance GInstrDeconstruct x => GInstrDeconstruct (G.M1 t i x) where+ gInstrDeconstruct = gInstrDeconstruct @x++instance ( GInstrDeconstruct x, GInstrDeconstruct y+ , t ~ (x :*: y)+ , KnownList (ToTs (GFieldTypes x)), KnownList (ToTs (GFieldTypes y))+ , ToTs (GFieldTypes x) ++ ToTs (GFieldTypes y) ~ ToTs (GFieldTypes x ++ GFieldTypes y)+ ) => GInstrDeconstruct (x :*: y) where+ gInstrDeconstruct =+ let linstr = gInstrDeconstruct @x+ rinstr = gInstrDeconstruct @y+ in UNPAIR `Seq` DIP rinstr `Seq` FrameInstr (Proxy @(ToTs (GFieldTypes y))) linstr++instance GInstrDeconstruct G.U1 where+ gInstrDeconstruct = DROP++instance ( TypeError ('Text "Cannot deconstruct sum type")+ , GIsoValue x, GIsoValue y+ ) => GInstrDeconstruct (x :+: y) where+ gInstrDeconstruct = error "impossible"++instance IsoValue a => GInstrDeconstruct (G.Rec0 a) where+ gInstrDeconstruct = Nop
src/Michelson/Typed/Haskell/Instr/Sum.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-redundant-constraints #-} -- | Instructions working on sum types derived from Haskell ones.@@ -53,7 +57,7 @@ import Michelson.Typed.T import Michelson.Typed.Value import Tezos.Address (Address)-import Tezos.Core (Mutez, Timestamp)+import Tezos.Core (Mutez, Timestamp, ChainId) import Tezos.Crypto (KeyHash, PublicKey, Signature) import Util.Label (Label) import Util.Type@@ -201,6 +205,7 @@ IsPrimitiveValue (Set _) = 'True IsPrimitiveValue ([_]) = 'True IsPrimitiveValue (Operation' _) = 'True+ IsPrimitiveValue ChainId = 'True IsPrimitiveValue _ = 'False -- Some types don't have Generic instances (e. g. primitives like Integer), so
src/Michelson/Typed/Haskell/LooseSum.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-redundant-constraints #-} -- | Representation of Haskell sum types via loosy typed Michelson values,
+ src/Michelson/Typed/Haskell/ValidateDescription.hs view
@@ -0,0 +1,135 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ++module Michelson.Typed.Haskell.ValidateDescription+ ( FieldDescriptions+ , FieldDescriptionsV++ , FieldDescriptionsValid+ ) where++import qualified Data.Kind as Kind+import Data.Singletons (Demote)+import Data.Type.Bool+import qualified GHC.Generics as G+import GHC.TypeLits++-- | Description of constructors and fields of some datatype.+--+-- This type is just two nested maps represented as associative lists. It is supposed to+-- be interpreted like this:+--+-- > [(Constructor name, (Maybe constructor description, [(Field name, Field description)]))]+--+-- Example with a concrete data type:+--+-- > data Foo+-- > = Foo+-- > { fFoo :: Int+-- > }+-- > | Bar+-- > { fBar :: Text+-- > }+-- > deriving (Generic)+-- >+-- > type FooDescriptions =+-- > '[ '( "Foo", '( 'Just "foo constructor",+-- > , '[ '("fFoo", "some number")+-- > ])+-- > )+-- > , '( "Bar", '( 'Nothing,+-- > , '[ '("fBar", "some string")+-- > ])+-- > )+-- > ]+type FieldDescriptions = [(Symbol, (Maybe Symbol, [(Symbol, Symbol)]))]++-- | Value-level counterpart to 'FieldDescriptions'.+type FieldDescriptionsV = Demote FieldDescriptions++-- | This type family checks that field descriptions mention only existing constructors and fields.+--+-- When @descr@ is empty this family does nothing, to avoid breaking for built-in, non-ADT types.+--+-- When @descr@ is not empty, this family will demand 'G.Generic' instance for @typ@ and fail with a+-- 'TypeError' if there none.+type family FieldDescriptionsValid (descr :: FieldDescriptions) (typ :: Kind.Type) :: Kind.Constraint where+ FieldDescriptionsValid '[] _ = ()+ FieldDescriptionsValid descr typ =+ Assert+ (TypeError+ ('Text "No Generic instance for " ':<>: 'ShowType typ ':<>: 'Text "." ':$$:+ 'Text "Generic is needed to validate TypeDocFieldDescriptions.")+ )+ (G.Rep typ)+ (FieldDescriptionsValidImpl descr typ)++-- | Actual recursive implementation for 'FieldDescriptionsValid'.+type family FieldDescriptionsValidImpl (descr :: FieldDescriptions) (typ :: Kind.Type) :: Kind.Constraint where+ FieldDescriptionsValidImpl '[] _ = ()+ FieldDescriptionsValidImpl ( '(conName, '(_, fields)) ': rest ) typ =+ ( HasAllFields conName fields typ+ , FieldDescriptionsValidImpl rest typ+ )++-- | Check whether given constructor name @conName@ is present in 'G.Rep' of a datatype.+type family HasConstructor (conName :: Symbol) (g :: Kind.Type -> Kind.Type) :: Bool where+ HasConstructor conName (G.D1 _ cs) = HasConstructor conName cs+ HasConstructor conName (G.C1 ('G.MetaCons conName _ _) _) = 'True+ HasConstructor conName (l G.:+: r) = HasConstructor conName l || HasConstructor conName r+ HasConstructor _ _ = 'False++-- | Check whether all fields described for given constructor @conName@ are present in the datatype.+--+-- This family also checks whether the constructor is present and fails with a 'TypeError'+-- otherwise.+type family HasAllFields (conName :: Symbol) (fields :: [(Symbol, Symbol)]) (typ :: Kind.Type) :: Kind.Constraint where+ HasAllFields conName fields typ =+ If+ (HasConstructor conName (G.Rep typ))+ (HasAllFieldsImpl conName fields typ)+ (TypeError+ ('Text "No constructor " ':<>: 'ShowType conName ':<>: 'Text " in type " ':<>: 'ShowType typ ':<>: 'Text "." )+ )++-- | Actual recursive implementation of 'HasAllFields'.+type family HasAllFieldsImpl (conName :: Symbol) (fields :: [(Symbol, Symbol)]) (typ :: Kind.Type) :: Kind.Constraint where+ HasAllFieldsImpl _ '[] _ = ()+ HasAllFieldsImpl conName ( '(fieldName, _) ': rest ) typ =+ ( If+ (HasField conName fieldName (G.Rep typ))+ (() :: Kind.Constraint)+ (TypeError+ ('Text "No field " ':<>: 'ShowType fieldName ':<>: 'Text " in constructor " ':<>:+ 'ShowType conName ':<>: 'Text " of type " ':<>: 'ShowType typ ':<>: 'Text "."+ )+ )+ , HasAllFieldsImpl conName rest typ+ )++-- | Check that Generic 'G.Rep' has given field @fieldName@ in a given constructor @conName@.+type family HasField (conName :: Symbol) (fieldName :: Symbol) (g :: Kind.Type -> Kind.Type) :: Bool where+ HasField conName fieldName (G.D1 _ cs) = HasField conName fieldName cs+ HasField conName fieldName (G.C1 ('G.MetaCons conName _ _) c) = ConHasField fieldName c+ HasField conName fieldName (l G.:+: r) = HasField conName fieldName l || HasField conName fieldName r+ HasField _ _ _ = 'False++-- | Check that Generic representation for a constructor has given field @fieldName@.+type family ConHasField (fieldName :: Symbol) (g :: Kind.Type -> Kind.Type) :: Bool where+ ConHasField fieldName (G.S1 ('G.MetaSel ('Just fieldName) _ _ _) _) = 'True+ ConHasField fieldName (l G.:*: r) = ConHasField fieldName l || ConHasField fieldName r+ ConHasField _ _ = 'False++-- A trick by Csongor Kiss: https://kcsongor.github.io/report-stuck-families/+--+-- 'T1' is a dummy type and 'Assert' will get stuck whenever its argument @break@ is stuck.+--+-- This happens because for stuck argument GHC can't check whether it is equal to 'T1' and therefore+-- can't select one of 'Assert's equations.++data T1 a++type family Assert (err :: Constraint) (break :: Kind.Type -> Kind.Type) (v :: k) :: k where+ Assert _ T1 _ = Any+ Assert _ _ k = k
src/Michelson/Typed/Haskell/Value.hs view
@@ -1,4 +1,9 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-redundant-constraints #-}+ -- | Conversions between haskell types/values and Michelson ones. module Michelson.Typed.Haskell.Value ( -- * Value conversions
src/Michelson/Typed/Instr.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE QuantifiedConstraints #-} -- | Module, containing data types for Michelson value.@@ -11,8 +15,8 @@ , PrintComment (..) , TestAssert (..) , ContractCode- , FullContract (..)- , mapFullContractCode+ , Contract (..)+ , mapContractCode , pattern CAR , pattern CDR , pattern UNPAIR@@ -327,7 +331,7 @@ CREATE_CONTRACT :: (ParameterScope p, StorageScope g)- => FullContract p g+ => Contract p g -> Instr ('TOption 'TKeyHash ': 'TMutez ': g ': s)@@ -444,22 +448,21 @@ -- | Typed contract and information about annotations -- which is not present in the contract code.--- TODO [#12]: rename this to 'Contract'-data FullContract cp st = (ParameterScope cp, StorageScope st) => FullContract- { fcCode :: ContractCode cp st- , fcParamNotes :: ParamNotes cp- , fcStoreNotes :: Notes st+data Contract cp st = (ParameterScope cp, StorageScope st) => Contract+ { cCode :: ContractCode cp st+ , cParamNotes :: ParamNotes cp+ , cStoreNotes :: Notes st } -deriving stock instance Show (FullContract cp st)-deriving stock instance Eq (ContractCode cp st) => Eq (FullContract cp st)-instance NFData (FullContract cp st) where- rnf (FullContract a b c) = rnf (a, b, c)+deriving stock instance Show (Contract cp st)+deriving stock instance Eq (ContractCode cp st) => Eq (Contract cp st)+instance NFData (Contract cp st) where+ rnf (Contract a b c) = rnf (a, b, c) -mapFullContractCode+mapContractCode :: (ContractCode cp st -> ContractCode cp st)- -> FullContract cp st- -> FullContract cp st-mapFullContractCode f contract = contract { fcCode = f $ fcCode contract }+ -> Contract cp st+ -> Contract cp st+mapContractCode f contract = contract { cCode = f $ cCode contract } $(deriveGADTNFData ''Instr)
src/Michelson/Typed/Polymorphic.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing type classes for operating with Michelson values -- in the context of polymorphic stack type operations.
src/Michelson/Typed/Scope.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE UndecidableSuperClasses #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-}
src/Michelson/Typed/Sing.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Module, providing singleton boilerplate for
src/Michelson/Typed/T.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE DataKinds #-} -- | Module, providing 'T' data type, representing Michelson
src/Michelson/Typed/Util.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | General-purpose utility functions for typed types. module Michelson.Typed.Util@@ -12,6 +16,9 @@ , linearizeLeftDeep -- * Value analysis+ , dfsValue+ , dfsFoldValue+ , dfsModifyValue , isStringValue , isBytesValue , allAtomicValues@@ -20,6 +27,9 @@ import Prelude hiding (Ordering(..)) import Data.Default (Default(..))+import qualified Data.Foldable as F+import qualified Data.Map as M+import qualified Data.Set as S import qualified Text.Show import Michelson.Text (MText)@@ -107,8 +117,8 @@ | otherwise -> step i CREATE_CONTRACT contract | dsGoToValues ->- let updateContractCode code = CREATE_CONTRACT $ contract{ fcCode = code }- in recursion1 updateContractCode $ fcCode contract+ let updateContractCode code = CREATE_CONTRACT $ contract{ cCode = code }+ in recursion1 updateContractCode $ cCode contract | otherwise -> step i Nop{} -> step i@@ -390,6 +400,112 @@ -- Value analysis ---------------------------------------------------------------------------- +-- | Traverse a value in depth-first order.+dfsValue ::+ forall t x.+ Monoid x+ => (forall t'. Value t' -> (Value t', x))+ -> Value t+ -> (Value t, x)+dfsValue step i = case i of+ -- Atomic+ VKey{} -> step i+ VUnit -> step i+ VSignature{} -> step i+ VChainId{} -> step i+ VOp{} -> step i+ VContract{} -> step i+ VLam{} -> step i+ VInt{} -> step i+ VNat{} -> step i+ VString{} -> step i+ VBytes{} -> step i+ VMutez{} -> step i+ VBool{} -> step i+ VKeyHash{} -> step i+ VTimestamp{} -> step i+ VAddress{} -> step i++ -- Non-atomic+ VOption mVal -> case mVal of+ Nothing -> step i+ Just val -> recursion1 (VOption . Just) val+ VList vals ->+ let+ (vs, xs) = unzip $ map (dfsValue step) vals+ (v, x) = step $ VList vs+ in+ (v, x <> F.fold xs)+ VSet vals ->+ let+ (cs, cxs) =+ S.foldr (\a (s, xs) -> let (c, x) = step a in (S.insert c s, x <> xs))+ (S.empty, mempty) vals+ (v, vx) = step (VSet cs)+ in (v, vx <> cxs)+ VPair (v1, v2) -> recursion2 (curry VPair) v1 v2+ VOr vEither -> case vEither of+ Left v -> recursion1 (VOr . Left) v+ Right v -> recursion1 (VOr . Right) v+ VMap vmap -> mapRecursion VMap vmap+ VBigMap vmap -> mapRecursion VBigMap vmap+ where+ recursion1 ::+ forall t'.+ (Value t' -> Value t)+ -> Value t'+ -> (Value t, x)+ recursion1 constructor i' =+ let+ (v, x) = dfsValue step i'+ (v', x') = step $ constructor v+ in+ (v', x <> x')+ recursion2 ::+ forall t1 t2.+ (Value t1 -> Value t2 -> Value t)+ -> Value t1+ -> Value t2+ -> (Value t, x)+ recursion2 constructor i1 i2 =+ let+ (v1, x1) = dfsValue step i1+ (v2, x2) = dfsValue step i2+ (v, x) = step $ constructor v1 v2+ in+ (v, x1 <> x2 <> x)++ mapRecursion+ :: forall t' k. Comparable k+ => (M.Map (Value k) (Value t') -> Value t)+ -> M.Map (Value k) (Value t')+ -> (Value t, x)+ mapRecursion constructor vmap =+ let+ (ms, cxs) = M.foldrWithKey (\k a (m, xs) ->+ let (c, cx) = step k+ (v, vx) = dfsValue step a+ in (M.insert c v m, vx <> cx <> xs)) (M.empty, mempty) vmap+ (v', x') = step $ constructor ms+ in+ (v', cxs <> x')++-- | Specialization of 'dfsValue' for case when changing the value is+-- not required.+dfsFoldValue ::+ Monoid x =>+ (forall t'. Value t' -> x)+ -> Value t+ -> x+dfsFoldValue f = snd . dfsValue (\v -> (v, f v))++-- | Specialization of 'dfsValue' which only modifies given value.+dfsModifyValue ::+ (forall t'. Value t' -> Value t')+ -> Value t+ -> Value t+dfsModifyValue f = fst . dfsValue ((, ()) . f)+ -- | If value is a string, return the stored string. isStringValue :: Value t -> Maybe MText isStringValue =@@ -404,25 +520,9 @@ VBytes bytes -> Just bytes _ -> Nothing --- | Takes a selector which checks whether an atomic value (i. e. that--- can not contain another value) can be converted to something.--- Recursively applies it to all atomic values in potentially--- non-atomic value. Collects extracted values in a list.------ Perhaps one day we'll have `dfsValue`.+-- | Takes a selector which checks whether a value can be converted+-- to something. Recursively applies it to all values. Collects extracted+-- values in a list. allAtomicValues :: forall t a. (forall t'. Value t' -> Maybe a) -> Value t -> [a]-allAtomicValues selector = go- where- go :: forall x. Value x -> [a]- go = \case- VList l -> foldMap go l- VSet s -> foldMap go s- VPair (l, r) -> go l <> go r- VOr e -> either go go e- VMap m -> goMap m- VBigMap m -> goMap m- v -> maybeToList $ selector v-- goMap :: Map (Value k) (Value v) -> [a]- goMap m = foldMap go (keys m) <> foldMap go (toList m)+allAtomicValues selector = dfsFoldValue (maybeToList . selector)
src/Michelson/Typed/Value.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE QuantifiedConstraints #-} -- | Module, containing data types for Michelson value.
src/Michelson/Untyped.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Untyped ( module Exports ) where
src/Michelson/Untyped/Aliases.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Some simple aliases for Michelson types. module Michelson.Untyped.Aliases
src/Michelson/Untyped/Annotation.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Michelson annotations in untyped model. module Michelson.Untyped.Annotation@@ -37,7 +41,7 @@ ) where import Data.Aeson.TH (deriveJSON)-import Data.Char (isAlpha, isAscii, isNumber)+import Data.Char (isAlpha, isAscii, isDigit, isNumber) import Data.Data (Data(..)) import Data.Default (Default(..)) import qualified Data.Kind as Kind@@ -57,7 +61,7 @@ -- As per Michelson documentation, this type has an invariant: -- (except for the first character, here parametrized in the type `tag`) the -- allowed character set is the one matching the following regexp:--- @%|@%%|%@|[@:%][_a-zA-Z][_0-9a-zA-Z\.%@]*+-- @%|@%%|%@|[@:%][_0-9a-zA-Z][_0-9a-zA-Z\.%@]* newtype Annotation tag = AnnotationUnsafe { unAnnotation :: Text } deriving stock (Eq, Data, Functor, Generic) deriving newtype (IsString)@@ -259,7 +263,7 @@ -- Note that this does not check Special Annotations, see `specialVarAnns` -- and `specialFieldAnn` isValidAnnStart :: Char -> Bool-isValidAnnStart x = (isAscii x && isAlpha x) || x == '_'+isValidAnnStart x = (isAscii x && (isAlpha x || isDigit x)) || x == '_' -- | Checks if a `Char` is valid to be part of an annotation, following a valid -- first character (see `isValidAnnStart`) and the prefix (%/@/:).
src/Michelson/Untyped/Contract.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Michelson contract in untyped model. module Michelson.Untyped.Contract
src/Michelson/Untyped/EntryPoints.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Untyped.EntryPoints ( EpName (..) , pattern DefEpName
src/Michelson/Untyped/Ext.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Michelson.Untyped.Ext ( ExtInstrAbstract (..) , StackRef (..)
src/Michelson/Untyped/Instr.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Michelson instructions in untyped model. module Michelson.Untyped.Instr
src/Michelson/Untyped/Type.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Michelson types represented in untyped model. module Michelson.Untyped.Type
src/Michelson/Untyped/Value.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Untyped Michelson values (i. e. type of a value is not statically known). module Michelson.Untyped.Value
src/Morley/CLI.hs view
@@ -1,10 +1,16 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-orphans #-} -- | Utilities for parsing Morley types using @optparse-applicative@. module Morley.CLI- ( -- * Options- contractFileOption+ ( -- * Full parsers+ parserInfo+ -- * Options+ , contractFileOption , nowOption , maxStepsOption , dbPathOption@@ -18,8 +24,12 @@ , mTextOption ) where -import Options.Applicative (help, long, metavar, option, strOption, switch)+import Named (arg)+import Options.Applicative+ (footerDoc, fullDesc, header, help, helper, info, long, metavar, option, progDesc, strOption,+ switch) import qualified Options.Applicative as Opt+import Options.Applicative.Help.Pretty (Doc) import qualified Michelson.Parser as P import Michelson.Runtime (TxData(..))@@ -37,6 +47,26 @@ -- These options are mostly specifications of 'mkCLOptionParser' -- for concrete types (with more specific names). ----------------------------------------------------------------------------++-- | Full parser for a client.+parserInfo+ :: "usage" :! Doc+ -> "description" :! String+ -> "header" :! String+ -> "parser" :! Opt.Parser s+ -> Opt.ParserInfo s+parserInfo+ (arg #usage -> usage)+ (arg #description -> description)+ (arg #header -> clientHeader)+ (arg #parser -> parser) =+ info (helper <*> parser) $+ mconcat+ [ fullDesc+ , progDesc description+ , header clientHeader+ , footerDoc $ pure usage+ ] -- | Parser for path to a contract code. contractFileOption :: Opt.Parser FilePath
src/Morley/Micheline.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module that provides type classes for converting to and from low-level -- Micheline representation. module Morley.Micheline@@ -14,7 +18,7 @@ import Michelson.Interpret.Pack (encodeValue', packCode', packNotedT', packT') import Michelson.Interpret.Unpack (unpackInstr', unpackValue') import Michelson.Typed- (FullContract(..), HasNoOp, Instr(..), Notes(..), T(..), Value, pnNotes, pnRootAnn)+ (Contract(..), HasNoOp, Instr(..), Notes(..), T(..), Value, pnNotes, pnRootAnn) import Michelson.Typed.Scope (UnpackedValScope) import Michelson.Untyped.Annotation (Annotation(..), RootAnn) import Michelson.Untyped.Instr (ExpandedOp)@@ -37,21 +41,21 @@ instance (SingI t, HasNoOp t) => ToExpression (Value t) where toExpression = decode . encodeValue' -instance ToExpression (FullContract cp st) where- toExpression FullContract{..} = Expression_Seq $ fromList+instance ToExpression (Contract cp st) where+ toExpression Contract{..} = Expression_Seq $ fromList [ Expression_Prim $ MichelinePrimAp (MichelinePrimitive "parameter")- (fromList [ addRootAnnToExpression (pnRootAnn fcParamNotes) $- toExpression $ pnNotes fcParamNotes+ (fromList [ addRootAnnToExpression (pnRootAnn cParamNotes) $+ toExpression $ pnNotes cParamNotes ]) (fromList []) , Expression_Prim $ MichelinePrimAp (MichelinePrimitive "storage")- (fromList [toExpression $ fcStoreNotes])+ (fromList [toExpression $ cStoreNotes]) (fromList []) , Expression_Prim $ MichelinePrimAp (MichelinePrimitive "code")- (fromList [toExpression fcCode])+ (fromList [toExpression cCode]) (fromList []) ] where
src/Tezos/Address.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Address in Tezos. module Tezos.Address
src/Tezos/Core.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Core primitive Tezos types. module Tezos.Core@@ -70,7 +74,10 @@ newtype Mutez = Mutez { unMutez :: Word64 } deriving stock (Show, Eq, Ord, Data, Generic)- deriving newtype (Enum, Buildable)+ deriving newtype Enum++instance Buildable Mutez where+ build (Mutez w) = build w <> " μꜩ" instance Bounded Mutez where minBound = Mutez 0
src/Tezos/Crypto.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Cryptographic primitives used in Tezos. -- -- WARNING: some functions may be vulnerable to timing attacks.@@ -31,7 +35,7 @@ module Tezos.Crypto ( -- * Cryptographic primitive types PublicKey (..)- , SecretKey+ , SecretKey (..) -- Currently we need to differentiate secret keys in morley-client , Signature (..) , KeyHashTag (..) , KeyHash (..)
src/Tezos/Crypto/Ed25519.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Ed25519 cryptographic primitives. module Tezos.Crypto.Ed25519
src/Tezos/Crypto/Hash.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Cryptographic primitives related to hashing. module Tezos.Crypto.Hash
src/Tezos/Crypto/P256.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | P256 cryptographic primitives. -- -- This module is mostly a stub, it doesn't implement actual crypto.
src/Tezos/Crypto/Secp256k1.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Secp256k1 cryptographic primitives. module Tezos.Crypto.Secp256k1
src/Tezos/Crypto/Util.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utilities shared by multiple cryptographic primitives. module Tezos.Crypto.Util
src/Util/Aeson.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utilities related to the @aeson@ package. module Util.Aeson
src/Util/Alternative.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utilities related to 'Alternative'. module Util.Alternative
src/Util/ByteString.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Util.ByteString ( HexJSONByteString(..) ) where
src/Util/CLI.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utilities for command line options parsing -- (we use @optparse-applicative@). --
src/Util/Default.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Util.Default ( permute2Def , permute3Def , Default (..)
src/Util/Exception.hs view
@@ -1,5 +1,12 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Util.Exception- ( -- * Common exceptions+ ( -- * General simple helpers+ throwLeft++ , -- * Common exceptions TextException (..) -- * Better printing of exceptions@@ -10,6 +17,14 @@ import Fmt (Buildable(..), pretty) import System.Exit (ExitCode(..)) import qualified Text.Show++-- | If monadic action returns a 'Left' value, it will be+-- thrown. Otherwise the returned value will be returned as is.+throwLeft :: (MonadThrow m, Exception e) => m (Either e a) -> m a+throwLeft =+ (>>= \case+ Left e -> throwM e+ Right x -> return x) ---------------------------------------------------------------------------- -- Common exceptions
src/Util/Fcf.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Util.Fcf ( Over2 , type (<|>)
src/Util/Generic.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Generic-related utils. module Util.Generic ( mkGenericTree
src/Util/IO.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Util.IO ( readFileUtf8 , writeFileUtf8@@ -7,9 +11,11 @@ ) where import Data.Text.IO (hGetContents)-import GHC.IO.Encoding (textEncodingName)-import System.IO (TextEncoding, hGetEncoding, hSetBinaryMode, hSetEncoding, mkTextEncoding, utf8)+import System.IO (TextEncoding, hGetEncoding, hSetBinaryMode, hSetEncoding, utf8) +import Util.IO.GHC (hSetTranslit)++ readFileUtf8 :: FilePath -> IO Text readFileUtf8 name = openFile name ReadMode >>= \h -> hSetEncoding h utf8 >> hGetContents h@@ -29,19 +35,3 @@ (hSetEncoding handle encoding) (\_ -> maybe (hSetBinaryMode handle True) (hSetEncoding handle) mbInitialEncoding) (\_ -> action)---- This function was copied (with slight modifications) from--- <https://gitlab.haskell.org/ghc/ghc/blob/7105fb66a7bacf822f7f23028136f89ff5737d0e/libraries/ghc-boot/GHC/HandleEncoding.hs>------ © 2002 The University Court of the University of Glasgow--- (original license: LicenseRef-BSD-3-Clause-TheUniversityCourtOfTheUniversityOfGlasgow)--- | Change the character encoding of the given Handle to transliterate--- on unsupported characters instead of throwing an exception.-hSetTranslit :: Handle -> IO ()-hSetTranslit h = do- menc <- hGetEncoding h- case fmap textEncodingName menc of- Just name | '/' `notElem` name -> do- enc' <- mkTextEncoding $ name ++ "//TRANSLIT"- hSetEncoding h enc'- _ -> pass
+ src/Util/IO/GHC.hs view
@@ -0,0 +1,25 @@+-- SPDX-FileCopyrightText: 2002 The University Court of the University of Glasgow+--+-- SPDX-License-Identifier: LicenseRef-BSD-3-Clause-GHC++module Util.IO.GHC+ ( hSetTranslit+ ) where++import GHC.IO.Encoding (textEncodingName)+import System.IO (hGetEncoding, hSetEncoding, mkTextEncoding)+++-- This function was copied (with slight modifications) from+-- <https://gitlab.haskell.org/ghc/ghc/blob/7105fb66a7bacf822f7f23028136f89ff5737d0e/libraries/ghc-boot/GHC/HandleEncoding.hs>++-- | Change the character encoding of the given Handle to transliterate+-- on unsupported characters instead of throwing an exception.+hSetTranslit :: Handle -> IO ()+hSetTranslit h = do+ menc <- hGetEncoding h+ case fmap textEncodingName menc of+ Just name | '/' `notElem` name -> do+ enc' <- mkTextEncoding $ name ++ "//TRANSLIT"+ hSetEncoding h enc'+ _ -> pass
src/Util/Instances.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-orphans #-} -- | Missing instances from libraries.
src/Util/Label.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Definition of the Label type and utilities module Util.Label ( -- * Definitions
src/Util/Lens.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-redundant-constraints #-} module Util.Lens
src/Util/Markdown.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | A small Markdown eDSL. module Util.Markdown ( Markdown
src/Util/Named.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-orphans #-} -- | Additional functionality for 'named' package.
src/Util/Peano.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-orphans #-} {-# LANGUAGE UndecidableSuperClasses #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-}
src/Util/Positive.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Definition of 'Positive' type and related utilities. module Util.Positive ( Positive (..)
src/Util/TH.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Util.TH (deriveGADTNFData) where import Language.Haskell.TH
src/Util/Test/Arbitrary.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-orphans #-} module Util.Test.Arbitrary
src/Util/Test/Ingredients.hs view
@@ -1,14 +1,18 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Ingridients that we use in our test suite. module Util.Test.Ingredients ( ourIngredients ) where -import Test.Tasty (defaultIngredients)-import Test.Tasty.Ingredients (Ingredient)+import Test.Tasty.Ingredients (Ingredient, composeReporters)+import Test.Tasty.Ingredients.Basic (consoleTestReporter, listingTests) import Test.Tasty.Runners.AntXML (antXMLRunner) -- | This is the default set of ingredients extended with the -- 'antXMLRunner' which is used to generate xml reports for CI. ourIngredients :: [Ingredient]-ourIngredients = antXMLRunner:defaultIngredients+ourIngredients = [listingTests, antXMLRunner `composeReporters` consoleTestReporter]
src/Util/Text.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Util.Text ( headToLower , surround
src/Util/Type.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-redundant-constraints #-} {-# LANGUAGE QuantifiedConstraints #-}
src/Util/TypeLits.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-redundant-constraints #-} -- | Re-exports 'GHC.TypeLits', modifying it considering our practices.
src/Util/TypeTuple.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Conversions between tuples and list-like types. module Util.TypeTuple ( RecFromTuple (..)
src/Util/TypeTuple/Class.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Util.TypeTuple.Class ( RecFromTuple (..) ) where
src/Util/TypeTuple/Instances.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -Wno-orphans #-} module Util.TypeTuple.Instances () where
src/Util/TypeTuple/TH.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE QuasiQuotes #-} -- | Template haskell generator for 'RecFromTuple', in a separate module
src/Util/Typeable.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE QuantifiedConstraints #-} -- | Utility for 'Typeable'.
test/Main.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Main ( main ) where
test/Test/Analyzer.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for analyzer. module Test.Analyzer
test/Test/EntryPoints.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE DeriveAnyClass #-} -- | Tests for Lorentz compilation which uses 'LorentzCompilationWay'.
test/Test/Ext.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Test.Ext ( test_PRINT_and_TEST_ASSERT , test_STACKTYPE@@ -45,7 +49,7 @@ let check (a, InterpreterState s _) = if corr then isRight a && s == MorleyLogs ["Area is " <> show area'] else isLeft a && s == MorleyLogs ["Sides are " <> show x' <> " x " <> show y']- interpret (T.fcCode contract) epcPrimitive (T.VPair (x', y')) T.VUnit dummyContractEnv `shouldSatisfy` check+ interpret (T.cCode contract) epcPrimitive (T.VPair (x', y')) T.VUnit dummyContractEnv `shouldSatisfy` check test_STACKTYPE :: [TestTree] test_STACKTYPE =
test/Test/Integrational.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for integrational testing machinery. module Test.Integrational ( spec_Chain_id@@ -15,10 +19,10 @@ it "Chain id can be set" $ integrationalTestExpectation $ do let code = DROP `Seq` CHAIN_ID `Seq` NIL `Seq` PAIR- let contract = FullContract- { fcCode = code- , fcParamNotes = starParamNotes @'TUnit- , fcStoreNotes = starNotes+ let contract = Contract+ { cCode = code+ , cParamNotes = starParamNotes @'TUnit+ , cStoreNotes = starNotes } let chainId = mkChainIdUnsafe "aaaa"
test/Test/Interpreter.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Test.Interpreter ( test_basic5 , test_increment@@ -46,12 +50,12 @@ , T.ParameterScope (ToT cp) , T.ForbidOr (ToT cp) )- => T.FullContract (ToT cp) (ToT st)+ => T.Contract (ToT cp) (ToT st) -> cp -> st -> ContractReturn (ToT st) interpretSimple contract cp st =- interpret (T.fcCode contract) epcPrimitive (toVal cp) (toVal st) dummyContractEnv+ interpret (T.cCode contract) epcPrimitive (toVal cp) (toVal st) dummyContractEnv test_basic5 :: IO [TestTree] test_basic5 =
test/Test/Interpreter/Apply.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for the 'APPLY' instruction. module Test.Interpreter.Apply
test/Test/Interpreter/Auction.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing spec to test auction.tz contract. -- -- This spec is an example of using testing capabilities of morley.
test/Test/Interpreter/Balance.hs view
@@ -1,3 +1,6 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ module Test.Interpreter.Balance ( test_balanceIncludesAmount
test/Test/Interpreter/CallSelf.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for the contract that calls self several times. module Test.Interpreter.CallSelf@@ -56,7 +60,7 @@ type Storage = 'TNat testImpl ::- (U.Contract, FullContract Parameter Storage)+ (U.Contract, Contract Parameter Storage) -> [TestTree] testImpl (uSelfCaller, selfCaller) = [ testCase ("With parameter 1 single execution consumes " <>
test/Test/Interpreter/ComparableSet.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing spec to test compare.tz contract. module Test.Interpreter.ComparableSet ( test_comparable_set
test/Test/Interpreter/Compare.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing spec to test compare.tz contract. module Test.Interpreter.Compare ( test_compare
test/Test/Interpreter/ComparePairs.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing spec to test compare.tz contract. module Test.Interpreter.ComparePairs ( test_compare_pairs
test/Test/Interpreter/Conditionals.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing spec to test conditionals.tz contract. module Test.Interpreter.Conditionals ( test_conditionals
test/Test/Interpreter/ContractOp.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Module, containing spec to test contract_op.tz contract. module Test.Interpreter.ContractOp ( test_contract_op@@ -11,7 +15,7 @@ import Michelson.Interpret (ContractEnv(..), ContractReturn) import Michelson.Test (contractProp, dummyContractEnv, failedProp, testTreesWithTypedContract)-import Michelson.Typed (FullContract, ToT, fromVal)+import Michelson.Typed (Contract, ToT, fromVal) import Michelson.Untyped (ParameterType(..), T(..), Type(..), noAnn) import Tezos.Address @@ -60,7 +64,7 @@ validate _ _ = failedProp "Unexpected result of script execution" contractProp'- :: Bool -> [(ContractHash, ParameterType)] -> FullContract (ToT Address) (ToT Bool)+ :: Bool -> [(ContractHash, ParameterType)] -> Contract (ToT Address) (ToT Bool) -> Property contractProp' res ctrs contract = contractProp
test/Test/Interpreter/EnvironmentSpec.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for the 'environment.tz' contract module Test.Interpreter.EnvironmentSpec@@ -58,8 +62,8 @@ , fAmount fixture < unsafeMkMutez 15 ] -testImpl ::- (U.Contract, T.FullContract 'TAddress 'TUnit)+testImpl+ :: (U.Contract, T.Contract 'TAddress 'TUnit) -> TestTree testImpl (uEnvironment, _environment) = do testProperty description $
test/Test/Interpreter/StackRef.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Interpreter tests involving 'StackRef'. module Test.Interpreter.StackRef@@ -15,16 +19,16 @@ test_mkStackRef :: TestTree test_mkStackRef = testCase "does not segfault" $- contractProp fullContract (flip shouldSatisfy isRight . fst)+ contractProp contract (flip shouldSatisfy isRight . fst) dummyContractEnv () () where stackRef = PrintComment . one . Right $ mkStackRef @1 - fullContract :: FullContract 'TUnit 'TUnit- fullContract = FullContract- { fcCode = contractCode- , fcStoreNotes = starNotes- , fcParamNotes = starParamNotes+ contract :: Contract 'TUnit 'TUnit+ contract = Contract+ { cCode = contractCode+ , cStoreNotes = starNotes+ , cParamNotes = starParamNotes } contractCode :: ContractCode 'TUnit 'TUnit
test/Test/Interpreter/StringCaller.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for the 'stringCaller.tz' contract and its interaction with -- the 'failOrStoreAndTransfer.tz' contract. Both of them have comments describing -- their behavior.@@ -32,8 +36,8 @@ pure $ testImpl stringCaller failOrStoreAndTransfer testImpl ::- (U.Contract, T.FullContract 'TString 'TAddress)- -> (U.Contract, T.FullContract 'TString 'TString)+ (U.Contract, T.Contract 'TString 'TAddress)+ -> (U.Contract, T.Contract 'TString 'TString) -> [TestTree] testImpl (uStringCaller, _stringCaller) (uFailOrStore, _failOrStoreAndTransfer) = let scenario = integrationalScenario uStringCaller uFailOrStore
test/Test/Macro.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Test.Macro ( unit_PAPAIR , unit_UNPAIR
test/Test/Michelson/Runtime.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for Michelson.Runtime. module Test.Michelson.Runtime
test/Test/Michelson/Text.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests on 'MText'. module Test.Michelson.Text ( test_Roundtrip
test/Test/Michelson/Typed/Util.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for 'Michelson.Typed.Util'. module Test.Michelson.Typed.Util
test/Test/OpSize.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for operation size evaluation. module Test.OpSize
test/Test/Optimizer.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for optimizer. module Test.Optimizer
test/Test/Parser.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Test.Parser ( unit_Parse_contracts , unit_Parse_bad_contracts@@ -22,7 +26,7 @@ import qualified Data.List.NonEmpty as NE import Test.Hspec.Expectations (Expectation, expectationFailure, shouldBe, shouldSatisfy) import Text.Megaparsec (parse)-import Text.Megaparsec.Error (ErrorFancy(ErrorCustom), ParseError(FancyError), bundleErrors)+import Text.Megaparsec.Error (ErrorFancy(ErrorCustom), ErrorItem(Tokens), ParseError(FancyError, TrivialError), bundleErrors) import Michelson.ErrorPos (srcPos) import Michelson.Macro as Mo@@ -96,8 +100,8 @@ P.parseNoEnv PA.noteV "" "@" `shouldSatisfy` isRight P.parseNoEnv PA.noteV "" "@_" `shouldSatisfy` isRight P.parseNoEnv PA.noteV "" "@a." `shouldSatisfy` isRight+ P.parseNoEnv PA.noteV "" "@7a" `shouldSatisfy` isRight P.parseNoEnv PA.noteV "" "@.a" `shouldSatisfy` isLeft- P.parseNoEnv PA.noteV "" "@7a" `shouldSatisfy` isLeft P.parseNoEnv PA.noteV "" "@@@" `shouldSatisfy` isLeft P.parseNoEnv PA.noteV "" "@a b" `shouldSatisfy` isLeft P.parseNoEnv PA.noteV "" "@a\\" `shouldSatisfy` isLeft@@ -127,6 +131,8 @@ Prelude.Right [Mo.Prim (PAIR noAnn noAnn noAnn noAnn) (srcPos 0 1)] P.parseNoEnv P.codeEntry "" "{PAIR %a;}" `shouldBe` Prelude.Right [Mac (PAPAIR (P (F (noAnn, Mo.ann "a")) (F (noAnn,noAnn))) noAnn noAnn) (srcPos 0 1)]+ P.parseNoEnv P.codeEntry "" "{PAIR %0;}" `shouldBe`+ Prelude.Right [Mac (PAPAIR (P (F (noAnn, Mo.ann "0")) (F (noAnn,noAnn))) noAnn noAnn) (srcPos 0 1)] P.parseNoEnv P.codeEntry "" "{PAPAIR;}" `shouldBe` Prelude.Right [flip Mac (srcPos 0 1) $@@ -250,6 +256,10 @@ (WrongAccessArgs 2 (PositiveUnsafe 2)) handleCustomError "{ SET 2 2 }" P.codeEntry (WrongSetArgs 2 (PositiveUnsafe 2))+ handleTrivialError "type Store = (BigMap Address Nat, Nat); \ntest :: '[option int] -> '[int]\n= { IF_SOME { nop; } { PUSH int 3 }; };"+ (P.letInner P.parsedOp)+ (Tokens ('n' :| ""))+ where handleCustomError :: HasCallStack => Text -> Parser a -> CustomParserException -> Expectation@@ -262,6 +272,19 @@ _ -> expectationFailure $ "expecting single ErrorCustom, but got " <>+ errorBundlePretty bundle++ handleTrivialError+ :: HasCallStack => Text -> Parser a -> ErrorItem Char -> Expectation+ handleTrivialError text parser errorItem =+ case P.parseNoEnv parser "" text of+ Right _ -> expectationFailure "expecting parser to fail"+ Left bundle -> case toList $ bundleErrors bundle of+ [TrivialError _ e _] ->+ e `shouldBe` (Just errorItem)+ _ ->+ expectationFailure $+ "expecting single TrivialError, but got " <> errorBundlePretty bundle unit_letType :: Expectation
test/Test/Preprocess.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for preprocessing. module Test.Preprocess
test/Test/Printer/Michelson.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE DeriveAnyClass #-} module Test.Printer.Michelson
test/Test/Serialization/Aeson.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Test.Serialization.Aeson ( test_Roundtrip ) where
test/Test/Serialization/Michelson.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE OverloadedLists #-} module Test.Serialization.Michelson
test/Test/Tezos/Address.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for 'Tezos.Address'. module Test.Tezos.Address
test/Test/Tezos/Core.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Test.Tezos.Core ( test_ParseTimestamp , test_TimestampQuote
test/Test/Tezos/Crypto.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for 'Tezos.Crypto'. module Test.Tezos.Crypto
test/Test/Tezos/Crypto/Hash.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for 'Tezos.Crypto.Hash'. module Test.Tezos.Crypto.Hash
test/Test/Typeable.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests on 'Util.Typeable'. module Test.Typeable ( test_castIgnoringPhantom
test/Test/Typecheck.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# LANGUAGE ViewPatterns #-} module Test.Typecheck@@ -56,24 +60,56 @@ test_srcPosition = [ testProperty "Verify instruction position in a typecheck error" $ do checkIllFile (inContractsDir "ill-typed/basic3.tz") $ \case- TCFailedOnInstr (Un.CONS _) _ (IsSrcPos 4 6) _ (Just (AnnError _)) -> True+ TCFailedOnInstr (Un.CONS _) _ (IsSrcPos 8 6) _ (Just (AnnError _)) -> True _ -> False checkIllFile (inContractsDir "ill-typed/testassert_invalid_stack3.mtz") $ \case- TCFailedOnInstr Un.DROP _ (IsSrcPos 6 17) _ Nothing -> True+ TCFailedOnInstr Un.DROP _ (IsSrcPos 10 17) _ (Just NotEnoughItemsOnStack) -> True _ -> False checkIllFile (inContractsDir "ill-typed/testassert_invalid_stack2.mtz") $ \case- TCExtError _ (IsSrcPos 5 2) (TestAssertError _) -> True+ TCExtError _ (IsSrcPos 9 2) (TestAssertError _) -> True _ -> False checkIllFile (inContractsDir "ill-typed/macro_in_let_fail.mtz") $ \case- TCFailedOnInstr (Un.COMPARE _) _ (InstrCallStack [LetName "cmpLet"] (SrcPos (Pos 3) (Pos 6))) _+ TCFailedOnInstr (Un.COMPARE _) _ (InstrCallStack [LetName "cmpLet"] (SrcPos (Pos 7) (Pos 6))) _ (Just (TypeEqError _ _)) -> True _ -> False checkIllFile (inContractsDir "ill-typed/compare_annotation_mismatch.tz") $ \case TCFailedOnInstr (Un.COMPARE _) _ _ _ (Just (AnnError _)) -> True _ -> False++ checkIllFile (inContractsDir "ill-typed/annotation_mismatch_map_update.tz") $ \case+ TCFailedOnInstr (Un.UPDATE _) (SomeHST (_ ::& _ ::& (T.NTMap{}, _, _) ::& SNil)) _ _ (Just (AnnError _)) -> True+ _ -> False++ checkIllFile (inContractsDir "ill-typed/annotation_mismatch_map_get.tz") $ \case+ TCFailedOnInstr (Un.GET _) (SomeHST (_ ::& (T.NTMap{}, _, _) ::& SNil)) _ _ (Just (AnnError _)) -> True+ _ -> False++ checkIllFile (inContractsDir "ill-typed/annotation_mismatch_map_mem.tz") $ \case+ TCFailedOnInstr (Un.MEM _) (SomeHST (_ ::& (T.NTMap{}, _, _) ::& SNil)) _ _ (Just (AnnError _)) -> True+ _ -> False++ checkIllFile (inContractsDir "ill-typed/annotation_mismatch_big_map_update.tz") $ \case+ TCFailedOnInstr (Un.UPDATE _) (SomeHST (_ ::& _ ::& (T.NTBigMap{}, _, _) ::& SNil)) _ _ (Just (AnnError _)) -> True+ _ -> False++ checkIllFile (inContractsDir "ill-typed/annotation_mismatch_big_map_get.tz") $ \case+ TCFailedOnInstr (Un.GET _) (SomeHST (_ ::& (T.NTBigMap{}, _, _) ::& SNil)) _ _ (Just (AnnError _)) -> True+ _ -> False++ checkIllFile (inContractsDir "ill-typed/annotation_mismatch_big_map_mem.tz") $ \case+ TCFailedOnInstr (Un.MEM _) (SomeHST (_ ::& (T.NTBigMap{}, _, _) ::& SNil)) _ _ (Just (AnnError _)) -> True+ _ -> False++ checkIllFile (inContractsDir "ill-typed/annotation_mismatch_set_update.tz") $ \case+ TCFailedOnInstr (Un.UPDATE _) (SomeHST (_ ::& _ ::& (T.NTSet{}, _, _) ::& SNil)) _ _ (Just (AnnError _)) -> True+ _ -> False++ checkIllFile (inContractsDir "ill-typed/annotation_mismatch_set_mem.tz") $ \case+ TCFailedOnInstr (Un.MEM _) (SomeHST (_ ::& (T.NTSet{}, _, _) ::& SNil)) _ _ (Just (AnnError _)) -> True+ _ -> False ] where unexpected f e =@@ -107,7 +143,7 @@ unit_Unreachable_code :: Assertion unit_Unreachable_code = do let file = inContractsDir "ill-typed/fail_before_nop.tz"- let ics = InstrCallStack [] (srcPos 3 13)+ let ics = InstrCallStack [] (srcPos 7 13) econtract <- readContract @'T.TUnit @'T.TUnit file <$> readFileUtf8 file econtract @?= Left (ICETypeCheck $ TCUnreachableCode ics (one $ Un.WithSrcEx ics $ Un.SeqEx []))
test/Test/Untyped/Instr.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Tests for 'Michelson.Untyped.Instr'. module Test.Untyped.Instr
test/Test/Util/Contracts.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Utility functions to read sample contracts (for testing). module Test.Util.Contracts
test/Test/Util/HUnit.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Helpers for HUnit. module Test.Util.HUnit
test/Test/Util/Parser.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ module Test.Util.Parser ( shouldParse ) where
test/Test/Util/QuickCheck.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {- Copyright (c) 2017 IOHK
test/Test/ValConversion.hs view
@@ -1,3 +1,7 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ -- | Testing of toVal / fromVal conversions module Test.ValConversion
test/Tree.hs view
@@ -1,1 +1,5 @@+-- SPDX-FileCopyrightText: 2020 Tocqueville Group+--+-- SPDX-License-Identifier: LicenseRef-MIT-TQ+ {-# OPTIONS_GHC -F -pgmF tasty-discover -optF --tree-display -optF --generated-module -optF Tree #-}