From 3f6928f1f6eff367e6ddbfb63ebc5e568ffe0eb1 Mon Sep 17 00:00:00 2001 From: mark Date: Wed, 17 Jun 2020 14:25:00 -0500 Subject: [PATCH 01/12] move contributing.md to rustc-dev-guide and point at getting started --- CONTRIBUTING.md | 527 +----------------------------------------------- README.md | 29 +-- 2 files changed, 11 insertions(+), 545 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9c4afcefa1f22..373604adb0541 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,529 +1,8 @@ # Contributing to Rust -[contributing-to-rust]: #contributing-to-rust -Thank you for your interest in contributing to Rust! There are many ways to -contribute, and we appreciate all of them. This document is a bit long, so here's -links to the major sections: +Thank you for your interest in contributing to Rust! -* [Feature Requests](#feature-requests) -* [Bug Reports](#bug-reports) -* [The Build System](#the-build-system) -* [Pull Requests](#pull-requests) -* [Writing Documentation](#writing-documentation) -* [Issue Triage](#issue-triage) -* [Out-of-tree Contributions](#out-of-tree-contributions) -* [Helpful Links and Information](#helpful-links-and-information) +To get started, read the [Getting Started] guide in the [rustc-dev-guide]. -If you have questions, please make a post on [internals.rust-lang.org][internals] or -hop on the [Rust Discord server][rust-discord] or [Rust Zulip server][rust-zulip]. - -As a reminder, all contributors are expected to follow our [Code of Conduct][coc]. - -The [rustc-dev-guide] is your friend! It describes how the compiler works and how -to contribute to it in more detail than this document. - -If this is your first time contributing, the [walkthrough] chapter of the guide -can give you a good example of how a typical contribution would go. - -[internals]: https://internals.rust-lang.org -[rust-discord]: http://discord.gg/rust-lang -[rust-zulip]: https://rust-lang.zulipchat.com -[coc]: https://www.rust-lang.org/conduct.html +[Getting Started]: https://rustc-dev-guide.rust-lang.org/getting-started.md [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/ -[walkthrough]: https://rustc-dev-guide.rust-lang.org/walkthrough.html - -## Feature Requests -[feature-requests]: #feature-requests - -To request a change to the way the Rust language works, please head over -to the [RFCs repository](https://github.com/rust-lang/rfcs) and view the -[README](https://github.com/rust-lang/rfcs/blob/master/README.md) -for instructions. - -## Bug Reports -[bug-reports]: #bug-reports - -While bugs are unfortunate, they're a reality in software. We can't fix what we -don't know about, so please report liberally. If you're not sure if something -is a bug or not, feel free to file a bug anyway. - -**If you believe reporting your bug publicly represents a security risk to Rust users, -please follow our [instructions for reporting security vulnerabilities](https://www.rust-lang.org/policies/security)**. - -If you're using the nightly channel, please check if the bug exists in the -latest toolchain before filing your bug. It might be fixed already. - -If you have the chance, before reporting a bug, please [search existing -issues](https://github.com/rust-lang/rust/search?q=&type=Issues&utf8=%E2%9C%93), -as it's possible that someone else has already reported your error. This doesn't -always work, and sometimes it's hard to know what to search for, so consider this -extra credit. We won't mind if you accidentally file a duplicate report. - -Similarly, to help others who encountered the bug find your issue, -consider filing an issue with a descriptive title, which contains information that might be unique to it. -This can be the language or compiler feature used, the conditions that trigger the bug, -or part of the error message if there is any. -An example could be: **"impossible case reached" on lifetime inference for impl Trait in return position**. - -Opening an issue is as easy as following [this -link](https://github.com/rust-lang/rust/issues/new) and filling out the fields. -Here's a template that you can use to file a bug, though it's not necessary to -use it exactly: - - - - I tried this code: - - - - I expected to see this happen: - - Instead, this happened: - - ## Meta - - `rustc --version --verbose`: - - Backtrace: - -All three components are important: what you did, what you expected, what -happened instead. Please include the output of `rustc --version --verbose`, -which includes important information about what platform you're on, what -version of Rust you're using, etc. - -Sometimes, a backtrace is helpful, and so including that is nice. To get -a backtrace, set the `RUST_BACKTRACE` environment variable to a value -other than `0`. The easiest way -to do this is to invoke `rustc` like this: - -```bash -$ RUST_BACKTRACE=1 rustc ... -``` - -## The Build System - -For info on how to configure and build the compiler, please see [this -chapter][rustcguidebuild] of the rustc-dev-guide. This chapter contains info for -contributions to the compiler and the standard library. It also lists some -really useful commands to the build system (`./x.py`), which could save you a -lot of time. - -[rustcguidebuild]: https://rustc-dev-guide.rust-lang.org/building/how-to-build-and-run.html - -## Pull Requests -[pull-requests]: #pull-requests - -Pull requests are the primary mechanism we use to change Rust. GitHub itself -has some [great documentation][about-pull-requests] on using the Pull Request feature. -We use the "fork and pull" model [described here][development-models], where -contributors push changes to their personal fork and create pull requests to -bring those changes into the source repository. - -[about-pull-requests]: https://help.github.com/articles/about-pull-requests/ -[development-models]: https://help.github.com/articles/about-collaborative-development-models/ - -Please make pull requests against the `master` branch. - -Rust follows a no merge policy, meaning, when you encounter merge -conflicts you are expected to always rebase instead of merge. -E.g. always use rebase when bringing the latest changes from -the master branch to your feature branch. -Also, please make sure that fixup commits are squashed into other related -commits with meaningful commit messages. - -GitHub allows [closing issues using keywords][closing-keywords]. This feature -should be used to keep the issue tracker tidy. However, it is generally preferred -to put the "closes #123" text in the PR description rather than the issue commit; -particularly during rebasing, citing the issue number in the commit can "spam" -the issue in question. - -[closing-keywords]: https://help.github.com/en/articles/closing-issues-using-keywords - -Please make sure your pull request is in compliance with Rust's style -guidelines by running - - $ python x.py test tidy - -Make this check before every pull request (and every new commit in a pull -request); you can add [git hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) -before every push to make sure you never forget to make this check. - -All pull requests are reviewed by another person. We have a bot, -[@rust-highfive][rust-highfive], that will automatically assign a random person to review your -request. - -If you want to request that a specific person reviews your pull request, -you can add an `r?` to the pull request description. For example, [Steve][steveklabnik] usually reviews -documentation changes. So if you were to make a documentation change, add - - r? @steveklabnik - -to the end of the pull request description, and [@rust-highfive][rust-highfive] will assign -[@steveklabnik][steveklabnik] instead of a random person. This is entirely optional. - -After someone has reviewed your pull request, they will leave an annotation -on the pull request with an `r+`. It will look something like this: - - @bors r+ - -This tells [@bors][bors], our lovable integration bot, that your pull request has -been approved. The PR then enters the [merge queue][merge-queue], where [@bors][bors] -will run all the tests on every platform we support. If it all works out, -[@bors][bors] will merge your code into `master` and close the pull request. - -Depending on the scale of the change, you may see a slightly different form of `r+`: - - @bors r+ rollup - -The additional `rollup` tells [@bors][bors] that this change is eligible for to be -"rolled up". Changes that are rolled up are tested and merged at the same time, to -speed the process up. Typically only small changes that are expected not to conflict -with one another are rolled up. - -[rust-highfive]: https://github.com/rust-highfive -[steveklabnik]: https://github.com/steveklabnik -[bors]: https://github.com/bors -[merge-queue]: https://buildbot2.rust-lang.org/homu/queue/rust - -Speaking of tests, Rust has a comprehensive test suite. More information about -it can be found [here][rctd]. - -### External Dependencies (subtree) - -As a developer to this repository, you don't have to treat the following external projects -differently from other crates that are directly in this repo: - -* Clippy - -They are just regular files and directories. This is in contrast to `submodule` dependencies -(see below for those). Only tool authors will actually use any operations here. - -#### Synchronizing a subtree - -There are two synchronization directions: `subtree push` and `subtree pull`. - -``` -git subtree push -P src/tools/clippy git@github.com:your-github-name/rust-clippy sync-from-rust -``` - -takes all the changes that -happened to the copy in this repo and creates commits on the remote repo that match the local -changes. Every local commit that touched the subtree causes a commit on the remote repo, but is -modified to move the files from the specified directory to the tool repo root. - -Make sure to not pick the `master` branch on the tool repo, so you can open a normal PR to the tool -to merge that subrepo push. - -``` -git subtree pull -P src/tools/clippy https://github.com/rust-lang/rust-clippy master -``` - -takes all changes since the last `subtree pull` from the tool repo -repo and adds these commits to the rustc repo + a merge commit that moves the tool changes into -the specified directory in the rust repository. - -It is recommended that you always do a push first and get that merged to the tool master branch. -Then, when you do a pull, the merge works without conflicts. -While it's definitely possible to resolve conflicts during a pull, you may have to redo the conflict -resolution if your PR doesn't get merged fast enough and there are new conflicts. Do not try to -rebase the result of a `git subtree pull`, rebasing merge commits is a bad idea in general. - -You always need to specify the `-P` prefix to the subtree directory and the corresponding remote -repository. If you specify the wrong directory or repository -you'll get very fun merges that try to push the wrong directory to the wrong remote repository. -Luckily you can just abort this without any consequences by throwing away either the pulled commits -in rustc or the pushed branch on the remote and try again. It is usually fairly obvious -that this is happening because you suddenly get thousands of commits that want to be synchronized. - -#### Creating a new subtree dependency - -If you want to create a new subtree dependency from an existing repository, call (from this -repository's root directory!) - -``` -git subtree add -P src/tools/clippy https://github.com/rust-lang/rust-clippy.git master -``` - -This will create a new commit, which you may not rebase under any circumstances! Delete the commit -and redo the operation if you need to rebase. - -Now you're done, the `src/tools/clippy` directory behaves as if Clippy were part of the rustc -monorepo, so no one but you (or others that synchronize subtrees) actually needs to use `git subtree`. - - -### External Dependencies (submodules) - -Currently building Rust will also build the following external projects: - -* [miri](https://github.com/rust-lang/miri) -* [rustfmt](https://github.com/rust-lang/rustfmt) -* [rls](https://github.com/rust-lang/rls/) - -We allow breakage of these tools in the nightly channel. Maintainers of these -projects will be notified of the breakages and should fix them as soon as -possible. - -After the external is fixed, one could add the changes with - -```sh -git add path/to/submodule -``` - -outside the submodule. - -In order to prepare your tool-fixing PR, you can run the build locally by doing -`./x.py build src/tools/TOOL`. If you will be editing the sources -there, you may wish to set `submodules = false` in the `config.toml` -to prevent `x.py` from resetting to the original branch. - -Breakage is not allowed in the beta and stable channels, and must be addressed -before the PR is merged. - -#### Breaking Tools Built With The Compiler - -Rust's build system builds a number of tools that make use of the -internals of the compiler. This includes -[RLS](https://github.com/rust-lang/rls) and -[rustfmt](https://github.com/rust-lang/rustfmt). If these tools -break because of your changes, you may run into a sort of "chicken and egg" -problem. These tools rely on the latest compiler to be built so you can't update -them to reflect your changes to the compiler until those changes are merged into -the compiler. At the same time, you can't get your changes merged into the compiler -because the rust-lang/rust build won't pass until those tools build and pass their -tests. - -That means that, in the default state, you can't update the compiler without first -fixing rustfmt, rls and the other tools that the compiler builds. - -Luckily, a feature was [added to Rust's build](https://github.com/rust-lang/rust/issues/45861) -to make all of this easy to handle. The idea is that we allow these tools to be "broken", -so that the rust-lang/rust build passes without trying to build them, then land the change -in the compiler, wait for a nightly, and go update the tools that you broke. Once you're done -and the tools are working again, you go back in the compiler and update the tools -so they can be distributed again. - -This should avoid a bunch of synchronization dances and is also much easier on contributors as -there's no need to block on rls/rustfmt/other tools changes going upstream. - -Here are those same steps in detail: - -1. (optional) First, if it doesn't exist already, create a `config.toml` by copying - `config.toml.example` in the root directory of the Rust repository. - Set `submodules = false` in the `[build]` section. This will prevent `x.py` - from resetting to the original branch after you make your changes. If you - need to [update any submodules to their latest versions](#updating-submodules), - see the section of this file about that for more information. -2. (optional) Run `./x.py test src/tools/rustfmt` (substituting the submodule - that broke for `rustfmt`). Fix any errors in the submodule (and possibly others). -3. (optional) Make commits for your changes and send them to upstream repositories as a PR. -4. (optional) Maintainers of these submodules will **not** merge the PR. The PR can't be - merged because CI will be broken. You'll want to write a message on the PR referencing - your change, and how the PR should be merged once your change makes it into a nightly. -5. Wait for your PR to merge. -6. Wait for a nightly -7. (optional) Help land your PR on the upstream repository now that your changes are in nightly. -8. (optional) Send a PR to rust-lang/rust updating the submodule. - -#### Updating submodules - -These instructions are specific to updating `rustfmt`, however they may apply -to the other submodules as well. Please help by improving these instructions -if you find any discrepancies or special cases that need to be addressed. - -To update the `rustfmt` submodule, start by running the appropriate -[`git submodule` command](https://git-scm.com/book/en/v2/Git-Tools-Submodules). -For example, to update to the latest commit on the remote master branch, -you may want to run: -``` -git submodule update --remote src/tools/rustfmt -``` -If you run `./x.py build` now, and you are lucky, it may just work. If you see -an error message about patches that did not resolve to any crates, you will need -to complete a few more steps which are outlined with their rationale below. - -*(This error may change in the future to include more information.)* -``` -error: failed to resolve patches for `https://github.com/rust-lang/rustfmt` - -Caused by: - patch for `rustfmt-nightly` in `https://github.com/rust-lang/rustfmt` did not resolve to any crates -failed to run: ~/rust/build/x86_64-unknown-linux-gnu/stage0/bin/cargo build --manifest-path ~/rust/src/bootstrap/Cargo.toml -``` - -If you haven't used the `[patch]` -section of `Cargo.toml` before, there is [some relevant documentation about it -in the cargo docs](http://doc.crates.io/manifest.html#the-patch-section). In -addition to that, you should read the -[Overriding dependencies](http://doc.crates.io/specifying-dependencies.html#overriding-dependencies) -section of the documentation as well. - -Specifically, the following [section in Overriding dependencies](http://doc.crates.io/specifying-dependencies.html#testing-a-bugfix) reveals what the problem is: - -> Next up we need to ensure that our lock file is updated to use this new version of uuid so our project uses the locally checked out copy instead of one from crates.io. The way [patch] works is that it'll load the dependency at ../path/to/uuid and then whenever crates.io is queried for versions of uuid it'll also return the local version. -> -> This means that the version number of the local checkout is significant and will affect whether the patch is used. Our manifest declared uuid = "1.0" which means we'll only resolve to >= 1.0.0, < 2.0.0, and Cargo's greedy resolution algorithm also means that we'll resolve to the maximum version within that range. Typically this doesn't matter as the version of the git repository will already be greater or match the maximum version published on crates.io, but it's important to keep this in mind! - -This says that when we updated the submodule, the version number in our -`src/tools/rustfmt/Cargo.toml` changed. The new version is different from -the version in `Cargo.lock`, so the build can no longer continue. - -To resolve this, we need to update `Cargo.lock`. Luckily, cargo provides a -command to do this easily. - -``` -$ cargo update -p rustfmt-nightly -``` - -This should change the version listed in `Cargo.lock` to the new version you updated -the submodule to. Running `./x.py build` should work now. - -## Writing Documentation - -Documentation improvements are very welcome. The source of `doc.rust-lang.org` -is located in `src/doc` in the tree, and standard API documentation is generated -from the source code itself. Documentation pull requests function in the same way -as other pull requests. - -To find documentation-related issues, sort by the [T-doc label][tdoc]. - -[tdoc]: https://github.com/rust-lang/rust/issues?q=is%3Aopen%20is%3Aissue%20label%3AT-doc - -You can find documentation style guidelines in [RFC 1574][rfc1574]. - -[rfc1574]: https://github.com/rust-lang/rfcs/blob/master/text/1574-more-api-documentation-conventions.md#appendix-a-full-conventions-text - -In many cases, you don't need a full `./x.py doc`, which will build the entire -stage 2 compiler and compile the various books published on -[doc.rust-lang.org]. When updating documentation for the standard library, -first try `./x.py doc --stage 0 src/libstd`. If that fails, or if you need to -see the output from the latest version of `rustdoc`, use `--stage 1` instead of -`--stage 0`. Results should appear in `build/$TARGET/crate-docs`. - -[doc.rust-lang.org]: htts://doc.rust-lang.org - -You can also use `rustdoc` directly to check small fixes. For example, -`rustdoc src/doc/reference.md` will render reference to `doc/reference.html`. -The CSS might be messed up, but you can verify that the HTML is right. - -Additionally, contributions to the [rustc-dev-guide] are always welcome. Contributions -can be made directly at [the -rust-lang/rustc-dev-guide](https://github.com/rust-lang/rustc-dev-guide) repo. The issue -tracker in that repo is also a great way to find things that need doing. There -are issues for beginners and advanced compiler devs alike! - -## Issue Triage - -Sometimes, an issue will stay open, even though the bug has been fixed. And -sometimes, the original bug may go stale because something has changed in the -meantime. - -It can be helpful to go through older bug reports and make sure that they are -still valid. Load up an older issue, double check that it's still true, and -leave a comment letting us know if it is or is not. The [least recently -updated sort][lru] is good for finding issues like this. - -Contributors with sufficient permissions on the Rust repo can help by adding -labels to triage issues: - -* Yellow, **A**-prefixed labels state which **area** of the project an issue - relates to. - -* Magenta, **B**-prefixed labels identify bugs which are **blockers**. - -* Dark blue, **beta-** labels track changes which need to be backported into - the beta branches. - -* Light purple, **C**-prefixed labels represent the **category** of an issue. - -* Green, **E**-prefixed labels explain the level of **experience** necessary - to fix the issue. - -* The dark blue **final-comment-period** label marks bugs that are using the - RFC signoff functionality of [rfcbot] and are currently in the final - comment period. - -* Red, **I**-prefixed labels indicate the **importance** of the issue. The - [I-nominated][inom] label indicates that an issue has been nominated for - prioritizing at the next triage meeting. - -* The purple **metabug** label marks lists of bugs collected by other - categories. - -* Purple gray, **O**-prefixed labels are the **operating system** or platform - that this issue is specific to. - -* Orange, **P**-prefixed labels indicate a bug's **priority**. These labels - are only assigned during triage meetings, and replace the [I-nominated][inom] - label. - -* The gray **proposed-final-comment-period** label marks bugs that are using - the RFC signoff functionality of [rfcbot] and are currently awaiting - signoff of all team members in order to enter the final comment period. - -* Pink, **regression**-prefixed labels track regressions from stable to the - release channels. - -* The light orange **relnotes** label marks issues that should be documented in - the release notes of the next release. - -* Gray, **S**-prefixed labels are used for tracking the **status** of pull - requests. - -* Blue, **T**-prefixed bugs denote which **team** the issue belongs to. - -If you're looking for somewhere to start, check out the [E-easy][eeasy] tag. - -[inom]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AI-nominated -[eeasy]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AE-easy -[lru]: https://github.com/rust-lang/rust/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-asc -[rfcbot]: https://github.com/anp/rfcbot-rs/ - -## Out-of-tree Contributions - -There are a number of other ways to contribute to Rust that don't deal with -this repository. - -Answer questions in the _Get Help!_ channels from the [Rust Discord server][rust-discord], on [users.rust-lang.org][users], -or on [StackOverflow][so]. - -Participate in the [RFC process](https://github.com/rust-lang/rfcs). - -Find a [requested community library][community-library], build it, and publish -it to [Crates.io](http://crates.io). Easier said than done, but very, very -valuable! - -[rust-discord]: https://discord.gg/rust-lang -[users]: https://users.rust-lang.org/ -[so]: http://stackoverflow.com/questions/tagged/rust -[community-library]: https://github.com/rust-lang/rfcs/labels/A-community-library - -## Helpful Links and Information - -For people new to Rust, and just starting to contribute, or even for -more seasoned developers, some useful places to look for information -are: - -* The [rustc dev guide] contains information about how various parts of the compiler work and how to contribute to the compiler -* [Rust Forge][rustforge] contains additional documentation, including write-ups of how to achieve common tasks -* The [Rust Internals forum][rif], a place to ask questions and - discuss Rust's internals -* The [generated documentation for rust's compiler][gdfrustc] -* The [rust reference][rr], even though it doesn't specifically talk about Rust's internals, it's a great resource nonetheless -* Although out of date, [Tom Lee's great blog article][tlgba] is very helpful -* [rustaceans.org][ro] is helpful, but mostly dedicated to IRC -* The [Rust Compiler Testing Docs][rctd] -* For [@bors][bors], [this cheat sheet][cheatsheet] is helpful -(though you'll need to replace `@homu` with `@bors` in any commands) -* **Google!** ([search only in Rust Documentation][gsearchdocs] to find types, traits, etc. quickly) -* Don't be afraid to ask! The Rust community is friendly and helpful. - -[rustc dev guide]: https://rustc-dev-guide.rust-lang.org/about-this-guide.html -[gdfrustc]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ -[gsearchdocs]: https://www.google.com/search?q=site:doc.rust-lang.org+your+query+here -[rif]: http://internals.rust-lang.org -[rr]: https://doc.rust-lang.org/book/README.html -[rustforge]: https://forge.rust-lang.org/ -[tlgba]: http://tomlee.co/2014/04/a-more-detailed-tour-of-the-rust-compiler/ -[ro]: http://www.rustaceans.org/ -[rctd]: https://rustc-dev-guide.rust-lang.org/tests/intro.html -[cheatsheet]: https://buildbot2.rust-lang.org/homu/ diff --git a/README.md b/README.md index 42fc0a63c0ffb..44c618a0518da 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,8 @@ standard library, and documentation. [Rust]: https://www.rust-lang.org +**Note: this README is for _users_ rather than _contributors_.** + ## Quick Start Read ["Installation"] from [The Book]. @@ -14,13 +16,15 @@ Read ["Installation"] from [The Book]. ## Installing from Source -_Note: If you wish to contribute to the compiler, you should read [this -chapter][rustcguidebuild] of the rustc-dev-guide instead of this section._ +**Note: If you wish to _contribute_ to the compiler, you should read the +[Getting Started][gettingstarted] of the rustc-dev-guide instead of this +section.** The Rust build system has a Python script called `x.py` to bootstrap building the compiler. More information about it may be found by running `./x.py --help` or reading the [rustc dev guide][rustcguidebuild]. +[gettingstarted]: https://rustc-dev-guide.rust-lang.org/getting-started.md [rustcguidebuild]: https://rustc-dev-guide.rust-lang.org/building/how-to-build-and-run.html ### Building on a Unix-like system @@ -224,10 +228,6 @@ Snapshot binaries are currently built and tested on several platforms: You may find that other platforms work, but these are our officially supported build environments that are most likely to work. -There is more advice about hacking on Rust in [CONTRIBUTING.md]. - -[CONTRIBUTING.md]: https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md - ## Getting Help The Rust community congregates in a few places: @@ -242,21 +242,8 @@ The Rust community congregates in a few places: ## Contributing -To contribute to Rust, please see [CONTRIBUTING](CONTRIBUTING.md). - -Most real-time collaboration happens in a variety of channels on the -[Rust Discord server][rust-discord], with channels dedicated for getting help, -community, documentation, and all major contribution areas in the Rust ecosystem. -A good place to ask for help would be the #help channel. - -The [rustc dev guide] might be a good place to start if you want to find out how -various parts of the compiler work. - -Also, you may find the [rustdocs for the compiler itself][rustdocs] useful. - -[rust-discord]: https://discord.gg/rust-lang -[rustc dev guide]: https://rustc-dev-guide.rust-lang.org/about-this-guide.html -[rustdocs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ +If you are interested in contributing to the Rust project, please take a look +at the [Getting Started][gettingstarted] guide in the [rustc-dev-guide]. ## License From df88972f8ce9ddbebec6d551810f7127fe25d2a3 Mon Sep 17 00:00:00 2001 From: Simonas Kazlauskas Date: Sat, 27 Jun 2020 01:16:23 +0300 Subject: [PATCH 02/12] Update psm version This new version includes a fix for building on aarch64 windows. --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8cbf6cf6869ea..97b4e79a03c9a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2663,9 +2663,9 @@ dependencies = [ [[package]] name = "psm" -version = "0.1.8" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "659ecfea2142a458893bb7673134bad50b752fea932349c213d6a23874ce3aa7" +checksum = "092d385624a084892d07374caa7b0994956692cf40650419a1f1a787a8d229cf" dependencies = [ "cc", ] From a12b9e6a6e6ea2549b848098a0b73490ca44e699 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Tue, 30 Jun 2020 10:39:05 -0700 Subject: [PATCH 03/12] Update cargo --- Cargo.lock | 10 ++++------ src/tools/cargo | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e9fb097df92d2..1fb24bd55bcbc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -312,7 +312,6 @@ dependencies = [ "openssl", "percent-encoding 2.1.0", "pretty_env_logger", - "remove_dir_all", "rustc-workspace-hack", "rustfix", "same-file", @@ -655,9 +654,9 @@ dependencies = [ [[package]] name = "core-foundation" -version = "0.7.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171" +checksum = "3b5ed8e7e76c45974e15e41bfa8d5b0483cd90191639e01d8f5f1e606299d3fb" dependencies = [ "core-foundation-sys", "libc", @@ -665,9 +664,9 @@ dependencies = [ [[package]] name = "core-foundation-sys" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac" +checksum = "9a21fa21941700a3cd8fcb4091f361a6a712fac632f85d9f487cc892045d55c6" [[package]] name = "crates-io" @@ -677,7 +676,6 @@ dependencies = [ "curl", "percent-encoding 2.1.0", "serde", - "serde_derive", "serde_json", "url 2.1.0", ] diff --git a/src/tools/cargo b/src/tools/cargo index c26576f9adddd..305eaf0dc5f5a 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit c26576f9adddd254b3dd63aecba176434290a9f6 +Subproject commit 305eaf0dc5f5a38d6e8041319c2da95b71cf6a4a From ca1da73fd96318d9ed051b201fb5b2d715e1d59f Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Tue, 30 Jun 2020 14:52:16 -0700 Subject: [PATCH 04/12] Update rls --- src/tools/rls | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rls b/src/tools/rls index fb46b914c11b0..dd341d5307541 160000 --- a/src/tools/rls +++ b/src/tools/rls @@ -1 +1 @@ -Subproject commit fb46b914c11b06828680cb526e2abe9e1d69b868 +Subproject commit dd341d53075411cf0f71c5853c98facda35112ef From 4dc5685220466d67bb009c3dec08d8a89aeddd0e Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Wed, 1 Jul 2020 21:03:14 -0700 Subject: [PATCH 05/12] Add option for local docker testing. --- src/ci/docker/run.sh | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh index d891ad1b6680e..8071b6358040a 100755 --- a/src/ci/docker/run.sh +++ b/src/ci/docker/run.sh @@ -5,7 +5,27 @@ set -e export MSYS_NO_PATHCONV=1 script=`cd $(dirname $0) && pwd`/`basename $0` -image=$1 + +image="" +dev=0 + +while [[ $# -gt 0 ]] +do + case "$1" in + --dev) + dev=1 + ;; + *) + if [ -n "$image" ] + then + echo "expected single argument for the image name" + exit 1 + fi + image="$1" + ;; + esac + shift +done docker_dir="`dirname $script`" ci_dir="`dirname $docker_dir`" @@ -163,6 +183,15 @@ else args="$args --env LOCAL_USER_ID=`id -u`" fi +if [ "$dev" = "1" ] +then + # Interactive + TTY + args="$args -it" + command="/bin/bash" +else + command="/checkout/src/ci/run.sh" +fi + docker \ run \ --workdir /checkout/obj \ @@ -183,7 +212,7 @@ docker \ --init \ --rm \ rust-ci \ - /checkout/src/ci/run.sh + $command if [ -f /.dockerenv ]; then rm -rf $objdir From 94cd4f15d6479756af6e03a31a204bd588805cbd Mon Sep 17 00:00:00 2001 From: Christopher Serr Date: Thu, 25 Jun 2020 17:05:12 +0200 Subject: [PATCH 06/12] Use WASM's saturating casts if they are available WebAssembly supports saturating floating point to integer casts behind a target feature. The feature is already available on many browsers. Beginning with 1.45 Rust will start defining the behavior of floating point to integer casts to be saturating as well. For this Rust constructs additional checks on top of the `fptoui` / `fptosi` instructions it emits. Here we introduce the possibility for the codegen backend to construct saturating casts itself and only fall back to constructing the checks ourselves if that is not possible. --- src/librustc_codegen_llvm/builder.rs | 50 ++++++++++++++++++++++ src/librustc_codegen_llvm/context.rs | 9 ++++ src/librustc_codegen_llvm/llvm_util.rs | 7 ++- src/librustc_codegen_ssa/mir/rvalue.rs | 11 +++-- src/librustc_codegen_ssa/traits/builder.rs | 2 + 5 files changed, 74 insertions(+), 5 deletions(-) diff --git a/src/librustc_codegen_llvm/builder.rs b/src/librustc_codegen_llvm/builder.rs index ba285b5ef38d1..a6b55fee87026 100644 --- a/src/librustc_codegen_llvm/builder.rs +++ b/src/librustc_codegen_llvm/builder.rs @@ -652,6 +652,56 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) } } + fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> { + if self.sess().target.target.arch == "wasm32" + && self + .sess() + .target_features + .contains(&rustc_span::symbol::Symbol::intern("nontrapping-fptoint")) + { + let src_ty = self.cx.val_ty(val); + let float_width = self.cx.float_width(src_ty); + let int_width = self.cx.int_width(dest_ty); + let name = match (int_width, float_width) { + (32, 32) => Some("llvm.wasm.trunc.saturate.unsigned.i32.f32"), + (32, 64) => Some("llvm.wasm.trunc.saturate.unsigned.i32.f64"), + (64, 32) => Some("llvm.wasm.trunc.saturate.unsigned.i64.f32"), + (64, 64) => Some("llvm.wasm.trunc.saturate.unsigned.i64.f64"), + _ => None, + }; + if let Some(name) = name { + let intrinsic = self.get_intrinsic(name); + return Some(self.call(intrinsic, &[val], None)); + } + } + None + } + + fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> { + if self.sess().target.target.arch == "wasm32" + && self + .sess() + .target_features + .contains(&rustc_span::symbol::Symbol::intern("nontrapping-fptoint")) + { + let src_ty = self.cx.val_ty(val); + let float_width = self.cx.float_width(src_ty); + let int_width = self.cx.int_width(dest_ty); + let name = match (int_width, float_width) { + (32, 32) => Some("llvm.wasm.trunc.saturate.signed.i32.f32"), + (32, 64) => Some("llvm.wasm.trunc.saturate.signed.i32.f64"), + (64, 32) => Some("llvm.wasm.trunc.saturate.signed.i64.f32"), + (64, 64) => Some("llvm.wasm.trunc.saturate.signed.i64.f64"), + _ => None, + }; + if let Some(name) = name { + let intrinsic = self.get_intrinsic(name); + return Some(self.call(intrinsic, &[val], None)); + } + } + None + } + fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value { unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) } } diff --git a/src/librustc_codegen_llvm/context.rs b/src/librustc_codegen_llvm/context.rs index 7ff5ac5cbdc10..896d3c1de62d5 100644 --- a/src/librustc_codegen_llvm/context.rs +++ b/src/librustc_codegen_llvm/context.rs @@ -482,6 +482,15 @@ impl CodegenCx<'b, 'tcx> { t_v8f64: t_f64, 8; } + ifn!("llvm.wasm.trunc.saturate.unsigned.i32.f32", fn(t_f32) -> t_i32); + ifn!("llvm.wasm.trunc.saturate.unsigned.i32.f64", fn(t_f64) -> t_i32); + ifn!("llvm.wasm.trunc.saturate.unsigned.i64.f32", fn(t_f32) -> t_i64); + ifn!("llvm.wasm.trunc.saturate.unsigned.i64.f64", fn(t_f64) -> t_i64); + ifn!("llvm.wasm.trunc.saturate.signed.i32.f32", fn(t_f32) -> t_i32); + ifn!("llvm.wasm.trunc.saturate.signed.i32.f64", fn(t_f64) -> t_i32); + ifn!("llvm.wasm.trunc.saturate.signed.i64.f32", fn(t_f32) -> t_i64); + ifn!("llvm.wasm.trunc.saturate.signed.i64.f64", fn(t_f64) -> t_i64); + ifn!("llvm.trap", fn() -> void); ifn!("llvm.debugtrap", fn() -> void); ifn!("llvm.frameaddress", fn(t_i32) -> i8p); diff --git a/src/librustc_codegen_llvm/llvm_util.rs b/src/librustc_codegen_llvm/llvm_util.rs index 80278bb9f53d8..5ec93b0d4032d 100644 --- a/src/librustc_codegen_llvm/llvm_util.rs +++ b/src/librustc_codegen_llvm/llvm_util.rs @@ -250,8 +250,11 @@ const RISCV_WHITELIST: &[(&str, Option)] = &[ ("e", Some(sym::riscv_target_feature)), ]; -const WASM_WHITELIST: &[(&str, Option)] = - &[("simd128", Some(sym::wasm_target_feature)), ("atomics", Some(sym::wasm_target_feature))]; +const WASM_WHITELIST: &[(&str, Option)] = &[ + ("simd128", Some(sym::wasm_target_feature)), + ("atomics", Some(sym::wasm_target_feature)), + ("nontrapping-fptoint", Some(sym::wasm_target_feature)), // TODO: Maybe None? +]; /// When rustdoc is running, provide a list of all known features so that all their respective /// primitives may be documented. diff --git a/src/librustc_codegen_ssa/mir/rvalue.rs b/src/librustc_codegen_ssa/mir/rvalue.rs index 57f72b1065d05..4b2be7b5321ff 100644 --- a/src/librustc_codegen_ssa/mir/rvalue.rs +++ b/src/librustc_codegen_ssa/mir/rvalue.rs @@ -774,12 +774,17 @@ fn cast_float_to_int<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( float_ty: Bx::Type, int_ty: Bx::Type, ) -> Bx::Value { - let fptosui_result = if signed { bx.fptosi(x, int_ty) } else { bx.fptoui(x, int_ty) }; - if let Some(false) = bx.cx().sess().opts.debugging_opts.saturating_float_casts { - return fptosui_result; + return if signed { bx.fptosi(x, int_ty) } else { bx.fptoui(x, int_ty) }; + } + + let try_sat_result = if signed { bx.fptosi_sat(x, int_ty) } else { bx.fptoui_sat(x, int_ty) }; + if let Some(try_sat_result) = try_sat_result { + return try_sat_result; } + let fptosui_result = if signed { bx.fptosi(x, int_ty) } else { bx.fptoui(x, int_ty) }; + let int_width = bx.cx().int_width(int_ty); let float_width = bx.cx().float_width(float_ty); // LLVM's fpto[su]i returns undef when the input x is infinite, NaN, or does not fit into the diff --git a/src/librustc_codegen_ssa/traits/builder.rs b/src/librustc_codegen_ssa/traits/builder.rs index 7ffc9f15bffdc..d33d6857bc0ef 100644 --- a/src/librustc_codegen_ssa/traits/builder.rs +++ b/src/librustc_codegen_ssa/traits/builder.rs @@ -156,6 +156,8 @@ pub trait BuilderMethods<'a, 'tcx>: fn trunc(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; fn sext(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; + fn fptoui_sat(&mut self, val: Self::Value, dest_ty: Self::Type) -> Option; + fn fptosi_sat(&mut self, val: Self::Value, dest_ty: Self::Type) -> Option; fn fptoui(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; fn fptosi(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; fn uitofp(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; From b2490299fc2029f9b43be51f80003ebcf804f7ac Mon Sep 17 00:00:00 2001 From: Christopher Serr Date: Fri, 26 Jun 2020 17:53:52 +0200 Subject: [PATCH 07/12] Check for feature with pre-interned symbol --- src/librustc_codegen_llvm/builder.rs | 17 ++++++++--------- src/librustc_codegen_llvm/llvm_util.rs | 2 +- src/librustc_span/symbol.rs | 1 + 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/librustc_codegen_llvm/builder.rs b/src/librustc_codegen_llvm/builder.rs index a6b55fee87026..83cd0dbfcd47e 100644 --- a/src/librustc_codegen_llvm/builder.rs +++ b/src/librustc_codegen_llvm/builder.rs @@ -18,6 +18,7 @@ use rustc_data_structures::small_c_str::SmallCStr; use rustc_hir::def_id::DefId; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_span::sym; use rustc_target::abi::{self, Align, Size}; use rustc_target::spec::{HasTargetSpec, Target}; use std::borrow::Cow; @@ -478,7 +479,11 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { let llptr = self.struct_gep(place.llval, i as u64); let load = self.load(llptr, align); scalar_load_metadata(self, load, scalar); - if scalar.is_bool() { self.trunc(load, self.type_i1()) } else { load } + if scalar.is_bool() { + self.trunc(load, self.type_i1()) + } else { + load + } }; OperandValue::Pair( @@ -654,10 +659,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> { if self.sess().target.target.arch == "wasm32" - && self - .sess() - .target_features - .contains(&rustc_span::symbol::Symbol::intern("nontrapping-fptoint")) + && self.sess().target_features.contains(&sym::wasm_nontrapping_fptoint) { let src_ty = self.cx.val_ty(val); let float_width = self.cx.float_width(src_ty); @@ -679,10 +681,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> { if self.sess().target.target.arch == "wasm32" - && self - .sess() - .target_features - .contains(&rustc_span::symbol::Symbol::intern("nontrapping-fptoint")) + && self.sess().target_features.contains(&sym::wasm_nontrapping_fptoint) { let src_ty = self.cx.val_ty(val); let float_width = self.cx.float_width(src_ty); diff --git a/src/librustc_codegen_llvm/llvm_util.rs b/src/librustc_codegen_llvm/llvm_util.rs index 5ec93b0d4032d..2e2ce1544109a 100644 --- a/src/librustc_codegen_llvm/llvm_util.rs +++ b/src/librustc_codegen_llvm/llvm_util.rs @@ -253,7 +253,7 @@ const RISCV_WHITELIST: &[(&str, Option)] = &[ const WASM_WHITELIST: &[(&str, Option)] = &[ ("simd128", Some(sym::wasm_target_feature)), ("atomics", Some(sym::wasm_target_feature)), - ("nontrapping-fptoint", Some(sym::wasm_target_feature)), // TODO: Maybe None? + ("nontrapping-fptoint", Some(sym::wasm_target_feature)), ]; /// When rustdoc is running, provide a list of all known features so that all their respective diff --git a/src/librustc_span/symbol.rs b/src/librustc_span/symbol.rs index e2f0d0b94c46c..2f0a0584a302b 100644 --- a/src/librustc_span/symbol.rs +++ b/src/librustc_span/symbol.rs @@ -844,6 +844,7 @@ symbols! { warn, wasm_import_module, wasm_target_feature, + wasm_nontrapping_fptoint: "nontrapping-fptoint", while_let, windows, windows_subsystem, From 4c08451fc43f4185d122efa91b996e137365f49c Mon Sep 17 00:00:00 2001 From: Christopher Serr Date: Sat, 27 Jun 2020 13:26:30 +0200 Subject: [PATCH 08/12] Add codegen tests --- src/test/codegen/wasm_casts_nontrapping.rs | 162 ++++++++++++++++++++ src/test/codegen/wasm_casts_trapping.rs | 169 +++++++++++++++++++++ 2 files changed, 331 insertions(+) create mode 100644 src/test/codegen/wasm_casts_nontrapping.rs create mode 100644 src/test/codegen/wasm_casts_trapping.rs diff --git a/src/test/codegen/wasm_casts_nontrapping.rs b/src/test/codegen/wasm_casts_nontrapping.rs new file mode 100644 index 0000000000000..bd6073d8c204a --- /dev/null +++ b/src/test/codegen/wasm_casts_nontrapping.rs @@ -0,0 +1,162 @@ +// only-wasm32 +// compile-flags: -C target-feature=+nontrapping-fptoint +#![crate_type = "lib"] + +// CHECK-LABEL: @cast_f64_i64 +#[no_mangle] +pub fn cast_f64_i64(a: f64) -> i64 { + // CHECK: tail call i64 @llvm.wasm.trunc.saturate.signed.i64.f64(double {{.*}}) + // CHECK-NEXT: ret i64 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f64_i32 +#[no_mangle] +pub fn cast_f64_i32(a: f64) -> i32 { + // CHECK: tail call i32 @llvm.wasm.trunc.saturate.signed.i32.f64(double {{.*}}) + // CHECK-NEXT: ret i32 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_i64 +#[no_mangle] +pub fn cast_f32_i64(a: f32) -> i64 { + // CHECK: tail call i64 @llvm.wasm.trunc.saturate.signed.i64.f32(float {{.*}}) + // CHECK-NEXT: ret i64 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_i32 +#[no_mangle] +pub fn cast_f32_i32(a: f32) -> i32 { + // CHECK: tail call i32 @llvm.wasm.trunc.saturate.signed.i32.f32(float {{.*}}) + // CHECK-NEXT: ret i32 {{.*}} + a as _ +} + + +// CHECK-LABEL: @cast_f64_u64 +#[no_mangle] +pub fn cast_f64_u64(a: f64) -> u64 { + // CHECK: tail call i64 @llvm.wasm.trunc.saturate.unsigned.i64.f64(double {{.*}}) + // CHECK-NEXT: ret i64 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f64_u32 +#[no_mangle] +pub fn cast_f64_u32(a: f64) -> u32 { + // CHECK: tail call i32 @llvm.wasm.trunc.saturate.unsigned.i32.f64(double {{.*}}) + // CHECK-NEXT: ret i32 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_u64 +#[no_mangle] +pub fn cast_f32_u64(a: f32) -> u64 { + // CHECK: tail call i64 @llvm.wasm.trunc.saturate.unsigned.i64.f32(float {{.*}}) + // CHECK-NEXT: ret i64 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_u32 +#[no_mangle] +pub fn cast_f32_u32(a: f32) -> u32 { + // CHECK: tail call i32 @llvm.wasm.trunc.saturate.unsigned.i32.f32(float {{.*}}) + // CHECK-NEXT: ret i32 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_u8 +#[no_mangle] +pub fn cast_f32_u8(a: f32) -> u8 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i8 + // CHECK-NEXT: select i1 {{.*}}, i8 {{.*}}, i8 {{.*}} + // CHECK-NEXT: ret i8 {{.*}} + a as _ +} + + + +// CHECK-LABEL: @cast_unchecked_f64_i64 +#[no_mangle] +pub unsafe fn cast_unchecked_f64_i64(a: f64) -> i64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi double {{.*}} to i64 + // CHECK-NEXT: ret i64 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f64_i32 +#[no_mangle] +pub unsafe fn cast_unchecked_f64_i32(a: f64) -> i32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi double {{.*}} to i32 + // CHECK-NEXT: ret i32 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_i64 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_i64(a: f32) -> i64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi float {{.*}} to i64 + // CHECK-NEXT: ret i64 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_i32 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_i32(a: f32) -> i32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi float {{.*}} to i32 + // CHECK-NEXT: ret i32 {{.*}} + a.to_int_unchecked() +} + + +// CHECK-LABEL: @cast_unchecked_f64_u64 +#[no_mangle] +pub unsafe fn cast_unchecked_f64_u64(a: f64) -> u64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui double {{.*}} to i64 + // CHECK-NEXT: ret i64 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f64_u32 +#[no_mangle] +pub unsafe fn cast_unchecked_f64_u32(a: f64) -> u32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui double {{.*}} to i32 + // CHECK-NEXT: ret i32 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_u64 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_u64(a: f32) -> u64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i64 + // CHECK-NEXT: ret i64 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_u32 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_u32(a: f32) -> u32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i32 + // CHECK-NEXT: ret i32 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_u8 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_u8(a: f32) -> u8 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i8 + // CHECK-NEXT: ret i8 {{.*}} + a.to_int_unchecked() +} diff --git a/src/test/codegen/wasm_casts_trapping.rs b/src/test/codegen/wasm_casts_trapping.rs new file mode 100644 index 0000000000000..45b905190493a --- /dev/null +++ b/src/test/codegen/wasm_casts_trapping.rs @@ -0,0 +1,169 @@ +// only-wasm32 +// compile-flags: -C target-feature=-nontrapping-fptoint +#![crate_type = "lib"] + +// CHECK-LABEL: @cast_f64_i64 +#[no_mangle] +pub fn cast_f64_i64(a: f64) -> i64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi double {{.*}} to i64 + // CHECK-NEXT: select i1 {{.*}}, i64 {{.*}}, i64 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f64_i32 +#[no_mangle] +pub fn cast_f64_i32(a: f64) -> i32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi double {{.*}} to i32 + // CHECK-NEXT: select i1 {{.*}}, i32 {{.*}}, i32 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_i64 +#[no_mangle] +pub fn cast_f32_i64(a: f32) -> i64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi float {{.*}} to i64 + // CHECK-NEXT: select i1 {{.*}}, i64 {{.*}}, i64 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_i32 +#[no_mangle] +pub fn cast_f32_i32(a: f32) -> i32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi float {{.*}} to i32 + // CHECK-NEXT: select i1 {{.*}}, i32 {{.*}}, i32 {{.*}} + a as _ +} + + +// CHECK-LABEL: @cast_f64_u64 +#[no_mangle] +pub fn cast_f64_u64(a: f64) -> u64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui double {{.*}} to i64 + // CHECK-NEXT: select i1 {{.*}}, i64 {{.*}}, i64 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f64_u32 +#[no_mangle] +pub fn cast_f64_u32(a: f64) -> u32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui double {{.*}} to i32 + // CHECK-NEXT: select i1 {{.*}}, i32 {{.*}}, i32 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_u64 +#[no_mangle] +pub fn cast_f32_u64(a: f32) -> u64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i64 + // CHECK-NEXT: select i1 {{.*}}, i64 {{.*}}, i64 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_u32 +#[no_mangle] +pub fn cast_f32_u32(a: f32) -> u32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i32 + // CHECK-NEXT: select i1 {{.*}}, i32 {{.*}}, i32 {{.*}} + a as _ +} + +// CHECK-LABEL: @cast_f32_u8 +#[no_mangle] +pub fn cast_f32_u8(a: f32) -> u8 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i8 + // CHECK-NEXT: select i1 {{.*}}, i8 {{.*}}, i8 {{.*}} + a as _ +} + + + +// CHECK-LABEL: @cast_unchecked_f64_i64 +#[no_mangle] +pub unsafe fn cast_unchecked_f64_i64(a: f64) -> i64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi double {{.*}} to i64 + // CHECK-NEXT: ret i64 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f64_i32 +#[no_mangle] +pub unsafe fn cast_unchecked_f64_i32(a: f64) -> i32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi double {{.*}} to i32 + // CHECK-NEXT: ret i32 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_i64 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_i64(a: f32) -> i64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi float {{.*}} to i64 + // CHECK-NEXT: ret i64 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_i32 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_i32(a: f32) -> i32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptosi float {{.*}} to i32 + // CHECK-NEXT: ret i32 {{.*}} + a.to_int_unchecked() +} + + +// CHECK-LABEL: @cast_unchecked_f64_u64 +#[no_mangle] +pub unsafe fn cast_unchecked_f64_u64(a: f64) -> u64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui double {{.*}} to i64 + // CHECK-NEXT: ret i64 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f64_u32 +#[no_mangle] +pub unsafe fn cast_unchecked_f64_u32(a: f64) -> u32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui double {{.*}} to i32 + // CHECK-NEXT: ret i32 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_u64 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_u64(a: f32) -> u64 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i64 + // CHECK-NEXT: ret i64 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_u32 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_u32(a: f32) -> u32 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i32 + // CHECK-NEXT: ret i32 {{.*}} + a.to_int_unchecked() +} + +// CHECK-LABEL: @cast_unchecked_f32_u8 +#[no_mangle] +pub unsafe fn cast_unchecked_f32_u8(a: f32) -> u8 { + // CHECK-NOT: {{.*}} call {{.*}} @llvm.wasm.trunc.{{.*}} + // CHECK: fptoui float {{.*}} to i8 + // CHECK-NEXT: ret i8 {{.*}} + a.to_int_unchecked() +} From 8f8c90e5b5b9d005999c18257f3844e92bc89eee Mon Sep 17 00:00:00 2001 From: Christopher Serr Date: Sat, 27 Jun 2020 14:03:32 +0200 Subject: [PATCH 09/12] Add comments and format the code --- src/librustc_codegen_llvm/builder.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/librustc_codegen_llvm/builder.rs b/src/librustc_codegen_llvm/builder.rs index 83cd0dbfcd47e..eed327d0bc156 100644 --- a/src/librustc_codegen_llvm/builder.rs +++ b/src/librustc_codegen_llvm/builder.rs @@ -479,11 +479,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { let llptr = self.struct_gep(place.llval, i as u64); let load = self.load(llptr, align); scalar_load_metadata(self, load, scalar); - if scalar.is_bool() { - self.trunc(load, self.type_i1()) - } else { - load - } + if scalar.is_bool() { self.trunc(load, self.type_i1()) } else { load } }; OperandValue::Pair( @@ -658,6 +654,9 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { } fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> { + // WebAssembly has saturating floating point to integer casts if the + // `nontrapping-fptoint` target feature is activated. We'll use those if + // they are available. if self.sess().target.target.arch == "wasm32" && self.sess().target_features.contains(&sym::wasm_nontrapping_fptoint) { @@ -680,6 +679,9 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { } fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> { + // WebAssembly has saturating floating point to integer casts if the + // `nontrapping-fptoint` target feature is activated. We'll use those if + // they are available. if self.sess().target.target.arch == "wasm32" && self.sess().target_features.contains(&sym::wasm_nontrapping_fptoint) { From 838c497a4578bb4c939e9834240198e22815ad1b Mon Sep 17 00:00:00 2001 From: Christopher Serr Date: Tue, 30 Jun 2020 21:44:44 +0200 Subject: [PATCH 10/12] Address review comments and add UI test --- src/ci/docker/test-various/Dockerfile | 4 +- src/librustc_codegen_llvm/builder.rs | 4 +- src/librustc_span/symbol.rs | 2 +- .../saturating-float-casts-impl.rs | 507 ++++++++++++++++++ .../saturating-float-casts-wasm.rs | 13 + .../saturating-float-casts.rs | 503 +---------------- 6 files changed, 528 insertions(+), 505 deletions(-) create mode 100644 src/test/ui/numbers-arithmetic/saturating-float-casts-impl.rs create mode 100644 src/test/ui/numbers-arithmetic/saturating-float-casts-wasm.rs diff --git a/src/ci/docker/test-various/Dockerfile b/src/ci/docker/test-various/Dockerfile index 9276e4ed82d78..6775baa8c3273 100644 --- a/src/ci/docker/test-various/Dockerfile +++ b/src/ci/docker/test-various/Dockerfile @@ -17,7 +17,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ wget \ patch -RUN curl -sL https://nodejs.org/dist/v9.2.0/node-v9.2.0-linux-x64.tar.xz | \ +RUN curl -sL https://nodejs.org/dist/v14.4.0/node-v14.4.0-linux-x64.tar.xz | \ tar -xJ WORKDIR /build/ @@ -30,7 +30,7 @@ RUN sh /scripts/sccache.sh ENV RUST_CONFIGURE_ARGS \ --musl-root-x86_64=/usr/local/x86_64-linux-musl \ - --set build.nodejs=/node-v9.2.0-linux-x64/bin/node \ + --set build.nodejs=/node-v14.4.0-linux-x64/bin/node \ --set rust.lld # Some run-make tests have assertions about code size, and enabling debug diff --git a/src/librustc_codegen_llvm/builder.rs b/src/librustc_codegen_llvm/builder.rs index eed327d0bc156..89b70dce52c66 100644 --- a/src/librustc_codegen_llvm/builder.rs +++ b/src/librustc_codegen_llvm/builder.rs @@ -658,7 +658,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { // `nontrapping-fptoint` target feature is activated. We'll use those if // they are available. if self.sess().target.target.arch == "wasm32" - && self.sess().target_features.contains(&sym::wasm_nontrapping_fptoint) + && self.sess().target_features.contains(&sym::nontrapping_fptoint) { let src_ty = self.cx.val_ty(val); let float_width = self.cx.float_width(src_ty); @@ -683,7 +683,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { // `nontrapping-fptoint` target feature is activated. We'll use those if // they are available. if self.sess().target.target.arch == "wasm32" - && self.sess().target_features.contains(&sym::wasm_nontrapping_fptoint) + && self.sess().target_features.contains(&sym::nontrapping_fptoint) { let src_ty = self.cx.val_ty(val); let float_width = self.cx.float_width(src_ty); diff --git a/src/librustc_span/symbol.rs b/src/librustc_span/symbol.rs index 2f0a0584a302b..c94e049e52d4e 100644 --- a/src/librustc_span/symbol.rs +++ b/src/librustc_span/symbol.rs @@ -513,6 +513,7 @@ symbols! { None, non_exhaustive, non_modrs_mods, + nontrapping_fptoint: "nontrapping-fptoint", noreturn, no_niche, no_sanitize, @@ -844,7 +845,6 @@ symbols! { warn, wasm_import_module, wasm_target_feature, - wasm_nontrapping_fptoint: "nontrapping-fptoint", while_let, windows, windows_subsystem, diff --git a/src/test/ui/numbers-arithmetic/saturating-float-casts-impl.rs b/src/test/ui/numbers-arithmetic/saturating-float-casts-impl.rs new file mode 100644 index 0000000000000..6c3e503693c3c --- /dev/null +++ b/src/test/ui/numbers-arithmetic/saturating-float-casts-impl.rs @@ -0,0 +1,507 @@ +// ignore-test + +// Tests saturating float->int casts. See u128-as-f32.rs for the opposite direction. +// +// Some of these tests come from a similar file in miri, +// tests/run-pass/float.rs. Individual test cases are potentially duplicated +// with the previously existing tests, but since this runs so quickly anyway, +// we're not spending the time to figure out exactly which ones should be +// merged. + +extern crate test; + +use self::test::black_box; +use std::{f32, f64}; +#[cfg(not(target_os = "emscripten"))] +use std::{i128, u128}; +use std::{i16, i32, i64, i8, u16, u32, u64, u8}; + +macro_rules! test { + ($val:expr, $src_ty:ident -> $dest_ty:ident, $expected:expr) => ( + // black_box disables constant evaluation to test run-time conversions: + assert_eq!(black_box::<$src_ty>($val) as $dest_ty, $expected, + "run-time {} -> {}", stringify!($src_ty), stringify!($dest_ty)); + + { + const X: $src_ty = $val; + const Y: $dest_ty = X as $dest_ty; + assert_eq!(Y, $expected, + "const eval {} -> {}", stringify!($src_ty), stringify!($dest_ty)); + } + ); + + ($fval:expr, f* -> $ity:ident, $ival:expr) => ( + test!($fval, f32 -> $ity, $ival); + test!($fval, f64 -> $ity, $ival); + ) +} + +macro_rules! common_fptoi_tests { + ($fty:ident -> $($ity:ident)+) => ({ $( + test!($fty::NAN, $fty -> $ity, 0); + test!($fty::INFINITY, $fty -> $ity, $ity::MAX); + test!($fty::NEG_INFINITY, $fty -> $ity, $ity::MIN); + // These two tests are not solely float->int tests, in particular the latter relies on + // `u128::MAX as f32` not being UB. But that's okay, since this file tests int->float + // as well, the test is just slightly misplaced. + test!($ity::MIN as $fty, $fty -> $ity, $ity::MIN); + test!($ity::MAX as $fty, $fty -> $ity, $ity::MAX); + test!(0., $fty -> $ity, 0); + test!($fty::MIN_POSITIVE, $fty -> $ity, 0); + test!(-0.9, $fty -> $ity, 0); + test!(1., $fty -> $ity, 1); + test!(42., $fty -> $ity, 42); + )+ }); + + (f* -> $($ity:ident)+) => ({ + common_fptoi_tests!(f32 -> $($ity)+); + common_fptoi_tests!(f64 -> $($ity)+); + }) +} + +macro_rules! fptoui_tests { + ($fty: ident -> $($ity: ident)+) => ({ $( + test!(-0., $fty -> $ity, 0); + test!(-$fty::MIN_POSITIVE, $fty -> $ity, 0); + test!(-0.99999994, $fty -> $ity, 0); + test!(-1., $fty -> $ity, 0); + test!(-100., $fty -> $ity, 0); + test!(#[allow(overflowing_literals)] -1e50, $fty -> $ity, 0); + test!(#[allow(overflowing_literals)] -1e130, $fty -> $ity, 0); + )+ }); + + (f* -> $($ity:ident)+) => ({ + fptoui_tests!(f32 -> $($ity)+); + fptoui_tests!(f64 -> $($ity)+); + }) +} + +use std::fmt::Debug; + +// Helper function to avoid promotion so that this tests "run-time" casts, not CTFE. +#[track_caller] +#[inline(never)] +fn assert_eq(x: T, y: T) { + assert_eq!(x, y); +} + +trait FloatToInt: Copy { + fn cast(self) -> Int; + unsafe fn cast_unchecked(self) -> Int; +} + +impl FloatToInt for f32 { + fn cast(self) -> i8 { + self as _ + } + unsafe fn cast_unchecked(self) -> i8 { + self.to_int_unchecked() + } +} +impl FloatToInt for f32 { + fn cast(self) -> i32 { + self as _ + } + unsafe fn cast_unchecked(self) -> i32 { + self.to_int_unchecked() + } +} +impl FloatToInt for f32 { + fn cast(self) -> u32 { + self as _ + } + unsafe fn cast_unchecked(self) -> u32 { + self.to_int_unchecked() + } +} +impl FloatToInt for f32 { + fn cast(self) -> i64 { + self as _ + } + unsafe fn cast_unchecked(self) -> i64 { + self.to_int_unchecked() + } +} +impl FloatToInt for f32 { + fn cast(self) -> u64 { + self as _ + } + unsafe fn cast_unchecked(self) -> u64 { + self.to_int_unchecked() + } +} + +impl FloatToInt for f64 { + fn cast(self) -> i8 { + self as _ + } + unsafe fn cast_unchecked(self) -> i8 { + self.to_int_unchecked() + } +} +impl FloatToInt for f64 { + fn cast(self) -> i32 { + self as _ + } + unsafe fn cast_unchecked(self) -> i32 { + self.to_int_unchecked() + } +} +impl FloatToInt for f64 { + fn cast(self) -> u32 { + self as _ + } + unsafe fn cast_unchecked(self) -> u32 { + self.to_int_unchecked() + } +} +impl FloatToInt for f64 { + fn cast(self) -> i64 { + self as _ + } + unsafe fn cast_unchecked(self) -> i64 { + self.to_int_unchecked() + } +} +impl FloatToInt for f64 { + fn cast(self) -> u64 { + self as _ + } + unsafe fn cast_unchecked(self) -> u64 { + self.to_int_unchecked() + } +} +// FIXME emscripten does not support i128 +#[cfg(not(target_os = "emscripten"))] +impl FloatToInt for f64 { + fn cast(self) -> i128 { + self as _ + } + unsafe fn cast_unchecked(self) -> i128 { + self.to_int_unchecked() + } +} +// FIXME emscripten does not support i128 +#[cfg(not(target_os = "emscripten"))] +impl FloatToInt for f64 { + fn cast(self) -> u128 { + self as _ + } + unsafe fn cast_unchecked(self) -> u128 { + self.to_int_unchecked() + } +} + +/// Test this cast both via `as` and via `to_int_unchecked` (i.e., it must not saturate). +#[track_caller] +#[inline(never)] +fn test_both_cast(x: F, y: I) +where + F: FloatToInt, + I: PartialEq + Debug, +{ + assert_eq!(x.cast(), y); + assert_eq!(unsafe { x.cast_unchecked() }, y); +} + +fn casts() { + // f32 -> i8 + test_both_cast::(127.99, 127); + test_both_cast::(-128.99, -128); + + // f32 -> i32 + test_both_cast::(0.0, 0); + test_both_cast::(-0.0, 0); + test_both_cast::(/*0x1p-149*/ f32::from_bits(0x00000001), 0); + test_both_cast::(/*-0x1p-149*/ f32::from_bits(0x80000001), 0); + test_both_cast::(/*0x1.19999ap+0*/ f32::from_bits(0x3f8ccccd), 1); + test_both_cast::(/*-0x1.19999ap+0*/ f32::from_bits(0xbf8ccccd), -1); + test_both_cast::(1.9, 1); + test_both_cast::(-1.9, -1); + test_both_cast::(5.0, 5); + test_both_cast::(-5.0, -5); + test_both_cast::(2147483520.0, 2147483520); + test_both_cast::(-2147483648.0, -2147483648); + // unrepresentable casts + assert_eq::(2147483648.0f32 as i32, i32::MAX); + assert_eq::(-2147483904.0f32 as i32, i32::MIN); + assert_eq::(f32::MAX as i32, i32::MAX); + assert_eq::(f32::MIN as i32, i32::MIN); + assert_eq::(f32::INFINITY as i32, i32::MAX); + assert_eq::(f32::NEG_INFINITY as i32, i32::MIN); + assert_eq::(f32::NAN as i32, 0); + assert_eq::((-f32::NAN) as i32, 0); + + // f32 -> u32 + test_both_cast::(0.0, 0); + test_both_cast::(-0.0, 0); + test_both_cast::(-0.9999999, 0); + test_both_cast::(/*0x1p-149*/ f32::from_bits(0x1), 0); + test_both_cast::(/*-0x1p-149*/ f32::from_bits(0x80000001), 0); + test_both_cast::(/*0x1.19999ap+0*/ f32::from_bits(0x3f8ccccd), 1); + test_both_cast::(1.9, 1); + test_both_cast::(5.0, 5); + test_both_cast::(2147483648.0, 0x8000_0000); + test_both_cast::(4294967040.0, 0u32.wrapping_sub(256)); + test_both_cast::(/*-0x1.ccccccp-1*/ f32::from_bits(0xbf666666), 0); + test_both_cast::(/*-0x1.fffffep-1*/ f32::from_bits(0xbf7fffff), 0); + test_both_cast::((u32::MAX - 128) as f32, u32::MAX - 255); // rounding loss + + // unrepresentable casts: + + // rounds up and then becomes unrepresentable + assert_eq::((u32::MAX - 127) as f32 as u32, u32::MAX); + + assert_eq::(4294967296.0f32 as u32, u32::MAX); + assert_eq::(-5.0f32 as u32, 0); + assert_eq::(f32::MAX as u32, u32::MAX); + assert_eq::(f32::MIN as u32, 0); + assert_eq::(f32::INFINITY as u32, u32::MAX); + assert_eq::(f32::NEG_INFINITY as u32, 0); + assert_eq::(f32::NAN as u32, 0); + assert_eq::((-f32::NAN) as u32, 0); + + // f32 -> i64 + test_both_cast::(4294967296.0, 4294967296); + test_both_cast::(-4294967296.0, -4294967296); + test_both_cast::(9223371487098961920.0, 9223371487098961920); + test_both_cast::(-9223372036854775808.0, -9223372036854775808); + + // f64 -> i8 + test_both_cast::(127.99, 127); + test_both_cast::(-128.99, -128); + + // f64 -> i32 + test_both_cast::(0.0, 0); + test_both_cast::(-0.0, 0); + test_both_cast::(/*0x1.199999999999ap+0*/ f64::from_bits(0x3ff199999999999a), 1); + test_both_cast::( + /*-0x1.199999999999ap+0*/ f64::from_bits(0xbff199999999999a), + -1, + ); + test_both_cast::(1.9, 1); + test_both_cast::(-1.9, -1); + test_both_cast::(1e8, 100_000_000); + test_both_cast::(2147483647.0, 2147483647); + test_both_cast::(-2147483648.0, -2147483648); + // unrepresentable casts + assert_eq::(2147483648.0f64 as i32, i32::MAX); + assert_eq::(-2147483649.0f64 as i32, i32::MIN); + + // f64 -> i64 + test_both_cast::(0.0, 0); + test_both_cast::(-0.0, 0); + test_both_cast::(/*0x0.0000000000001p-1022*/ f64::from_bits(0x1), 0); + test_both_cast::( + /*-0x0.0000000000001p-1022*/ f64::from_bits(0x8000000000000001), + 0, + ); + test_both_cast::(/*0x1.199999999999ap+0*/ f64::from_bits(0x3ff199999999999a), 1); + test_both_cast::( + /*-0x1.199999999999ap+0*/ f64::from_bits(0xbff199999999999a), + -1, + ); + test_both_cast::(5.0, 5); + test_both_cast::(5.9, 5); + test_both_cast::(-5.0, -5); + test_both_cast::(-5.9, -5); + test_both_cast::(4294967296.0, 4294967296); + test_both_cast::(-4294967296.0, -4294967296); + test_both_cast::(9223372036854774784.0, 9223372036854774784); + test_both_cast::(-9223372036854775808.0, -9223372036854775808); + // unrepresentable casts + assert_eq::(9223372036854775808.0f64 as i64, i64::MAX); + assert_eq::(-9223372036854777856.0f64 as i64, i64::MIN); + assert_eq::(f64::MAX as i64, i64::MAX); + assert_eq::(f64::MIN as i64, i64::MIN); + assert_eq::(f64::INFINITY as i64, i64::MAX); + assert_eq::(f64::NEG_INFINITY as i64, i64::MIN); + assert_eq::(f64::NAN as i64, 0); + assert_eq::((-f64::NAN) as i64, 0); + + // f64 -> u64 + test_both_cast::(0.0, 0); + test_both_cast::(-0.0, 0); + test_both_cast::(-0.99999999999, 0); + test_both_cast::(5.0, 5); + test_both_cast::(1e16, 10000000000000000); + test_both_cast::((u64::MAX - 1024) as f64, u64::MAX - 2047); // rounding loss + test_both_cast::(9223372036854775808.0, 9223372036854775808); + // unrepresentable casts + assert_eq::(-5.0f64 as u64, 0); + // rounds up and then becomes unrepresentable + assert_eq::((u64::MAX - 1023) as f64 as u64, u64::MAX); + assert_eq::(18446744073709551616.0f64 as u64, u64::MAX); + assert_eq::(f64::MAX as u64, u64::MAX); + assert_eq::(f64::MIN as u64, 0); + assert_eq::(f64::INFINITY as u64, u64::MAX); + assert_eq::(f64::NEG_INFINITY as u64, 0); + assert_eq::(f64::NAN as u64, 0); + assert_eq::((-f64::NAN) as u64, 0); + + // FIXME emscripten does not support i128 + #[cfg(not(target_os = "emscripten"))] + { + // f64 -> i128 + assert_eq::(f64::MAX as i128, i128::MAX); + assert_eq::(f64::MIN as i128, i128::MIN); + + // f64 -> u128 + assert_eq::(f64::MAX as u128, u128::MAX); + assert_eq::(f64::MIN as u128, 0); + } + + // int -> f32 + assert_eq::(127i8 as f32, 127.0); + assert_eq::(2147483647i32 as f32, 2147483648.0); + assert_eq::((-2147483648i32) as f32, -2147483648.0); + assert_eq::(1234567890i32 as f32, /*0x1.26580cp+30*/ f32::from_bits(0x4e932c06)); + assert_eq::(16777217i32 as f32, 16777216.0); + assert_eq::((-16777217i32) as f32, -16777216.0); + assert_eq::(16777219i32 as f32, 16777220.0); + assert_eq::((-16777219i32) as f32, -16777220.0); + assert_eq::( + 0x7fffff4000000001i64 as f32, + /*0x1.fffffep+62*/ f32::from_bits(0x5effffff), + ); + assert_eq::( + 0x8000004000000001u64 as i64 as f32, + /*-0x1.fffffep+62*/ f32::from_bits(0xdeffffff), + ); + assert_eq::( + 0x0020000020000001i64 as f32, + /*0x1.000002p+53*/ f32::from_bits(0x5a000001), + ); + assert_eq::( + 0xffdfffffdfffffffu64 as i64 as f32, + /*-0x1.000002p+53*/ f32::from_bits(0xda000001), + ); + // FIXME emscripten does not support i128 + #[cfg(not(target_os = "emscripten"))] + { + assert_eq::(i128::MIN as f32, -170141183460469231731687303715884105728.0f32); + assert_eq::(u128::MAX as f32, f32::INFINITY); // saturation + } + + // int -> f64 + assert_eq::(127i8 as f64, 127.0); + assert_eq::(i16::MIN as f64, -32768.0f64); + assert_eq::(2147483647i32 as f64, 2147483647.0); + assert_eq::(-2147483648i32 as f64, -2147483648.0); + assert_eq::(987654321i32 as f64, 987654321.0); + assert_eq::(9223372036854775807i64 as f64, 9223372036854775807.0); + assert_eq::(-9223372036854775808i64 as f64, -9223372036854775808.0); + assert_eq::(4669201609102990i64 as f64, 4669201609102990.0); // Feigenbaum (?) + assert_eq::(9007199254740993i64 as f64, 9007199254740992.0); + assert_eq::(-9007199254740993i64 as f64, -9007199254740992.0); + assert_eq::(9007199254740995i64 as f64, 9007199254740996.0); + assert_eq::(-9007199254740995i64 as f64, -9007199254740996.0); + // FIXME emscripten does not support i128 + #[cfg(not(target_os = "emscripten"))] + { + // even that fits... + assert_eq::(u128::MAX as f64, 340282366920938463463374607431768211455.0f64); + } + + // f32 -> f64 + assert_eq::((0.0f32 as f64).to_bits(), 0.0f64.to_bits()); + assert_eq::(((-0.0f32) as f64).to_bits(), (-0.0f64).to_bits()); + assert_eq::(5.0f32 as f64, 5.0f64); + assert_eq::( + /*0x1p-149*/ f32::from_bits(0x1) as f64, + /*0x1p-149*/ f64::from_bits(0x36a0000000000000), + ); + assert_eq::( + /*-0x1p-149*/ f32::from_bits(0x80000001) as f64, + /*-0x1p-149*/ f64::from_bits(0xb6a0000000000000), + ); + assert_eq::( + /*0x1.fffffep+127*/ f32::from_bits(0x7f7fffff) as f64, + /*0x1.fffffep+127*/ f64::from_bits(0x47efffffe0000000), + ); + assert_eq::( + /*-0x1.fffffep+127*/ (-f32::from_bits(0x7f7fffff)) as f64, + /*-0x1.fffffep+127*/ -f64::from_bits(0x47efffffe0000000), + ); + assert_eq::( + /*0x1p-119*/ f32::from_bits(0x4000000) as f64, + /*0x1p-119*/ f64::from_bits(0x3880000000000000), + ); + assert_eq::( + /*0x1.8f867ep+125*/ f32::from_bits(0x7e47c33f) as f64, + 6.6382536710104395e+37, + ); + assert_eq::(f32::INFINITY as f64, f64::INFINITY); + assert_eq::(f32::NEG_INFINITY as f64, f64::NEG_INFINITY); + + // f64 -> f32 + assert_eq::((0.0f64 as f32).to_bits(), 0.0f32.to_bits()); + assert_eq::(((-0.0f64) as f32).to_bits(), (-0.0f32).to_bits()); + assert_eq::(5.0f64 as f32, 5.0f32); + assert_eq::(/*0x0.0000000000001p-1022*/ f64::from_bits(0x1) as f32, 0.0); + assert_eq::(/*-0x0.0000000000001p-1022*/ (-f64::from_bits(0x1)) as f32, -0.0); + assert_eq::( + /*0x1.fffffe0000000p-127*/ f64::from_bits(0x380fffffe0000000) as f32, + /*0x1p-149*/ f32::from_bits(0x800000), + ); + assert_eq::( + /*0x1.4eae4f7024c7p+108*/ f64::from_bits(0x46b4eae4f7024c70) as f32, + /*0x1.4eae5p+108*/ f32::from_bits(0x75a75728), + ); + assert_eq::(f64::MAX as f32, f32::INFINITY); + assert_eq::(f64::MIN as f32, f32::NEG_INFINITY); + assert_eq::(f64::INFINITY as f32, f32::INFINITY); + assert_eq::(f64::NEG_INFINITY as f32, f32::NEG_INFINITY); +} + +pub fn run() { + casts(); // from miri's tests + + common_fptoi_tests!(f* -> i8 i16 i32 i64 u8 u16 u32 u64); + fptoui_tests!(f* -> u8 u16 u32 u64); + // FIXME emscripten does not support i128 + #[cfg(not(target_os = "emscripten"))] + { + common_fptoi_tests!(f* -> i128 u128); + fptoui_tests!(f* -> u128); + } + + // The following tests cover edge cases for some integer types. + + // # u8 + test!(254., f* -> u8, 254); + test!(256., f* -> u8, 255); + + // # i8 + test!(-127., f* -> i8, -127); + test!(-129., f* -> i8, -128); + test!(126., f* -> i8, 126); + test!(128., f* -> i8, 127); + + // # i32 + // -2147483648. is i32::MIN (exactly) + test!(-2147483648., f* -> i32, i32::MIN); + // 2147483648. is i32::MAX rounded up + test!(2147483648., f32 -> i32, 2147483647); + // With 24 significand bits, floats with magnitude in [2^30 + 1, 2^31] are rounded to + // multiples of 2^7. Therefore, nextDown(round(i32::MAX)) is 2^31 - 128: + test!(2147483520., f32 -> i32, 2147483520); + // Similarly, nextUp(i32::MIN) is i32::MIN + 2^8 and nextDown(i32::MIN) is i32::MIN - 2^7 + test!(-2147483904., f* -> i32, i32::MIN); + test!(-2147483520., f* -> i32, -2147483520); + + // # u32 + // round(MAX) and nextUp(round(MAX)) + test!(4294967040., f* -> u32, 4294967040); + test!(4294967296., f* -> u32, 4294967295); + + // # u128 + #[cfg(not(target_os = "emscripten"))] + { + // float->int: + test!(f32::MAX, f32 -> u128, 0xffffff00000000000000000000000000); + // nextDown(f32::MAX) = 2^128 - 2 * 2^104 + const SECOND_LARGEST_F32: f32 = 340282326356119256160033759537265639424.; + test!(SECOND_LARGEST_F32, f32 -> u128, 0xfffffe00000000000000000000000000); + } +} diff --git a/src/test/ui/numbers-arithmetic/saturating-float-casts-wasm.rs b/src/test/ui/numbers-arithmetic/saturating-float-casts-wasm.rs new file mode 100644 index 0000000000000..cad05917391be --- /dev/null +++ b/src/test/ui/numbers-arithmetic/saturating-float-casts-wasm.rs @@ -0,0 +1,13 @@ +// run-pass +// only-wasm32 +// compile-flags: -Zmir-opt-level=0 -C target-feature=+nontrapping-fptoint + +#![feature(test, stmt_expr_attributes)] +#![deny(overflowing_literals)] + +#[path = "saturating-float-casts-impl.rs"] +mod implementation; + +pub fn main() { + implementation::run(); +} diff --git a/src/test/ui/numbers-arithmetic/saturating-float-casts.rs b/src/test/ui/numbers-arithmetic/saturating-float-casts.rs index 825a11972aeeb..cc248a9bea087 100644 --- a/src/test/ui/numbers-arithmetic/saturating-float-casts.rs +++ b/src/test/ui/numbers-arithmetic/saturating-float-casts.rs @@ -1,509 +1,12 @@ // run-pass // compile-flags:-Zmir-opt-level=0 -// Tests saturating float->int casts. See u128-as-f32.rs for the opposite direction. -// -// Some of these tests come from a similar file in miri, -// tests/run-pass/float.rs. Individual test cases are potentially duplicated -// with the previously existing tests, but since this runs so quickly anyway, -// we're not spending the time to figure out exactly which ones should be -// merged. #![feature(test, stmt_expr_attributes)] #![deny(overflowing_literals)] -extern crate test; -use std::{f32, f64}; -#[cfg(not(target_os = "emscripten"))] -use std::{i128, u128}; -use std::{i16, i32, i64, i8, u16, u32, u64, u8}; -use test::black_box; - -macro_rules! test { - ($val:expr, $src_ty:ident -> $dest_ty:ident, $expected:expr) => ( - // black_box disables constant evaluation to test run-time conversions: - assert_eq!(black_box::<$src_ty>($val) as $dest_ty, $expected, - "run-time {} -> {}", stringify!($src_ty), stringify!($dest_ty)); - - { - const X: $src_ty = $val; - const Y: $dest_ty = X as $dest_ty; - assert_eq!(Y, $expected, - "const eval {} -> {}", stringify!($src_ty), stringify!($dest_ty)); - } - ); - - ($fval:expr, f* -> $ity:ident, $ival:expr) => ( - test!($fval, f32 -> $ity, $ival); - test!($fval, f64 -> $ity, $ival); - ) -} - -macro_rules! common_fptoi_tests { - ($fty:ident -> $($ity:ident)+) => ({ $( - test!($fty::NAN, $fty -> $ity, 0); - test!($fty::INFINITY, $fty -> $ity, $ity::MAX); - test!($fty::NEG_INFINITY, $fty -> $ity, $ity::MIN); - // These two tests are not solely float->int tests, in particular the latter relies on - // `u128::MAX as f32` not being UB. But that's okay, since this file tests int->float - // as well, the test is just slightly misplaced. - test!($ity::MIN as $fty, $fty -> $ity, $ity::MIN); - test!($ity::MAX as $fty, $fty -> $ity, $ity::MAX); - test!(0., $fty -> $ity, 0); - test!($fty::MIN_POSITIVE, $fty -> $ity, 0); - test!(-0.9, $fty -> $ity, 0); - test!(1., $fty -> $ity, 1); - test!(42., $fty -> $ity, 42); - )+ }); - - (f* -> $($ity:ident)+) => ({ - common_fptoi_tests!(f32 -> $($ity)+); - common_fptoi_tests!(f64 -> $($ity)+); - }) -} - -macro_rules! fptoui_tests { - ($fty: ident -> $($ity: ident)+) => ({ $( - test!(-0., $fty -> $ity, 0); - test!(-$fty::MIN_POSITIVE, $fty -> $ity, 0); - test!(-0.99999994, $fty -> $ity, 0); - test!(-1., $fty -> $ity, 0); - test!(-100., $fty -> $ity, 0); - test!(#[allow(overflowing_literals)] -1e50, $fty -> $ity, 0); - test!(#[allow(overflowing_literals)] -1e130, $fty -> $ity, 0); - )+ }); - - (f* -> $($ity:ident)+) => ({ - fptoui_tests!(f32 -> $($ity)+); - fptoui_tests!(f64 -> $($ity)+); - }) -} - -use std::fmt::Debug; - -// Helper function to avoid promotion so that this tests "run-time" casts, not CTFE. -#[track_caller] -#[inline(never)] -fn assert_eq(x: T, y: T) { - assert_eq!(x, y); -} - -trait FloatToInt: Copy { - fn cast(self) -> Int; - unsafe fn cast_unchecked(self) -> Int; -} - -impl FloatToInt for f32 { - fn cast(self) -> i8 { - self as _ - } - unsafe fn cast_unchecked(self) -> i8 { - self.to_int_unchecked() - } -} -impl FloatToInt for f32 { - fn cast(self) -> i32 { - self as _ - } - unsafe fn cast_unchecked(self) -> i32 { - self.to_int_unchecked() - } -} -impl FloatToInt for f32 { - fn cast(self) -> u32 { - self as _ - } - unsafe fn cast_unchecked(self) -> u32 { - self.to_int_unchecked() - } -} -impl FloatToInt for f32 { - fn cast(self) -> i64 { - self as _ - } - unsafe fn cast_unchecked(self) -> i64 { - self.to_int_unchecked() - } -} -impl FloatToInt for f32 { - fn cast(self) -> u64 { - self as _ - } - unsafe fn cast_unchecked(self) -> u64 { - self.to_int_unchecked() - } -} - -impl FloatToInt for f64 { - fn cast(self) -> i8 { - self as _ - } - unsafe fn cast_unchecked(self) -> i8 { - self.to_int_unchecked() - } -} -impl FloatToInt for f64 { - fn cast(self) -> i32 { - self as _ - } - unsafe fn cast_unchecked(self) -> i32 { - self.to_int_unchecked() - } -} -impl FloatToInt for f64 { - fn cast(self) -> u32 { - self as _ - } - unsafe fn cast_unchecked(self) -> u32 { - self.to_int_unchecked() - } -} -impl FloatToInt for f64 { - fn cast(self) -> i64 { - self as _ - } - unsafe fn cast_unchecked(self) -> i64 { - self.to_int_unchecked() - } -} -impl FloatToInt for f64 { - fn cast(self) -> u64 { - self as _ - } - unsafe fn cast_unchecked(self) -> u64 { - self.to_int_unchecked() - } -} -// FIXME emscripten does not support i128 -#[cfg(not(target_os = "emscripten"))] -impl FloatToInt for f64 { - fn cast(self) -> i128 { - self as _ - } - unsafe fn cast_unchecked(self) -> i128 { - self.to_int_unchecked() - } -} -// FIXME emscripten does not support i128 -#[cfg(not(target_os = "emscripten"))] -impl FloatToInt for f64 { - fn cast(self) -> u128 { - self as _ - } - unsafe fn cast_unchecked(self) -> u128 { - self.to_int_unchecked() - } -} - -/// Test this cast both via `as` and via `to_int_unchecked` (i.e., it must not saturate). -#[track_caller] -#[inline(never)] -fn test_both_cast(x: F, y: I) -where - F: FloatToInt, - I: PartialEq + Debug, -{ - assert_eq!(x.cast(), y); - assert_eq!(unsafe { x.cast_unchecked() }, y); -} - -fn casts() { - // f32 -> i8 - test_both_cast::(127.99, 127); - test_both_cast::(-128.99, -128); - - // f32 -> i32 - test_both_cast::(0.0, 0); - test_both_cast::(-0.0, 0); - test_both_cast::(/*0x1p-149*/ f32::from_bits(0x00000001), 0); - test_both_cast::(/*-0x1p-149*/ f32::from_bits(0x80000001), 0); - test_both_cast::(/*0x1.19999ap+0*/ f32::from_bits(0x3f8ccccd), 1); - test_both_cast::(/*-0x1.19999ap+0*/ f32::from_bits(0xbf8ccccd), -1); - test_both_cast::(1.9, 1); - test_both_cast::(-1.9, -1); - test_both_cast::(5.0, 5); - test_both_cast::(-5.0, -5); - test_both_cast::(2147483520.0, 2147483520); - test_both_cast::(-2147483648.0, -2147483648); - // unrepresentable casts - assert_eq::(2147483648.0f32 as i32, i32::MAX); - assert_eq::(-2147483904.0f32 as i32, i32::MIN); - assert_eq::(f32::MAX as i32, i32::MAX); - assert_eq::(f32::MIN as i32, i32::MIN); - assert_eq::(f32::INFINITY as i32, i32::MAX); - assert_eq::(f32::NEG_INFINITY as i32, i32::MIN); - assert_eq::(f32::NAN as i32, 0); - assert_eq::((-f32::NAN) as i32, 0); - - // f32 -> u32 - test_both_cast::(0.0, 0); - test_both_cast::(-0.0, 0); - test_both_cast::(-0.9999999, 0); - test_both_cast::(/*0x1p-149*/ f32::from_bits(0x1), 0); - test_both_cast::(/*-0x1p-149*/ f32::from_bits(0x80000001), 0); - test_both_cast::(/*0x1.19999ap+0*/ f32::from_bits(0x3f8ccccd), 1); - test_both_cast::(1.9, 1); - test_both_cast::(5.0, 5); - test_both_cast::(2147483648.0, 0x8000_0000); - test_both_cast::(4294967040.0, 0u32.wrapping_sub(256)); - test_both_cast::(/*-0x1.ccccccp-1*/ f32::from_bits(0xbf666666), 0); - test_both_cast::(/*-0x1.fffffep-1*/ f32::from_bits(0xbf7fffff), 0); - test_both_cast::((u32::MAX - 128) as f32, u32::MAX - 255); // rounding loss - - // unrepresentable casts: - - // rounds up and then becomes unrepresentable - assert_eq::((u32::MAX - 127) as f32 as u32, u32::MAX); - - assert_eq::(4294967296.0f32 as u32, u32::MAX); - assert_eq::(-5.0f32 as u32, 0); - assert_eq::(f32::MAX as u32, u32::MAX); - assert_eq::(f32::MIN as u32, 0); - assert_eq::(f32::INFINITY as u32, u32::MAX); - assert_eq::(f32::NEG_INFINITY as u32, 0); - assert_eq::(f32::NAN as u32, 0); - assert_eq::((-f32::NAN) as u32, 0); - - // f32 -> i64 - test_both_cast::(4294967296.0, 4294967296); - test_both_cast::(-4294967296.0, -4294967296); - test_both_cast::(9223371487098961920.0, 9223371487098961920); - test_both_cast::(-9223372036854775808.0, -9223372036854775808); - - // f64 -> i8 - test_both_cast::(127.99, 127); - test_both_cast::(-128.99, -128); - - // f64 -> i32 - test_both_cast::(0.0, 0); - test_both_cast::(-0.0, 0); - test_both_cast::(/*0x1.199999999999ap+0*/ f64::from_bits(0x3ff199999999999a), 1); - test_both_cast::( - /*-0x1.199999999999ap+0*/ f64::from_bits(0xbff199999999999a), - -1, - ); - test_both_cast::(1.9, 1); - test_both_cast::(-1.9, -1); - test_both_cast::(1e8, 100_000_000); - test_both_cast::(2147483647.0, 2147483647); - test_both_cast::(-2147483648.0, -2147483648); - // unrepresentable casts - assert_eq::(2147483648.0f64 as i32, i32::MAX); - assert_eq::(-2147483649.0f64 as i32, i32::MIN); - - // f64 -> i64 - test_both_cast::(0.0, 0); - test_both_cast::(-0.0, 0); - test_both_cast::(/*0x0.0000000000001p-1022*/ f64::from_bits(0x1), 0); - test_both_cast::( - /*-0x0.0000000000001p-1022*/ f64::from_bits(0x8000000000000001), - 0, - ); - test_both_cast::(/*0x1.199999999999ap+0*/ f64::from_bits(0x3ff199999999999a), 1); - test_both_cast::( - /*-0x1.199999999999ap+0*/ f64::from_bits(0xbff199999999999a), - -1, - ); - test_both_cast::(5.0, 5); - test_both_cast::(5.9, 5); - test_both_cast::(-5.0, -5); - test_both_cast::(-5.9, -5); - test_both_cast::(4294967296.0, 4294967296); - test_both_cast::(-4294967296.0, -4294967296); - test_both_cast::(9223372036854774784.0, 9223372036854774784); - test_both_cast::(-9223372036854775808.0, -9223372036854775808); - // unrepresentable casts - assert_eq::(9223372036854775808.0f64 as i64, i64::MAX); - assert_eq::(-9223372036854777856.0f64 as i64, i64::MIN); - assert_eq::(f64::MAX as i64, i64::MAX); - assert_eq::(f64::MIN as i64, i64::MIN); - assert_eq::(f64::INFINITY as i64, i64::MAX); - assert_eq::(f64::NEG_INFINITY as i64, i64::MIN); - assert_eq::(f64::NAN as i64, 0); - assert_eq::((-f64::NAN) as i64, 0); - - // f64 -> u64 - test_both_cast::(0.0, 0); - test_both_cast::(-0.0, 0); - test_both_cast::(-0.99999999999, 0); - test_both_cast::(5.0, 5); - test_both_cast::(1e16, 10000000000000000); - test_both_cast::((u64::MAX - 1024) as f64, u64::MAX - 2047); // rounding loss - test_both_cast::(9223372036854775808.0, 9223372036854775808); - // unrepresentable casts - assert_eq::(-5.0f64 as u64, 0); - // rounds up and then becomes unrepresentable - assert_eq::((u64::MAX - 1023) as f64 as u64, u64::MAX); - assert_eq::(18446744073709551616.0f64 as u64, u64::MAX); - assert_eq::(f64::MAX as u64, u64::MAX); - assert_eq::(f64::MIN as u64, 0); - assert_eq::(f64::INFINITY as u64, u64::MAX); - assert_eq::(f64::NEG_INFINITY as u64, 0); - assert_eq::(f64::NAN as u64, 0); - assert_eq::((-f64::NAN) as u64, 0); - - // FIXME emscripten does not support i128 - #[cfg(not(target_os = "emscripten"))] - { - // f64 -> i128 - assert_eq::(f64::MAX as i128, i128::MAX); - assert_eq::(f64::MIN as i128, i128::MIN); - - // f64 -> u128 - assert_eq::(f64::MAX as u128, u128::MAX); - assert_eq::(f64::MIN as u128, 0); - } - - // int -> f32 - assert_eq::(127i8 as f32, 127.0); - assert_eq::(2147483647i32 as f32, 2147483648.0); - assert_eq::((-2147483648i32) as f32, -2147483648.0); - assert_eq::(1234567890i32 as f32, /*0x1.26580cp+30*/ f32::from_bits(0x4e932c06)); - assert_eq::(16777217i32 as f32, 16777216.0); - assert_eq::((-16777217i32) as f32, -16777216.0); - assert_eq::(16777219i32 as f32, 16777220.0); - assert_eq::((-16777219i32) as f32, -16777220.0); - assert_eq::( - 0x7fffff4000000001i64 as f32, - /*0x1.fffffep+62*/ f32::from_bits(0x5effffff), - ); - assert_eq::( - 0x8000004000000001u64 as i64 as f32, - /*-0x1.fffffep+62*/ f32::from_bits(0xdeffffff), - ); - assert_eq::( - 0x0020000020000001i64 as f32, - /*0x1.000002p+53*/ f32::from_bits(0x5a000001), - ); - assert_eq::( - 0xffdfffffdfffffffu64 as i64 as f32, - /*-0x1.000002p+53*/ f32::from_bits(0xda000001), - ); - // FIXME emscripten does not support i128 - #[cfg(not(target_os = "emscripten"))] - { - assert_eq::(i128::MIN as f32, -170141183460469231731687303715884105728.0f32); - assert_eq::(u128::MAX as f32, f32::INFINITY); // saturation - } - - // int -> f64 - assert_eq::(127i8 as f64, 127.0); - assert_eq::(i16::MIN as f64, -32768.0f64); - assert_eq::(2147483647i32 as f64, 2147483647.0); - assert_eq::(-2147483648i32 as f64, -2147483648.0); - assert_eq::(987654321i32 as f64, 987654321.0); - assert_eq::(9223372036854775807i64 as f64, 9223372036854775807.0); - assert_eq::(-9223372036854775808i64 as f64, -9223372036854775808.0); - assert_eq::(4669201609102990i64 as f64, 4669201609102990.0); // Feigenbaum (?) - assert_eq::(9007199254740993i64 as f64, 9007199254740992.0); - assert_eq::(-9007199254740993i64 as f64, -9007199254740992.0); - assert_eq::(9007199254740995i64 as f64, 9007199254740996.0); - assert_eq::(-9007199254740995i64 as f64, -9007199254740996.0); - // FIXME emscripten does not support i128 - #[cfg(not(target_os = "emscripten"))] - { - // even that fits... - assert_eq::(u128::MAX as f64, 340282366920938463463374607431768211455.0f64); - } - - // f32 -> f64 - assert_eq::((0.0f32 as f64).to_bits(), 0.0f64.to_bits()); - assert_eq::(((-0.0f32) as f64).to_bits(), (-0.0f64).to_bits()); - assert_eq::(5.0f32 as f64, 5.0f64); - assert_eq::( - /*0x1p-149*/ f32::from_bits(0x1) as f64, - /*0x1p-149*/ f64::from_bits(0x36a0000000000000), - ); - assert_eq::( - /*-0x1p-149*/ f32::from_bits(0x80000001) as f64, - /*-0x1p-149*/ f64::from_bits(0xb6a0000000000000), - ); - assert_eq::( - /*0x1.fffffep+127*/ f32::from_bits(0x7f7fffff) as f64, - /*0x1.fffffep+127*/ f64::from_bits(0x47efffffe0000000), - ); - assert_eq::( - /*-0x1.fffffep+127*/ (-f32::from_bits(0x7f7fffff)) as f64, - /*-0x1.fffffep+127*/ -f64::from_bits(0x47efffffe0000000), - ); - assert_eq::( - /*0x1p-119*/ f32::from_bits(0x4000000) as f64, - /*0x1p-119*/ f64::from_bits(0x3880000000000000), - ); - assert_eq::( - /*0x1.8f867ep+125*/ f32::from_bits(0x7e47c33f) as f64, - 6.6382536710104395e+37, - ); - assert_eq::(f32::INFINITY as f64, f64::INFINITY); - assert_eq::(f32::NEG_INFINITY as f64, f64::NEG_INFINITY); - - // f64 -> f32 - assert_eq::((0.0f64 as f32).to_bits(), 0.0f32.to_bits()); - assert_eq::(((-0.0f64) as f32).to_bits(), (-0.0f32).to_bits()); - assert_eq::(5.0f64 as f32, 5.0f32); - assert_eq::(/*0x0.0000000000001p-1022*/ f64::from_bits(0x1) as f32, 0.0); - assert_eq::(/*-0x0.0000000000001p-1022*/ (-f64::from_bits(0x1)) as f32, -0.0); - assert_eq::( - /*0x1.fffffe0000000p-127*/ f64::from_bits(0x380fffffe0000000) as f32, - /*0x1p-149*/ f32::from_bits(0x800000), - ); - assert_eq::( - /*0x1.4eae4f7024c7p+108*/ f64::from_bits(0x46b4eae4f7024c70) as f32, - /*0x1.4eae5p+108*/ f32::from_bits(0x75a75728), - ); - assert_eq::(f64::MAX as f32, f32::INFINITY); - assert_eq::(f64::MIN as f32, f32::NEG_INFINITY); - assert_eq::(f64::INFINITY as f32, f32::INFINITY); - assert_eq::(f64::NEG_INFINITY as f32, f32::NEG_INFINITY); -} +#[path = "saturating-float-casts-impl.rs"] +mod implementation; pub fn main() { - casts(); // from miri's tests - - common_fptoi_tests!(f* -> i8 i16 i32 i64 u8 u16 u32 u64); - fptoui_tests!(f* -> u8 u16 u32 u64); - // FIXME emscripten does not support i128 - #[cfg(not(target_os = "emscripten"))] - { - common_fptoi_tests!(f* -> i128 u128); - fptoui_tests!(f* -> u128); - } - - // The following tests cover edge cases for some integer types. - - // # u8 - test!(254., f* -> u8, 254); - test!(256., f* -> u8, 255); - - // # i8 - test!(-127., f* -> i8, -127); - test!(-129., f* -> i8, -128); - test!(126., f* -> i8, 126); - test!(128., f* -> i8, 127); - - // # i32 - // -2147483648. is i32::MIN (exactly) - test!(-2147483648., f* -> i32, i32::MIN); - // 2147483648. is i32::MAX rounded up - test!(2147483648., f32 -> i32, 2147483647); - // With 24 significand bits, floats with magnitude in [2^30 + 1, 2^31] are rounded to - // multiples of 2^7. Therefore, nextDown(round(i32::MAX)) is 2^31 - 128: - test!(2147483520., f32 -> i32, 2147483520); - // Similarly, nextUp(i32::MIN) is i32::MIN + 2^8 and nextDown(i32::MIN) is i32::MIN - 2^7 - test!(-2147483904., f* -> i32, i32::MIN); - test!(-2147483520., f* -> i32, -2147483520); - - // # u32 - // round(MAX) and nextUp(round(MAX)) - test!(4294967040., f* -> u32, 4294967040); - test!(4294967296., f* -> u32, 4294967295); - - // # u128 - #[cfg(not(target_os = "emscripten"))] - { - // float->int: - test!(f32::MAX, f32 -> u128, 0xffffff00000000000000000000000000); - // nextDown(f32::MAX) = 2^128 - 2 * 2^104 - const SECOND_LARGEST_F32: f32 = 340282326356119256160033759537265639424.; - test!(SECOND_LARGEST_F32, f32 -> u128, 0xfffffe00000000000000000000000000); - } + implementation::run(); } From dca9310ceb495ae2d5c6c775c151d75202e686d7 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 2 Jul 2020 10:25:04 +0200 Subject: [PATCH 11/12] disable BTree min_max test in Miri for now --- src/liballoc/tests/btree/map.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/liballoc/tests/btree/map.rs b/src/liballoc/tests/btree/map.rs index 682d829d219f3..f66b5814ca0d4 100644 --- a/src/liballoc/tests/btree/map.rs +++ b/src/liballoc/tests/btree/map.rs @@ -310,6 +310,7 @@ fn test_iter_mixed() { } #[test] +#[cfg_attr(miri, ignore)] // FIXME: fails in Miri fn test_iter_min_max() { let mut a = BTreeMap::new(); assert_eq!(a.iter().min(), None); From cb541dc12cdf2ba14a8f5d210ac7a6b1efa69c22 Mon Sep 17 00:00:00 2001 From: David Wood Date: Thu, 25 Jun 2020 15:16:38 +0100 Subject: [PATCH 12/12] resolve: disallow label use through closure/async This commit modifies resolve to disallow `break`/`continue` to labels through closures or async blocks. This doesn't make sense and should have been prohibited anyway. Signed-off-by: David Wood --- src/librustc_error_codes/error_codes.rs | 1 + src/librustc_error_codes/error_codes/E0767.md | 20 +++ src/librustc_passes/liveness.rs | 11 +- src/librustc_resolve/diagnostics.rs | 78 ++++++-- src/librustc_resolve/late.rs | 167 +++++++++++------- src/librustc_resolve/late/diagnostics.rs | 28 ++- src/librustc_resolve/lib.rs | 8 +- src/test/ui/break-outside-loop.rs | 4 +- src/test/ui/break-outside-loop.stderr | 15 +- src/test/ui/error-codes/E0767.rs | 7 + src/test/ui/error-codes/E0767.stderr | 14 ++ src/test/ui/issues/issue-62480.rs | 4 +- src/test/ui/issues/issue-62480.stderr | 20 ++- .../issue-66702-break-outside-loop-val.rs | 4 +- .../issue-66702-break-outside-loop-val.stderr | 15 +- src/test/ui/issues/issue-73541-1.rs | 12 ++ src/test/ui/issues/issue-73541-1.stderr | 14 ++ src/test/ui/issues/issue-73541-2.rs | 20 +++ src/test/ui/issues/issue-73541-2.stderr | 18 ++ src/test/ui/issues/issue-73541-3.rs | 9 + src/test/ui/issues/issue-73541-3.stderr | 12 ++ src/test/ui/issues/issue-73541.rs | 9 + src/test/ui/issues/issue-73541.stderr | 14 ++ src/test/ui/resolve/resolve-label.rs | 2 +- src/test/ui/resolve/resolve-label.stderr | 11 +- src/test/ui/suggestions/suggest-labels.stderr | 30 ++-- 26 files changed, 427 insertions(+), 120 deletions(-) create mode 100644 src/librustc_error_codes/error_codes/E0767.md create mode 100644 src/test/ui/error-codes/E0767.rs create mode 100644 src/test/ui/error-codes/E0767.stderr create mode 100644 src/test/ui/issues/issue-73541-1.rs create mode 100644 src/test/ui/issues/issue-73541-1.stderr create mode 100644 src/test/ui/issues/issue-73541-2.rs create mode 100644 src/test/ui/issues/issue-73541-2.stderr create mode 100644 src/test/ui/issues/issue-73541-3.rs create mode 100644 src/test/ui/issues/issue-73541-3.stderr create mode 100644 src/test/ui/issues/issue-73541.rs create mode 100644 src/test/ui/issues/issue-73541.stderr diff --git a/src/librustc_error_codes/error_codes.rs b/src/librustc_error_codes/error_codes.rs index a5527158aab3c..00c072e1b04a1 100644 --- a/src/librustc_error_codes/error_codes.rs +++ b/src/librustc_error_codes/error_codes.rs @@ -448,6 +448,7 @@ E0763: include_str!("./error_codes/E0763.md"), E0764: include_str!("./error_codes/E0764.md"), E0765: include_str!("./error_codes/E0765.md"), E0766: include_str!("./error_codes/E0766.md"), +E0767: include_str!("./error_codes/E0767.md"), ; // E0006, // merged with E0005 // E0008, // cannot bind by-move into a pattern guard diff --git a/src/librustc_error_codes/error_codes/E0767.md b/src/librustc_error_codes/error_codes/E0767.md new file mode 100644 index 0000000000000..679fe7e41e9c7 --- /dev/null +++ b/src/librustc_error_codes/error_codes/E0767.md @@ -0,0 +1,20 @@ +An unreachable label was used. + +Erroneous code example: + +```compile_fail,E0767 +'a: loop { + || { + loop { break 'a } // error: use of unreachable label `'a` + }; +} +``` + +Ensure that the label is within scope. Labels are not reachable through +functions, closures, async blocks or modules. Example: + +``` +'a: loop { + break 'a; // ok! +} +``` diff --git a/src/librustc_passes/liveness.rs b/src/librustc_passes/liveness.rs index 798c6b8925bbf..b288a41e0cfd6 100644 --- a/src/librustc_passes/liveness.rs +++ b/src/librustc_passes/liveness.rs @@ -1123,16 +1123,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { match target { Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b), - None => { - // FIXME: This should have been checked earlier. Once this is fixed, - // replace with `delay_span_bug`. (#62480) - self.ir - .tcx - .sess - .struct_span_err(expr.span, "`break` to unknown label") - .emit(); - rustc_errors::FatalError.raise() - } + None => span_bug!(expr.span, "`break` to unknown label"), } } diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 2854683b61bab..c64c617b54b59 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -33,6 +33,10 @@ type Res = def::Res; /// A vector of spans and replacements, a message and applicability. crate type Suggestion = (Vec<(Span, String)>, String, Applicability); +/// Potential candidate for an undeclared or out-of-scope label - contains the ident of a +/// similarly named label and whether or not it is reachable. +crate type LabelSuggestion = (Ident, bool); + crate struct TypoSuggestion { pub candidate: Symbol, pub res: Res, @@ -282,7 +286,7 @@ impl<'a> Resolver<'a> { err.span_label(span, "used in a pattern more than once"); err } - ResolutionError::UndeclaredLabel(name, lev_candidate) => { + ResolutionError::UndeclaredLabel { name, suggestion } => { let mut err = struct_span_err!( self.session, span, @@ -290,16 +294,31 @@ impl<'a> Resolver<'a> { "use of undeclared label `{}`", name ); - if let Some(lev_candidate) = lev_candidate { - err.span_suggestion( - span, - "a label with a similar name exists in this scope", - lev_candidate.to_string(), - Applicability::MaybeIncorrect, - ); - } else { - err.span_label(span, format!("undeclared label `{}`", name)); + + err.span_label(span, format!("undeclared label `{}`", name)); + + match suggestion { + // A reachable label with a similar name exists. + Some((ident, true)) => { + err.span_label(ident.span, "a label with a similar name is reachable"); + err.span_suggestion( + span, + "try using similarly named label", + ident.name.to_string(), + Applicability::MaybeIncorrect, + ); + } + // An unreachable label with a similar name exists. + Some((ident, false)) => { + err.span_label( + ident.span, + "a label with a similar name exists but is unreachable", + ); + } + // No similarly-named labels exist. + None => (), } + err } ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => { @@ -433,6 +452,45 @@ impl<'a> Resolver<'a> { err.span_label(span, "`Self` in type parameter default".to_string()); err } + ResolutionError::UnreachableLabel { name, definition_span, suggestion } => { + let mut err = struct_span_err!( + self.session, + span, + E0767, + "use of unreachable label `{}`", + name, + ); + + err.span_label(definition_span, "unreachable label defined here"); + err.span_label(span, format!("unreachable label `{}`", name)); + err.note( + "labels are unreachable through functions, closures, async blocks and modules", + ); + + match suggestion { + // A reachable label with a similar name exists. + Some((ident, true)) => { + err.span_label(ident.span, "a label with a similar name is reachable"); + err.span_suggestion( + span, + "try using similarly named label", + ident.name.to_string(), + Applicability::MaybeIncorrect, + ); + } + // An unreachable label with a similar name exists. + Some((ident, false)) => { + err.span_label( + ident.span, + "a label with a similar name exists but is also unreachable", + ); + } + // No similarly-named labels exist. + None => (), + } + + err + } } } diff --git a/src/librustc_resolve/late.rs b/src/librustc_resolve/late.rs index 84ba9094ea16f..4451791780ead 100644 --- a/src/librustc_resolve/late.rs +++ b/src/librustc_resolve/late.rs @@ -13,7 +13,6 @@ use crate::{ResolutionError, Resolver, Segment, UseError}; use rustc_ast::ast::*; use rustc_ast::ptr::P; -use rustc_ast::util::lev_distance::find_best_match_for_name; use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; use rustc_ast::{unwrap_or, walk_list}; use rustc_ast_lowering::ResolverAstLowering; @@ -101,6 +100,9 @@ crate enum RibKind<'a> { /// upvars). AssocItemRibKind, + /// We passed through a closure. Disallow labels. + ClosureOrAsyncRibKind, + /// We passed through a function definition. Disallow upvars. /// Permit only those const parameters that are specified in the function's generics. FnItemRibKind, @@ -124,11 +126,15 @@ crate enum RibKind<'a> { } impl RibKind<'_> { - // Whether this rib kind contains generic parameters, as opposed to local - // variables. + /// Whether this rib kind contains generic parameters, as opposed to local + /// variables. crate fn contains_params(&self) -> bool { match self { - NormalRibKind | FnItemRibKind | ConstantItemRibKind | ModuleRibKind(_) + NormalRibKind + | ClosureOrAsyncRibKind + | FnItemRibKind + | ConstantItemRibKind + | ModuleRibKind(_) | MacroDefinition(_) => false, AssocItemRibKind | ItemRibKind(_) | ForwardTyParamBanRibKind => true, } @@ -474,7 +480,8 @@ impl<'a, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> { // Bail if there's no body. FnKind::Fn(.., None) => return visit::walk_fn(self, fn_kind, sp), FnKind::Fn(FnCtxt::Free | FnCtxt::Foreign, ..) => FnItemRibKind, - FnKind::Fn(FnCtxt::Assoc(_), ..) | FnKind::Closure(..) => NormalRibKind, + FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind, + FnKind::Closure(..) => ClosureOrAsyncRibKind, }; let previous_value = replace(&mut self.diagnostic_metadata.current_function, Some((fn_kind, sp))); @@ -725,37 +732,81 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { } } - /// Searches the current set of local scopes for labels. Returns the first non-`None` label that - /// is returned by the given predicate function - /// - /// Stops after meeting a closure. - fn search_label(&self, mut ident: Ident, pred: P) -> Option - where - P: Fn(&Rib<'_, NodeId>, Ident) -> Option, - { - for rib in self.label_ribs.iter().rev() { - match rib.kind { - NormalRibKind => {} + /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved + /// label and reports an error if the label is not found or is unreachable. + fn resolve_label(&self, mut label: Ident) -> Option { + let mut suggestion = None; + + // Preserve the original span so that errors contain "in this macro invocation" + // information. + let original_span = label.span; + + for i in (0..self.label_ribs.len()).rev() { + let rib = &self.label_ribs[i]; + + if let MacroDefinition(def) = rib.kind { // If an invocation of this macro created `ident`, give up on `ident` // and switch to `ident`'s source from the macro definition. - MacroDefinition(def) => { - if def == self.r.macro_def(ident.span.ctxt()) { - ident.span.remove_mark(); - } - } - _ => { - // Do not resolve labels across function boundary - return None; + if def == self.r.macro_def(label.span.ctxt()) { + label.span.remove_mark(); } } - let r = pred(rib, ident); - if r.is_some() { - return r; + + let ident = label.normalize_to_macro_rules(); + if let Some((ident, id)) = rib.bindings.get_key_value(&ident) { + return if self.is_label_valid_from_rib(i) { + Some(*id) + } else { + self.r.report_error( + original_span, + ResolutionError::UnreachableLabel { + name: &label.name.as_str(), + definition_span: ident.span, + suggestion, + }, + ); + + None + }; } + + // Diagnostics: Check if this rib contains a label with a similar name, keep track of + // the first such label that is encountered. + suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label)); } + + self.r.report_error( + original_span, + ResolutionError::UndeclaredLabel { name: &label.name.as_str(), suggestion }, + ); None } + /// Determine whether or not a label from the `rib_index`th label rib is reachable. + fn is_label_valid_from_rib(&self, rib_index: usize) -> bool { + let ribs = &self.label_ribs[rib_index + 1..]; + + for rib in ribs { + match rib.kind { + NormalRibKind | MacroDefinition(..) => { + // Nothing to do. Continue. + } + + AssocItemRibKind + | ClosureOrAsyncRibKind + | FnItemRibKind + | ItemRibKind(..) + | ConstantItemRibKind + | ModuleRibKind(..) + | ForwardTyParamBanRibKind => { + return false; + } + } + } + + true + } + fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) { debug!("resolve_adt"); self.with_current_self_item(item, |this| { @@ -2044,35 +2095,10 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { } ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => { - let node_id = self.search_label(label.ident, |rib, ident| { - rib.bindings.get(&ident.normalize_to_macro_rules()).cloned() - }); - match node_id { - None => { - // Search again for close matches... - // Picks the first label that is "close enough", which is not necessarily - // the closest match - let close_match = self.search_label(label.ident, |rib, ident| { - let names = rib.bindings.iter().filter_map(|(id, _)| { - if id.span.ctxt() == label.ident.span.ctxt() { - Some(&id.name) - } else { - None - } - }); - find_best_match_for_name(names, &ident.as_str(), None) - }); - self.r.record_partial_res(expr.id, PartialRes::new(Res::Err)); - self.r.report_error( - label.ident.span, - ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match), - ); - } - Some(node_id) => { - // Since this res is a label, it is never read. - self.r.label_res_map.insert(expr.id, node_id); - self.diagnostic_metadata.unused_labels.remove(&node_id); - } + if let Some(node_id) = self.resolve_label(label.ident) { + // Since this res is a label, it is never read. + self.r.label_res_map.insert(expr.id, node_id); + self.diagnostic_metadata.unused_labels.remove(&node_id); } // visit `break` argument if any @@ -2144,21 +2170,26 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { // closure are detected as upvars rather than normal closure arg usages. ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => { self.with_rib(ValueNS, NormalRibKind, |this| { - // Resolve arguments: - this.resolve_params(&fn_decl.inputs); - // No need to resolve return type -- - // the outer closure return type is `FnRetTy::Default`. + this.with_label_rib(ClosureOrAsyncRibKind, |this| { + // Resolve arguments: + this.resolve_params(&fn_decl.inputs); + // No need to resolve return type -- + // the outer closure return type is `FnRetTy::Default`. - // Now resolve the inner closure - { - // No need to resolve arguments: the inner closure has none. - // Resolve the return type: - visit::walk_fn_ret_ty(this, &fn_decl.output); - // Resolve the body - this.visit_expr(body); - } + // Now resolve the inner closure + { + // No need to resolve arguments: the inner closure has none. + // Resolve the return type: + visit::walk_fn_ret_ty(this, &fn_decl.output); + // Resolve the body + this.visit_expr(body); + } + }) }); } + ExprKind::Async(..) | ExprKind::Closure(..) => { + self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr)); + } _ => { visit::walk_expr(self, expr); } diff --git a/src/librustc_resolve/late/diagnostics.rs b/src/librustc_resolve/late/diagnostics.rs index 1bce160acb610..e469ca80c590a 100644 --- a/src/librustc_resolve/late/diagnostics.rs +++ b/src/librustc_resolve/late/diagnostics.rs @@ -1,4 +1,4 @@ -use crate::diagnostics::{ImportSuggestion, TypoSuggestion}; +use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion}; use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext}; use crate::late::{LateResolutionVisitor, RibKind}; use crate::path_names_to_string; @@ -992,6 +992,32 @@ impl<'a> LateResolutionVisitor<'a, '_, '_> { } None } + + /// Given the target `label`, search the `rib_index`th label rib for similarly named labels, + /// optionally returning the closest match and whether it is reachable. + crate fn suggestion_for_label_in_rib( + &self, + rib_index: usize, + label: Ident, + ) -> Option { + // Are ribs from this `rib_index` within scope? + let within_scope = self.is_label_valid_from_rib(rib_index); + + let rib = &self.label_ribs[rib_index]; + let names = rib + .bindings + .iter() + .filter(|(id, _)| id.span.ctxt() == label.span.ctxt()) + .map(|(id, _)| &id.name); + + find_best_match_for_name(names, &label.as_str(), None).map(|symbol| { + // Upon finding a similar name, get the ident that it was from - the span + // contained within helps make a useful diagnostic. In addition, determine + // whether this candidate is within scope. + let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap(); + (*ident, within_scope) + }) + } } impl<'tcx> LifetimeContext<'_, 'tcx> { diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index dccaf76723a58..f3a1934abc9fe 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -61,7 +61,7 @@ use std::collections::BTreeSet; use std::{cmp, fmt, iter, ptr}; use diagnostics::{extend_span_to_previous_binding, find_span_of_binding_until_next_binding}; -use diagnostics::{ImportSuggestion, Suggestion}; +use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion}; use imports::{Import, ImportKind, ImportResolver, NameResolution}; use late::{HasGenericParams, PathSource, Rib, RibKind::*}; use macros::{MacroRulesBinding, MacroRulesScope}; @@ -197,7 +197,7 @@ enum ResolutionError<'a> { /// Error E0416: identifier is bound more than once in the same pattern. IdentifierBoundMoreThanOnceInSamePattern(&'a str), /// Error E0426: use of undeclared label. - UndeclaredLabel(&'a str, Option), + UndeclaredLabel { name: &'a str, suggestion: Option }, /// Error E0429: `self` imports are only allowed within a `{ }` list. SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span }, /// Error E0430: `self` import can only appear once in the list. @@ -216,6 +216,8 @@ enum ResolutionError<'a> { ForwardDeclaredTyParam, // FIXME(const_generics:defaults) /// Error E0735: type parameters with a default cannot use `Self` SelfInTyParamDefault, + /// Error E0767: use of unreachable label + UnreachableLabel { name: &'a str, definition_span: Span, suggestion: Option }, } enum VisResolutionError<'a> { @@ -2453,6 +2455,7 @@ impl<'a> Resolver<'a> { for rib in ribs { match rib.kind { NormalRibKind + | ClosureOrAsyncRibKind | ModuleRibKind(..) | MacroDefinition(..) | ForwardTyParamBanRibKind => { @@ -2488,6 +2491,7 @@ impl<'a> Resolver<'a> { for rib in ribs { let has_generic_params = match rib.kind { NormalRibKind + | ClosureOrAsyncRibKind | AssocItemRibKind | ModuleRibKind(..) | MacroDefinition(..) diff --git a/src/test/ui/break-outside-loop.rs b/src/test/ui/break-outside-loop.rs index a6f9d0423d082..26769b30dd5f0 100644 --- a/src/test/ui/break-outside-loop.rs +++ b/src/test/ui/break-outside-loop.rs @@ -27,7 +27,9 @@ fn main() { // not the `loop`, which failed in the call to `find_breakable`. (#65383) 'lab: loop { || { - break 'lab; //~ ERROR `break` inside of a closure + break 'lab; + //~^ ERROR use of unreachable label `'lab` + //~| ERROR `break` inside of a closure }; } } diff --git a/src/test/ui/break-outside-loop.stderr b/src/test/ui/break-outside-loop.stderr index 8e300fd848dab..287bf9af62e49 100644 --- a/src/test/ui/break-outside-loop.stderr +++ b/src/test/ui/break-outside-loop.stderr @@ -1,3 +1,14 @@ +error[E0767]: use of unreachable label `'lab` + --> $DIR/break-outside-loop.rs:30:19 + | +LL | 'lab: loop { + | ---- unreachable label defined here +LL | || { +LL | break 'lab; + | ^^^^ unreachable label `'lab` + | + = note: labels are unreachable through functions, closures, async blocks and modules + error[E0268]: `break` outside of a loop --> $DIR/break-outside-loop.rs:10:15 | @@ -41,7 +52,7 @@ LL | || { LL | break 'lab; | ^^^^^^^^^^ cannot `break` inside of a closure -error: aborting due to 6 previous errors +error: aborting due to 7 previous errors -Some errors have detailed explanations: E0267, E0268. +Some errors have detailed explanations: E0267, E0268, E0767. For more information about an error, try `rustc --explain E0267`. diff --git a/src/test/ui/error-codes/E0767.rs b/src/test/ui/error-codes/E0767.rs new file mode 100644 index 0000000000000..6c6cb746e6c75 --- /dev/null +++ b/src/test/ui/error-codes/E0767.rs @@ -0,0 +1,7 @@ +fn main () { + 'a: loop { + || { + loop { break 'a; } //~ ERROR E0767 + } + } +} diff --git a/src/test/ui/error-codes/E0767.stderr b/src/test/ui/error-codes/E0767.stderr new file mode 100644 index 0000000000000..2429823306b6e --- /dev/null +++ b/src/test/ui/error-codes/E0767.stderr @@ -0,0 +1,14 @@ +error[E0767]: use of unreachable label `'a` + --> $DIR/E0767.rs:4:26 + | +LL | 'a: loop { + | -- unreachable label defined here +LL | || { +LL | loop { break 'a; } + | ^^ unreachable label `'a` + | + = note: labels are unreachable through functions, closures, async blocks and modules + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0767`. diff --git a/src/test/ui/issues/issue-62480.rs b/src/test/ui/issues/issue-62480.rs index bc3e6c69a6024..5c3be3e64ee1a 100644 --- a/src/test/ui/issues/issue-62480.rs +++ b/src/test/ui/issues/issue-62480.rs @@ -5,6 +5,8 @@ fn main() { // `propagate_through_expr` would be the closure and not the `loop`, which wouldn't be found in // `self.break_ln`. (#62480) 'a: { - || break 'a //~ ERROR `break` to unknown label + || break 'a + //~^ ERROR use of unreachable label `'a` + //~| ERROR `break` inside of a closure } } diff --git a/src/test/ui/issues/issue-62480.stderr b/src/test/ui/issues/issue-62480.stderr index de8451ad7df0a..17085ef908bdf 100644 --- a/src/test/ui/issues/issue-62480.stderr +++ b/src/test/ui/issues/issue-62480.stderr @@ -1,8 +1,22 @@ -error: `break` to unknown label +error[E0767]: use of unreachable label `'a` + --> $DIR/issue-62480.rs:8:18 + | +LL | 'a: { + | -- unreachable label defined here +LL | || break 'a + | ^^ unreachable label `'a` + | + = note: labels are unreachable through functions, closures, async blocks and modules + +error[E0267]: `break` inside of a closure --> $DIR/issue-62480.rs:8:12 | LL | || break 'a - | ^^^^^^^^ + | -- ^^^^^^^^ cannot `break` inside of a closure + | | + | enclosing closure -error: aborting due to previous error +error: aborting due to 2 previous errors +Some errors have detailed explanations: E0267, E0767. +For more information about an error, try `rustc --explain E0267`. diff --git a/src/test/ui/issues/issue-66702-break-outside-loop-val.rs b/src/test/ui/issues/issue-66702-break-outside-loop-val.rs index bd3c00d262128..05b86cbbf8f05 100644 --- a/src/test/ui/issues/issue-66702-break-outside-loop-val.rs +++ b/src/test/ui/issues/issue-66702-break-outside-loop-val.rs @@ -2,6 +2,8 @@ fn main() { 'some_label: loop { - || break 'some_label (); //~ ERROR: `break` inside of a closure + || break 'some_label (); + //~^ ERROR: use of unreachable label `'some_label` + //~| ERROR: `break` inside of a closure } } diff --git a/src/test/ui/issues/issue-66702-break-outside-loop-val.stderr b/src/test/ui/issues/issue-66702-break-outside-loop-val.stderr index 83bde9775b2ec..f92ede311afb4 100644 --- a/src/test/ui/issues/issue-66702-break-outside-loop-val.stderr +++ b/src/test/ui/issues/issue-66702-break-outside-loop-val.stderr @@ -1,3 +1,13 @@ +error[E0767]: use of unreachable label `'some_label` + --> $DIR/issue-66702-break-outside-loop-val.rs:5:18 + | +LL | 'some_label: loop { + | ----------- unreachable label defined here +LL | || break 'some_label (); + | ^^^^^^^^^^^ unreachable label `'some_label` + | + = note: labels are unreachable through functions, closures, async blocks and modules + error[E0267]: `break` inside of a closure --> $DIR/issue-66702-break-outside-loop-val.rs:5:12 | @@ -6,6 +16,7 @@ LL | || break 'some_label (); | | | enclosing closure -error: aborting due to previous error +error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0267`. +Some errors have detailed explanations: E0267, E0767. +For more information about an error, try `rustc --explain E0267`. diff --git a/src/test/ui/issues/issue-73541-1.rs b/src/test/ui/issues/issue-73541-1.rs new file mode 100644 index 0000000000000..7fb0d6c39ff6b --- /dev/null +++ b/src/test/ui/issues/issue-73541-1.rs @@ -0,0 +1,12 @@ +// edition:2018 + +fn main() { + 'a: loop { + async { + loop { + continue 'a + //~^ ERROR use of unreachable label `'a` + } + }; + } +} diff --git a/src/test/ui/issues/issue-73541-1.stderr b/src/test/ui/issues/issue-73541-1.stderr new file mode 100644 index 0000000000000..80c1fdf002a83 --- /dev/null +++ b/src/test/ui/issues/issue-73541-1.stderr @@ -0,0 +1,14 @@ +error[E0767]: use of unreachable label `'a` + --> $DIR/issue-73541-1.rs:7:26 + | +LL | 'a: loop { + | -- unreachable label defined here +... +LL | continue 'a + | ^^ unreachable label `'a` + | + = note: labels are unreachable through functions, closures, async blocks and modules + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0767`. diff --git a/src/test/ui/issues/issue-73541-2.rs b/src/test/ui/issues/issue-73541-2.rs new file mode 100644 index 0000000000000..70b4ab2537626 --- /dev/null +++ b/src/test/ui/issues/issue-73541-2.rs @@ -0,0 +1,20 @@ +// edition:2018 + +async fn c() { + 'a: loop { + macro_rules! b { + () => { + continue 'a + //~^ ERROR use of unreachable label `'a` + } + } + + async { + loop { + b!(); + } + }; + } +} + +fn main() { } diff --git a/src/test/ui/issues/issue-73541-2.stderr b/src/test/ui/issues/issue-73541-2.stderr new file mode 100644 index 0000000000000..75d769c4e1545 --- /dev/null +++ b/src/test/ui/issues/issue-73541-2.stderr @@ -0,0 +1,18 @@ +error[E0767]: use of unreachable label `'a` + --> $DIR/issue-73541-2.rs:7:26 + | +LL | 'a: loop { + | -- unreachable label defined here +... +LL | continue 'a + | ^^ unreachable label `'a` +... +LL | b!(); + | ----- in this macro invocation + | + = note: labels are unreachable through functions, closures, async blocks and modules + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0767`. diff --git a/src/test/ui/issues/issue-73541-3.rs b/src/test/ui/issues/issue-73541-3.rs new file mode 100644 index 0000000000000..02ca02da8ed61 --- /dev/null +++ b/src/test/ui/issues/issue-73541-3.rs @@ -0,0 +1,9 @@ +fn main() { + 'aaaaab: loop { + || { + loop { continue 'aaaaaa } + //~^ ERROR use of undeclared label `'aaaaaa` + }; + + } +} diff --git a/src/test/ui/issues/issue-73541-3.stderr b/src/test/ui/issues/issue-73541-3.stderr new file mode 100644 index 0000000000000..53487aaca998c --- /dev/null +++ b/src/test/ui/issues/issue-73541-3.stderr @@ -0,0 +1,12 @@ +error[E0426]: use of undeclared label `'aaaaaa` + --> $DIR/issue-73541-3.rs:4:29 + | +LL | 'aaaaab: loop { + | ------- a label with a similar name exists but is unreachable +LL | || { +LL | loop { continue 'aaaaaa } + | ^^^^^^^ undeclared label `'aaaaaa` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0426`. diff --git a/src/test/ui/issues/issue-73541.rs b/src/test/ui/issues/issue-73541.rs new file mode 100644 index 0000000000000..399a07cd3fcc8 --- /dev/null +++ b/src/test/ui/issues/issue-73541.rs @@ -0,0 +1,9 @@ +fn main() { + 'a: loop { + || { + loop { continue 'a } + //~^ ERROR use of unreachable label `'a` + }; + + } +} diff --git a/src/test/ui/issues/issue-73541.stderr b/src/test/ui/issues/issue-73541.stderr new file mode 100644 index 0000000000000..4bb466ff16c58 --- /dev/null +++ b/src/test/ui/issues/issue-73541.stderr @@ -0,0 +1,14 @@ +error[E0767]: use of unreachable label `'a` + --> $DIR/issue-73541.rs:4:29 + | +LL | 'a: loop { + | -- unreachable label defined here +LL | || { +LL | loop { continue 'a } + | ^^ unreachable label `'a` + | + = note: labels are unreachable through functions, closures, async blocks and modules + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0767`. diff --git a/src/test/ui/resolve/resolve-label.rs b/src/test/ui/resolve/resolve-label.rs index 965ee4501044b..ac5410cd35522 100644 --- a/src/test/ui/resolve/resolve-label.rs +++ b/src/test/ui/resolve/resolve-label.rs @@ -2,7 +2,7 @@ fn f() { 'l: loop { fn g() { loop { - break 'l; //~ ERROR use of undeclared label + break 'l; //~ ERROR use of unreachable label } } } diff --git a/src/test/ui/resolve/resolve-label.stderr b/src/test/ui/resolve/resolve-label.stderr index 72a8e443bac9f..5729348ef2104 100644 --- a/src/test/ui/resolve/resolve-label.stderr +++ b/src/test/ui/resolve/resolve-label.stderr @@ -1,9 +1,14 @@ -error[E0426]: use of undeclared label `'l` +error[E0767]: use of unreachable label `'l` --> $DIR/resolve-label.rs:5:23 | +LL | 'l: loop { + | -- unreachable label defined here +... LL | break 'l; - | ^^ undeclared label `'l` + | ^^ unreachable label `'l` + | + = note: labels are unreachable through functions, closures, async blocks and modules error: aborting due to previous error -For more information about this error, try `rustc --explain E0426`. +For more information about this error, try `rustc --explain E0767`. diff --git a/src/test/ui/suggestions/suggest-labels.stderr b/src/test/ui/suggestions/suggest-labels.stderr index 079821e649070..aac6515b527c7 100644 --- a/src/test/ui/suggestions/suggest-labels.stderr +++ b/src/test/ui/suggestions/suggest-labels.stderr @@ -1,35 +1,35 @@ error[E0426]: use of undeclared label `'fo` --> $DIR/suggest-labels.rs:4:15 | +LL | 'foo: loop { + | ---- a label with a similar name is reachable LL | break 'fo; | ^^^ - | -help: a label with a similar name exists in this scope - | -LL | break 'foo; - | ^^^^ + | | + | undeclared label `'fo` + | help: try using similarly named label: `'foo` error[E0426]: use of undeclared label `'bor` --> $DIR/suggest-labels.rs:8:18 | +LL | 'bar: loop { + | ---- a label with a similar name is reachable LL | continue 'bor; | ^^^^ - | -help: a label with a similar name exists in this scope - | -LL | continue 'bar; - | ^^^^ + | | + | undeclared label `'bor` + | help: try using similarly named label: `'bar` error[E0426]: use of undeclared label `'longlable` --> $DIR/suggest-labels.rs:13:19 | +LL | 'longlabel1: loop { + | ----------- a label with a similar name is reachable LL | break 'longlable; | ^^^^^^^^^^ - | -help: a label with a similar name exists in this scope - | -LL | break 'longlabel1; - | ^^^^^^^^^^^ + | | + | undeclared label `'longlable` + | help: try using similarly named label: `'longlabel1` error: aborting due to 3 previous errors