├── .cspell.yml ├── .envrc ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── coverage.yml │ ├── dependabot-reviewer.yml │ └── lint.yml ├── .gitignore ├── .prettierrc.yml ├── .rustfmt.toml ├── .taplo.toml ├── .vscode └── settings.json ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── examples └── library.rs ├── flake.lock ├── flake.nix ├── justfile ├── src ├── implementation │ ├── codegen.rs │ ├── doc.rs │ ├── ensures.rs │ ├── invariant.rs │ ├── mod.rs │ ├── parse.rs │ ├── requires.rs │ └── traits.rs └── lib.rs └── tests ├── functions.rs ├── implication.rs ├── issues.rs ├── methods.rs ├── mirai_assertion_mocks └── mod.rs ├── old.rs ├── ranged_int.rs └── traits.rs /.cspell.yml: -------------------------------------------------------------------------------- 1 | version: "0.2" 2 | words: 3 | - clippy 4 | - codegen 5 | - direnv 6 | - elems 7 | - msrv 8 | - nextest 9 | - nixos 10 | - nixpkgs 11 | - nonminimal 12 | - pkgs 13 | - punct 14 | - RUSTDOCFLAGS 15 | - taplo 16 | - toks 17 | -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | use flake 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [robjtede] 4 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | - package-ecosystem: cargo 8 | directory: / 9 | schedule: 10 | interval: weekly 11 | versioning-strategy: lockfile-only 12 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | branches: [main] 6 | merge_group: 7 | types: [checks_requested] 8 | push: 9 | branches: [main] 10 | 11 | permissions: 12 | contents: read 13 | 14 | concurrency: 15 | group: ${{ github.workflow }}-${{ github.ref }} 16 | cancel-in-progress: true 17 | 18 | jobs: 19 | read_msrv: 20 | name: Read MSRV 21 | uses: actions-rust-lang/msrv/.github/workflows/msrv.yml@main 22 | 23 | test: 24 | needs: read_msrv 25 | 26 | strategy: 27 | fail-fast: false 28 | matrix: 29 | toolchain: 30 | - { name: msrv, version: "${{ needs.read_msrv.outputs.msrv }}" } 31 | - { name: stable, version: stable } 32 | 33 | runs-on: ubuntu-latest 34 | 35 | name: Test / ${{ matrix.toolchain.name }} 36 | 37 | steps: 38 | - uses: actions/checkout@v4 39 | 40 | - name: Install Nix 41 | uses: cachix/install-nix-action@v31 42 | 43 | - name: Install Rust (${{ matrix.toolchain.name }}) 44 | uses: actions-rust-lang/setup-rust-toolchain@v1.12.0 45 | with: 46 | toolchain: ${{ matrix.toolchain.version }} 47 | 48 | - name: Install cargo-nextest 49 | uses: taiki-e/install-action@v2.50.7 50 | with: 51 | tool: cargo-nextest 52 | 53 | - name: Enter Nix devshell 54 | uses: nicknovitski/nix-develop@v1.2.1 55 | 56 | - name: Downgrade for MSRV 57 | if: matrix.toolchain.name == 'msrv' 58 | run: | 59 | rm -f Cargo.lock 60 | just downgrade-for-msrv 61 | 62 | - name: Test 63 | run: just test-no-coverage 64 | -------------------------------------------------------------------------------- /.github/workflows/coverage.yml: -------------------------------------------------------------------------------- 1 | name: Coverage 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | 7 | permissions: 8 | contents: read 9 | 10 | concurrency: 11 | group: ${{ github.workflow }}-${{ github.ref }} 12 | cancel-in-progress: true 13 | 14 | jobs: 15 | coverage: 16 | runs-on: ubuntu-latest 17 | name: Coverage 18 | steps: 19 | - uses: actions/checkout@v4 20 | 21 | - name: Install Nix 22 | uses: cachix/install-nix-action@v31 23 | 24 | - name: Install Rust 25 | uses: actions-rust-lang/setup-rust-toolchain@v1.5.0 26 | with: 27 | components: llvm-tools-preview 28 | 29 | - name: Enter Nix devshell 30 | uses: nicknovitski/nix-develop@v1.2.1 31 | 32 | - name: Install cargo-llvm-cov 33 | uses: taiki-e/install-action@v2.50.7 34 | with: 35 | tool: cargo-llvm-cov 36 | 37 | - name: Generate code coverage 38 | run: just test-coverage-codecov 39 | 40 | - name: Upload coverage to Codecov 41 | uses: codecov/codecov-action@v5.4.2 42 | with: 43 | files: codecov.json 44 | fail_ci_if_error: true 45 | env: 46 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 47 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-reviewer.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot Reviewer 2 | 3 | on: pull_request_target 4 | 5 | permissions: 6 | pull-requests: write 7 | contents: write 8 | 9 | jobs: 10 | review-dependabot-pr: 11 | name: Approve PR 12 | runs-on: ubuntu-latest 13 | if: ${{ github.actor == 'dependabot[bot]' }} 14 | env: 15 | PR_URL: ${{ github.event.pull_request.html_url }} 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 17 | steps: 18 | - name: Fetch Dependabot metadata 19 | id: dependabot-metadata 20 | uses: dependabot/fetch-metadata@v2.3.0 21 | 22 | - name: Enable auto-merge for Dependabot PRs 23 | run: gh pr merge --auto --squash "$PR_URL" 24 | 25 | - name: Approve patch and minor updates 26 | if: ${{ steps.dependabot-metadata.outputs.update-type == 'version-update:semver-patch'|| steps.dependabot-metadata.outputs.update-type == 'version-update:semver-minor'}} 27 | run: | 28 | gh pr review "$PR_URL" --approve --body "I'm **approving** this pull request because **it only includes patch or minor updates**." 29 | 30 | - name: Approve major updates of dev dependencies 31 | if: ${{ steps.dependabot-metadata.outputs.update-type == 'version-update:semver-major' && steps.dependabot-metadata.outputs.dependency-type == 'direct:development'}} 32 | run: | 33 | gh pr review "$PR_URL" --approve --body "I'm **approving** this pull request because **it only includes major updates of dev dependencies**." 34 | 35 | - name: Comment on major updates of normal dependencies 36 | if: ${{ steps.dependabot-metadata.outputs.update-type == 'version-update:semver-major' && steps.dependabot-metadata.outputs.dependency-type == 'direct:production'}} 37 | run: | 38 | gh pr comment "$PR_URL" --body "I'm **not approving** this PR because **it includes major updates of normal dependencies**." 39 | gh pr edit "$PR_URL" --add-label "requires-manual-qa" 40 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | pull_request: 5 | types: [opened, synchronize, reopened] 6 | push: 7 | branches: [main] 8 | 9 | permissions: 10 | contents: read 11 | 12 | concurrency: 13 | group: ${{ github.workflow }}-${{ github.ref }} 14 | cancel-in-progress: true 15 | 16 | jobs: 17 | fmt: 18 | name: Rustfmt 19 | runs-on: ubuntu-latest 20 | 21 | steps: 22 | - uses: actions/checkout@v4 23 | 24 | - name: Install Rust 25 | uses: actions-rust-lang/setup-rust-toolchain@v1 26 | with: 27 | components: rustfmt 28 | 29 | - name: Format Check 30 | uses: actions-rust-lang/rustfmt@v1 31 | 32 | clippy: 33 | name: Clippy 34 | runs-on: ubuntu-latest 35 | permissions: 36 | contents: read 37 | checks: write 38 | 39 | steps: 40 | - uses: actions/checkout@v4 41 | 42 | - name: Install Rust 43 | uses: actions-rust-lang/setup-rust-toolchain@v1 44 | with: 45 | components: clippy 46 | 47 | - name: Clippy Check 48 | uses: giraffate/clippy-action@v1 49 | with: 50 | clippy_flags: --workspace --all-targets --all-features 51 | reporter: github-pr-check 52 | github_token: ${{ secrets.GITHUB_TOKEN }} 53 | 54 | docs: 55 | name: Docs 56 | runs-on: ubuntu-latest 57 | steps: 58 | - uses: actions/checkout@v4 59 | - name: Install Rust 60 | uses: actions-rust-lang/setup-rust-toolchain@v1.5.0 61 | with: 62 | components: rust-docs 63 | 64 | - name: Validate Intra-doc Links 65 | env: 66 | RUSTDOCFLAGS: -D warnings 67 | run: cargo doc --workspace --no-deps --all-features 68 | 69 | audit: 70 | name: Audit 71 | runs-on: ubuntu-latest 72 | 73 | steps: 74 | - uses: actions/checkout@v4 75 | 76 | - name: Install Rust 77 | uses: actions-rust-lang/setup-rust-toolchain@v1 78 | 79 | - name: Install cargo-deny 80 | uses: taiki-e/install-action@v2.50.7 81 | with: 82 | tool: cargo-deny 83 | 84 | - name: Audit check 85 | run: cargo deny --all-features check advisories 86 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # rust 2 | /target/ 3 | **/*.rs.bk 4 | 5 | # direnv 6 | /.toolchain/ 7 | /.direnv/ 8 | 9 | # code coverage 10 | /codecov.json 11 | /lcov.info 12 | -------------------------------------------------------------------------------- /.prettierrc.yml: -------------------------------------------------------------------------------- 1 | overrides: 2 | - files: "*.md" 3 | options: 4 | printWidth: 9999 5 | proseWrap: never 6 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | group_imports = "StdExternalCrate" 2 | imports_granularity = "Crate" 3 | use_field_init_shorthand = true 4 | -------------------------------------------------------------------------------- /.taplo.toml: -------------------------------------------------------------------------------- 1 | exclude = ["target/*"] 2 | include = ["**/*.toml"] 3 | 4 | [formatting] 5 | column_width = 110 6 | 7 | [[rule]] 8 | include = ["**/Cargo.toml"] 9 | keys = [ 10 | "dependencies", 11 | "*-dependencies", 12 | "workspace.dependencies", 13 | "workspace.*-dependencies", 14 | "target.*.dependencies", 15 | "target.*.*-dependencies", 16 | ] 17 | formatting.reorder_keys = true 18 | 19 | [[rule]] 20 | include = ["**/Cargo.toml"] 21 | keys = [ 22 | "dependencies.*", 23 | "*-dependencies.*", 24 | "workspace.dependencies.*", 25 | "workspace.*-dependencies.*", 26 | "target.*.dependencies", 27 | "target.*.*-dependencies", 28 | ] 29 | formatting.reorder_keys = false 30 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "rust-analyzer.cargo.features": [] 3 | } 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## Unreleased 8 | 9 | ## 0.6.6 10 | 11 | - Update `syn` requirement to `2`. 12 | 13 | ## 0.6.5 14 | 15 | - Improve support for async functions and mutable borrows in contracts. 16 | 17 | ## 0.6.4 18 | 19 | - Add effective contract type to invariant violation messages. 20 | 21 | ## 0.6.3 22 | 23 | ### Fixed 24 | 25 | - improved hygiene around `self` parameters 26 | - fix contract messages containing `{}` emitting warnings as they are interpreted as format strings 27 | 28 | ## 0.6.2 29 | 30 | ### Changed 31 | 32 | - better handling of mutable borrows and lifetime relationships for functions with contracts 33 | 34 | ## 0.6.1 35 | 36 | ### Added 37 | 38 | - support for `impl Trait` return types 39 | 40 | ## 0.6.0 41 | 42 | ### Changed 43 | 44 | - `pre` is now `requires` 45 | - `post` is now `ensures` 46 | 47 | ## 0.5.2 48 | 49 | ### Fixed 50 | 51 | - Unused braces in function body generated code are removed 52 | 53 | ## 0.5.1 54 | 55 | ### Changed 56 | 57 | - Trait methods now handle attributes better. 58 | 59 | ## 0.5.0 60 | 61 | ### Changed 62 | 63 | - Implication operator is now `->`. 64 | 65 | ## 0.4.0 66 | 67 | ### Added 68 | 69 | - Added support for MIRAI assertions 70 | - Added implication operator 71 | 72 | ## 0.3.0 73 | 74 | ### Added 75 | 76 | - Pseudo-function `old(expr)` which in a post-condition evaluates the expression before function execution. 77 | - Automatic generation of documentation containing all contracts. 78 | 79 | ## 0.2.2 80 | 81 | ### Fixed 82 | 83 | - Errors inside functions/methods are now properly reported with the correct source location. 84 | 85 | ### Changed 86 | 87 | - internal handling of contracts is now done in a single proc-macro pass instead of one for each contract. 88 | 89 | ## 0.2.1 90 | 91 | ### Fixed 92 | 93 | - Functions/methods with explicit return statements no longer skip `post` conditions 94 | 95 | ## 0.2.0 96 | 97 | ### Added 98 | 99 | - `contract_trait` attribute to make all implementors of a trait respect contracts. 100 | 101 | ## 0.1.1 102 | 103 | ### Added 104 | 105 | - Feature flags to override contract behavior. 106 | - `disable_contracts` ignores all checks 107 | - `override_debug` only checks contracts in debug configurations. 108 | - `override_log` only prints using the `log`-crate interface. 109 | 110 | ## 0.1.0 111 | 112 | ### Added 113 | 114 | - attributes `pre`/`post`/`invariant` and `debug_` versions of each. 115 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "contracts" 7 | version = "0.6.6" 8 | dependencies = [ 9 | "proc-macro2", 10 | "quote", 11 | "syn", 12 | ] 13 | 14 | [[package]] 15 | name = "proc-macro2" 16 | version = "1.0.95" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" 19 | dependencies = [ 20 | "unicode-ident", 21 | ] 22 | 23 | [[package]] 24 | name = "quote" 25 | version = "1.0.40" 26 | source = "registry+https://github.com/rust-lang/crates.io-index" 27 | checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" 28 | dependencies = [ 29 | "proc-macro2", 30 | ] 31 | 32 | [[package]] 33 | name = "syn" 34 | version = "2.0.101" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" 37 | dependencies = [ 38 | "proc-macro2", 39 | "quote", 40 | "unicode-ident", 41 | ] 42 | 43 | [[package]] 44 | name = "unicode-ident" 45 | version = "1.0.18" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" 48 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "contracts" 3 | version = "0.6.6" 4 | description = "Design-by-contract attributes" 5 | authors = ["karroffel "] 6 | categories = ["development-tools", "development-tools::procedural-macro-helpers"] 7 | keywords = ["design-by-contract", "precondition", "postcondition", "invariant", "verification"] 8 | repository = "https://github.com/x52dev/contracts" 9 | license = "MPL-2.0" 10 | edition = "2018" 11 | rust-version = "1.65" 12 | 13 | [lib] 14 | name = "contracts" 15 | path = "src/lib.rs" 16 | proc-macro = true 17 | 18 | [features] 19 | disable_contracts = [] 20 | override_debug = [] 21 | override_log = [] 22 | mirai_assertions = [] 23 | 24 | [dependencies] 25 | proc-macro2 = "1" 26 | quote = "1" 27 | syn = { version = "2", features = ["extra-traits", "full", "visit", "visit-mut"] } 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `contracts` 2 | 3 | > _Design By Contract_ for Rust 4 | 5 | 6 | 7 | [![crates.io](https://img.shields.io/crates/v/contracts?label=latest)](https://crates.io/crates/contracts) 8 | [![Documentation](https://docs.rs/contracts/badge.svg?version=0.6.6)](https://docs.rs/contracts/0.6.6) 9 | [![dependency status](https://deps.rs/crate/contracts/0.6.6/status.svg)](https://deps.rs/crate/contracts/0.6.6) 10 | ![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/contracts.svg) 11 |
12 | [![CI](https://github.com/x52dev/contracts/actions/workflows/ci.yml/badge.svg)](https://github.com/x52dev/contracts-rs/actions/workflows/ci.yml) 13 | [![codecov](https://codecov.io/gh/x52dev/contracts/graph/badge.svg?token=OpYe6I7dj5)](https://codecov.io/gh/x52dev/contracts-rs) 14 | ![Version](https://img.shields.io/crates/msrv/contracts.svg) 15 | [![Download](https://img.shields.io/crates/d/contracts.svg)](https://crates.io/crates/contracts) 16 | 17 | 18 | 19 | Annotate functions and methods with "contracts", using _invariants_, _pre-conditions_ and _post-conditions_. 20 | 21 | [Design by contract][dbc] is a popular method to augment code with formal interface specifications. These specifications are used to increase the correctness of the code by checking them as assertions at runtime. 22 | 23 | [dbc]: https://en.wikipedia.org/wiki/Design_by_contract 24 | 25 | ```rust 26 | pub struct Library { 27 | available: HashSet, 28 | lent: HashSet, 29 | } 30 | 31 | impl Library { 32 | fn book_exists(&self, book_id: &str) -> bool { 33 | self.available.contains(book_id) 34 | || self.lent.contains(book_id) 35 | } 36 | 37 | #[debug_requires(!self.book_exists(book_id), "Book IDs are unique")] 38 | #[debug_ensures(self.available.contains(book_id), "Book now available")] 39 | #[ensures(self.available.len() == old(self.available.len()) + 1)] 40 | #[ensures(self.lent.len() == old(self.lent.len()), "No lent change")] 41 | pub fn add_book(&mut self, book_id: &str) { 42 | self.available.insert(book_id.to_string()); 43 | } 44 | 45 | #[debug_requires(self.book_exists(book_id))] 46 | #[ensures(ret -> self.available.len() == old(self.available.len()) - 1)] 47 | #[ensures(ret -> self.lent.len() == old(self.lent.len()) + 1)] 48 | #[debug_ensures(ret -> self.lent.contains(book_id))] 49 | #[debug_ensures(!ret -> self.lent.contains(book_id), "Book already lent")] 50 | pub fn lend(&mut self, book_id: &str) -> bool { 51 | if self.available.contains(book_id) { 52 | self.available.remove(book_id); 53 | self.lent.insert(book_id.to_string()); 54 | true 55 | } else { 56 | false 57 | } 58 | } 59 | 60 | #[debug_requires(self.lent.contains(book_id), "Can't return a non-lent book")] 61 | #[ensures(self.lent.len() == old(self.lent.len()) - 1)] 62 | #[ensures(self.available.len() == old(self.available.len()) + 1)] 63 | #[debug_ensures(!self.lent.contains(book_id))] 64 | #[debug_ensures(self.available.contains(book_id), "Book available again")] 65 | pub fn return_book(&mut self, book_id: &str) { 66 | self.lent.remove(book_id); 67 | self.available.insert(book_id.to_string()); 68 | } 69 | } 70 | ``` 71 | 72 | ## Attributes 73 | 74 | This crate exposes the `requires`, `ensures` and `invariant` attributes. 75 | 76 | - `requires` are checked before a function/method is executed. 77 | - `ensures` are checked after a function/method ran to completion 78 | - `invariant`s are checked both before _and_ after a function/method ran. 79 | 80 | Additionally, all those attributes have versions with different "modes". See [the Modes section](#Modes) below. 81 | 82 | For `trait`s and trait `impl`s the `contract_trait` attribute can be used. 83 | 84 | More specific information can be found in the crate documentation. 85 | 86 | ## Pseudo-functions and operators 87 | 88 | ### `old()` function 89 | 90 | One unique feature that this crate provides is an `old()` pseudo-function which allows to perform checks using a value of a parameter before the function call happened. This is only available in `ensures` attributes. 91 | 92 | ```rust 93 | #[ensures(*x == old(*x) + 1, "after the call `x` was incremented")] 94 | fn incr(x: &mut usize) { 95 | *x += 1; 96 | } 97 | ``` 98 | 99 | ### `->` operator 100 | 101 | For more complex functions it can be useful to express behaviour using logical implication. Because Rust does not feature an operator for implication, this crate adds this operator for use in attributes. 102 | 103 | ```rust 104 | #[ensures(person_name.is_some() -> ret.contains(person_name.unwrap()))] 105 | fn geeting(person_name: Option<&str>) -> String { 106 | let mut s = String::from("Hello"); 107 | if let Some(name) = person_name { 108 | s.push(' '); 109 | s.push_str(name); 110 | } 111 | s.push('!'); 112 | s 113 | } 114 | ``` 115 | 116 | This operator is right-associative. 117 | 118 | **Note**: Because of the design of `syn`, it is tricky to add custom operators to be parsed, so this crate performs a rewrite of the `TokenStream` instead. The rewrite works by separating the expression into a part that's left of the `->` operator and the rest on the right side. This means that `if a -> b { c } else { d }` will not generate the expected code. Explicit grouping using parenthesis or curly-brackets can be used to avoid this. 119 | 120 | ## Modes 121 | 122 | All the attributes (requires, ensures, invariant) have `debug_*` and `test_*` versions. 123 | 124 | - `debug_requires`/`debug_ensures`/`debug_invariant` use `debug_assert!` internally rather than `assert!` 125 | - `test_requires`/`test_ensures`/`test_invariant` guard the `assert!` with an `if cfg!(test)`. This should mostly be used for stating equivalence to "slow but obviously correct" alternative implementations or checks. 126 | 127 | For example, a merge-sort implementation might look like this 128 | 129 | ```rust 130 | #[test_ensures(is_sorted(input))] 131 | fn merge_sort(input: &mut [T]) { 132 | // ... 133 | } 134 | ``` 135 | 136 | ## Set-up 137 | 138 | To install the latest version, add `contracts` to the dependency section of the `Cargo.toml` file. 139 | 140 | ```shell 141 | $ cargo add contracts 142 | ``` 143 | 144 | To then bring all procedural macros into scope, you can add `use contracts::*;` in all files you plan to use the contract attributes. 145 | 146 | ## Configuration 147 | 148 | This crate exposes a number of feature flags to configure the assertion behavior. 149 | 150 | - `disable_contracts` - disables all checks and assertions. 151 | - `override_debug` - changes all contracts (except `test_` ones) into `debug_*` versions 152 | - `override_log` - changes all contracts (except `test_` ones) into a `log::error!()` call if the condition is violated. No abortion happens. 153 | - `mirai_assertions` - instead of regular assert! style macros, emit macros used by the [MIRAI] static analyzer. For more documentation of this usage, head to the [MIRAI] repo. 154 | 155 | [MIRAI]: https://github.com/endorlabs/MIRAI 156 | 157 | ## TODOs 158 | 159 | - implement more contracts for traits. 160 | - add a static analyzer à la SPARK for whole-projects using the contracts to make static assertions. 161 | -------------------------------------------------------------------------------- /examples/library.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use std::collections::HashSet; 6 | 7 | use contracts::*; 8 | 9 | pub struct Library { 10 | available: HashSet, 11 | lent: HashSet, 12 | } 13 | 14 | impl Library { 15 | fn book_exists(&self, book_id: &str) -> bool { 16 | self.available.contains(book_id) || self.lent.contains(book_id) 17 | } 18 | 19 | #[debug_requires(!self.book_exists(book_id), "Book IDs are unique")] 20 | #[debug_ensures(self.available.contains(book_id), "Book now available")] 21 | #[ensures(self.available.len() == old(self.available.len()) + 1)] 22 | #[ensures(self.lent.len() == old(self.lent.len()), "No lent change")] 23 | pub fn add_book(&mut self, book_id: &str) { 24 | self.available.insert(book_id.to_string()); 25 | } 26 | 27 | #[debug_requires(self.book_exists(book_id))] 28 | #[ensures(ret -> self.available.len() == old(self.available.len()) - 1)] 29 | #[ensures(ret -> self.lent.len() == old(self.lent.len()) + 1)] 30 | #[debug_ensures(ret -> self.lent.contains(book_id))] 31 | #[debug_ensures(!ret -> self.lent.contains(book_id), "Book already lent")] 32 | pub fn lend(&mut self, book_id: &str) -> bool { 33 | if self.available.contains(book_id) { 34 | self.available.remove(book_id); 35 | self.lent.insert(book_id.to_string()); 36 | true 37 | } else { 38 | false 39 | } 40 | } 41 | 42 | #[debug_requires(self.lent.contains(book_id), "Can't return a non-lent book")] 43 | #[ensures(self.lent.len() == old(self.lent.len()) - 1)] 44 | #[ensures(self.available.len() == old(self.available.len()) + 1)] 45 | #[debug_ensures(!self.lent.contains(book_id))] 46 | #[debug_ensures(self.available.contains(book_id), "Book available again")] 47 | pub fn return_book(&mut self, book_id: &str) { 48 | self.lent.remove(book_id); 49 | self.available.insert(book_id.to_string()); 50 | } 51 | } 52 | 53 | fn main() { 54 | let mut lib = Library { 55 | available: HashSet::new(), 56 | lent: HashSet::new(), 57 | }; 58 | 59 | lib.add_book("Das Kapital"); 60 | println!("Adding a book."); 61 | 62 | let lent_successful = lib.lend("Das Kapital"); 63 | assert!(lent_successful); 64 | 65 | if lent_successful { 66 | println!("Lent out the book."); 67 | println!("Reading for a bit..."); 68 | 69 | println!("Giving back the book."); 70 | 71 | lib.return_book("Das Kapital"); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "flake-parts": { 4 | "inputs": { 5 | "nixpkgs-lib": "nixpkgs-lib" 6 | }, 7 | "locked": { 8 | "lastModified": 1738453229, 9 | "narHash": "sha256-7H9XgNiGLKN1G1CgRh0vUL4AheZSYzPm+zmZ7vxbJdo=", 10 | "owner": "hercules-ci", 11 | "repo": "flake-parts", 12 | "rev": "32ea77a06711b758da0ad9bd6a844c5740a87abd", 13 | "type": "github" 14 | }, 15 | "original": { 16 | "owner": "hercules-ci", 17 | "repo": "flake-parts", 18 | "type": "github" 19 | } 20 | }, 21 | "nixpkgs": { 22 | "locked": { 23 | "lastModified": 1740339700, 24 | "narHash": "sha256-cbrw7EgQhcdFnu6iS3vane53bEagZQy/xyIkDWpCgVE=", 25 | "owner": "NixOS", 26 | "repo": "nixpkgs", 27 | "rev": "04ef94c4c1582fd485bbfdb8c4a8ba250e359195", 28 | "type": "github" 29 | }, 30 | "original": { 31 | "owner": "NixOS", 32 | "ref": "nixos-24.11", 33 | "repo": "nixpkgs", 34 | "type": "github" 35 | } 36 | }, 37 | "nixpkgs-lib": { 38 | "locked": { 39 | "lastModified": 1738452942, 40 | "narHash": "sha256-vJzFZGaCpnmo7I6i416HaBLpC+hvcURh/BQwROcGIp8=", 41 | "type": "tarball", 42 | "url": "https://github.com/NixOS/nixpkgs/archive/072a6db25e947df2f31aab9eccd0ab75d5b2da11.tar.gz" 43 | }, 44 | "original": { 45 | "type": "tarball", 46 | "url": "https://github.com/NixOS/nixpkgs/archive/072a6db25e947df2f31aab9eccd0ab75d5b2da11.tar.gz" 47 | } 48 | }, 49 | "nixpkgs-unstable": { 50 | "locked": { 51 | "lastModified": 1746328495, 52 | "narHash": "sha256-uKCfuDs7ZM3QpCE/jnfubTg459CnKnJG/LwqEVEdEiw=", 53 | "owner": "NixOS", 54 | "repo": "nixpkgs", 55 | "rev": "979daf34c8cacebcd917d540070b52a3c2b9b16e", 56 | "type": "github" 57 | }, 58 | "original": { 59 | "owner": "NixOS", 60 | "ref": "nixos-unstable", 61 | "repo": "nixpkgs", 62 | "type": "github" 63 | } 64 | }, 65 | "root": { 66 | "inputs": { 67 | "flake-parts": "flake-parts", 68 | "nixpkgs": "nixpkgs", 69 | "nixpkgs-unstable": "nixpkgs-unstable", 70 | "x52": "x52" 71 | } 72 | }, 73 | "x52": { 74 | "inputs": { 75 | "flake-parts": [ 76 | "flake-parts" 77 | ], 78 | "nixpkgs": [ 79 | "nixpkgs" 80 | ] 81 | }, 82 | "locked": { 83 | "lastModified": 1716077176, 84 | "narHash": "sha256-CJLStpZHEVZ+fgXG3H61R97KzQePkdNXpnhkDBtHUec=", 85 | "owner": "x52dev", 86 | "repo": "nix", 87 | "rev": "4afdfa74f1bef9a7e2e99498c47a25b0753a43e0", 88 | "type": "github" 89 | }, 90 | "original": { 91 | "owner": "x52dev", 92 | "repo": "nix", 93 | "type": "github" 94 | } 95 | } 96 | }, 97 | "root": "root", 98 | "version": 7 99 | } 100 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | inputs = { 3 | nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11"; 4 | nixpkgs-unstable.url = "github:NixOS/nixpkgs/nixos-unstable"; 5 | flake-parts.url = "github:hercules-ci/flake-parts"; 6 | x52 = { 7 | url = "github:x52dev/nix"; 8 | inputs.nixpkgs.follows = "nixpkgs"; 9 | inputs.flake-parts.follows = "flake-parts"; 10 | }; 11 | }; 12 | 13 | outputs = inputs @ { flake-parts, ... }: 14 | flake-parts.lib.mkFlake { inherit inputs; } { 15 | systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ]; 16 | perSystem = { pkgs, config, inputs', system, lib, ... }: 17 | let 18 | x52just = inputs'.x52.packages.x52-just; 19 | in 20 | { 21 | formatter = pkgs.nixpkgs-fmt; 22 | 23 | devShells.default = pkgs.mkShell { 24 | buildInputs = [ x52just ]; 25 | 26 | packages = [ 27 | config.formatter 28 | inputs'.nixpkgs-unstable.legacyPackages.cargo-shear 29 | pkgs.fd 30 | pkgs.just 31 | pkgs.nodePackages.prettier 32 | pkgs.taplo 33 | ] ++ lib.optional pkgs.stdenv.isDarwin [ 34 | pkgs.pkgsBuildHost.darwin.apple_sdk.frameworks.CoreFoundation 35 | pkgs.pkgsBuildHost.darwin.apple_sdk.frameworks.Security 36 | pkgs.pkgsBuildHost.libiconv 37 | ]; 38 | 39 | shellHook = '' 40 | mkdir -p .toolchain 41 | cp ${x52just}/*.just .toolchain/ 42 | ''; 43 | }; 44 | }; 45 | }; 46 | } 47 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | import '.toolchain/rust.just' 2 | 3 | toolchain := "" 4 | 5 | _list: 6 | @just --list 7 | 8 | # Downgrade dependencies necessary to run MSRV checks/tests. 9 | [private] 10 | downgrade-for-msrv: 11 | # No downgrades currently needed. 12 | 13 | # Check project 14 | check: 15 | just --unstable --fmt --check 16 | fd --hidden --extension=md --extension=yml --exec-batch prettier --check 17 | fd --hidden --extension=toml --exec-batch taplo format --check 18 | fd --hidden --extension=toml --exec-batch taplo lint 19 | cargo +nightly fmt -- --check 20 | cargo shear 21 | 22 | # Format project 23 | fmt: 24 | just --unstable --fmt 25 | nixpkgs-fmt . 26 | fd --hidden --extension=md --extension=yml --exec-batch prettier --write 27 | fd --hidden --extension=toml --exec-batch taplo format 28 | cargo +nightly fmt 29 | 30 | # Lint workspace with Clippy 31 | clippy: 32 | cargo clippy --workspace --no-default-features 33 | cargo clippy --workspace 34 | # cargo clippy --workspace --all-features 35 | 36 | # Test workspace without generating coverage files 37 | [private] 38 | test-no-coverage: 39 | cargo {{ toolchain }} nextest run --workspace --no-default-features 40 | # cargo {{ toolchain }} nextest run --workspace --all-features 41 | cargo {{ toolchain }} test --doc --workspace 42 | # cargo {{ toolchain }} test --doc --workspace --all-features 43 | RUSTDOCFLAGS="-D warnings" cargo {{ toolchain }} doc --workspace --no-deps --all-features 44 | 45 | # Test workspace and generate coverage files 46 | test: test-no-coverage 47 | # @just test-coverage-codecov 48 | # @just test-coverage-lcov 49 | 50 | # Test workspace using MSRV 51 | test-msrv: downgrade-for-msrv test 52 | 53 | # Test workspace and generate Codecov coverage file 54 | test-coverage-codecov: 55 | cargo {{ toolchain }} llvm-cov --workspace --all-features --codecov --output-path codecov.json 56 | 57 | # Test workspace and generate LCOV coverage file 58 | test-coverage-lcov: 59 | cargo {{ toolchain }} llvm-cov --workspace --all-features --lcov --output-path lcov.info 60 | 61 | # Document workspace 62 | doc *args: 63 | RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly doc --no-deps --workspace --all-features {{ args }} 64 | 65 | # Document workspace and watch for changes 66 | doc-watch: (doc "--open") 67 | cargo watch -- just doc 68 | -------------------------------------------------------------------------------- /src/implementation/codegen.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use proc_macro2::{Ident, Span, TokenStream}; 6 | use quote::ToTokens; 7 | use syn::{ 8 | spanned::Spanned, 9 | visit::{visit_return_type, Visit}, 10 | visit_mut::{self as visitor, visit_block_mut, visit_expr_mut, VisitMut}, 11 | Attribute, Expr, ExprCall, ReturnType, TypeImplTrait, 12 | }; 13 | 14 | use crate::implementation::{Contract, ContractMode, ContractType, FuncWithContracts}; 15 | 16 | /// Substitution for `old()` expressions. 17 | pub(crate) struct OldExpr { 18 | /// Name of the variable binder. 19 | pub(crate) name: String, 20 | /// Expression to be evaluated. 21 | pub(crate) expr: Expr, 22 | } 23 | 24 | /// Extract calls to the pseudo-function `old()` in post-conditions, 25 | /// which evaluates an expression in a context *before* the 26 | /// to-be-checked-function is executed. 27 | pub(crate) fn extract_old_calls(contracts: &mut [Contract]) -> Vec { 28 | struct OldExtractor { 29 | last_id: usize, 30 | olds: Vec, 31 | } 32 | 33 | // if the call is a call to old() then the argument will be 34 | // returned. 35 | fn get_old_data(call: &ExprCall) -> Option { 36 | // must have only one argument 37 | if call.args.len() != 1 { 38 | return None; 39 | } 40 | 41 | if let Expr::Path(path) = &*call.func { 42 | if path.path.is_ident("old") { 43 | Some(call.args[0].clone()) 44 | } else { 45 | None 46 | } 47 | } else { 48 | None 49 | } 50 | } 51 | 52 | impl visitor::VisitMut for OldExtractor { 53 | fn visit_expr_mut(&mut self, expr: &mut Expr) { 54 | if let Expr::Call(call) = expr { 55 | if let Some(mut old_arg) = get_old_data(call) { 56 | // if it's a call to old() then add to list of 57 | // old expressions and continue to check the 58 | // argument. 59 | 60 | self.visit_expr_mut(&mut old_arg); 61 | 62 | let id = self.last_id; 63 | self.last_id += 1; 64 | 65 | let old_var_name = format!("__contract_old_{}", id); 66 | 67 | let old_expr = OldExpr { 68 | name: old_var_name.clone(), 69 | expr: old_arg, 70 | }; 71 | 72 | self.olds.push(old_expr); 73 | 74 | // override the original expression with the new variable 75 | // identifier 76 | *expr = { 77 | let span = expr.span(); 78 | 79 | let ident = syn::Ident::new(&old_var_name, span); 80 | 81 | let toks = quote::quote_spanned! { span=> #ident }; 82 | 83 | syn::parse(toks.into()).unwrap() 84 | }; 85 | } else { 86 | // otherwise continue visiting the expression call 87 | visitor::visit_expr_call_mut(self, call); 88 | } 89 | } else { 90 | visitor::visit_expr_mut(self, expr); 91 | } 92 | } 93 | } 94 | 95 | let mut extractor = OldExtractor { 96 | last_id: 0, 97 | olds: vec![], 98 | }; 99 | 100 | for contract in contracts { 101 | if contract.ty != ContractType::Ensures { 102 | continue; 103 | } 104 | 105 | for assertion in &mut contract.assertions { 106 | extractor.visit_expr_mut(assertion); 107 | } 108 | } 109 | 110 | extractor.olds 111 | } 112 | 113 | fn get_assert_macro( 114 | ctype: ContractType, // only Pre/Post allowed. 115 | mode: ContractMode, 116 | span: Span, 117 | ) -> Option { 118 | if cfg!(feature = "mirai_assertions") { 119 | match (ctype, mode) { 120 | (ContractType::Requires, ContractMode::Always) => { 121 | Some(Ident::new("checked_precondition", span)) 122 | } 123 | (ContractType::Requires, ContractMode::Debug) => { 124 | Some(Ident::new("debug_checked_precondition", span)) 125 | } 126 | (ContractType::Requires, ContractMode::Test) => { 127 | Some(Ident::new("debug_checked_precondition", span)) 128 | } 129 | (ContractType::Requires, ContractMode::Disabled) => { 130 | Some(Ident::new("precondition", span)) 131 | } 132 | (ContractType::Requires, ContractMode::LogOnly) => { 133 | Some(Ident::new("precondition", span)) 134 | } 135 | (ContractType::Ensures, ContractMode::Always) => { 136 | Some(Ident::new("checked_postcondition", span)) 137 | } 138 | (ContractType::Ensures, ContractMode::Debug) => { 139 | Some(Ident::new("debug_checked_postcondition", span)) 140 | } 141 | (ContractType::Ensures, ContractMode::Test) => { 142 | Some(Ident::new("debug_checked_postcondition", span)) 143 | } 144 | (ContractType::Ensures, ContractMode::Disabled) => { 145 | Some(Ident::new("postcondition", span)) 146 | } 147 | (ContractType::Ensures, ContractMode::LogOnly) => { 148 | Some(Ident::new("postcondition", span)) 149 | } 150 | (ContractType::Invariant, _) => { 151 | panic!("expected Invariant to be narrowed down to Pre/Post") 152 | } 153 | } 154 | } else { 155 | match mode { 156 | ContractMode::Always => Some(Ident::new("assert", span)), 157 | ContractMode::Debug => Some(Ident::new("debug_assert", span)), 158 | ContractMode::Test => Some(Ident::new("debug_assert", span)), 159 | ContractMode::Disabled => None, 160 | ContractMode::LogOnly => None, 161 | } 162 | } 163 | } 164 | 165 | /// Generate the resulting code for this function by inserting assertions. 166 | pub(crate) fn generate( 167 | mut func: FuncWithContracts, 168 | docs: Vec, 169 | olds: Vec, 170 | ) -> TokenStream { 171 | let func_name = func.function.sig.ident.to_string(); 172 | 173 | // creates an assertion appropriate for the current mode 174 | let make_assertion = |mode: ContractMode, 175 | ctype: ContractType, 176 | display: TokenStream, 177 | exec_expr: &Expr, 178 | desc: &str| { 179 | let span = display.span(); 180 | let mut result = TokenStream::new(); 181 | 182 | let format_args = quote::quote_spanned! { span=> 183 | concat!(concat!(#desc, ": "), stringify!(#display)) 184 | }; 185 | 186 | if mode == ContractMode::LogOnly { 187 | result.extend(quote::quote_spanned! { span=> 188 | #[allow(clippy::nonminimal_bool)] 189 | { 190 | if !(#exec_expr) { 191 | log::error!("{}", #format_args); 192 | } 193 | } 194 | }); 195 | } 196 | 197 | if let Some(assert_macro) = get_assert_macro(ctype, mode, span) { 198 | result.extend(quote::quote_spanned! { span=> 199 | #[allow(clippy::nonminimal_bool)] { 200 | #assert_macro!(#exec_expr, "{}", #format_args); 201 | } 202 | }); 203 | } 204 | 205 | if mode == ContractMode::Test { 206 | quote::quote_spanned! { span=> 207 | #[cfg(test)] { 208 | #result 209 | } 210 | } 211 | } else { 212 | result 213 | } 214 | }; 215 | 216 | // 217 | // generate assertion code for pre-conditions 218 | // 219 | 220 | let pre = func 221 | .contracts 222 | .iter() 223 | .filter(|c| c.ty == ContractType::Requires || c.ty == ContractType::Invariant) 224 | .flat_map(|c| { 225 | let contract_type_name = if c.ty == ContractType::Invariant { 226 | format!("{} (as pre-condition)", c.ty.message_name()) 227 | } else { 228 | c.ty.message_name().to_string() 229 | }; 230 | 231 | let desc = if let Some(desc) = c.desc.as_ref() { 232 | format!("{} of {} violated: {}", contract_type_name, func_name, desc) 233 | } else { 234 | format!("{} of {} violated", contract_type_name, func_name) 235 | }; 236 | 237 | c.assertions 238 | .iter() 239 | .zip(c.streams.iter()) 240 | .map(move |(expr, display)| { 241 | let mode = c.mode.final_mode(); 242 | 243 | make_assertion( 244 | mode, 245 | ContractType::Requires, 246 | display.clone(), 247 | expr, 248 | &desc.clone(), 249 | ) 250 | }) 251 | }) 252 | .collect::(); 253 | 254 | // 255 | // generate assertion code for post-conditions 256 | // 257 | 258 | let post = func 259 | .contracts 260 | .iter() 261 | .filter(|c| c.ty == ContractType::Ensures || c.ty == ContractType::Invariant) 262 | .flat_map(|c| { 263 | let contract_type_name = if c.ty == ContractType::Invariant { 264 | format!("{} (as post-condition)", c.ty.message_name()) 265 | } else { 266 | c.ty.message_name().to_string() 267 | }; 268 | 269 | let desc = if let Some(desc) = c.desc.as_ref() { 270 | format!("{} of {} violated: {}", contract_type_name, func_name, desc) 271 | } else { 272 | format!("{} of {} violated", contract_type_name, func_name) 273 | }; 274 | 275 | c.assertions 276 | .iter() 277 | .zip(c.streams.iter()) 278 | .map(move |(expr, display)| { 279 | let mode = c.mode.final_mode(); 280 | 281 | make_assertion( 282 | mode, 283 | ContractType::Ensures, 284 | display.clone(), 285 | expr, 286 | &desc.clone(), 287 | ) 288 | }) 289 | }) 290 | .collect::(); 291 | 292 | // 293 | // bind "old()" expressions 294 | // 295 | 296 | let olds = { 297 | let mut toks = TokenStream::new(); 298 | 299 | for old in olds { 300 | let span = old.expr.span(); 301 | 302 | let name = syn::Ident::new(&old.name, span); 303 | 304 | let expr = old.expr; 305 | 306 | let binding = quote::quote_spanned! { span=> 307 | let #name = #expr; 308 | }; 309 | 310 | toks.extend(Some(binding)); 311 | } 312 | 313 | toks 314 | }; 315 | 316 | // 317 | // wrap the function body in a block so that we can use its return value 318 | // 319 | 320 | let body = 'blk: { 321 | let mut block = func.function.block.clone(); 322 | visit_block_mut(&mut ReturnReplacer, &mut block); 323 | 324 | let mut impl_detector = ImplDetector { found_impl: false }; 325 | visit_return_type(&mut impl_detector, &func.function.sig.output); 326 | 327 | if !impl_detector.found_impl { 328 | if let ReturnType::Type(.., ref return_type) = func.function.sig.output { 329 | break 'blk quote::quote! { 330 | let ret: #return_type = 'run: #block; 331 | }; 332 | } 333 | } 334 | 335 | quote::quote! { 336 | let ret = 'run: #block; 337 | } 338 | }; 339 | 340 | // 341 | // create a new function body containing all assertions 342 | // 343 | 344 | let new_block = quote::quote! { 345 | 346 | { 347 | #pre 348 | 349 | #olds 350 | 351 | #body 352 | 353 | #post 354 | 355 | ret 356 | } 357 | 358 | }; 359 | 360 | // insert documentation attributes 361 | 362 | func.function.attrs.extend(docs); 363 | 364 | // replace the old function body with the new one 365 | 366 | func.function.block = Box::new(syn::parse_quote!(#new_block)); 367 | 368 | func.function.into_token_stream() 369 | } 370 | 371 | struct ReturnReplacer; 372 | 373 | impl VisitMut for ReturnReplacer { 374 | fn visit_expr_mut(&mut self, node: &mut Expr) { 375 | if let Expr::Return(ret_expr) = node { 376 | let ret_expr_expr = ret_expr.expr.clone(); 377 | *node = syn::parse_quote!(break 'run #ret_expr_expr); 378 | } 379 | 380 | visit_expr_mut(self, node); 381 | } 382 | } 383 | 384 | struct ImplDetector { 385 | found_impl: bool, 386 | } 387 | 388 | impl<'a> Visit<'a> for ImplDetector { 389 | fn visit_type_impl_trait(&mut self, _node: &'a TypeImplTrait) { 390 | self.found_impl = true; 391 | } 392 | } 393 | -------------------------------------------------------------------------------- /src/implementation/doc.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use proc_macro2::{Span, TokenStream}; 6 | use syn::{parse::Parser, Attribute}; 7 | 8 | use crate::implementation::{Contract, ContractMode}; 9 | 10 | pub(crate) fn generate_attributes(contracts: &[Contract]) -> Vec { 11 | let mut attrs = vec![]; 12 | 13 | fn make_attribute(content: &str) -> Attribute { 14 | let span = Span::call_site(); 15 | 16 | let content_str = syn::LitStr::new(content, span); 17 | 18 | let toks: TokenStream = quote::quote_spanned!( span=> #[doc = #content_str] ); 19 | 20 | let parser = Attribute::parse_outer; 21 | 22 | let mut attributes = parser.parse2(toks).unwrap(); 23 | 24 | attributes.remove(0) 25 | } 26 | 27 | fn print_stream(stream: &TokenStream) -> String { 28 | stream.to_string() 29 | } 30 | 31 | // header 32 | attrs.push(make_attribute("# Contracts")); 33 | 34 | for contract in contracts { 35 | let ty = contract.ty; 36 | let mode = match contract.mode { 37 | ContractMode::Always => None, 38 | ContractMode::Disabled => None, 39 | ContractMode::Debug => Some("debug"), 40 | ContractMode::Test => Some("test"), 41 | ContractMode::LogOnly => None, 42 | }; 43 | 44 | if let Some(desc) = &contract.desc { 45 | // document all assertions under the description 46 | 47 | let header_txt = if let Some(name) = mode { 48 | format!("{} - {}: {}", ty.message_name(), name, desc) 49 | } else { 50 | format!("{}: {}", ty.message_name(), desc) 51 | }; 52 | 53 | attrs.push(make_attribute(&header_txt)); 54 | 55 | for (_assert, stream) in contract.assertions.iter().zip(contract.streams.iter()) { 56 | attrs.push(make_attribute(&format!(" - `{}`", print_stream(stream)))); 57 | } 58 | 59 | attrs.push(make_attribute("")); 60 | } else { 61 | // document each assertion on its own 62 | 63 | for stream in &contract.streams { 64 | let doc_str = if let Some(name) = mode { 65 | format!( 66 | "{} - {}: `{}`", 67 | ty.message_name(), 68 | name, 69 | print_stream(stream) 70 | ) 71 | } else { 72 | format!("{}: `{}`", ty.message_name(), print_stream(stream)) 73 | }; 74 | 75 | attrs.push(make_attribute(&doc_str)); 76 | attrs.push(make_attribute("")); 77 | } 78 | } 79 | } 80 | 81 | attrs 82 | } 83 | -------------------------------------------------------------------------------- /src/implementation/ensures.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use proc_macro2::TokenStream; 6 | 7 | use crate::implementation::{ContractMode, ContractType, FuncWithContracts}; 8 | 9 | pub(crate) fn ensures(mode: ContractMode, attr: TokenStream, toks: TokenStream) -> TokenStream { 10 | let ty = ContractType::Ensures; 11 | 12 | let func = syn::parse_quote!(#toks); 13 | 14 | let f = FuncWithContracts::new_with_initial_contract(func, ty, mode, attr); 15 | 16 | f.generate() 17 | } 18 | -------------------------------------------------------------------------------- /src/implementation/invariant.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use proc_macro2::TokenStream; 6 | use quote::ToTokens; 7 | use syn::{FnArg, ImplItem, ImplItemFn, Item, ItemFn, ItemImpl}; 8 | 9 | use crate::implementation::{ContractMode, ContractType, FuncWithContracts}; 10 | 11 | pub(crate) fn invariant(mode: ContractMode, attr: TokenStream, toks: TokenStream) -> TokenStream { 12 | let item: Item = syn::parse_quote!(#toks); 13 | 14 | let name = mode.name().unwrap().to_string() + "invariant"; 15 | 16 | match item { 17 | Item::Fn(fn_) => invariant_fn(mode, attr, fn_), 18 | Item::Impl(impl_) => invariant_impl(mode, attr, impl_), 19 | _ => unimplemented!( 20 | "The #[{}] attribute only works on functions and impl-blocks.", 21 | name 22 | ), 23 | } 24 | } 25 | 26 | fn invariant_fn(mode: ContractMode, attr: TokenStream, func: ItemFn) -> TokenStream { 27 | let ty = ContractType::Invariant; 28 | 29 | let f = FuncWithContracts::new_with_initial_contract(func, ty, mode, attr); 30 | 31 | f.generate() 32 | } 33 | 34 | /// Generate the token-stream for an `impl` block with a "global" invariant. 35 | fn invariant_impl( 36 | mode: ContractMode, 37 | invariant: TokenStream, 38 | mut impl_def: ItemImpl, 39 | ) -> TokenStream { 40 | // all that is done is prefix all the function definitions with 41 | // the invariant attribute. 42 | // The following expansion of the attributes will then implement the 43 | // invariant just like it's done for functions. 44 | 45 | // The mode received is "raw", so it can't be "Disabled" or "LogOnly" 46 | // but it can't hurt to deal with it anyway. 47 | let name = match mode.name() { 48 | Some(n) => n.to_string() + "invariant", 49 | None => { 50 | return quote::quote!( #impl_def ); 51 | } 52 | }; 53 | 54 | let invariant_ident = syn::Ident::new(&name, proc_macro2::Span::call_site()); 55 | 56 | fn method_uses_self(method: &ImplItemFn) -> bool { 57 | let inputs = &method.sig.inputs; 58 | 59 | if !inputs.is_empty() { 60 | matches!(inputs[0], FnArg::Receiver(_)) 61 | } else { 62 | false 63 | } 64 | } 65 | 66 | for item in &mut impl_def.items { 67 | if let ImplItem::Fn(method) = item { 68 | // only implement invariants for methods that take `self` 69 | if !method_uses_self(method) { 70 | continue; 71 | } 72 | 73 | let method_toks = quote::quote! { 74 | #[#invariant_ident(#invariant)] 75 | #method 76 | }; 77 | 78 | let met: ImplItemFn = syn::parse_quote!(#method_toks); 79 | 80 | *method = met; 81 | } 82 | } 83 | 84 | impl_def.into_token_stream() 85 | } 86 | -------------------------------------------------------------------------------- /src/implementation/mod.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | pub(crate) mod codegen; 6 | pub(crate) mod doc; 7 | pub(crate) mod ensures; 8 | pub(crate) mod invariant; 9 | pub(crate) mod parse; 10 | pub(crate) mod requires; 11 | pub(crate) mod traits; 12 | 13 | pub(crate) use ensures::ensures; 14 | pub(crate) use invariant::invariant; 15 | use proc_macro2::{Span, TokenStream}; 16 | use quote::ToTokens; 17 | pub(crate) use requires::requires; 18 | use syn::{Expr, ItemFn}; 19 | pub(crate) use traits::{contract_trait_item_impl, contract_trait_item_trait}; 20 | 21 | /// Checking-mode of a contract. 22 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] 23 | pub(crate) enum ContractMode { 24 | /// Always check contract 25 | Always, 26 | /// Never check contract 27 | Disabled, 28 | /// Check contract only in debug builds 29 | Debug, 30 | /// Check contract only in `#[cfg(test)]` configurations 31 | Test, 32 | /// Check the contract and print information upon violation, but don't abort 33 | /// the program. 34 | LogOnly, 35 | } 36 | 37 | impl ContractMode { 38 | /// Return the prefix of attributes of `self` mode. 39 | pub(crate) fn name(self) -> Option<&'static str> { 40 | match self { 41 | ContractMode::Always => Some(""), 42 | ContractMode::Disabled => None, 43 | ContractMode::Debug => Some("debug_"), 44 | ContractMode::Test => Some("test_"), 45 | ContractMode::LogOnly => None, 46 | } 47 | } 48 | 49 | /// Computes the contract type based on feature flags. 50 | pub(crate) fn final_mode(self) -> Self { 51 | // disabled ones can't be "forced", test ones should stay test, no 52 | // matter what. 53 | if self == ContractMode::Disabled || self == ContractMode::Test { 54 | return self; 55 | } 56 | 57 | if cfg!(feature = "disable_contracts") { 58 | ContractMode::Disabled 59 | } else if cfg!(feature = "override_debug") { 60 | // log is "weaker" than debug, so keep log 61 | if self == ContractMode::LogOnly { 62 | self 63 | } else { 64 | ContractMode::Debug 65 | } 66 | } else if cfg!(feature = "override_log") { 67 | ContractMode::LogOnly 68 | } else { 69 | self 70 | } 71 | } 72 | } 73 | 74 | /// The different contract types. 75 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 76 | pub(crate) enum ContractType { 77 | Requires, 78 | Ensures, 79 | Invariant, 80 | } 81 | 82 | impl ContractType { 83 | /// Get the name that is used as a message-prefix on violation of a 84 | /// contract. 85 | pub(crate) fn message_name(self) -> &'static str { 86 | match self { 87 | ContractType::Requires => "Pre-condition", 88 | ContractType::Ensures => "Post-condition", 89 | ContractType::Invariant => "Invariant", 90 | } 91 | } 92 | 93 | /// Determine the type and mode of an identifier. 94 | pub(crate) fn contract_type_and_mode(ident: &str) -> Option<(ContractType, ContractMode)> { 95 | match ident { 96 | "requires" => Some((ContractType::Requires, ContractMode::Always)), 97 | "ensures" => Some((ContractType::Ensures, ContractMode::Always)), 98 | "invariant" => Some((ContractType::Invariant, ContractMode::Always)), 99 | "debug_requires" => Some((ContractType::Requires, ContractMode::Debug)), 100 | "debug_ensures" => Some((ContractType::Ensures, ContractMode::Debug)), 101 | "debug_invariant" => Some((ContractType::Invariant, ContractMode::Debug)), 102 | "test_requires" => Some((ContractType::Requires, ContractMode::Test)), 103 | "test_ensures" => Some((ContractType::Ensures, ContractMode::Test)), 104 | "test_invariant" => Some((ContractType::Invariant, ContractMode::Test)), 105 | _ => None, 106 | } 107 | } 108 | } 109 | 110 | /// Representation of a contract 111 | #[derive(Debug)] 112 | pub(crate) struct Contract { 113 | pub(crate) _span: Span, 114 | pub(crate) ty: ContractType, 115 | pub(crate) mode: ContractMode, 116 | pub(crate) assertions: Vec, 117 | pub(crate) streams: Vec, 118 | pub(crate) desc: Option, 119 | } 120 | 121 | impl Contract { 122 | pub(crate) fn from_toks(ty: ContractType, mode: ContractMode, toks: TokenStream) -> Self { 123 | let (assertions, streams, desc) = parse::parse_attributes(toks); 124 | 125 | let span = Span::call_site(); 126 | 127 | Self { 128 | _span: span, 129 | ty, 130 | mode, 131 | assertions, 132 | streams, 133 | desc, 134 | } 135 | } 136 | } 137 | 138 | /// A function that is annotated with contracts 139 | #[derive(Debug)] 140 | pub(crate) struct FuncWithContracts { 141 | pub(crate) contracts: Vec, 142 | pub(crate) function: ItemFn, 143 | } 144 | 145 | impl FuncWithContracts { 146 | /// Create a `FuncWithContracts` value from the attribute-tokens of the 147 | /// first contract and a parsed version of the function. 148 | /// 149 | /// The initial contract is parsed from the tokens, others will be read from 150 | /// parsed function. 151 | pub(crate) fn new_with_initial_contract( 152 | mut func: ItemFn, 153 | cty: ContractType, 154 | cmode: ContractMode, 155 | ctoks: TokenStream, 156 | ) -> Self { 157 | // add in the first attribute 158 | let mut contracts: Vec = { 159 | let initial_contract = Contract::from_toks(cty, cmode, ctoks); 160 | vec![initial_contract] 161 | }; 162 | 163 | // find all other attributes 164 | 165 | let contract_attrs = func 166 | .attrs 167 | .iter() 168 | .filter_map(|a| { 169 | let name = a.path().segments.last().unwrap().ident.to_string(); 170 | let (ty, mode) = ContractType::contract_type_and_mode(&name)?; 171 | Some((ty, mode, a)) 172 | }) 173 | .map(|(ty, mode, attr)| { 174 | // the tts on attributes contains the out parenthesis, so some 175 | // code might be mistakenly parsed as tuples, that's not good! 176 | // 177 | // this is a hack to get to the inner token stream. 178 | 179 | fn extract_first_arg_stream(attr: &syn::Attribute) -> TokenStream { 180 | match &attr.meta { 181 | syn::Meta::List(list) => list.tokens.clone(), 182 | syn::Meta::Path(path) => path.to_token_stream(), 183 | syn::Meta::NameValue(nv) => nv.value.to_token_stream(), 184 | } 185 | } 186 | 187 | let toks = extract_first_arg_stream(attr); 188 | 189 | Contract::from_toks(ty, mode, toks) 190 | }); 191 | 192 | contracts.extend(contract_attrs); 193 | 194 | // remove contract attributes 195 | { 196 | let attrs = std::mem::take(&mut func.attrs); 197 | 198 | let other_attrs = attrs 199 | .into_iter() 200 | .filter(|attr| { 201 | ContractType::contract_type_and_mode( 202 | &attr.path().segments.last().unwrap().ident.to_string(), 203 | ) 204 | .is_none() 205 | }) 206 | .collect(); 207 | 208 | func.attrs = other_attrs; 209 | } 210 | 211 | Self { 212 | function: func, 213 | contracts, 214 | } 215 | } 216 | 217 | /// Generates the resulting tokens including all contract-checks 218 | pub(crate) fn generate(mut self) -> TokenStream { 219 | let doc_attrs = doc::generate_attributes(&self.contracts); 220 | let olds = codegen::extract_old_calls(&mut self.contracts); 221 | 222 | codegen::generate(self, doc_attrs, olds) 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /src/implementation/parse.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use proc_macro2::{Spacing, TokenStream, TokenTree}; 6 | use syn::{Expr, ExprLit, Lit}; 7 | 8 | /// Parse attributes into a list of expression and an optional description of 9 | /// the assert 10 | pub(crate) fn parse_attributes( 11 | attrs: TokenStream, 12 | ) -> (Vec, Vec, Option) { 13 | let segments = segment_input(attrs); 14 | let mut segments_stream: Vec = segments 15 | .iter() 16 | .map(|x| x.iter().cloned().collect::()) 17 | .collect(); 18 | let rewritten_segs: Vec<_> = segments.into_iter().map(rewrite).collect(); 19 | 20 | let mut conds: Vec = vec![]; 21 | 22 | for seg in rewritten_segs { 23 | let expr = match syn::parse2::(seg) { 24 | Ok(val) => val, 25 | Err(err) => Expr::Verbatim(err.to_compile_error()), 26 | }; 27 | conds.push(expr); 28 | } 29 | 30 | let desc = conds 31 | .last() 32 | .map(|expr| match expr { 33 | Expr::Lit(ExprLit { 34 | lit: Lit::Str(str), .. 35 | }) => Some(str.value()), 36 | _ => None, 37 | }) 38 | .unwrap_or(None); 39 | 40 | if desc.is_some() { 41 | conds.pop(); 42 | segments_stream.pop(); 43 | } 44 | 45 | (conds, segments_stream, desc) 46 | } 47 | 48 | // This function rewrites a list of TokenTrees so that the "pseudooperator" for 49 | // implication `==>` gets transformed into an `if` expression. 50 | // 51 | // This has to happen on a TokenStream/Tree because it's not possible to easily 52 | // add new syntax to the syn parsers without basically re-writing the whole 53 | // expression parsing functions from scratch. 54 | // 55 | // The input gets classified into "before `==>` op" and "after `==>` op". Those 56 | // two groups are then used to create an `if` that has implication semantics. 57 | // However, because the input is only split based on the operator, no precedence 58 | // is respected, including keywords such as `if`. This means the implication 59 | // operator should only be used in grouped expressions. 60 | // This also has the effect that implication is right-associative, which is the 61 | // expected behaviour. 62 | fn rewrite(segments: Vec) -> proc_macro2::TokenStream { 63 | let mut lhs = vec![]; 64 | let mut rhs: Option<_> = None; 65 | let mut span: Option<_> = None; 66 | 67 | let mut idx = 0; 68 | 69 | 'segment: while let Some(tt) = segments.get(idx) { 70 | match tt { 71 | TokenTree::Group(group) => { 72 | let stream: Vec<_> = group.stream().into_iter().collect(); 73 | 74 | let new_stream: TokenStream = rewrite(stream).into_iter().collect(); 75 | 76 | let mut new_group = proc_macro2::Group::new(group.delimiter(), new_stream); 77 | new_group.set_span(group.span()); 78 | 79 | lhs.push(TokenTree::Group(new_group)); 80 | idx += 1; 81 | } 82 | TokenTree::Ident(_) => { 83 | lhs.push(tt.clone()); 84 | idx += 1; 85 | } 86 | TokenTree::Literal(_) => { 87 | lhs.push(tt.clone()); 88 | idx += 1; 89 | } 90 | TokenTree::Punct(_) => { 91 | let punct = |idx: usize, c: char, s: Spacing| -> bool { 92 | let tt = if let Some(val) = segments.get(idx) { 93 | val 94 | } else { 95 | return false; 96 | }; 97 | 98 | if let TokenTree::Punct(p) = tt { 99 | p.as_char() == c && p.spacing() == s 100 | } else { 101 | false 102 | } 103 | }; 104 | 105 | if punct(idx, '-', Spacing::Joint) && punct(idx + 1, '>', Spacing::Alone) { 106 | // found the implication 107 | let rest = Vec::from(&segments[idx + 2..]); 108 | let rhs_stream = rewrite(rest); 109 | 110 | rhs = Some(rhs_stream); 111 | span = Some(segments[idx + 1].span()); 112 | break 'segment; 113 | } else { 114 | // consume all so that =========> would not match with 115 | // implication 116 | 'op: while let Some(tt) = segments.get(idx) { 117 | match tt { 118 | TokenTree::Punct(p) => { 119 | if p.spacing() == Spacing::Alone { 120 | // read this one but finish afterwards 121 | lhs.push(tt.clone()); 122 | idx += 1; 123 | break 'op; 124 | } else { 125 | // this punctuation is a joint-punctuation 126 | // so needs to be read and then continue 127 | lhs.push(tt.clone()); 128 | idx += 1; 129 | } 130 | } 131 | _ => { 132 | // not a punktuation, so do not increase idx 133 | break 'op; 134 | } 135 | } 136 | } 137 | } 138 | } 139 | } 140 | } 141 | 142 | match (rhs, span) { 143 | (None, None) => lhs.into_iter().collect(), 144 | (None, Some(_)) => { 145 | unreachable!("If there's a span there should be an implication") 146 | } 147 | (Some(_), None) => unreachable!("Invalid spans"), 148 | (Some(rhs), Some(span)) => { 149 | let lhs: TokenStream = lhs.into_iter().collect(); 150 | 151 | quote::quote_spanned! { 152 | span => 153 | (!(#lhs) || #rhs) 154 | } 155 | } 156 | } 157 | } 158 | 159 | // The tokenstream can contain multiple expressions to be checked, separated by 160 | // a comma. This function "pulls" those expressions apart. 161 | fn segment_input(tts: TokenStream) -> Vec> { 162 | let mut groups = vec![]; 163 | 164 | let mut group = vec![]; 165 | 166 | for tt in tts { 167 | match tt { 168 | TokenTree::Punct(p) if p.as_char() == ',' && p.spacing() == Spacing::Alone => { 169 | groups.push(group); 170 | group = vec![]; 171 | } 172 | t => group.push(t), 173 | } 174 | } 175 | 176 | if !group.is_empty() { 177 | groups.push(group); 178 | } 179 | 180 | groups 181 | } 182 | -------------------------------------------------------------------------------- /src/implementation/requires.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use proc_macro2::TokenStream; 6 | use syn::ItemFn; 7 | 8 | use crate::implementation::{ContractMode, ContractType, FuncWithContracts}; 9 | 10 | pub(crate) fn requires(mode: ContractMode, attr: TokenStream, toks: TokenStream) -> TokenStream { 11 | let ty = ContractType::Requires; 12 | 13 | let func: ItemFn = syn::parse_quote!(#toks); 14 | 15 | let f = FuncWithContracts::new_with_initial_contract(func, ty, mode, attr); 16 | 17 | f.generate() 18 | } 19 | -------------------------------------------------------------------------------- /src/implementation/traits.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use proc_macro2::TokenStream; 6 | use quote::ToTokens; 7 | use syn::{FnArg, ImplItem, ItemImpl, ItemTrait, Pat, TraitItem, TraitItemFn}; 8 | 9 | use crate::implementation::ContractType; 10 | 11 | /// Name used for the "re-routed" method. 12 | fn contract_method_impl_name(name: &str) -> String { 13 | format!("__contracts_impl_{}", name) 14 | } 15 | 16 | /// Modifies a trait item in a way that it includes contracts. 17 | pub(crate) fn contract_trait_item_trait(_attrs: TokenStream, mut trait_: ItemTrait) -> TokenStream { 18 | /// Just rename the method to have an internal, generated name. 19 | fn create_method_rename(method: &TraitItemFn) -> TraitItemFn { 20 | let mut m = method.clone(); 21 | 22 | // rename method and modify attributes 23 | { 24 | // remove any contracts attributes and rename 25 | let name = m.sig.ident.to_string(); 26 | 27 | let new_name = contract_method_impl_name(&name); 28 | 29 | let mut new_attrs = vec![]; 30 | new_attrs.push(syn::parse_quote!(#[doc(hidden)])); 31 | new_attrs.push(syn::parse_quote!(#[doc = "This is an internal function that is not meant to be used directly!"])); 32 | new_attrs.push(syn::parse_quote!(#[doc = "See the documentation of the `#[contract_trait]` attribute."])); 33 | 34 | // add all existing non-contract attributes 35 | new_attrs.extend( 36 | m.attrs 37 | .iter() 38 | .filter(|attr| { 39 | let name = attr.path().segments.last().unwrap().ident.to_string(); 40 | 41 | ContractType::contract_type_and_mode(&name).is_none() 42 | }) 43 | .cloned(), 44 | ); 45 | 46 | m.attrs = new_attrs; 47 | 48 | m.sig.ident = syn::Ident::new(&new_name, m.sig.ident.span()); 49 | } 50 | 51 | m 52 | } 53 | 54 | /// Create a wrapper function which has a default implementation and 55 | /// includes contracts. 56 | /// 57 | /// This new function forwards the call to the actual implementation. 58 | fn create_method_wrapper(method: &TraitItemFn) -> TraitItemFn { 59 | struct ArgInfo { 60 | call_toks: proc_macro2::TokenStream, 61 | } 62 | 63 | // Calculate name and pattern tokens 64 | fn arg_pat_info(pat: &Pat) -> ArgInfo { 65 | match pat { 66 | Pat::Ident(ident) => { 67 | let toks = quote::quote! { 68 | #ident 69 | }; 70 | ArgInfo { call_toks: toks } 71 | } 72 | Pat::Tuple(tup) => { 73 | let infos = tup.elems.iter().map(arg_pat_info); 74 | 75 | let toks = { 76 | let mut toks = proc_macro2::TokenStream::new(); 77 | 78 | for info in infos { 79 | toks.extend(info.call_toks); 80 | toks.extend(quote::quote!(,)); 81 | } 82 | 83 | toks 84 | }; 85 | 86 | ArgInfo { 87 | call_toks: quote::quote!((#toks)), 88 | } 89 | } 90 | Pat::TupleStruct(_tup) => unimplemented!(), 91 | p => panic!("Unsupported pattern type: {:?}", p), 92 | } 93 | } 94 | 95 | let mut m = method.clone(); 96 | 97 | let argument_data = m 98 | .sig 99 | .inputs 100 | .clone() 101 | .into_iter() 102 | .map(|t: FnArg| match &t { 103 | FnArg::Receiver(_) => quote::quote!(self), 104 | FnArg::Typed(p) => { 105 | let info = arg_pat_info(&p.pat); 106 | 107 | info.call_toks 108 | } 109 | }) 110 | .collect::>(); 111 | 112 | let arguments = { 113 | let mut toks = proc_macro2::TokenStream::new(); 114 | 115 | for arg in argument_data { 116 | toks.extend(arg); 117 | toks.extend(quote::quote!(,)); 118 | } 119 | 120 | toks 121 | }; 122 | 123 | let body: TokenStream = { 124 | let name = contract_method_impl_name(&m.sig.ident.to_string()); 125 | let name = syn::Ident::new(&name, m.sig.ident.span()); 126 | 127 | quote::quote! { 128 | { 129 | Self::#name(#arguments) 130 | } 131 | } 132 | }; 133 | 134 | let mut attrs = vec![]; 135 | 136 | // keep the documentation and contracts of the original method 137 | attrs.extend( 138 | m.attrs 139 | .iter() 140 | .filter(|a| { 141 | let name = a.path().segments.last().unwrap().ident.to_string(); 142 | // is doc? 143 | if name == "doc" { 144 | return true; 145 | } 146 | 147 | // is contract? 148 | ContractType::contract_type_and_mode(&name).is_some() 149 | }) 150 | .cloned(), 151 | ); 152 | // always inline 153 | attrs.push(syn::parse_quote!(#[inline(always)])); 154 | 155 | m.attrs = attrs; 156 | 157 | { 158 | let block: syn::Block = syn::parse2(body).unwrap(); 159 | m.default = Some(block); 160 | m.semi_token = None; 161 | } 162 | 163 | m 164 | } 165 | 166 | // create method wrappers and renamed items 167 | let funcs = trait_ 168 | .items 169 | .iter() 170 | .filter_map(|item| { 171 | if let TraitItem::Fn(m) = item { 172 | let rename = create_method_rename(m); 173 | let wrapper = create_method_wrapper(m); 174 | 175 | Some(vec![TraitItem::Fn(rename), TraitItem::Fn(wrapper)]) 176 | } else { 177 | None 178 | } 179 | }) 180 | .flatten() 181 | .collect::>(); 182 | 183 | // remove all previous methods 184 | trait_ 185 | .items 186 | .retain(|item| !matches!(item, TraitItem::Fn(_))); 187 | 188 | // add back new methods 189 | trait_.items.extend(funcs); 190 | 191 | trait_.into_token_stream() 192 | } 193 | 194 | /// Rename all methods inside an `impl` to use the "internal implementation" 195 | /// name. 196 | pub(crate) fn contract_trait_item_impl(_attrs: TokenStream, impl_: ItemImpl) -> TokenStream { 197 | let new_impl = { 198 | let mut impl_: ItemImpl = impl_; 199 | 200 | impl_.items.iter_mut().for_each(|it| { 201 | if let ImplItem::Fn(method) = it { 202 | let new_name = contract_method_impl_name(&method.sig.ident.to_string()); 203 | let new_ident = syn::Ident::new(&new_name, method.sig.ident.span()); 204 | 205 | method.sig.ident = new_ident; 206 | } 207 | }); 208 | 209 | impl_ 210 | }; 211 | 212 | new_impl.to_token_stream() 213 | } 214 | 215 | #[cfg(test)] 216 | mod tests { 217 | 218 | #[test] 219 | fn attributes_stay_on_trait_def() { 220 | // attributes on functions should apply to the outer "wrapping" function 221 | // only, the "internal" function should be hidden and be inlined. 222 | 223 | let code = syn::parse_quote! { 224 | trait Random { 225 | /// Test! 226 | #[aaa] 227 | #[ensures((min..max).contains(ret))] 228 | fn random_number(min: u8, max: u8) -> u8; 229 | } 230 | }; 231 | 232 | let expected = quote::quote! { 233 | trait Random { 234 | #[doc(hidden)] 235 | #[doc = "This is an internal function that is not meant to be used directly!"] 236 | #[doc = "See the documentation of the `#[contract_trait]` attribute."] 237 | /// Test! 238 | #[aaa] 239 | fn __contracts_impl_random_number(min: u8, max: u8) -> u8; 240 | 241 | /// Test! 242 | #[ensures((min..max).contains(ret))] 243 | #[inline(always)] 244 | fn random_number(min: u8, max: u8) -> u8 { 245 | Self::__contracts_impl_random_number(min, max,) 246 | } 247 | } 248 | }; 249 | 250 | let generated = super::contract_trait_item_trait(Default::default(), code); 251 | 252 | assert_eq!(generated.to_string(), expected.to_string()); 253 | } 254 | 255 | #[test] 256 | fn attributes_stay_on_trait_impl() { 257 | // attributes on functions should apply to the outer "wrapping" function 258 | // only, the "internal" function should be hidden and be inlined. 259 | 260 | let code = syn::parse_quote! { 261 | impl Random for AlwaysMin { 262 | /// docs for this function! 263 | #[no_panic] 264 | fn random_number(min: u8, max: u8) -> u8 { 265 | min 266 | } 267 | } 268 | }; 269 | 270 | let expected = quote::quote! { 271 | impl Random for AlwaysMin { 272 | /// docs for this function! 273 | #[no_panic] 274 | fn __contracts_impl_random_number(min: u8, max: u8) -> u8 { 275 | min 276 | } 277 | } 278 | }; 279 | 280 | let generated = super::contract_trait_item_impl(Default::default(), code); 281 | 282 | assert_eq!(generated.to_string(), expected.to_string()); 283 | } 284 | } 285 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | //! A crate implementing ["Design by Contract"][dbc] via procedural macros. 6 | //! 7 | //! This crate is heavily inspired by the [`libhoare`] compiler plugin. 8 | //! 9 | //! The main use of this crate is to annotate functions and methods using 10 | //! "contracts" in the form of [*pre-conditions* (`requires`)][precond], 11 | //! [*post-conditions* (`ensures`)][postcond] and [*invariants*][invariant]. 12 | //! 13 | //! Each "contract" annotation that is violated will cause an assertion failure. 14 | //! 15 | //! The attributes use "function call form" and can contain 1 or more conditions 16 | //! to check. 17 | //! If the last argument to an attribute is a string constant it will be 18 | //! inserted into the assertion message. 19 | //! 20 | //! ## Example 21 | //! 22 | //! ```rust 23 | //! # use contracts::*; 24 | //! #[requires(x > 0, "x must be in the valid input range")] 25 | //! #[ensures(ret.is_some() -> ret.unwrap() * ret.unwrap() == x)] 26 | //! fn integer_sqrt(x: u64) -> Option { 27 | //! // ... 28 | //! # unimplemented!() 29 | //! } 30 | //! ``` 31 | //! 32 | //! ```rust 33 | //! # use std::collections::HashSet; 34 | //! # use contracts::*; 35 | //! pub struct Library { 36 | //! available: HashSet, 37 | //! lent: HashSet, 38 | //! } 39 | //! 40 | //! impl Library { 41 | //! fn book_exists(&self, book_id: &str) -> bool { 42 | //! self.available.contains(book_id) 43 | //! || self.lent.contains(book_id) 44 | //! } 45 | //! 46 | //! #[debug_requires(!self.book_exists(book_id), "Book IDs are unique")] 47 | //! #[debug_ensures(self.available.contains(book_id), "Book now available")] 48 | //! #[ensures(self.available.len() == old(self.available.len()) + 1)] 49 | //! #[ensures(self.lent.len() == old(self.lent.len()), "No lent change")] 50 | //! pub fn add_book(&mut self, book_id: &str) { 51 | //! self.available.insert(book_id.to_string()); 52 | //! } 53 | //! 54 | //! #[debug_requires(self.book_exists(book_id))] 55 | //! #[ensures(ret -> self.available.len() == old(self.available.len()) - 1)] 56 | //! #[ensures(ret -> self.lent.len() == old(self.lent.len()) + 1)] 57 | //! #[debug_ensures(ret -> self.lent.contains(book_id))] 58 | //! #[debug_ensures(!ret -> self.lent.contains(book_id), "Book already lent")] 59 | //! pub fn lend(&mut self, book_id: &str) -> bool { 60 | //! if self.available.contains(book_id) { 61 | //! self.available.remove(book_id); 62 | //! self.lent.insert(book_id.to_string()); 63 | //! true 64 | //! } else { 65 | //! false 66 | //! } 67 | //! } 68 | //! 69 | //! #[debug_requires(self.lent.contains(book_id), "Can't return a non-lent book")] 70 | //! #[ensures(self.lent.len() == old(self.lent.len()) - 1)] 71 | //! #[ensures(self.available.len() == old(self.available.len()) + 1)] 72 | //! #[debug_ensures(!self.lent.contains(book_id))] 73 | //! #[debug_ensures(self.available.contains(book_id), "Book available again")] 74 | //! pub fn return_book(&mut self, book_id: &str) { 75 | //! self.lent.remove(book_id); 76 | //! self.available.insert(book_id.to_string()); 77 | //! } 78 | //! } 79 | //! ``` 80 | //! 81 | //! ## Attributes 82 | //! 83 | //! This crate exposes the `requires`, `ensures` and `invariant` attributes. 84 | //! 85 | //! - `requires` are checked before a function/method is executed. 86 | //! - `ensures` are checked after a function/method ran to completion 87 | //! - `invariant`s are checked both before *and* after a function/method ran. 88 | //! 89 | //! Additionally, all those attributes have versions with different "modes". See 90 | //! [the Modes section](#modes) below. 91 | //! 92 | //! For `trait`s and trait `impl`s the `contract_trait` attribute can be used. 93 | //! 94 | //! ## Pseudo-functions and operators 95 | //! 96 | //! ### `old()` function 97 | //! 98 | //! One unique feature that this crate provides is an `old()` pseudo-function which 99 | //! allows to perform checks using a value of a parameter before the function call 100 | //! happened. This is only available in `ensures` attributes. 101 | //! 102 | //! ```rust 103 | //! # use contracts::*; 104 | //! #[ensures(*x == old(*x) + 1, "after the call `x` was incremented")] 105 | //! fn incr(x: &mut usize) { 106 | //! *x += 1; 107 | //! } 108 | //! ``` 109 | //! 110 | //! ### `->` operator 111 | //! 112 | //! For more complex functions it can be useful to express behaviour using logical 113 | //! implication. Because Rust does not feature an operator for implication, this 114 | //! crate adds this operator for use in attributes. 115 | //! 116 | //! ```rust 117 | //! # use contracts::*; 118 | //! #[ensures(person_name.is_some() -> ret.contains(person_name.unwrap()))] 119 | //! fn geeting(person_name: Option<&str>) -> String { 120 | //! let mut s = String::from("Hello"); 121 | //! if let Some(name) = person_name { 122 | //! s.push(' '); 123 | //! s.push_str(name); 124 | //! } 125 | //! s.push('!'); 126 | //! s 127 | //! } 128 | //! ``` 129 | //! 130 | //! This operator is right-associative. 131 | //! 132 | //! **Note**: Because of the design of `syn`, it is tricky to add custom operators 133 | //! to be parsed, so this crate performs a rewrite of the `TokenStream` instead. 134 | //! The rewrite works by separating the expression into a part that's left of the 135 | //! `->` operator and the rest on the right side. This means that 136 | //! `if a -> b { c } else { d }` will not generate the expected code. 137 | //! Explicit grouping using parenthesis or curly-brackets can be used to avoid this. 138 | //! 139 | //! ## Modes 140 | //! 141 | //! All the attributes (requires, ensures, invariant) have `debug_*` and `test_*` versions. 142 | //! 143 | //! - `debug_requires`/`debug_ensures`/`debug_invariant` use `debug_assert!` 144 | //! internally rather than `assert!` 145 | //! - `test_requires`/`test_ensures`/`test_invariant` guard the `assert!` with an 146 | //! `if cfg!(test)`. 147 | //! This should mostly be used for stating equivalence to "slow but obviously 148 | //! correct" alternative implementations or checks. 149 | //! 150 | //! For example, a merge-sort implementation might look like this 151 | //! ```rust 152 | //! # use contracts::*; 153 | //! # fn is_sorted(x: T) -> bool { true } 154 | //! #[test_ensures(is_sorted(input))] 155 | //! fn merge_sort(input: &mut [T]) { 156 | //! // ... 157 | //! } 158 | //! ``` 159 | //! 160 | //! ## Feature flags 161 | //! 162 | //! Following feature flags are available: 163 | //! - `disable_contracts` - disables all checks and assertions. 164 | //! - `override_debug` - changes all contracts (except `test_` ones) into 165 | //! `debug_*` versions 166 | //! - `override_log` - changes all contracts (except `test_` ones) into a 167 | //! `log::error!()` call if the condition is violated. 168 | //! No abortion happens. 169 | //! - `mirai_assertions` - instead of regular assert! style macros, emit macros 170 | //! used by the [MIRAI] static analyzer. 171 | //! 172 | //! [dbc]: https://en.wikipedia.org/wiki/Design_by_contract 173 | //! [`libhoare`]: https://github.com/nrc/libhoare 174 | //! [precond]: attr.requires.html 175 | //! [postcond]: attr.ensures.html 176 | //! [invariant]: attr.invariant.html 177 | //! [MIRAI]: https://github.com/facebookexperimental/MIRAI 178 | 179 | extern crate proc_macro; 180 | 181 | mod implementation; 182 | 183 | use implementation::ContractMode; 184 | use proc_macro::TokenStream; 185 | 186 | /// Pre-conditions are checked before the function body is run. 187 | /// 188 | /// ## Example 189 | /// 190 | /// ```rust 191 | /// # use contracts::*; 192 | /// #[requires(elems.len() >= 1)] 193 | /// fn max(elems: &[T]) -> T { 194 | /// // ... 195 | /// # unimplemented!() 196 | /// } 197 | /// ``` 198 | #[proc_macro_attribute] 199 | pub fn requires(attr: TokenStream, toks: TokenStream) -> TokenStream { 200 | let attr = attr.into(); 201 | let toks = toks.into(); 202 | implementation::requires(ContractMode::Always, attr, toks).into() 203 | } 204 | 205 | /// Same as [`requires`], but uses `debug_assert!`. 206 | /// 207 | /// [`requires`]: attr.requires.html 208 | #[proc_macro_attribute] 209 | pub fn debug_requires(attr: TokenStream, toks: TokenStream) -> TokenStream { 210 | let attr = attr.into(); 211 | let toks = toks.into(); 212 | implementation::requires(ContractMode::Debug, attr, toks).into() 213 | } 214 | 215 | /// Same as [`requires`], but is only enabled in `#[cfg(test)]` environments. 216 | /// 217 | /// [`requires`]: attr.requires.html 218 | #[proc_macro_attribute] 219 | pub fn test_requires(attr: TokenStream, toks: TokenStream) -> TokenStream { 220 | let attr = attr.into(); 221 | let toks = toks.into(); 222 | implementation::requires(ContractMode::Test, attr, toks).into() 223 | } 224 | 225 | /// Post-conditions are checked after the function body is run. 226 | /// 227 | /// The result of the function call is accessible in conditions using the `ret` 228 | /// identifier. 229 | /// 230 | /// A "pseudo-function" named `old` can be used to evaluate expressions in a 231 | /// context *prior* to function execution. 232 | /// This function takes only a single argument and the result of it will be 233 | /// stored in a variable before the function is called. Because of this, 234 | /// handling references might require special care. 235 | /// 236 | /// ## Examples 237 | /// 238 | /// ```rust 239 | /// # use contracts::*; 240 | /// #[ensures(ret > x)] 241 | /// fn incr(x: usize) -> usize { 242 | /// x + 1 243 | /// } 244 | /// ``` 245 | /// 246 | /// ```rust 247 | /// # use contracts::*; 248 | /// #[ensures(*x == old(*x) + 1, "x is incremented")] 249 | /// fn incr(x: &mut usize) { 250 | /// *x += 1; 251 | /// } 252 | /// ``` 253 | #[proc_macro_attribute] 254 | pub fn ensures(attr: TokenStream, toks: TokenStream) -> TokenStream { 255 | let attr = attr.into(); 256 | let toks = toks.into(); 257 | implementation::ensures(ContractMode::Always, attr, toks).into() 258 | } 259 | 260 | /// Same as [`ensures`], but uses `debug_assert!`. 261 | /// 262 | /// [`ensures`]: attr.ensures.html 263 | #[proc_macro_attribute] 264 | pub fn debug_ensures(attr: TokenStream, toks: TokenStream) -> TokenStream { 265 | let attr = attr.into(); 266 | let toks = toks.into(); 267 | implementation::ensures(ContractMode::Debug, attr, toks).into() 268 | } 269 | 270 | /// Same as [`ensures`], but is only enabled in `#[cfg(test)]` environments. 271 | /// 272 | /// [`ensures`]: attr.ensures.html 273 | #[proc_macro_attribute] 274 | pub fn test_ensures(attr: TokenStream, toks: TokenStream) -> TokenStream { 275 | let attr = attr.into(); 276 | let toks = toks.into(); 277 | implementation::ensures(ContractMode::Test, attr, toks).into() 278 | } 279 | 280 | /// Invariants are conditions that have to be maintained at the "interface 281 | /// boundaries". 282 | /// 283 | /// Invariants can be supplied to functions (and "methods"), as well as on 284 | /// `impl` blocks. 285 | /// 286 | /// When applied to an `impl`-block all methods taking `self` (either by value 287 | /// or reference) will be checked for the invariant. 288 | /// 289 | /// ## Example 290 | /// 291 | /// On a function: 292 | /// 293 | /// ```rust 294 | /// # use contracts::*; 295 | /// /// Update `num` to the next bigger even number. 296 | /// #[invariant(*num % 2 == 0)] 297 | /// fn advance_even(num: &mut usize) { 298 | /// *num += 2; 299 | /// } 300 | /// ``` 301 | /// 302 | /// On an `impl`-block: 303 | /// 304 | /// ```rust 305 | /// # use contracts::*; 306 | /// struct EvenAdder { 307 | /// count: usize, 308 | /// } 309 | /// 310 | /// #[invariant(self.count % 2 == 0)] 311 | /// impl EvenAdder { 312 | /// pub fn tell(&self) -> usize { 313 | /// self.count 314 | /// } 315 | /// 316 | /// pub fn advance(&mut self) { 317 | /// self.count += 2; 318 | /// } 319 | /// } 320 | /// ``` 321 | #[proc_macro_attribute] 322 | pub fn invariant(attr: TokenStream, toks: TokenStream) -> TokenStream { 323 | // Invariant attributes might apply to `impl` blocks as well, where the same 324 | // level is simply replicated on all methods. 325 | // Function expansions will resolve the actual mode themselves, so the 326 | // actual "raw" mode is passed here 327 | // 328 | // TODO: update comment when implemented for traits 329 | let attr = attr.into(); 330 | let toks = toks.into(); 331 | let mode = ContractMode::Always; 332 | implementation::invariant(mode, attr, toks).into() 333 | } 334 | 335 | /// Same as [`invariant`], but uses `debug_assert!`. 336 | /// 337 | /// [`invariant`]: attr.invariant.html 338 | #[proc_macro_attribute] 339 | pub fn debug_invariant(attr: TokenStream, toks: TokenStream) -> TokenStream { 340 | let mode = ContractMode::Debug; 341 | let attr = attr.into(); 342 | let toks = toks.into(); 343 | implementation::invariant(mode, attr, toks).into() 344 | } 345 | 346 | /// Same as [`invariant`], but is only enabled in `#[cfg(test)]` environments. 347 | /// 348 | /// [`invariant`]: attr.invariant.html 349 | #[proc_macro_attribute] 350 | pub fn test_invariant(attr: TokenStream, toks: TokenStream) -> TokenStream { 351 | let mode = ContractMode::Test; 352 | let attr = attr.into(); 353 | let toks = toks.into(); 354 | implementation::invariant(mode, attr, toks).into() 355 | } 356 | 357 | /// A "contract_trait" is a trait which ensures all implementors respect all 358 | /// provided contracts. 359 | /// 360 | /// When this attribute is applied to a `trait` definition, the trait gets 361 | /// modified so that all invocations of methods are checked. 362 | /// 363 | /// When this attribute is applied to an `impl Trait for Type` item, the 364 | /// implementation gets modified so it matches the trait definition. 365 | /// 366 | /// **When the `#[contract_trait]` is not applied to either the trait or an 367 | /// `impl` it will cause compile errors**. 368 | /// 369 | /// ## Example 370 | /// 371 | /// ```rust 372 | /// # use contracts::*; 373 | /// #[contract_trait] 374 | /// trait MyRandom { 375 | /// #[requires(min < max)] 376 | /// #[ensures(min <= ret, ret <= max)] 377 | /// fn gen(min: f64, max: f64) -> f64; 378 | /// } 379 | /// 380 | /// // Not a very useful random number generator, but a valid one! 381 | /// struct AlwaysMax; 382 | /// 383 | /// #[contract_trait] 384 | /// impl MyRandom for AlwaysMax { 385 | /// fn gen(min: f64, max: f64) -> f64 { 386 | /// max 387 | /// } 388 | /// } 389 | /// ``` 390 | #[proc_macro_attribute] 391 | pub fn contract_trait(attrs: TokenStream, toks: TokenStream) -> TokenStream { 392 | let attrs: proc_macro2::TokenStream = attrs.into(); 393 | let toks: proc_macro2::TokenStream = toks.into(); 394 | 395 | let item: syn::Item = syn::parse_quote!(#toks); 396 | 397 | let tts = match item { 398 | syn::Item::Trait(trait_) => implementation::contract_trait_item_trait(attrs, trait_), 399 | syn::Item::Impl(impl_) => { 400 | assert!( 401 | impl_.trait_.is_some(), 402 | "#[contract_trait] can only be applied to `trait` and `impl ... for` items" 403 | ); 404 | implementation::contract_trait_item_impl(attrs, impl_) 405 | } 406 | _ => panic!("#[contract_trait] can only be applied to `trait` and `impl ... for` items"), 407 | }; 408 | 409 | tts.into() 410 | } 411 | -------------------------------------------------------------------------------- /tests/functions.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | //! Testing of simple functions. 6 | 7 | use contracts::*; 8 | 9 | #[cfg(feature = "mirai_assertions")] 10 | mod mirai_assertion_mocks; 11 | 12 | #[test] 13 | fn test_a_thing() { 14 | #[requires(x > 10, x < 20, "x must be in valid range")] 15 | #[ensures(ret > x, "result will be bigger than input")] 16 | fn a(x: usize) -> usize { 17 | x + 1 18 | } 19 | 20 | a(15); 21 | } 22 | 23 | #[test] 24 | fn test_sort() { 25 | fn is_sorted(input: &[usize]) -> bool { 26 | if input.len() < 2 { 27 | return true; 28 | } 29 | 30 | for i in 1..input.len() { 31 | if input[i - 1] > input[i] { 32 | return false; 33 | } 34 | } 35 | 36 | true 37 | } 38 | 39 | #[ensures(ret.len() == input.len())] 40 | #[test_ensures(is_sorted(&ret))] 41 | fn sort(input: &[usize]) -> Vec { 42 | let mut vec = input.to_owned(); 43 | 44 | vec.sort_unstable(); 45 | 46 | vec 47 | } 48 | 49 | let input = vec![31, 234, 34, 0, 4234, 85]; 50 | 51 | sort(&input); 52 | } 53 | 54 | #[test] 55 | fn test_invariant() { 56 | #[invariant(*val <= 10)] 57 | fn add_to_10(val: &mut usize) { 58 | if *val >= 10 { 59 | return; 60 | } 61 | *val += 1; 62 | } 63 | 64 | let mut val = 8; 65 | 66 | add_to_10(&mut val); 67 | add_to_10(&mut val); 68 | add_to_10(&mut val); 69 | add_to_10(&mut val); 70 | add_to_10(&mut val); 71 | } 72 | 73 | #[test] 74 | #[should_panic(expected = "Post-condition of abs violated")] 75 | fn test_early_return() { 76 | // make sure that post-conditions are executed even if an early return happened. 77 | 78 | #[ensures(ret >= 0)] 79 | #[ensures(ret == x || ret == -x)] 80 | #[ensures(ret * ret == x * x)] 81 | fn abs(x: isize) -> isize { 82 | if x < 0 { 83 | // this implementation does not respect the contracts! 84 | return 0; 85 | } 86 | x 87 | } 88 | 89 | abs(-4); 90 | } 91 | 92 | #[test] 93 | fn test_mut_ref_and_lifetimes() { 94 | #[requires(i < s.len())] 95 | #[ensures(*ret == 0)] 96 | fn insert_zero<'a>(s: &'a mut [u8], i: usize) -> &'a mut u8 { 97 | s[i] = 0; 98 | &mut s[i] 99 | } 100 | 101 | insert_zero(&mut [4, 2], 1); 102 | } 103 | 104 | #[test] 105 | fn test_pattern_match() { 106 | #[ensures(ret > a && ret > b)] 107 | fn add((a, b): (u8, u8)) -> u8 { 108 | a.saturating_add(b) 109 | } 110 | 111 | assert_eq!(add((4, 2)), 6); 112 | } 113 | 114 | #[test] 115 | fn test_impl_trait_return() { 116 | // make sure that compiling functions that return existentially 117 | // qualified types works properly. 118 | 119 | #[requires(x >= 10)] 120 | #[ensures(Clone::clone(&ret) == ret)] 121 | #[allow(unused_variables)] 122 | fn impl_test(x: isize) -> impl Clone + PartialEq + std::fmt::Debug { 123 | "it worked" 124 | } 125 | 126 | let x = impl_test(200); 127 | let y = x.clone(); 128 | assert_eq!( 129 | format!("{:?} and {:?}", x, y), 130 | r#""it worked" and "it worked""# 131 | ); 132 | } 133 | 134 | #[test] 135 | fn test_impl_trait_arg() { 136 | #[requires(Clone::clone(&x) == x)] 137 | #[ensures(Clone::clone(&ret) == ret)] 138 | fn impl_test(x: impl Clone + PartialEq + std::fmt::Debug) -> &'static str { 139 | "it worked" 140 | } 141 | 142 | let x = impl_test(200); 143 | let y = Clone::clone(&x); 144 | assert_eq!( 145 | format!("{:?} and {:?}", x, y), 146 | r#""it worked" and "it worked""# 147 | ); 148 | } 149 | 150 | #[allow(unused)] 151 | #[test] 152 | #[deny(clippy::used_underscore_binding)] 153 | fn test_unbound_parameters_clippy() { 154 | #[requires(__y == 3)] 155 | #[ensures(ret)] 156 | fn param_test(_x: i32, __y: i32) -> bool { 157 | true 158 | } 159 | } 160 | 161 | #[allow(unused)] 162 | #[test] 163 | #[deny(non_fmt_panics)] 164 | fn test_braced_condition_expression_clippy() { 165 | #[requires(if __y == 3 { 166 | __y != 0 167 | } else { 168 | false 169 | })] 170 | fn param_test(_x: i32, __y: i32) {} 171 | } 172 | -------------------------------------------------------------------------------- /tests/implication.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use contracts::*; 6 | 7 | #[cfg(feature = "mirai_assertions")] 8 | mod mirai_assertion_mocks; 9 | 10 | #[test] 11 | fn test_ret_implication() { 12 | #[ensures(do_thing -> ret.is_some(), "do_thing should cause a Some(_)")] 13 | #[ensures(!do_thing -> ret.is_none(), "!do_thing should cause a None")] 14 | fn perform_thing(do_thing: bool) -> Option { 15 | if do_thing { 16 | Some(12) 17 | } else { 18 | None 19 | } 20 | } 21 | 22 | perform_thing(true); 23 | perform_thing(false); 24 | } 25 | 26 | #[test] 27 | fn test_ret_implication_old() { 28 | #[ensures(old(*x) % 2 == 0 -> *x % 2 == 0)] 29 | #[ensures(old(*x) % 2 == 1 -> *x % 2 == 1)] 30 | fn incr(x: &mut usize) { 31 | *x += 2; 32 | } 33 | 34 | let mut x = 0; 35 | incr(&mut x); 36 | 37 | let mut x = 1; 38 | incr(&mut x); 39 | } 40 | 41 | #[test] 42 | fn test_requires_implication() { 43 | #[requires(!negative -> value >= 0)] 44 | #[requires(negative -> value < 0)] 45 | fn thing(negative: bool, value: isize) {} 46 | 47 | thing(true, -123); 48 | 49 | thing(false, 123); 50 | } 51 | 52 | #[test] 53 | #[should_panic(expected = "Post")] 54 | fn test_failing_implication() { 55 | #[ensures(t -> ret)] 56 | #[allow(unused_variables)] 57 | fn only_true(t: bool) -> bool { 58 | false // oops 59 | } 60 | 61 | only_true(true); 62 | } 63 | 64 | #[test] 65 | fn test_nested_implication() { 66 | #[ensures(a -> b -> ret.is_some())] 67 | fn test(a: bool, b: bool) -> Option { 68 | if a { 69 | if b { 70 | Some(9) 71 | } else { 72 | Some(3) 73 | } 74 | } else { 75 | None 76 | } 77 | } 78 | 79 | test(true, false); 80 | test(false, true); 81 | test(true, true); 82 | } 83 | -------------------------------------------------------------------------------- /tests/issues.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused)] // compile-only test 2 | #[test] 3 | fn gl_issue_11() { 4 | use contracts::ensures; 5 | 6 | struct Test; 7 | 8 | impl Test { 9 | pub fn contains_key(&self, key: &str) -> bool { 10 | todo!() 11 | } 12 | 13 | #[ensures(self.contains_key(key) -> ret.is_some())] 14 | #[ensures(!self.contains_key(key) -> ret.is_none())] 15 | pub fn get_mut(&mut self, key: &str) -> Option<&mut u8> { 16 | None 17 | } 18 | } 19 | } 20 | 21 | #[allow(unused)] // compile-only test 22 | #[test] 23 | fn gl_issue_16() { 24 | use std::fmt::Debug; 25 | 26 | use contracts::debug_ensures; 27 | 28 | trait Sortable { 29 | fn insertion_sort(&mut self); 30 | } 31 | 32 | // TODO(MSRV 1.82): remove and use std's [T].is_sorted() 33 | fn is_sorted(s: &[T]) -> bool { 34 | s.windows(2).all(|w| w[0] <= w[1]) 35 | } 36 | 37 | impl Sortable for Vec { 38 | #[debug_ensures(is_sorted(self))] 39 | fn insertion_sort(&mut self) { 40 | assert!(self[0] < self[1]); 41 | } 42 | } 43 | } 44 | 45 | #[allow(unused, clippy::assertions_on_constants)] // compile-only test 46 | #[test] 47 | fn gl_issue_17() { 48 | use std::future::pending; 49 | 50 | use contracts::ensures; 51 | 52 | #[ensures(true)] 53 | async fn foo() { 54 | pending::<()>().await; 55 | } 56 | } 57 | 58 | #[test] 59 | fn gl_issue_18() { 60 | use std::ops::{Div, Mul, Rem, Sub}; 61 | 62 | // use contracts::ensures; // <- unused warning 63 | use contracts::requires; 64 | 65 | trait Zero { 66 | fn zero() -> Self; 67 | } 68 | 69 | impl Zero for u32 { 70 | fn zero() -> Self { 71 | 0 72 | } 73 | } 74 | 75 | #[requires( n != T::zero() || d != T::zero() )] 76 | #[ensures( ret != T::zero() && n % ret == T::zero() && d % ret == T::zero() )] 77 | fn euclidean(n: T, d: T) -> T 78 | where 79 | T: Sub 80 | + Mul 81 | + Div 82 | + Rem 83 | + Ord 84 | + Zero 85 | + Copy, 86 | { 87 | let (mut a, mut b) = (n.max(d), n.min(d)); 88 | while b != T::zero() { 89 | let q: T = a / b; 90 | let r: T = a - q * b; 91 | a = b; 92 | b = r; 93 | } 94 | a 95 | } 96 | 97 | assert_eq!(1, euclidean(3, 4)); 98 | } 99 | -------------------------------------------------------------------------------- /tests/methods.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | //! Testing of methods and `impl`-blocks. 6 | 7 | use contracts::*; 8 | 9 | #[cfg(feature = "mirai_assertions")] 10 | mod mirai_assertion_mocks; 11 | 12 | #[test] 13 | fn methods() { 14 | fn is_even(x: usize) -> bool { 15 | x % 2 == 0 16 | } 17 | 18 | struct EvenAdder { 19 | count: usize, 20 | } 21 | 22 | impl EvenAdder { 23 | #[invariant(is_even(self.count))] 24 | #[ensures(self.count == old(self.count) + 2)] 25 | fn next_even(&mut self) { 26 | self.count += 2; 27 | } 28 | 29 | // Manually express the invariant in terms of `ret` since `self.count` is mutably borrowed. 30 | #[requires(is_even(self.count))] 31 | #[ensures(is_even(*ret))] 32 | #[ensures(*ret == old(self.count) + 2)] 33 | fn next_even_and_get<'a>(&'a mut self) -> &'a mut usize { 34 | self.count += 2; 35 | &mut self.count 36 | } 37 | 38 | #[invariant(is_even(self.count))] 39 | #[requires(self.count >= 2)] 40 | #[ensures(self.count == old(self.count) - 2)] 41 | fn prev_even(&mut self) { 42 | self.count -= 2; 43 | } 44 | 45 | #[allow(dead_code)] 46 | #[invariant(is_even(self.count))] 47 | fn this_var_collision(&mut self) -> usize { 48 | #[allow(unused_variables)] 49 | let (this, this__) = (42, 42); 50 | self.count 51 | } 52 | } 53 | 54 | let mut adder = EvenAdder { count: 0 }; 55 | 56 | adder.next_even(); 57 | adder.next_even(); 58 | 59 | adder.prev_even(); 60 | adder.prev_even(); 61 | 62 | assert_eq!(*adder.next_even_and_get(), 2); 63 | } 64 | 65 | #[test] 66 | fn impl_invariant() { 67 | fn is_even(x: usize) -> bool { 68 | x % 2 == 0 69 | } 70 | 71 | struct EvenAdder { 72 | count: usize, 73 | } 74 | 75 | #[invariant(is_even(self.count), "Count has to always be even")] 76 | impl EvenAdder { 77 | const fn step() -> usize { 78 | 2 79 | } 80 | 81 | fn new() -> Self { 82 | EvenAdder { count: 0 } 83 | } 84 | 85 | #[ensures(self.count == old(self.count) + 2)] 86 | fn next_even(&mut self) { 87 | self.count += Self::step(); 88 | } 89 | 90 | #[requires(self.count >= 2)] 91 | #[ensures(self.count == old(self.count) - 2)] 92 | fn prev_even(&mut self) { 93 | self.count -= Self::step(); 94 | } 95 | } 96 | 97 | let mut adder = EvenAdder::new(); 98 | 99 | adder.next_even(); 100 | adder.next_even(); 101 | 102 | adder.prev_even(); 103 | adder.prev_even(); 104 | } 105 | 106 | #[test] 107 | fn test_self_macro_hygiene() { 108 | struct S { 109 | value: i32, 110 | } 111 | 112 | // Use a macro to generate the function impl 113 | // This requires strict hygiene of the `self` receiver 114 | macro_rules! __impl { 115 | ( 116 | $(#[$metas:meta])* 117 | fn $function:ident(&mut $this:ident, $value:ident: $ty:ty) 118 | $body:block 119 | ) => { 120 | $(#[$metas])* 121 | fn $function(&mut $this, $value: $ty) 122 | $body 123 | }; 124 | } 125 | 126 | impl S { 127 | __impl! { 128 | #[ensures(self.value == old(value))] 129 | fn set_value(&mut self, value: i32) { 130 | self.value = value; 131 | } 132 | } 133 | } 134 | 135 | let mut s = S { value: 24 }; 136 | s.set_value(42); 137 | assert_eq!(s.value, 42); 138 | } 139 | -------------------------------------------------------------------------------- /tests/mirai_assertion_mocks/mod.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | */ 5 | 6 | #[macro_export] 7 | macro_rules! debug_checked_precondition { 8 | ($condition:expr, $($arg:tt)*) => ( debug_assert!($condition, $($arg)*); ); 9 | } 10 | 11 | #[macro_export] 12 | macro_rules! debug_checked_postcondition { 13 | ($condition:expr, $($arg:tt)*) => ( debug_assert!($condition, $($arg)*); ); 14 | } 15 | 16 | #[macro_export] 17 | macro_rules! checked_precondition { 18 | ($condition:expr, $($arg:tt)*) => ( assert!($condition, $($arg)*); ); 19 | } 20 | 21 | #[macro_export] 22 | macro_rules! checked_postcondition { 23 | ($condition:expr, $($arg:tt)*) => ( assert!($condition, $($arg)*); ); 24 | } 25 | -------------------------------------------------------------------------------- /tests/old.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use contracts::*; 6 | 7 | #[cfg(feature = "mirai_assertions")] 8 | mod mirai_assertion_mocks; 9 | 10 | #[test] 11 | fn test_old_simple() { 12 | #[ensures(*x == old(*x) + 1, "x increments")] 13 | fn incr(x: &mut usize) { 14 | *x += 1; 15 | } 16 | 17 | let mut val = 0; 18 | incr(&mut val); 19 | } 20 | 21 | #[test] 22 | fn test_old_nested() { 23 | #[ensures(*x == old(old(old(*x))) + 1, "x increments")] 24 | fn incr(x: &mut usize) { 25 | *x += 1; 26 | } 27 | 28 | let mut val = 0; 29 | incr(&mut val); 30 | } 31 | 32 | #[test] 33 | #[should_panic(expected = "Post-condition of incr violated")] 34 | fn test_violation() { 35 | #[ensures(*x == old(*x) + 1, "x increments")] 36 | fn incr(x: &mut usize) { 37 | *x += 0; // oops 38 | } 39 | 40 | let mut val = 0; 41 | incr(&mut val); 42 | } 43 | -------------------------------------------------------------------------------- /tests/ranged_int.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | //! Test implementing a `RangedInt` type. 6 | 7 | use std::ops::{Add, Deref}; 8 | 9 | use contracts::*; 10 | 11 | #[cfg(feature = "mirai_assertions")] 12 | mod mirai_assertion_mocks; 13 | 14 | #[derive(Copy, Clone, Debug)] 15 | pub struct Range { 16 | min: usize, 17 | max: usize, 18 | } 19 | 20 | impl Range { 21 | #[requires(min < max)] 22 | pub fn new(min: usize, max: usize) -> Self { 23 | Range { min, max } 24 | } 25 | 26 | #[ensures(ret.min == self.min.min(other.min))] 27 | #[ensures(ret.max == self.max.max(other.max))] 28 | pub fn merge(self, other: Range) -> Range { 29 | let min = self.min.min(other.min); 30 | let max = self.max.max(other.max); 31 | 32 | Range::new(min, max) 33 | } 34 | 35 | pub fn contains(self, val: usize) -> bool { 36 | self.min <= val && val <= self.max 37 | } 38 | } 39 | 40 | #[derive(Copy, Clone, Debug)] 41 | pub struct RangedInt { 42 | range: Range, 43 | value: usize, 44 | } 45 | 46 | #[invariant(self.range.contains(self.value))] 47 | impl RangedInt { 48 | #[requires(range.contains(val))] 49 | pub fn new(range: Range, val: usize) -> Self { 50 | RangedInt { range, value: val } 51 | } 52 | 53 | pub fn to_usize(self) -> usize { 54 | self.value 55 | } 56 | 57 | pub fn range(self) -> Range { 58 | self.range 59 | } 60 | 61 | #[ensures(ret.range.contains(ret.value))] 62 | pub fn extend(self, range: Range) -> Self { 63 | let new_range = self.range.merge(range); 64 | 65 | RangedInt::new(new_range, self.value) 66 | } 67 | } 68 | 69 | impl Add for RangedInt { 70 | type Output = RangedInt; 71 | 72 | #[requires(self.range.merge(rhs.range).contains(self.value + rhs.value))] 73 | #[ensures(ret.range.contains(ret.value))] 74 | #[ensures(ret.value == self.value + rhs.value)] 75 | fn add(self, rhs: Self) -> Self::Output { 76 | let mut new_ranged = self.extend(rhs.range); 77 | 78 | new_ranged.value += rhs.value; 79 | 80 | new_ranged 81 | } 82 | } 83 | 84 | impl Add for RangedInt { 85 | type Output = RangedInt; 86 | 87 | #[requires(self.range.contains(rhs))] 88 | #[ensures(ret.value == self.value + rhs)] 89 | fn add(self, rhs: usize) -> Self::Output { 90 | let mut new = self; 91 | new.value += rhs; 92 | new 93 | } 94 | } 95 | 96 | impl Deref for RangedInt { 97 | type Target = usize; 98 | 99 | fn deref(&self) -> &Self::Target { 100 | &self.value 101 | } 102 | } 103 | 104 | #[test] 105 | fn ranged_int_add() { 106 | let days = RangedInt::new(Range::new(0, 6), 0); 107 | 108 | assert_eq!(*days, 0); 109 | 110 | assert_eq!(*(days + 1), 1); 111 | assert_eq!(*(days + 5), 5); 112 | assert_eq!(*(days + 6), 6); 113 | } 114 | 115 | #[test] 116 | fn ranged_int_add_reassign() { 117 | let mut days = RangedInt::new(Range::new(0, 6), 0); 118 | assert_eq!(*days, 0); 119 | 120 | days = days + 3; 121 | assert_eq!(*days, 3); 122 | 123 | days = days + 2; 124 | assert_eq!(*days, 5); 125 | } 126 | 127 | #[test] 128 | #[should_panic(expected = "Pre-condition of add violated")] 129 | fn ranged_overflow() { 130 | let days = RangedInt::new(Range::new(0, 6), 0); 131 | 132 | // cause overflow 133 | let _ = days + 7; 134 | } 135 | 136 | #[test] 137 | #[should_panic(expected = "Pre-condition of new violated")] 138 | fn construction_underflow() { 139 | // value below of permitted range 140 | RangedInt::new(Range::new(4, 6), 0); 141 | } 142 | 143 | #[test] 144 | #[should_panic(expected = "Pre-condition of new violated")] 145 | fn construction_overflow() { 146 | // value above of permitted range 147 | RangedInt::new(Range::new(0, 6), 8); 148 | } 149 | -------------------------------------------------------------------------------- /tests/traits.rs: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | use contracts::*; 6 | 7 | #[cfg(feature = "mirai_assertions")] 8 | mod mirai_assertion_mocks; 9 | 10 | #[test] 11 | fn adder_example() { 12 | #[contract_trait] 13 | trait Adder { 14 | fn tell(&self) -> usize; 15 | 16 | #[requires((self.tell() + val) < 20)] 17 | fn add(&mut self, val: usize); 18 | } 19 | 20 | struct MyAdder(usize); 21 | 22 | #[contract_trait] 23 | impl Adder for MyAdder { 24 | fn tell(&self) -> usize { 25 | self.0 26 | } 27 | 28 | fn add(&mut self, val: usize) { 29 | self.0 += val; 30 | } 31 | } 32 | 33 | let mut add = MyAdder(0); 34 | 35 | add.add(3); 36 | add.add(16); 37 | 38 | // this would violate the contract 39 | // add.add(2); 40 | } 41 | 42 | #[test] 43 | fn interpolate_example() { 44 | #[contract_trait] 45 | trait Interpolate { 46 | #[requires(0.0 <= val, val <= 1.0)] 47 | #[requires(min < max)] 48 | #[ensures(min <= ret, ret <= max)] 49 | fn interpolate(min: f64, max: f64, val: f64) -> f64; 50 | } 51 | 52 | struct Linear; 53 | 54 | #[contract_trait] 55 | impl Interpolate for Linear { 56 | fn interpolate(min: f64, max: f64, val: f64) -> f64 { 57 | min + (val * (max - min)) 58 | } 59 | } 60 | 61 | struct Quadratic; 62 | 63 | #[contract_trait] 64 | impl Interpolate for Quadratic { 65 | fn interpolate(min: f64, max: f64, val: f64) -> f64 { 66 | let val = val * val; 67 | 68 | Linear::interpolate(min, max, val) 69 | } 70 | } 71 | 72 | let min = 12.00; 73 | let max = 24.00; 74 | 75 | let val = 0.4; 76 | 77 | Linear::interpolate(min, max, val); 78 | Quadratic::interpolate(min, max, val); 79 | } 80 | --------------------------------------------------------------------------------