Auto merge of #3885 - rust-lang:rustup-2024-09-14, r=RalfJung

Automatic Rustup
This commit is contained in:
bors 2024-09-14 07:07:30 +00:00
commit 583f358e94
423 changed files with 5462 additions and 2998 deletions

4
.gitmodules vendored
View File

@ -51,3 +51,7 @@
path = src/tools/enzyme
url = https://github.com/EnzymeAD/Enzyme.git
shallow = true
[submodule "src/gcc"]
path = src/gcc
url = https://github.com/rust-lang/gcc.git
shallow = true

View File

@ -0,0 +1,30 @@
GCC RUNTIME LIBRARY EXCEPTION
Version 3.1, 31 March 2009
Copyright © 2009 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
This GCC Runtime Library Exception ("Exception") is an additional permission under section 7 of the GNU General Public License, version 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that bears a notice placed by the copyright holder of the file stating that the file is governed by GPLv3 along with this Exception.
When you use GCC to compile a program, GCC may combine portions of certain GCC header files and runtime libraries with the compiled program. The purpose of this Exception is to allow compilation of non-GPL (including proprietary) programs to use, in this way, the header files and runtime libraries covered by this Exception.
0. Definitions.
A file is an "Independent Module" if it either requires the Runtime Library for execution after a Compilation Process, or makes use of an interface provided by the Runtime Library, but is not otherwise based on the Runtime Library.
"GCC" means a version of the GNU Compiler Collection, with or without modifications, governed by version 3 (or a specified later version) of the GNU General Public License (GPL) with the option of using any subsequent versions published by the FSF.
"GPL-compatible Software" is software whose conditions of propagation, modification and use would permit combination with GCC in accord with the license of GCC.
"Target Code" refers to output from any compiler for a real or virtual target processor architecture, in executable form or suitable for input to an assembler, loader, linker and/or execution phase. Notwithstanding that, Target Code does not include data in any format that is used as a compiler intermediate representation, or used for producing a compiler intermediate representation.
The "Compilation Process" transforms code entirely represented in non-intermediate languages designed for human-written code, and/or in Java Virtual Machine byte code, into Target Code. Thus, for example, use of source code generators and preprocessors need not be considered part of the Compilation Process, since the Compilation Process can be understood as starting with the output of the generators or preprocessors.
A Compilation Process is "Eligible" if it is done using GCC, alone or with other GPL-compatible software, or if it is done without using any work based on GCC. For example, using non-GPL-compatible Software to optimize any GCC intermediate representations would not qualify as an Eligible Compilation Process.
1. Grant of Additional Permission.
You have permission to propagate a work of Target Code formed by combining the Runtime Library with Independent Modules, even if such propagation would otherwise violate the terms of GPLv3, provided that all Target Code was generated by Eligible Compilation Processes. You may then convey such a combination under terms of your choice, consistent with the licensing of the Independent Modules.
2. No Weakening of GCC Copyleft.
The availability of this Exception does not imply any general presumption that third-party software is unaffected by the copyleft requirements of the license of GCC.

133
LICENSES/GPL-2.0-only.txt Normal file
View File

@ -0,0 +1,133 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does.
Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'. This is free software, and you are welcome
to redistribute it under certain conditions; type `show c'
for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written
by James Hacker.
signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.

View File

@ -0,0 +1,202 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https: //www.gnu.org/licenses/why-not-lgpl.html>.

7
LICENSES/ISC.txt Normal file
View File

@ -0,0 +1,7 @@
ISC License
<copyright notice>
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@ -168,3 +168,37 @@ SPDX-FileCopyrightText = [
"2003-2019 University of Illinois at Urbana-Champaign.",
]
SPDX-License-Identifier = "NCSA AND Apache-2.0 WITH LLVM-exception"
[[annotations]]
path = "src/gcc/**"
precedence = "override"
SPDX-FileCopyrightText = [
"Copyright (C) 1997-2024 Free Software Foundation, Inc.",
]
SPDX-License-Identifier = "GPL-3.0-or-later"
[[annotations]]
path = "src/gcc/gcc/testsuite/**"
precedence = "override"
SPDX-FileCopyrightText = [
"Copyright (C) 2000-2024 Free Software Foundation, Inc.",
]
SPDX-License-Identifier = "GPL-2.0-only"
[[annotations]]
path = "src/gcc/gcc/testsuite/c-c++-common/analyzer/*.c"
precedence = "override"
SPDX-FileCopyrightText = [
"Copyright (c) 2007-2011 Atheros Communications Inc.",
"Copyright (c) 2011-2012,2017 Qualcomm Atheros, Inc.",
"Copyright (c) 2016-2017 Erik Stromdahl <erik.stromdahl@gmail.com>",
]
SPDX-License-Identifier = "ISC"
[[annotations]]
path = "src/gcc/libstdc++-v3/config/os/aix/os_defines.h"
precedence = "override"
SPDX-FileCopyrightText = [
"Copyright (C) 2000-2024 Free Software Foundation, Inc.",
]
SPDX-License-Identifier = "GCC-exception-3.1"

View File

@ -1188,14 +1188,7 @@ impl Expr {
///
/// Does not ensure that the path resolves to a const param, the caller should check this.
pub fn is_potential_trivial_const_arg(&self) -> bool {
let this = if let ExprKind::Block(block, None) = &self.kind
&& let [stmt] = block.stmts.as_slice()
&& let StmtKind::Expr(expr) = &stmt.kind
{
expr
} else {
self
};
let this = self.maybe_unwrap_block();
if let ExprKind::Path(None, path) = &this.kind
&& path.is_potential_trivial_const_arg()
@ -1206,6 +1199,17 @@ impl Expr {
}
}
pub fn maybe_unwrap_block(&self) -> &Expr {
if let ExprKind::Block(block, None) = &self.kind
&& let [stmt] = block.stmts.as_slice()
&& let StmtKind::Expr(expr) = &stmt.kind
{
expr
} else {
self
}
}
pub fn to_bound(&self) -> Option<GenericBound> {
match &self.kind {
ExprKind::Path(None, path) => Some(GenericBound::Trait(
@ -2602,12 +2606,12 @@ impl CoroutineKind {
}
}
pub fn is_async(self) -> bool {
matches!(self, CoroutineKind::Async { .. })
}
pub fn is_gen(self) -> bool {
matches!(self, CoroutineKind::Gen { .. })
pub fn as_str(self) -> &'static str {
match self {
CoroutineKind::Async { .. } => "async",
CoroutineKind::Gen { .. } => "gen",
CoroutineKind::AsyncGen { .. } => "async gen",
}
}
pub fn closure_id(self) -> NodeId {
@ -3486,7 +3490,7 @@ impl From<ForeignItemKind> for ItemKind {
fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
match foreign_item_kind {
ForeignItemKind::Static(box static_foreign_item) => {
ItemKind::Static(Box::new(static_foreign_item.into()))
ItemKind::Static(Box::new(static_foreign_item))
}
ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
@ -3500,9 +3504,7 @@ impl TryFrom<ItemKind> for ForeignItemKind {
fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
Ok(match item_kind {
ItemKind::Static(box static_item) => {
ForeignItemKind::Static(Box::new(static_item.into()))
}
ItemKind::Static(box static_item) => ForeignItemKind::Static(Box::new(static_item)),
ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),

View File

@ -45,18 +45,16 @@ pub fn entry_point_type(
EntryPointType::Start
} else if attr::contains_name(attrs, sym::rustc_main) {
EntryPointType::RustcMainAttr
} else {
if let Some(name) = name
&& name == sym::main
{
if at_root {
// This is a top-level function so it can be `main`.
EntryPointType::MainNamed
} else {
EntryPointType::OtherMain
}
} else if let Some(name) = name
&& name == sym::main
{
if at_root {
// This is a top-level function so it can be `main`.
EntryPointType::MainNamed
} else {
EntryPointType::None
EntryPointType::OtherMain
}
} else {
EntryPointType::None
}
}

View File

@ -220,9 +220,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let parent_def_id = self.current_def_id_parent;
let node_id = self.next_node_id();
// HACK(min_generic_const_args): see lower_anon_const
if !self.tcx.features().const_arg_path
|| !expr.is_potential_trivial_const_arg()
{
if !expr.is_potential_trivial_const_arg() {
self.create_def(
parent_def_id,
node_id,

View File

@ -387,7 +387,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let node_id = self.next_node_id();
// HACK(min_generic_const_args): see lower_anon_const
if !self.tcx.features().const_arg_path || !arg.is_potential_trivial_const_arg() {
if !arg.is_potential_trivial_const_arg() {
// Add a definition for the in-band const def.
self.create_def(parent_def_id, node_id, kw::Empty, DefKind::AnonConst, f.span);
}

View File

@ -78,26 +78,24 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
// Make sure that the DepNode of some node coincides with the HirId
// owner of that node.
if cfg!(debug_assertions) {
if hir_id.owner != self.owner {
span_bug!(
span,
"inconsistent HirId at `{:?}` for `{:?}`: \
if cfg!(debug_assertions) && hir_id.owner != self.owner {
span_bug!(
span,
"inconsistent HirId at `{:?}` for `{:?}`: \
current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
self.tcx.sess.source_map().span_to_diagnostic_string(span),
node,
self.tcx
.definitions_untracked()
.def_path(self.owner.def_id)
.to_string_no_crate_verbose(),
self.owner,
self.tcx
.definitions_untracked()
.def_path(hir_id.owner.def_id)
.to_string_no_crate_verbose(),
hir_id.owner,
)
}
self.tcx.sess.source_map().span_to_diagnostic_string(span),
node,
self.tcx
.definitions_untracked()
.def_path(self.owner.def_id)
.to_string_no_crate_verbose(),
self.owner,
self.tcx
.definitions_untracked()
.def_path(hir_id.owner.def_id)
.to_string_no_crate_verbose(),
hir_id.owner,
)
}
self.nodes[hir_id.local_id] = ParentedNode { parent: self.parent_node, node };

View File

@ -628,13 +628,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
.map_or(Const::No, |attr| Const::Yes(attr.span)),
_ => Const::No,
}
} else if self.tcx.is_const_trait(def_id) {
// FIXME(effects) span
Const::Yes(self.tcx.def_ident_span(def_id).unwrap())
} else {
if self.tcx.is_const_trait(def_id) {
// FIXME(effects) span
Const::Yes(self.tcx.def_ident_span(def_id).unwrap())
} else {
Const::No
}
Const::No
}
} else {
Const::No

View File

@ -2335,7 +2335,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
span: Span,
) -> &'hir hir::ConstArg<'hir> {
let ct_kind = match res {
Res::Def(DefKind::ConstParam, _) if self.tcx.features().const_arg_path => {
Res::Def(DefKind::ConstParam, _) => {
let qpath = self.lower_qpath(
ty_id,
&None,
@ -2410,8 +2410,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
debug!("res={:?}", maybe_res);
// FIXME(min_generic_const_args): for now we only lower params to ConstArgKind::Path
if self.tcx.features().const_arg_path
&& let Some(res) = maybe_res
if let Some(res) = maybe_res
&& let Res::Def(DefKind::ConstParam, _) = res
&& let ExprKind::Path(qself, path) = &expr.kind
{
@ -2442,7 +2441,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
/// See [`hir::ConstArg`] for when to use this function vs
/// [`Self::lower_anon_const_to_const_arg`].
fn lower_anon_const_to_anon_const(&mut self, c: &AnonConst) -> &'hir hir::AnonConst {
if self.tcx.features().const_arg_path && c.value.is_potential_trivial_const_arg() {
if c.value.is_potential_trivial_const_arg() {
// HACK(min_generic_const_args): see DefCollector::visit_anon_const
// Over there, we guess if this is a bare param and only create a def if
// we think it's not. However we may can guess wrong (see there for example)

View File

@ -40,15 +40,15 @@ ast_passes_body_in_extern = incorrect `{$kind}` inside `extern` block
ast_passes_bound_in_context = bounds on `type`s in {$ctx} have no effect
ast_passes_const_and_async = functions cannot be both `const` and `async`
.const = `const` because of this
.async = `async` because of this
.label = {""}
ast_passes_const_and_c_variadic = functions cannot be both `const` and C-variadic
.const = `const` because of this
.variadic = C-variadic because of this
ast_passes_const_and_coroutine = functions cannot be both `const` and `{$coroutine_kind}`
.const = `const` because of this
.coroutine = `{$coroutine_kind}` because of this
.label = {""}
ast_passes_const_bound_trait_object = const trait bounds are not allowed in trait object types
ast_passes_const_without_body =

View File

@ -447,13 +447,13 @@ impl<'a> AstValidator<'a> {
fn check_item_safety(&self, span: Span, safety: Safety) {
match self.extern_mod_safety {
Some(extern_safety) => {
if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_)) {
if extern_safety == Safety::Default {
self.dcx().emit_err(errors::InvalidSafetyOnExtern {
item_span: span,
block: Some(self.current_extern_span().shrink_to_lo()),
});
}
if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_))
&& extern_safety == Safety::Default
{
self.dcx().emit_err(errors::InvalidSafetyOnExtern {
item_span: span,
block: Some(self.current_extern_span().shrink_to_lo()),
});
}
}
None => {
@ -1418,21 +1418,16 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
// Functions cannot both be `const async` or `const gen`
if let Some(&FnHeader {
constness: Const::Yes(cspan),
constness: Const::Yes(const_span),
coroutine_kind: Some(coroutine_kind),
..
}) = fk.header()
{
let aspan = match coroutine_kind {
CoroutineKind::Async { span: aspan, .. }
| CoroutineKind::Gen { span: aspan, .. }
| CoroutineKind::AsyncGen { span: aspan, .. } => aspan,
};
// FIXME(gen_blocks): Report a different error for `const gen`
self.dcx().emit_err(errors::ConstAndAsync {
spans: vec![cspan, aspan],
cspan,
aspan,
self.dcx().emit_err(errors::ConstAndCoroutine {
spans: vec![coroutine_kind.span(), const_span],
const_span,
coroutine_span: coroutine_kind.span(),
coroutine_kind: coroutine_kind.as_str(),
span,
});
}

View File

@ -657,16 +657,17 @@ pub(crate) enum TildeConstReason {
}
#[derive(Diagnostic)]
#[diag(ast_passes_const_and_async)]
pub(crate) struct ConstAndAsync {
#[diag(ast_passes_const_and_coroutine)]
pub(crate) struct ConstAndCoroutine {
#[primary_span]
pub spans: Vec<Span>,
#[label(ast_passes_const)]
pub cspan: Span,
#[label(ast_passes_async)]
pub aspan: Span,
pub const_span: Span,
#[label(ast_passes_coroutine)]
pub coroutine_span: Span,
#[label]
pub span: Span,
pub coroutine_kind: &'static str,
}
#[derive(Diagnostic)]

View File

@ -9,7 +9,7 @@ use rustc_middle::mir::{
use rustc_middle::ty::{RegionVid, TyCtxt};
use rustc_mir_dataflow::fmt::DebugWithContext;
use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces};
use rustc_mir_dataflow::{Analysis, AnalysisDomain, GenKill, Results, ResultsVisitable};
use rustc_mir_dataflow::{Analysis, AnalysisDomain, Forward, GenKill, Results, ResultsVisitable};
use tracing::debug;
use crate::{places_conflict, BorrowSet, PlaceConflictBias, PlaceExt, RegionInferenceContext};
@ -23,26 +23,25 @@ pub(crate) struct BorrowckResults<'a, 'tcx> {
/// The transient state of the dataflow analyses used by the borrow checker.
#[derive(Debug)]
pub(crate) struct BorrowckFlowState<'a, 'tcx> {
pub(crate) struct BorrowckDomain<'a, 'tcx> {
pub(crate) borrows: <Borrows<'a, 'tcx> as AnalysisDomain<'tcx>>::Domain,
pub(crate) uninits: <MaybeUninitializedPlaces<'a, 'tcx> as AnalysisDomain<'tcx>>::Domain,
pub(crate) ever_inits: <EverInitializedPlaces<'a, 'tcx> as AnalysisDomain<'tcx>>::Domain,
}
impl<'a, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'tcx> {
// All three analyses are forward, but we have to use just one here.
type Direction = <Borrows<'a, 'tcx> as AnalysisDomain<'tcx>>::Direction;
type FlowState = BorrowckFlowState<'a, 'tcx>;
type Direction = Forward;
type Domain = BorrowckDomain<'a, 'tcx>;
fn new_flow_state(&self, body: &mir::Body<'tcx>) -> Self::FlowState {
BorrowckFlowState {
fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
BorrowckDomain {
borrows: self.borrows.analysis.bottom_value(body),
uninits: self.uninits.analysis.bottom_value(body),
ever_inits: self.ever_inits.analysis.bottom_value(body),
}
}
fn reset_to_block_entry(&self, state: &mut Self::FlowState, block: BasicBlock) {
fn reset_to_block_entry(&self, state: &mut Self::Domain, block: BasicBlock) {
state.borrows.clone_from(self.borrows.entry_set_for_block(block));
state.uninits.clone_from(self.uninits.entry_set_for_block(block));
state.ever_inits.clone_from(self.ever_inits.entry_set_for_block(block));
@ -50,7 +49,7 @@ impl<'a, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'tcx> {
fn reconstruct_before_statement_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
stmt: &mir::Statement<'tcx>,
loc: Location,
) {
@ -61,7 +60,7 @@ impl<'a, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'tcx> {
fn reconstruct_statement_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
stmt: &mir::Statement<'tcx>,
loc: Location,
) {
@ -72,7 +71,7 @@ impl<'a, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'tcx> {
fn reconstruct_before_terminator_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
term: &mir::Terminator<'tcx>,
loc: Location,
) {
@ -83,7 +82,7 @@ impl<'a, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'tcx> {
fn reconstruct_terminator_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
term: &mir::Terminator<'tcx>,
loc: Location,
) {

View File

@ -1999,19 +1999,32 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
) {
let used_in_call = matches!(
explanation,
BorrowExplanation::UsedLater(LaterUseKind::Call | LaterUseKind::Other, _call_span, _)
BorrowExplanation::UsedLater(
_,
LaterUseKind::Call | LaterUseKind::Other,
_call_span,
_
)
);
if !used_in_call {
debug!("not later used in call");
return;
}
if matches!(
self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
LocalInfo::IfThenRescopeTemp { .. }
) {
// A better suggestion will be issued by the `if_let_rescope` lint
return;
}
let use_span =
if let BorrowExplanation::UsedLater(LaterUseKind::Other, use_span, _) = explanation {
Some(use_span)
} else {
None
};
let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
explanation
{
Some(use_span)
} else {
None
};
let outer_call_loc =
if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
@ -2574,33 +2587,31 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
if e.span.contains(self.capture_span) {
if let hir::ExprKind::Closure(&hir::Closure {
if e.span.contains(self.capture_span)
&& let hir::ExprKind::Closure(&hir::Closure {
kind: hir::ClosureKind::Closure,
body,
fn_arg_span,
fn_decl: hir::FnDecl { inputs, .. },
..
}) = e.kind
&& let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
{
self.suggest_arg = "this: &Self".to_string();
if inputs.len() > 0 {
self.suggest_arg.push_str(", ");
}
self.in_closure = true;
self.closure_arg_span = fn_arg_span;
self.visit_expr(body);
self.in_closure = false;
&& let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
{
self.suggest_arg = "this: &Self".to_string();
if inputs.len() > 0 {
self.suggest_arg.push_str(", ");
}
self.in_closure = true;
self.closure_arg_span = fn_arg_span;
self.visit_expr(body);
self.in_closure = false;
}
if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e {
if let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
&& seg.ident.name == kw::SelfLower
&& self.in_closure
{
self.closure_change_spans.push(e.span);
}
if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
&& let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
&& seg.ident.name == kw::SelfLower
&& self.in_closure
{
self.closure_change_spans.push(e.span);
}
hir::intravisit::walk_expr(self, e);
}
@ -2609,8 +2620,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
local.pat
&& let Some(init) = local.init
{
if let hir::Expr {
&& let hir::Expr {
kind:
hir::ExprKind::Closure(&hir::Closure {
kind: hir::ClosureKind::Closure,
@ -2618,11 +2628,11 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}),
..
} = init
&& init.span.contains(self.capture_span)
{
self.closure_local_id = Some(*hir_id);
}
&& init.span.contains(self.capture_span)
{
self.closure_local_id = Some(*hir_id);
}
hir::intravisit::walk_local(self, local);
}
@ -2862,7 +2872,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// and `move` will not help here.
(
Some(name),
BorrowExplanation::UsedLater(LaterUseKind::ClosureCapture, var_or_use_span, _),
BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
.report_escaping_closure_capture(
borrow_spans,

View File

@ -30,7 +30,7 @@ use crate::{MirBorrowckCtxt, WriteKind};
#[derive(Debug)]
pub(crate) enum BorrowExplanation<'tcx> {
UsedLater(LaterUseKind, Span, Option<Span>),
UsedLater(Local, LaterUseKind, Span, Option<Span>),
UsedLaterInLoop(LaterUseKind, Span, Option<Span>),
UsedLaterWhenDropped {
drop_loc: Location,
@ -99,7 +99,12 @@ impl<'tcx> BorrowExplanation<'tcx> {
}
}
match *self {
BorrowExplanation::UsedLater(later_use_kind, var_or_use_span, path_span) => {
BorrowExplanation::UsedLater(
dropped_local,
later_use_kind,
var_or_use_span,
path_span,
) => {
let message = match later_use_kind {
LaterUseKind::TraitCapture => "captured here by trait object",
LaterUseKind::ClosureCapture => "captured here by closure",
@ -107,9 +112,26 @@ impl<'tcx> BorrowExplanation<'tcx> {
LaterUseKind::FakeLetRead => "stored here",
LaterUseKind::Other => "used here",
};
// We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same
if path_span.map(|path_span| path_span == var_or_use_span).unwrap_or(true) {
if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) {
let local_decl = &body.local_decls[dropped_local];
if let &LocalInfo::IfThenRescopeTemp { if_then } = local_decl.local_info()
&& let Some((_, hir::Node::Expr(expr))) = tcx.hir().parent_iter(if_then).next()
&& let hir::ExprKind::If(cond, conseq, alt) = expr.kind
&& let hir::ExprKind::Let(&hir::LetExpr {
span: _,
pat,
init,
// FIXME(#101728): enable rewrite when type ascription is stabilized again
ty: None,
recovered: _,
}) = cond.kind
&& pat.span.can_be_used_for_suggestions()
&& let Ok(pat) = tcx.sess.source_map().span_to_snippet(pat.span)
{
suggest_rewrite_if_let(tcx, expr, &pat, init, conseq, alt, err);
} else if path_span.map_or(true, |path_span| path_span == var_or_use_span) {
// We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same
if borrow_span.map_or(true, |sp| !sp.overlaps(var_or_use_span)) {
err.span_label(
var_or_use_span,
format!("{borrow_desc}borrow later {message}"),
@ -255,6 +277,22 @@ impl<'tcx> BorrowExplanation<'tcx> {
Applicability::MaybeIncorrect,
);
};
} else if let &LocalInfo::IfThenRescopeTemp { if_then } =
local_decl.local_info()
&& let hir::Node::Expr(expr) = tcx.hir_node(if_then)
&& let hir::ExprKind::If(cond, conseq, alt) = expr.kind
&& let hir::ExprKind::Let(&hir::LetExpr {
span: _,
pat,
init,
// FIXME(#101728): enable rewrite when type ascription is stabilized again
ty: None,
recovered: _,
}) = cond.kind
&& pat.span.can_be_used_for_suggestions()
&& let Ok(pat) = tcx.sess.source_map().span_to_snippet(pat.span)
{
suggest_rewrite_if_let(tcx, expr, &pat, init, conseq, alt, err);
}
}
}
@ -390,6 +428,53 @@ impl<'tcx> BorrowExplanation<'tcx> {
}
}
fn suggest_rewrite_if_let(
tcx: TyCtxt<'_>,
expr: &hir::Expr<'_>,
pat: &str,
init: &hir::Expr<'_>,
conseq: &hir::Expr<'_>,
alt: Option<&hir::Expr<'_>>,
err: &mut Diag<'_>,
) {
let source_map = tcx.sess.source_map();
err.span_note(
source_map.end_point(conseq.span),
"lifetimes for temporaries generated in `if let`s have been shortened in Edition 2024 so that they are dropped here instead",
);
if expr.span.can_be_used_for_suggestions() && conseq.span.can_be_used_for_suggestions() {
let needs_block = if let Some(hir::Node::Expr(expr)) =
alt.and_then(|alt| tcx.hir().parent_iter(alt.hir_id).next()).map(|(_, node)| node)
{
matches!(expr.kind, hir::ExprKind::If(..))
} else {
false
};
let mut sugg = vec![
(
expr.span.shrink_to_lo().between(init.span),
if needs_block { "{ match ".into() } else { "match ".into() },
),
(conseq.span.shrink_to_lo(), format!(" {{ {pat} => ")),
];
let expr_end = expr.span.shrink_to_hi();
let mut expr_end_code;
if let Some(alt) = alt {
sugg.push((conseq.span.between(alt.span), " _ => ".into()));
expr_end_code = "}".to_string();
} else {
expr_end_code = " _ => {} }".into();
}
expr_end_code.push('}');
sugg.push((expr_end, expr_end_code));
err.multipart_suggestion(
"consider rewriting the `if` into `match` which preserves the extended lifetime",
sugg,
Applicability::MaybeIncorrect,
);
}
}
impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
fn free_region_constraint_info(
&self,
@ -465,14 +550,21 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
.or_else(|| self.borrow_spans(span, location));
if use_in_later_iteration_of_loop {
let later_use = self.later_use_kind(borrow, spans, use_location);
BorrowExplanation::UsedLaterInLoop(later_use.0, later_use.1, later_use.2)
let (later_use_kind, var_or_use_span, path_span) =
self.later_use_kind(borrow, spans, use_location);
BorrowExplanation::UsedLaterInLoop(later_use_kind, var_or_use_span, path_span)
} else {
// Check if the location represents a `FakeRead`, and adapt the error
// message to the `FakeReadCause` it is from: in particular,
// the ones inserted in optimized `let var = <expr>` patterns.
let later_use = self.later_use_kind(borrow, spans, location);
BorrowExplanation::UsedLater(later_use.0, later_use.1, later_use.2)
let (later_use_kind, var_or_use_span, path_span) =
self.later_use_kind(borrow, spans, location);
BorrowExplanation::UsedLater(
borrow.borrowed_place.local,
later_use_kind,
var_or_use_span,
path_span,
)
}
}

View File

@ -83,7 +83,7 @@ mod util;
pub mod consumers;
use borrow_set::{BorrowData, BorrowSet};
use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
use dataflow::{BorrowIndex, BorrowckDomain, BorrowckResults, Borrows};
use nll::PoloniusOutput;
use place_ext::PlaceExt;
use places_conflict::{places_conflict, PlaceConflictBias};
@ -602,25 +602,25 @@ struct MirBorrowckCtxt<'a, 'infcx, 'tcx> {
impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
for MirBorrowckCtxt<'a, '_, 'tcx>
{
type FlowState = Flows<'a, 'tcx>;
type Domain = BorrowckDomain<'a, 'tcx>;
fn visit_statement_before_primary_effect(
&mut self,
_results: &mut R,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
stmt: &'a Statement<'tcx>,
location: Location,
) {
debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
let span = stmt.source_info.span;
self.check_activations(location, span, flow_state);
self.check_activations(location, span, state);
match &stmt.kind {
StatementKind::Assign(box (lhs, rhs)) => {
self.consume_rvalue(location, (rhs, span), flow_state);
self.consume_rvalue(location, (rhs, span), state);
self.mutate_place(location, (*lhs, span), Shallow(None), flow_state);
self.mutate_place(location, (*lhs, span), Shallow(None), state);
}
StatementKind::FakeRead(box (_, place)) => {
// Read for match doesn't access any memory and is used to
@ -637,11 +637,11 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
flow_state,
state,
);
}
StatementKind::Intrinsic(box kind) => match kind {
NonDivergingIntrinsic::Assume(op) => self.consume_operand(location, (op, span), flow_state),
NonDivergingIntrinsic::Assume(op) => self.consume_operand(location, (op, span), state),
NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
span,
"Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
@ -662,7 +662,7 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
(Place::from(*local), span),
(Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
LocalMutationIsAllowed::Yes,
flow_state,
state,
);
}
StatementKind::Nop
@ -677,18 +677,18 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
fn visit_terminator_before_primary_effect(
&mut self,
_results: &mut R,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
term: &'a Terminator<'tcx>,
loc: Location,
) {
debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
let span = term.source_info.span;
self.check_activations(loc, span, flow_state);
self.check_activations(loc, span, state);
match &term.kind {
TerminatorKind::SwitchInt { discr, targets: _ } => {
self.consume_operand(loc, (discr, span), flow_state);
self.consume_operand(loc, (discr, span), state);
}
TerminatorKind::Drop { place, target: _, unwind: _, replace } => {
debug!(
@ -704,7 +704,7 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
(*place, span),
(AccessDepth::Drop, Write(write_kind)),
LocalMutationIsAllowed::Yes,
flow_state,
state,
);
}
TerminatorKind::Call {
@ -716,29 +716,29 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
call_source: _,
fn_span: _,
} => {
self.consume_operand(loc, (func, span), flow_state);
self.consume_operand(loc, (func, span), state);
for arg in args {
self.consume_operand(loc, (&arg.node, arg.span), flow_state);
self.consume_operand(loc, (&arg.node, arg.span), state);
}
self.mutate_place(loc, (*destination, span), Deep, flow_state);
self.mutate_place(loc, (*destination, span), Deep, state);
}
TerminatorKind::TailCall { func, args, fn_span: _ } => {
self.consume_operand(loc, (func, span), flow_state);
self.consume_operand(loc, (func, span), state);
for arg in args {
self.consume_operand(loc, (&arg.node, arg.span), flow_state);
self.consume_operand(loc, (&arg.node, arg.span), state);
}
}
TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
self.consume_operand(loc, (cond, span), flow_state);
self.consume_operand(loc, (cond, span), state);
if let AssertKind::BoundsCheck { len, index } = &**msg {
self.consume_operand(loc, (len, span), flow_state);
self.consume_operand(loc, (index, span), flow_state);
self.consume_operand(loc, (len, span), state);
self.consume_operand(loc, (index, span), state);
}
}
TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
self.consume_operand(loc, (value, span), flow_state);
self.mutate_place(loc, (*resume_arg, span), Deep, flow_state);
self.consume_operand(loc, (value, span), state);
self.mutate_place(loc, (*resume_arg, span), Deep, state);
}
TerminatorKind::InlineAsm {
@ -752,22 +752,17 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
for op in operands {
match op {
InlineAsmOperand::In { reg: _, value } => {
self.consume_operand(loc, (value, span), flow_state);
self.consume_operand(loc, (value, span), state);
}
InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
if let Some(place) = place {
self.mutate_place(loc, (*place, span), Shallow(None), flow_state);
self.mutate_place(loc, (*place, span), Shallow(None), state);
}
}
InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
self.consume_operand(loc, (in_value, span), flow_state);
self.consume_operand(loc, (in_value, span), state);
if let &Some(out_place) = out_place {
self.mutate_place(
loc,
(out_place, span),
Shallow(None),
flow_state,
);
self.mutate_place(loc, (out_place, span), Shallow(None), state);
}
}
InlineAsmOperand::Const { value: _ }
@ -794,7 +789,7 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
fn visit_terminator_after_primary_effect(
&mut self,
_results: &mut R,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
term: &'a Terminator<'tcx>,
loc: Location,
) {
@ -805,7 +800,7 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
if self.movable_coroutine {
// Look for any active borrows to locals
let borrow_set = self.borrow_set.clone();
for i in flow_state.borrows.iter() {
for i in state.borrows.iter() {
let borrow = &borrow_set[i];
self.check_for_local_borrow(borrow, span);
}
@ -821,7 +816,7 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
// StorageDead, but we don't always emit those (notably on unwind paths),
// so this "extra check" serves as a kind of backup.
let borrow_set = self.borrow_set.clone();
for i in flow_state.borrows.iter() {
for i in state.borrows.iter() {
let borrow = &borrow_set[i];
self.check_for_invalidation_at_exit(loc, borrow, span);
}
@ -989,7 +984,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
place_span: (Place<'tcx>, Span),
kind: (AccessDepth, ReadOrWrite),
is_local_mutation_allowed: LocalMutationIsAllowed,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) {
let (sd, rw) = kind;
@ -1020,11 +1015,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
place_span,
rw,
is_local_mutation_allowed,
flow_state,
state,
location,
);
let conflict_error =
self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
if conflict_error || mutability_error {
debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
@ -1032,14 +1026,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
}
}
#[instrument(level = "debug", skip(self, flow_state))]
#[instrument(level = "debug", skip(self, state))]
fn check_access_for_conflict(
&mut self,
location: Location,
place_span: (Place<'tcx>, Span),
sd: AccessDepth,
rw: ReadOrWrite,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) -> bool {
let mut error_reported = false;
let borrow_set = Rc::clone(&self.borrow_set);
@ -1054,7 +1048,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
}
&polonius_output
} else {
&flow_state.borrows
&state.borrows
};
each_borrow_involving_path(
@ -1180,17 +1174,17 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
location: Location,
place_span: (Place<'tcx>, Span),
kind: AccessDepth,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) {
// Write of P[i] or *P requires P init'd.
self.check_if_assigned_path_is_moved(location, place_span, flow_state);
self.check_if_assigned_path_is_moved(location, place_span, state);
self.access_place(
location,
place_span,
(kind, Write(WriteKind::Mutate)),
LocalMutationIsAllowed::No,
flow_state,
state,
);
}
@ -1198,7 +1192,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
&mut self,
location: Location,
(rvalue, span): (&'a Rvalue<'tcx>, Span),
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) {
match rvalue {
&Rvalue::Ref(_ /*rgn*/, bk, place) => {
@ -1224,7 +1218,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
(place, span),
access_kind,
LocalMutationIsAllowed::No,
flow_state,
state,
);
let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
@ -1237,7 +1231,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
location,
action,
(place.as_ref(), span),
flow_state,
state,
);
}
@ -1257,14 +1251,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
(place, span),
access_kind,
LocalMutationIsAllowed::No,
flow_state,
state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Borrow,
(place.as_ref(), span),
flow_state,
state,
);
}
@ -1275,7 +1269,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
| Rvalue::UnaryOp(_ /*un_op*/, operand)
| Rvalue::Cast(_ /*cast_kind*/, operand, _ /*ty*/)
| Rvalue::ShallowInitBox(operand, _ /*ty*/) => {
self.consume_operand(location, (operand, span), flow_state)
self.consume_operand(location, (operand, span), state)
}
&Rvalue::CopyForDeref(place) => {
@ -1284,7 +1278,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
(place, span),
(Deep, Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
flow_state,
state,
);
// Finally, check if path was already moved.
@ -1292,7 +1286,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
flow_state,
state,
);
}
@ -1307,19 +1301,19 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
(place, span),
(Shallow(af), Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
flow_state,
state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
flow_state,
state,
);
}
Rvalue::BinaryOp(_bin_op, box (operand1, operand2)) => {
self.consume_operand(location, (operand1, span), flow_state);
self.consume_operand(location, (operand2, span), flow_state);
self.consume_operand(location, (operand1, span), state);
self.consume_operand(location, (operand2, span), state);
}
Rvalue::NullaryOp(_op, _ty) => {
@ -1349,7 +1343,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
}
for operand in operands {
self.consume_operand(location, (operand, span), flow_state);
self.consume_operand(location, (operand, span), state);
}
}
}
@ -1456,7 +1450,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
&mut self,
location: Location,
(operand, span): (&'a Operand<'tcx>, Span),
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) {
match *operand {
Operand::Copy(place) => {
@ -1467,7 +1461,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
(place, span),
(Deep, Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
flow_state,
state,
);
// Finally, check if path was already moved.
@ -1475,7 +1469,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
flow_state,
state,
);
}
Operand::Move(place) => {
@ -1488,7 +1482,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
(place, span),
(Deep, Write(WriteKind::Move)),
LocalMutationIsAllowed::Yes,
flow_state,
state,
);
// Finally, check if path was already moved.
@ -1496,7 +1490,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
flow_state,
state,
);
}
Operand::Constant(_) => {}
@ -1576,7 +1570,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
}
}
fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'a, 'tcx>) {
fn check_activations(
&mut self,
location: Location,
span: Span,
state: &BorrowckDomain<'a, 'tcx>,
) {
// Two-phase borrow support: For each activation that is newly
// generated at this statement, check if it interferes with
// another borrow.
@ -1595,7 +1594,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
(borrow.borrowed_place, span),
(Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
LocalMutationIsAllowed::No,
flow_state,
state,
);
// We do not need to call `check_if_path_or_subpath_is_moved`
// again, as we already called it when we made the
@ -1739,9 +1738,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
location: Location,
desired_action: InitializationRequiringAction,
place_span: (PlaceRef<'tcx>, Span),
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) {
let maybe_uninits = &flow_state.uninits;
let maybe_uninits = &state.uninits;
// Bad scenarios:
//
@ -1844,9 +1843,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
location: Location,
desired_action: InitializationRequiringAction,
place_span: (PlaceRef<'tcx>, Span),
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) {
let maybe_uninits = &flow_state.uninits;
let maybe_uninits = &state.uninits;
// Bad scenarios:
//
@ -1863,7 +1862,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
// must have been initialized for the use to be sound.
// 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
self.check_if_full_path_is_moved(location, desired_action, place_span, state);
if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
place_span.0.last_projection()
@ -1943,7 +1942,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
&mut self,
location: Location,
(place, span): (Place<'tcx>, Span),
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) {
debug!("check_if_assigned_path_is_moved place: {:?}", place);
@ -1965,7 +1964,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
ProjectionElem::Deref => {
self.check_if_full_path_is_moved(
location, InitializationRequiringAction::Use,
(place_base, span), flow_state);
(place_base, span), state);
// (base initialized; no need to
// recur further)
break;
@ -1985,7 +1984,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
ty::Adt(def, _) if def.has_dtor(tcx) => {
self.check_if_path_or_subpath_is_moved(
location, InitializationRequiringAction::Assignment,
(place_base, span), flow_state);
(place_base, span), state);
// (base initialized; no need to
// recur further)
@ -1995,7 +1994,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
// Once `let s; s.x = V; read(s.x);`,
// is allowed, remove this match arm.
ty::Adt(..) | ty::Tuple(..) => {
check_parent_of_field(self, location, place_base, span, flow_state);
check_parent_of_field(self, location, place_base, span, state);
}
_ => {}
@ -2009,7 +2008,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
location: Location,
base: PlaceRef<'tcx>,
span: Span,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) {
// rust-lang/rust#21232: Until Rust allows reads from the
// initialized parts of partially initialized structs, we
@ -2042,7 +2041,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
// Shallow so that we'll stop at any dereference; we'll
// report errors about issues with such bases elsewhere.
let maybe_uninits = &flow_state.uninits;
let maybe_uninits = &state.uninits;
// Find the shortest uninitialized prefix you can reach
// without going over a Deref.
@ -2069,12 +2068,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
// no move out from an earlier location) then this is an attempt at initialization
// of the union - we should error in that case.
let tcx = this.infcx.tcx;
if base.ty(this.body(), tcx).ty.is_union() {
if this.move_data.path_map[mpi].iter().any(|moi| {
if base.ty(this.body(), tcx).ty.is_union()
&& this.move_data.path_map[mpi].iter().any(|moi| {
this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
}) {
return;
}
})
{
return;
}
this.report_use_of_moved_or_uninitialized(
@ -2100,7 +2099,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
(place, span): (Place<'tcx>, Span),
kind: ReadOrWrite,
is_local_mutation_allowed: LocalMutationIsAllowed,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
location: Location,
) -> bool {
debug!(
@ -2124,7 +2123,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
};
match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
Ok(root_place) => {
self.add_used_mut(root_place, flow_state);
self.add_used_mut(root_place, state);
return false;
}
Err(place_err) => {
@ -2136,7 +2135,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
Ok(root_place) => {
self.add_used_mut(root_place, flow_state);
self.add_used_mut(root_place, state);
return false;
}
Err(place_err) => {
@ -2194,7 +2193,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
// partial initialization, do not complain about mutability
// errors except for actual mutation (as opposed to an attempt
// to do a partial initialization).
let previously_initialized = self.is_local_ever_initialized(place.local, flow_state);
let previously_initialized = self.is_local_ever_initialized(place.local, state);
// at this point, we have set up the error reporting state.
if let Some(init_index) = previously_initialized {
@ -2216,22 +2215,22 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
fn is_local_ever_initialized(
&self,
local: Local,
flow_state: &Flows<'a, 'tcx>,
state: &BorrowckDomain<'a, 'tcx>,
) -> Option<InitIndex> {
let mpi = self.move_data.rev_lookup.find_local(local)?;
let ii = &self.move_data.init_path_map[mpi];
ii.into_iter().find(|&&index| flow_state.ever_inits.contains(index)).copied()
ii.into_iter().find(|&&index| state.ever_inits.contains(index)).copied()
}
/// Adds the place into the used mutable variables set
fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'a, 'tcx>) {
fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain<'a, 'tcx>) {
match root_place {
RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
// If the local may have been initialized, and it is now currently being
// mutated, then it is justified to be annotated with the `mut`
// keyword, since the mutation may be a possible reassignment.
if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
&& self.is_local_ever_initialized(local, flow_state).is_some()
&& self.is_local_ever_initialized(local, state).is_some()
{
self.used_mut.insert(local);
}

View File

@ -118,10 +118,8 @@ impl LivenessValues {
debug!("LivenessValues::add_location(region={:?}, location={:?})", region, location);
if let Some(points) = &mut self.points {
points.insert(region, point);
} else {
if self.elements.point_in_range(point) {
self.live_regions.as_mut().unwrap().insert(region);
}
} else if self.elements.point_in_range(point) {
self.live_regions.as_mut().unwrap().insert(region);
}
// When available, record the loans flowing into this region as live at the given point.
@ -137,10 +135,8 @@ impl LivenessValues {
debug!("LivenessValues::add_points(region={:?}, points={:?})", region, points);
if let Some(this) = &mut self.points {
this.union_row(region, points);
} else {
if points.iter().any(|point| self.elements.point_in_range(point)) {
self.live_regions.as_mut().unwrap().insert(region);
}
} else if points.iter().any(|point| self.elements.point_in_range(point)) {
self.live_regions.as_mut().unwrap().insert(region);
}
// When available, record the loans flowing into this region as live at the given points.

View File

@ -353,11 +353,11 @@ impl<'a, 'typeck, 'b, 'tcx> LivenessResults<'a, 'typeck, 'b, 'tcx> {
let location = self.cx.elements.to_location(drop_point);
debug_assert_eq!(self.cx.body.terminator_loc(location.block), location,);
if self.cx.initialized_at_terminator(location.block, mpi) {
if self.drop_live_at.insert(drop_point) {
self.drop_locations.push(location);
self.stack.push(drop_point);
}
if self.cx.initialized_at_terminator(location.block, mpi)
&& self.drop_live_at.insert(drop_point)
{
self.drop_locations.push(location);
self.stack.push(drop_point);
}
}

View File

@ -235,13 +235,11 @@ pub fn parse_asm_args<'a>(
continue;
}
args.named_args.insert(name, slot);
} else {
if !args.named_args.is_empty() || !args.reg_args.is_empty() {
let named = args.named_args.values().map(|p| args.operands[*p].1).collect();
let explicit = args.reg_args.iter().map(|p| args.operands[p].1).collect();
} else if !args.named_args.is_empty() || !args.reg_args.is_empty() {
let named = args.named_args.values().map(|p| args.operands[*p].1).collect();
let explicit = args.reg_args.iter().map(|p| args.operands[p].1).collect();
dcx.emit_err(errors::AsmPositionalAfter { span, named, explicit });
}
dcx.emit_err(errors::AsmPositionalAfter { span, named, explicit });
}
}

View File

@ -48,6 +48,10 @@ impl<'a, 'gcc, 'tcx> DebugInfoBuilderMethods for Builder<'a, 'gcc, 'tcx> {
fn set_dbg_loc(&mut self, dbg_loc: Self::DILocation) {
self.location = Some(dbg_loc);
}
fn clear_dbg_loc(&mut self) {
self.location = None;
}
}
/// Generate the `debug_context` in an MIR Body.

View File

@ -92,11 +92,9 @@ fn prepare_lto(
dcx.emit_err(LtoDylib);
return Err(FatalError);
}
} else if *crate_type == CrateType::ProcMacro {
if !cgcx.opts.unstable_opts.dylib_lto {
dcx.emit_err(LtoProcMacro);
return Err(FatalError);
}
} else if *crate_type == CrateType::ProcMacro && !cgcx.opts.unstable_opts.dylib_lto {
dcx.emit_err(LtoProcMacro);
return Err(FatalError);
}
}

View File

@ -27,7 +27,7 @@ use rustc_span::source_map::Spanned;
use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::call::FnAbi;
use rustc_target::abi::{HasDataLayout, TargetDataLayout, VariantIdx};
use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel};
use rustc_target::spec::{HasTargetSpec, RelocModel, SmallDataThresholdSupport, Target, TlsModel};
use smallvec::SmallVec;
use crate::back::write::to_llvm_code_model;
@ -387,6 +387,24 @@ pub(crate) unsafe fn create_module<'ll>(
}
}
match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
{
// Set up the small-data optimization limit for architectures that use
// an LLVM module flag to control this.
(Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
let flag = SmallCStr::new(flag.as_ref());
unsafe {
llvm::LLVMRustAddModuleFlagU32(
llmod,
llvm::LLVMModFlagBehavior::Error,
flag.as_c_str().as_ptr(),
threshold as u32,
)
}
}
_ => (),
};
// Insert `llvm.ident` metadata.
//
// On the wasm targets it will get hooked up to the "producer" sections

View File

@ -1,8 +1,8 @@
#![doc = include_str!("doc.md")]
use std::cell::{OnceCell, RefCell};
use std::iter;
use std::ops::Range;
use std::{iter, ptr};
use libc::c_uint;
use rustc_codegen_ssa::debuginfo::type_names;
@ -209,6 +209,12 @@ impl<'ll> DebugInfoBuilderMethods for Builder<'_, 'll, '_> {
}
}
fn clear_dbg_loc(&mut self) {
unsafe {
llvm::LLVMSetCurrentDebugLocation2(self.llbuilder, ptr::null());
}
}
fn insert_reference_to_gdb_debug_scripts_section_global(&mut self) {
gdb::insert_reference_to_gdb_debug_scripts_section_global(self)
}

View File

@ -1041,7 +1041,7 @@ unsafe extern "C" {
pub fn LLVMDisposeBuilder<'a>(Builder: &'a mut Builder<'a>);
// Metadata
pub fn LLVMSetCurrentDebugLocation2<'a>(Builder: &Builder<'a>, Loc: &'a Metadata);
pub fn LLVMSetCurrentDebugLocation2<'a>(Builder: &Builder<'a>, Loc: *const Metadata);
// Terminators
pub fn LLVMBuildRetVoid<'a>(B: &Builder<'a>) -> &'a Value;

View File

@ -14,7 +14,7 @@ use rustc_middle::bug;
use rustc_session::config::{PrintKind, PrintRequest};
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use rustc_target::spec::{MergeFunctions, PanicStrategy};
use rustc_target::spec::{MergeFunctions, PanicStrategy, SmallDataThresholdSupport};
use rustc_target::target_features::{RUSTC_SPECIAL_FEATURES, RUSTC_SPECIFIC_FEATURES};
use crate::back::write::create_informational_target_machine;
@ -125,6 +125,18 @@ unsafe fn configure_llvm(sess: &Session) {
for arg in sess_args {
add(&(*arg), true);
}
match (
sess.opts.unstable_opts.small_data_threshold,
sess.target.small_data_threshold_support(),
) {
// Set up the small-data optimization limit for architectures that use
// an LLVM argument to control this.
(Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
add(&format!("--{arg}={threshold}"), false)
}
_ => (),
};
}
if sess.opts.unstable_opts.llvm_time_trace {

View File

@ -281,12 +281,10 @@ pub fn each_linked_rlib(
let used_crate_source = &info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.rlib {
f(cnum, path);
} else if used_crate_source.rmeta.is_some() {
return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
if used_crate_source.rmeta.is_some() {
return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
return Err(errors::LinkRlibError::NotFound { crate_name });
}
return Err(errors::LinkRlibError::NotFound { crate_name });
}
}
Ok(())
@ -628,12 +626,10 @@ fn link_staticlib(
let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.dylib {
all_rust_dylibs.push(&**path);
} else if used_crate_source.rmeta.is_some() {
sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
if used_crate_source.rmeta.is_some() {
sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
}
sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
}
}
@ -1972,10 +1968,8 @@ fn add_late_link_args(
if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref));
}
} else {
if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref));
}
} else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref));
}
if let Some(args) = sess.target.late_link_args.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref));
@ -2635,10 +2629,8 @@ fn add_native_libs_from_crate(
if link_static {
cmd.link_staticlib_by_name(name, verbatim, false);
}
} else {
if link_dynamic {
cmd.link_dylib_by_name(name, verbatim, true);
}
} else if link_dynamic {
cmd.link_dylib_by_name(name, verbatim, true);
}
}
NativeLibKind::Framework { as_needed } => {

View File

@ -791,14 +791,12 @@ impl<'a> Linker for GccLinker<'a> {
self.link_arg("-exported_symbols_list").link_arg(path);
} else if self.sess.target.is_like_solaris {
self.link_arg("-M").link_arg(path);
} else if is_windows {
self.link_arg(path);
} else {
if is_windows {
self.link_arg(path);
} else {
let mut arg = OsString::from("--version-script=");
arg.push(path);
self.link_arg(arg).link_arg("--no-undefined-version");
}
let mut arg = OsString::from("--version-script=");
arg.push(path);
self.link_arg(arg).link_arg("--no-undefined-version");
}
}

View File

@ -617,32 +617,29 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// purpose functions as they wouldn't have the right target features
// enabled. For that reason we also forbid #[inline(always)] as it can't be
// respected.
if !codegen_fn_attrs.target_features.is_empty() {
if codegen_fn_attrs.inline == InlineAttr::Always {
if let Some(span) = inline_span {
tcx.dcx().span_err(
span,
"cannot use `#[inline(always)]` with \
if !codegen_fn_attrs.target_features.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always
{
if let Some(span) = inline_span {
tcx.dcx().span_err(
span,
"cannot use `#[inline(always)]` with \
`#[target_feature]`",
);
}
);
}
}
if !codegen_fn_attrs.no_sanitize.is_empty() {
if codegen_fn_attrs.inline == InlineAttr::Always {
if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
let hir_id = tcx.local_def_id_to_hir_id(did);
tcx.node_span_lint(
lint::builtin::INLINE_NO_SANITIZE,
hir_id,
no_sanitize_span,
|lint| {
lint.primary_message("`no_sanitize` will have no effect after inlining");
lint.span_note(inline_span, "inlining requested here");
},
)
}
if !codegen_fn_attrs.no_sanitize.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always {
if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
let hir_id = tcx.local_def_id_to_hir_id(did);
tcx.node_span_lint(
lint::builtin::INLINE_NO_SANITIZE,
hir_id,
no_sanitize_span,
|lint| {
lint.primary_message("`no_sanitize` will have no effect after inlining");
lint.span_note(inline_span, "inlining requested here");
},
)
}
}

View File

@ -236,15 +236,13 @@ fn push_debuginfo_type_name<'tcx>(
let has_enclosing_parens = if cpp_like_debuginfo {
output.push_str("dyn$<");
false
} else if trait_data.len() > 1 && auto_traits.len() != 0 {
// We need enclosing parens because there is more than one trait
output.push_str("(dyn ");
true
} else {
if trait_data.len() > 1 && auto_traits.len() != 0 {
// We need enclosing parens because there is more than one trait
output.push_str("(dyn ");
true
} else {
output.push_str("dyn ");
false
}
output.push_str("dyn ");
false
};
if let Some(principal) = trait_data.principal() {

View File

@ -547,6 +547,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
self.set_debug_loc(bx, var.source_info);
let base =
Self::spill_operand_to_stack(operand, Some(var.name.to_string()), bx);
bx.clear_dbg_loc();
bx.dbg_var_addr(
dbg_var,

View File

@ -80,6 +80,7 @@ pub trait DebugInfoBuilderMethods: BackendTypes {
fragment: Option<Range<Size>>,
);
fn set_dbg_loc(&mut self, dbg_loc: Self::DILocation);
fn clear_dbg_loc(&mut self);
fn insert_reference_to_gdb_debug_scripts_section_global(&mut self);
fn set_var_name(&mut self, value: Self::Value, name: &str);
}

View File

@ -73,12 +73,7 @@ fn eval_body_using_ecx<'tcx, R: InterpretationResult<'tcx>>(
// This can't use `init_stack_frame` since `body` is not a function,
// so computing its ABI would fail. It's also not worth it since there are no arguments to pass.
ecx.push_stack_frame_raw(
cid.instance,
body,
&ret.clone().into(),
StackPopCleanup::Root { cleanup: false },
)?;
ecx.push_stack_frame_raw(cid.instance, body, &ret, StackPopCleanup::Root { cleanup: false })?;
ecx.storage_live_for_always_live_locals()?;
// The main interpreter loop.

View File

@ -823,7 +823,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
(Abi::Rust, fn_abi),
&[FnArg::Copy(arg.into())],
false,
&ret.into(),
&ret,
Some(target),
unwind,
)

View File

@ -16,7 +16,7 @@ use rustc_span::Span;
use rustc_target::abi::call::FnAbi;
use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout};
use rustc_trait_selection::traits::ObligationCtxt;
use tracing::{debug, trace};
use tracing::{debug, instrument, trace};
use super::{
err_inval, throw_inval, throw_ub, throw_ub_custom, Frame, FrameInfo, GlobalId, InterpErrorInfo,
@ -315,6 +315,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
/// Check if the two things are equal in the current param_env, using an infctx to get proper
/// equality checks.
#[instrument(level = "trace", skip(self), ret)]
pub(super) fn eq_in_param_env<T>(&self, a: T, b: T) -> bool
where
T: PartialEq + TypeFoldable<TyCtxt<'tcx>> + ToTrace<'tcx>,
@ -330,13 +331,20 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
// equate the two trait refs after normalization
let a = ocx.normalize(&cause, self.param_env, a);
let b = ocx.normalize(&cause, self.param_env, b);
if ocx.eq(&cause, self.param_env, a, b).is_ok() {
if ocx.select_all_or_error().is_empty() {
// All good.
return true;
}
if let Err(terr) = ocx.eq(&cause, self.param_env, a, b) {
trace!(?terr);
return false;
}
return false;
let errors = ocx.select_all_or_error();
if !errors.is_empty() {
trace!(?errors);
return false;
}
// All good.
true
}
/// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a

View File

@ -384,8 +384,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
sym::simd_insert => {
let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
let elem = &args[2];
let (input, input_len) = self.operand_to_simd(&args[0])?;
let (dest, dest_len) = self.mplace_to_simd(dest)?;
let (input, input_len) = self.project_to_simd(&args[0])?;
let (dest, dest_len) = self.project_to_simd(dest)?;
assert_eq!(input_len, dest_len, "Return vector length must match input length");
// Bounds are not checked by typeck so we have to do it ourselves.
if index >= input_len {
@ -406,7 +406,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
}
sym::simd_extract => {
let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
let (input, input_len) = self.operand_to_simd(&args[0])?;
let (input, input_len) = self.project_to_simd(&args[0])?;
// Bounds are not checked by typeck so we have to do it ourselves.
if index >= input_len {
throw_ub_format!(

View File

@ -681,30 +681,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
Ok(str)
}
/// Converts a repr(simd) operand into an operand where `place_index` accesses the SIMD elements.
/// Also returns the number of elements.
///
/// Can (but does not always) trigger UB if `op` is uninitialized.
pub fn operand_to_simd(
&self,
op: &OpTy<'tcx, M::Provenance>,
) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
// Basically we just transmute this place into an array following simd_size_and_type.
// This only works in memory, but repr(simd) types should never be immediates anyway.
assert!(op.layout.ty.is_simd());
match op.as_mplace_or_imm() {
Left(mplace) => self.mplace_to_simd(&mplace),
Right(imm) => match *imm {
Immediate::Uninit => {
throw_ub!(InvalidUninitBytes(None))
}
Immediate::Scalar(..) | Immediate::ScalarPair(..) => {
bug!("arrays/slices can never have Scalar/ScalarPair layout")
}
},
}
}
/// Read from a local of the current frame.
/// Will not access memory, instead an indirect `Operand` is returned.
///

View File

@ -377,13 +377,15 @@ where
Prov: Provenance,
M: Machine<'tcx, Provenance = Prov>,
{
pub fn ptr_with_meta_to_mplace(
fn ptr_with_meta_to_mplace(
&self,
ptr: Pointer<Option<M::Provenance>>,
meta: MemPlaceMeta<M::Provenance>,
layout: TyAndLayout<'tcx>,
unaligned: bool,
) -> MPlaceTy<'tcx, M::Provenance> {
let misaligned = self.is_ptr_misaligned(ptr, layout.align.abi);
let misaligned =
if unaligned { None } else { self.is_ptr_misaligned(ptr, layout.align.abi) };
MPlaceTy { mplace: MemPlace { ptr, meta, misaligned }, layout }
}
@ -393,7 +395,16 @@ where
layout: TyAndLayout<'tcx>,
) -> MPlaceTy<'tcx, M::Provenance> {
assert!(layout.is_sized());
self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout)
self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout, /*unaligned*/ false)
}
pub fn ptr_to_mplace_unaligned(
&self,
ptr: Pointer<Option<M::Provenance>>,
layout: TyAndLayout<'tcx>,
) -> MPlaceTy<'tcx, M::Provenance> {
assert!(layout.is_sized());
self.ptr_with_meta_to_mplace(ptr, MemPlaceMeta::None, layout, /*unaligned*/ true)
}
/// Take a value, which represents a (thin or wide) reference, and make it a place.
@ -414,7 +425,7 @@ where
// `ref_to_mplace` is called on raw pointers even if they don't actually get dereferenced;
// we hence can't call `size_and_align_of` since that asserts more validity than we want.
let ptr = ptr.to_pointer(self)?;
Ok(self.ptr_with_meta_to_mplace(ptr, meta, layout))
Ok(self.ptr_with_meta_to_mplace(ptr, meta, layout, /*unaligned*/ false))
}
/// Turn a mplace into a (thin or wide) mutable raw pointer, pointing to the same space.
@ -484,23 +495,6 @@ where
Ok(a)
}
/// Converts a repr(simd) place into a place where `place_index` accesses the SIMD elements.
/// Also returns the number of elements.
pub fn mplace_to_simd(
&self,
mplace: &MPlaceTy<'tcx, M::Provenance>,
) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
// Basically we want to transmute this place into an array following simd_size_and_type.
let (len, e_ty) = mplace.layout.ty.simd_size_and_type(*self.tcx);
// Some SIMD types have padding, so `len` many `e_ty` does not cover the entire place.
// Therefore we cannot transmute, and instead we project at offset 0, which side-steps
// the size check.
let array_layout = self.layout_of(Ty::new_array(self.tcx.tcx, e_ty, len))?;
assert!(array_layout.size <= mplace.layout.size);
let mplace = mplace.offset(Size::ZERO, array_layout, self)?;
Ok((mplace, len))
}
/// Turn a local in the current frame into a place.
pub fn local_to_place(
&self,
@ -986,7 +980,7 @@ where
span_bug!(self.cur_span(), "cannot allocate space for `extern` type, size is not known")
};
let ptr = self.allocate_ptr(size, align, kind)?;
Ok(self.ptr_with_meta_to_mplace(ptr.into(), meta, layout))
Ok(self.ptr_with_meta_to_mplace(ptr.into(), meta, layout, /*unaligned*/ false))
}
pub fn allocate(
@ -1021,7 +1015,12 @@ where
};
let meta = Scalar::from_target_usize(u64::try_from(str.len()).unwrap(), self);
let layout = self.layout_of(self.tcx.types.str_).unwrap();
Ok(self.ptr_with_meta_to_mplace(ptr.into(), MemPlaceMeta::Meta(meta), layout))
Ok(self.ptr_with_meta_to_mplace(
ptr.into(),
MemPlaceMeta::Meta(meta),
layout,
/*unaligned*/ false,
))
}
pub fn raw_const_to_mplace(

View File

@ -244,6 +244,19 @@ where
base.offset(offset, field_layout, self)
}
/// Converts a repr(simd) value into an array of the right size, such that `project_index`
/// accesses the SIMD elements. Also returns the number of elements.
pub fn project_to_simd<P: Projectable<'tcx, M::Provenance>>(
&self,
base: &P,
) -> InterpResult<'tcx, (P, u64)> {
assert!(base.layout().ty.ty_adt_def().unwrap().repr().simd());
// SIMD types must be newtypes around arrays, so all we have to do is project to their only field.
let array = self.project_field(base, 0)?;
let len = array.len(self)?;
Ok((array, len))
}
fn project_constant_index<P: Projectable<'tcx, M::Provenance>>(
&self,
base: &P,

View File

@ -9,7 +9,7 @@ use rustc_middle::ty::{
};
use tracing::debug;
use super::{throw_inval, InterpCx, MPlaceTy, MemPlaceMeta, MemoryKind};
use super::{throw_inval, InterpCx, MPlaceTy, MemoryKind};
use crate::const_eval::{CompileTimeInterpCx, CompileTimeMachine, InterpretationResult};
/// Checks whether a type contains generic parameters which must be instantiated.
@ -103,5 +103,5 @@ pub(crate) fn create_static_alloc<'tcx>(
assert_eq!(ecx.machine.static_root_ids, None);
ecx.machine.static_root_ids = Some((alloc_id, static_def_id));
assert!(ecx.memory.alloc_map.insert(alloc_id, (MemoryKind::Stack, alloc)).is_none());
Ok(ecx.ptr_with_meta_to_mplace(Pointer::from(alloc_id).into(), MemPlaceMeta::None, layout))
Ok(ecx.ptr_to_mplace(Pointer::from(alloc_id).into(), layout))
}

View File

@ -222,10 +222,8 @@ impl<'tcx> PrintExtra<'tcx> {
}
pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
if ppm.needs_analysis() {
if ex.tcx().analysis(()).is_err() {
FatalError.raise();
}
if ppm.needs_analysis() && ex.tcx().analysis(()).is_err() {
FatalError.raise();
}
let (src, src_name) = get_source(sess);

View File

@ -681,10 +681,10 @@ impl<'a, G: EmissionGuarantee> Diag<'a, G> {
" ".repeat(expected_padding),
expected_label
))];
msg.extend(expected.0.into_iter());
msg.extend(expected.0);
msg.push(StringPart::normal(format!("`{expected_extra}\n")));
msg.push(StringPart::normal(format!("{}{} `", " ".repeat(found_padding), found_label)));
msg.extend(found.0.into_iter());
msg.extend(found.0);
msg.push(StringPart::normal(format!("`{found_extra}")));
// For now, just attach these as notes.

View File

@ -193,8 +193,6 @@ declare_features! (
(unstable, anonymous_lifetime_in_impl_trait, "1.63.0", None),
/// Allows identifying the `compiler_builtins` crate.
(internal, compiler_builtins, "1.13.0", None),
/// Gating for a new desugaring of const arguments of usages of const parameters
(internal, const_arg_path, "1.81.0", None),
/// Allows writing custom MIR
(internal, custom_mir, "1.65.0", None),
/// Outputs useful `assert!` messages
@ -497,6 +495,8 @@ declare_features! (
(unstable, half_open_range_patterns_in_slices, "1.66.0", Some(67264)),
/// Allows `if let` guard in match arms.
(unstable, if_let_guard, "1.47.0", Some(51114)),
/// Rescoping temporaries in `if let` to align with Rust 2024.
(unstable, if_let_rescope, "CURRENT_RUSTC_VERSION", Some(124085)),
/// Allows `impl Trait` to be used inside associated types (RFC 2515).
(unstable, impl_trait_in_assoc_type, "1.70.0", Some(63063)),
/// Allows `impl Trait` as output type in `Fn` traits in return position of functions.

View File

@ -1151,42 +1151,40 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
"type has conflicting packed and align representation hints"
)
.emit();
} else {
if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
let mut err = struct_span_code_err!(
tcx.dcx(),
sp,
E0588,
"packed type cannot transitively contain a `#[repr(align)]` type"
);
} else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
let mut err = struct_span_code_err!(
tcx.dcx(),
sp,
E0588,
"packed type cannot transitively contain a `#[repr(align)]` type"
);
err.span_note(
tcx.def_span(def_spans[0].0),
format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
);
err.span_note(
tcx.def_span(def_spans[0].0),
format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
);
if def_spans.len() > 2 {
let mut first = true;
for (adt_def, span) in def_spans.iter().skip(1).rev() {
let ident = tcx.item_name(*adt_def);
err.span_note(
*span,
if first {
format!(
"`{}` contains a field of type `{}`",
tcx.type_of(def.did()).instantiate_identity(),
ident
)
} else {
format!("...which contains a field of type `{ident}`")
},
);
first = false;
}
if def_spans.len() > 2 {
let mut first = true;
for (adt_def, span) in def_spans.iter().skip(1).rev() {
let ident = tcx.item_name(*adt_def);
err.span_note(
*span,
if first {
format!(
"`{}` contains a field of type `{}`",
tcx.type_of(def.did()).instantiate_identity(),
ident
)
} else {
format!("...which contains a field of type `{ident}`")
},
);
first = false;
}
err.emit();
}
err.emit();
}
}
}

View File

@ -186,17 +186,15 @@ fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: LocalDefId) {
if let Ok(alloc) = tcx.eval_static_initializer(id.to_def_id())
&& alloc.inner().provenance().ptrs().len() != 0
{
if attrs
&& attrs
.link_section
.map(|link_section| !link_section.as_str().starts_with(".init_array"))
.unwrap()
{
let msg = "statics with a custom `#[link_section]` must be a \
{
let msg = "statics with a custom `#[link_section]` must be a \
simple list of bytes on the wasm target with no \
extra levels of indirection such as references";
tcx.dcx().span_err(tcx.def_span(id), msg);
}
tcx.dcx().span_err(tcx.def_span(id), msg);
}
}

View File

@ -472,7 +472,12 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h
hir::ExprKind::If(cond, then, Some(otherwise)) => {
let expr_cx = visitor.cx;
visitor.enter_scope(Scope { id: then.hir_id.local_id, data: ScopeData::IfThen });
let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope {
ScopeData::IfThenRescope
} else {
ScopeData::IfThen
};
visitor.enter_scope(Scope { id: then.hir_id.local_id, data });
visitor.cx.var_parent = visitor.cx.parent;
visitor.visit_expr(cond);
visitor.visit_expr(then);
@ -482,7 +487,12 @@ fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx h
hir::ExprKind::If(cond, then, None) => {
let expr_cx = visitor.cx;
visitor.enter_scope(Scope { id: then.hir_id.local_id, data: ScopeData::IfThen });
let data = if expr.span.at_least_rust_2024() && visitor.tcx.features().if_let_rescope {
ScopeData::IfThenRescope
} else {
ScopeData::IfThen
};
visitor.enter_scope(Scope { id: then.hir_id.local_id, data });
visitor.cx.var_parent = visitor.cx.parent;
visitor.visit_expr(cond);
visitor.visit_expr(then);

View File

@ -1602,7 +1602,7 @@ fn check_fn_or_method<'tcx>(
function: def_id,
// Note that the `param_idx` of the output type is
// one greater than the index of the last input type.
param_idx: idx.try_into().unwrap(),
param_idx: idx,
}),
ty,
)
@ -1611,7 +1611,7 @@ fn check_fn_or_method<'tcx>(
for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
wfcx.register_wf_obligation(
arg_span(idx),
Some(WellFormedLoc::Param { function: def_id, param_idx: idx.try_into().unwrap() }),
Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
ty.into(),
);
}

View File

@ -53,17 +53,15 @@ fn enforce_trait_manually_implementable(
) -> Result<(), ErrorGuaranteed> {
let impl_header_span = tcx.def_span(impl_def_id);
if tcx.is_lang_item(trait_def_id, LangItem::Freeze) {
if !tcx.features().freeze_impls {
feature_err(
&tcx.sess,
sym::freeze_impls,
impl_header_span,
"explicit impls for the `Freeze` trait are not permitted",
)
.with_span_label(impl_header_span, format!("impl of `Freeze` not allowed"))
.emit();
}
if tcx.is_lang_item(trait_def_id, LangItem::Freeze) && !tcx.features().freeze_impls {
feature_err(
&tcx.sess,
sym::freeze_impls,
impl_header_span,
"explicit impls for the `Freeze` trait are not permitted",
)
.with_span_label(impl_header_span, format!("impl of `Freeze` not allowed"))
.emit();
}
// Disallow *all* explicit impls of traits marked `#[rustc_deny_explicit_impl]`

View File

@ -381,24 +381,22 @@ pub(super) fn find_opaque_ty_constraints_for_rpit<'tcx>(
}
mir_opaque_ty.ty
} else if let Some(guar) = tables.tainted_by_errors {
// Some error in the owner fn prevented us from populating
// the `concrete_opaque_types` table.
Ty::new_error(tcx, guar)
} else {
if let Some(guar) = tables.tainted_by_errors {
// Some error in the owner fn prevented us from populating
// the `concrete_opaque_types` table.
Ty::new_error(tcx, guar)
// Fall back to the RPIT we inferred during HIR typeck
if let Some(hir_opaque_ty) = hir_opaque_ty {
hir_opaque_ty.ty
} else {
// Fall back to the RPIT we inferred during HIR typeck
if let Some(hir_opaque_ty) = hir_opaque_ty {
hir_opaque_ty.ty
} else {
// We failed to resolve the opaque type or it
// resolves to itself. We interpret this as the
// no values of the hidden type ever being constructed,
// so we can just make the hidden type be `!`.
// For backwards compatibility reasons, we fall back to
// `()` until we the diverging default is changed.
Ty::new_diverging_default(tcx)
}
// We failed to resolve the opaque type or it
// resolves to itself. We interpret this as the
// no values of the hidden type ever being constructed,
// so we can just make the hidden type be `!`.
// For backwards compatibility reasons, we fall back to
// `()` until we the diverging default is changed.
Ty::new_diverging_default(tcx)
}
}
}

View File

@ -827,20 +827,18 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
if num_generic_args_supplied_to_trait + num_assoc_fn_excess_args
== num_trait_generics_except_self
&& let Some(span) = self.gen_args.span_ext()
&& let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
{
if let Some(span) = self.gen_args.span_ext()
&& let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
{
let sugg = vec![
(
self.path_segment.ident.span,
format!("{}::{}", snippet, self.path_segment.ident),
),
(span.with_lo(self.path_segment.ident.span.hi()), "".to_owned()),
];
let sugg = vec![
(
self.path_segment.ident.span,
format!("{}::{}", snippet, self.path_segment.ident),
),
(span.with_lo(self.path_segment.ident.span.hi()), "".to_owned()),
];
err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
}
err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
}
}
}

View File

@ -562,13 +562,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
tcx.const_param_default(param.def_id)
.instantiate(tcx, preceding_args)
.into()
} else if infer_args {
self.lowerer.ct_infer(Some(param), self.span).into()
} else {
if infer_args {
self.lowerer.ct_infer(Some(param), self.span).into()
} else {
// We've already errored above about the mismatch.
ty::Const::new_misc_error(tcx).into()
}
// We've already errored above about the mismatch.
ty::Const::new_misc_error(tcx).into()
}
}
}

View File

@ -58,7 +58,7 @@ pub(crate) fn check_legal_trait_for_method_call(
enum CallStep<'tcx> {
Builtin(Ty<'tcx>),
DeferredClosure(LocalDefId, ty::FnSig<'tcx>),
/// E.g., enum variant constructors.
/// Call overloading when callee implements one of the Fn* traits.
Overloaded(MethodCallee<'tcx>),
}

View File

@ -732,12 +732,11 @@ impl<'a, 'tcx> CastCheck<'tcx> {
}
_ => return Err(CastError::NonScalar),
};
if let ty::Adt(adt_def, _) = *self.expr_ty.kind() {
if adt_def.did().krate != LOCAL_CRATE {
if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) {
return Err(CastError::ForeignNonExhaustiveAdt);
}
}
if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
&& adt_def.did().krate != LOCAL_CRATE
&& adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
{
return Err(CastError::ForeignNonExhaustiveAdt);
}
match (t_from, t_cast) {
// These types have invariants! can't cast into them.

View File

@ -1780,16 +1780,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
// Make sure the programmer specified correct number of fields.
if adt_kind == AdtKind::Union {
if hir_fields.len() != 1 {
struct_span_code_err!(
self.dcx(),
span,
E0784,
"union expressions should have exactly one field",
)
.emit();
}
if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
struct_span_code_err!(
self.dcx(),
span,
E0784,
"union expressions should have exactly one field",
)
.emit();
}
// If check_expr_struct_fields hit an error, do not attempt to populate
@ -2904,21 +2902,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
candidate_fields.iter().map(|path| format!("{unwrap}{path}")),
Applicability::MaybeIncorrect,
);
} else {
if let Some(field_name) = find_best_match_for_name(&field_names, field.name, None) {
err.span_suggestion_verbose(
field.span,
"a field with a similar name exists",
format!("{unwrap}{}", field_name),
Applicability::MaybeIncorrect,
);
} else if !field_names.is_empty() {
let is = if field_names.len() == 1 { " is" } else { "s are" };
err.note(format!(
"available field{is}: {}",
self.name_series_display(field_names),
));
}
} else if let Some(field_name) =
find_best_match_for_name(&field_names, field.name, None)
{
err.span_suggestion_verbose(
field.span,
"a field with a similar name exists",
format!("{unwrap}{}", field_name),
Applicability::MaybeIncorrect,
);
} else if !field_names.is_empty() {
let is = if field_names.len() == 1 { " is" } else { "s are" };
err.note(
format!("available field{is}: {}", self.name_series_display(field_names),),
);
}
}
err

View File

@ -506,6 +506,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn_def_id,
call_span,
call_expr,
tuple_arguments,
);
}
}
@ -520,6 +521,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn_def_id: Option<DefId>,
call_span: Span,
call_expr: &'tcx hir::Expr<'tcx>,
tuple_arguments: TupleArgumentsFlag,
) -> ErrorGuaranteed {
// Next, let's construct the error
let (error_span, call_ident, full_call_span, call_name, is_method) = match &call_expr.kind {
@ -865,6 +867,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&matched_inputs,
&formal_and_expected_inputs,
is_method,
tuple_arguments,
);
suggest_confusable(&mut err);
return err.emit();
@ -1001,6 +1004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&matched_inputs,
&formal_and_expected_inputs,
is_method,
tuple_arguments,
);
suggest_confusable(&mut err);
return err.emit();
@ -1448,6 +1452,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&matched_inputs,
&formal_and_expected_inputs,
is_method,
tuple_arguments,
);
// And add a suggestion block for all of the parameters
@ -2219,21 +2224,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
matched_inputs: &IndexVec<ExpectedIdx, Option<ProvidedIdx>>,
formal_and_expected_inputs: &IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
is_method: bool,
tuple_arguments: TupleArgumentsFlag,
) {
let Some(mut def_id) = callable_def_id else {
return;
};
// If we're calling a method of a Fn/FnMut/FnOnce trait object implicitly
// (eg invoking a closure) we want to point at the underlying callable,
// not the method implicitly invoked (eg call_once).
if let Some(assoc_item) = self.tcx.opt_associated_item(def_id)
// Possibly points at either impl or trait item, so try to get it
// to point to trait item, then get the parent.
// This parent might be an impl in the case of an inherent function,
// but the next check will fail.
// Since this is an associated item, it might point at either an impl or a trait item.
// We want it to always point to the trait item.
// If we're pointing at an inherent function, we don't need to do anything,
// so we fetch the parent and verify if it's a trait item.
&& let maybe_trait_item_def_id = assoc_item.trait_item_def_id.unwrap_or(def_id)
&& let maybe_trait_def_id = self.tcx.parent(maybe_trait_item_def_id)
// Just an easy way to check "trait_def_id == Fn/FnMut/FnOnce"
&& let Some(call_kind) = self.tcx.fn_trait_kind_from_def_id(maybe_trait_def_id)
&& let Some(callee_ty) = callee_ty
// TupleArguments is set only when this is an implicit call (my_closure(...)) rather than explicit (my_closure.call(...))
&& tuple_arguments == TupleArguments
{
let callee_ty = callee_ty.peel_refs();
match *callee_ty.kind() {
@ -2303,81 +2314,154 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{
let mut spans: MultiSpan = def_span.into();
let params_with_generics = self.get_hir_params_with_generics(def_id, is_method);
let mut generics_with_unmatched_params = Vec::new();
if let Some(params_with_generics) = self.get_hir_params_with_generics(def_id, is_method)
{
debug_assert_eq!(params_with_generics.len(), matched_inputs.len());
let check_for_matched_generics = || {
if matched_inputs.iter().any(|x| x.is_some())
&& params_with_generics.iter().any(|x| x.0.is_some())
{
for (idx, (generic, _)) in params_with_generics.iter().enumerate() {
// Param has to have a generic and be matched to be relevant
if matched_inputs[idx.into()].is_none() {
continue;
}
let mut generics_with_unmatched_params = Vec::new();
let Some(generic) = generic else {
continue;
};
let check_for_matched_generics = || {
if matched_inputs.iter().any(|x| x.is_some())
&& params_with_generics.iter().any(|x| x.0.is_some())
{
for (idx, (generic, _)) in params_with_generics.iter().enumerate() {
// Param has to have a generic and be matched to be relevant
if matched_inputs[idx.into()].is_none() {
continue;
}
for unmatching_idx in idx + 1..params_with_generics.len() {
if matched_inputs[unmatching_idx.into()].is_none()
&& let Some(unmatched_idx_param_generic) =
params_with_generics[unmatching_idx].0
&& unmatched_idx_param_generic.name.ident() == generic.name.ident()
{
// We found a parameter that didn't match that needed to
return true;
let Some(generic) = generic else {
continue;
};
for unmatching_idx in idx + 1..params_with_generics.len() {
if matched_inputs[unmatching_idx.into()].is_none()
&& let Some(unmatched_idx_param_generic) =
params_with_generics[unmatching_idx].0
&& unmatched_idx_param_generic.name.ident()
== generic.name.ident()
{
// We found a parameter that didn't match that needed to
return true;
}
}
}
}
}
false
};
let check_for_matched_generics = check_for_matched_generics();
for (idx, (generic_param, param)) in
params_with_generics.iter().enumerate().filter(|(idx, _)| {
check_for_matched_generics
|| expected_idx.is_none_or(|expected_idx| expected_idx == *idx)
})
{
let Some(generic_param) = generic_param else {
spans.push_span_label(param.span, "");
continue;
false
};
let other_params_matched: Vec<(usize, &hir::Param<'_>)> = params_with_generics
.iter()
.enumerate()
.filter(|(other_idx, (other_generic_param, _))| {
if *other_idx == idx {
return false;
}
let Some(other_generic_param) = other_generic_param else {
return false;
};
if matched_inputs[idx.into()].is_none()
&& matched_inputs[(*other_idx).into()].is_none()
{
return false;
}
if matched_inputs[idx.into()].is_some()
&& matched_inputs[(*other_idx).into()].is_some()
{
return false;
}
other_generic_param.name.ident() == generic_param.name.ident()
})
.map(|(other_idx, (_, other_param))| (other_idx, *other_param))
.collect();
let check_for_matched_generics = check_for_matched_generics();
if !other_params_matched.is_empty() {
let other_param_matched_names: Vec<String> = other_params_matched
for (idx, (generic_param, param)) in
params_with_generics.iter().enumerate().filter(|(idx, _)| {
check_for_matched_generics
|| expected_idx.is_none_or(|expected_idx| expected_idx == *idx)
})
{
let Some(generic_param) = generic_param else {
spans.push_span_label(param.span, "");
continue;
};
let other_params_matched: Vec<(usize, &hir::Param<'_>)> = params_with_generics
.iter()
.map(|(_, other_param)| {
if let hir::PatKind::Binding(_, _, ident, _) = other_param.pat.kind {
.enumerate()
.filter(|(other_idx, (other_generic_param, _))| {
if *other_idx == idx {
return false;
}
let Some(other_generic_param) = other_generic_param else {
return false;
};
if matched_inputs[idx.into()].is_none()
&& matched_inputs[(*other_idx).into()].is_none()
{
return false;
}
if matched_inputs[idx.into()].is_some()
&& matched_inputs[(*other_idx).into()].is_some()
{
return false;
}
other_generic_param.name.ident() == generic_param.name.ident()
})
.map(|(other_idx, (_, other_param))| (other_idx, *other_param))
.collect();
if !other_params_matched.is_empty() {
let other_param_matched_names: Vec<String> = other_params_matched
.iter()
.map(|(_, other_param)| {
if let hir::PatKind::Binding(_, _, ident, _) = other_param.pat.kind
{
format!("`{ident}`")
} else {
"{unknown}".to_string()
}
})
.collect();
let matched_ty = self
.resolve_vars_if_possible(formal_and_expected_inputs[idx.into()].1)
.sort_string(self.tcx);
if matched_inputs[idx.into()].is_some() {
spans.push_span_label(
param.span,
format!(
"{} {} to match the {} type of this parameter",
display_list_with_comma_and(&other_param_matched_names),
format!(
"need{}",
pluralize!(if other_param_matched_names.len() == 1 {
0
} else {
1
})
),
matched_ty,
),
);
} else {
spans.push_span_label(
param.span,
format!(
"this parameter needs to match the {} type of {}",
matched_ty,
display_list_with_comma_and(&other_param_matched_names),
),
);
}
generics_with_unmatched_params.push(generic_param);
} else {
spans.push_span_label(param.span, "");
}
}
for generic_param in self
.tcx
.hir()
.get_if_local(def_id)
.and_then(|node| node.generics())
.into_iter()
.flat_map(|x| x.params)
.filter(|x| {
generics_with_unmatched_params
.iter()
.any(|y| x.name.ident() == y.name.ident())
})
{
let param_idents_matching: Vec<String> = params_with_generics
.iter()
.filter(|(generic, _)| {
if let Some(generic) = generic {
generic.name.ident() == generic_param.name.ident()
} else {
false
}
})
.map(|(_, param)| {
if let hir::PatKind::Binding(_, _, ident, _) = param.pat.kind {
format!("`{ident}`")
} else {
"{unknown}".to_string()
@ -2385,84 +2469,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
})
.collect();
let matched_ty = self
.resolve_vars_if_possible(formal_and_expected_inputs[idx.into()].1)
.sort_string(self.tcx);
if matched_inputs[idx.into()].is_some() {
if !param_idents_matching.is_empty() {
spans.push_span_label(
param.span,
generic_param.span,
format!(
"{} {} to match the {} type of this parameter",
display_list_with_comma_and(&other_param_matched_names),
format!(
"need{}",
pluralize!(if other_param_matched_names.len() == 1 {
0
} else {
1
})
),
matched_ty,
),
);
} else {
spans.push_span_label(
param.span,
format!(
"this parameter needs to match the {} type of {}",
matched_ty,
display_list_with_comma_and(&other_param_matched_names),
"{} all reference this parameter {}",
display_list_with_comma_and(&param_idents_matching),
generic_param.name.ident().name,
),
);
}
generics_with_unmatched_params.push(generic_param);
} else {
spans.push_span_label(param.span, "");
}
}
for generic_param in self
.tcx
.hir()
.get_if_local(def_id)
.and_then(|node| node.generics())
.into_iter()
.flat_map(|x| x.params)
.filter(|x| {
generics_with_unmatched_params.iter().any(|y| x.name.ident() == y.name.ident())
})
{
let param_idents_matching: Vec<String> = params_with_generics
.iter()
.filter(|(generic, _)| {
if let Some(generic) = generic {
generic.name.ident() == generic_param.name.ident()
} else {
false
}
})
.map(|(_, param)| {
if let hir::PatKind::Binding(_, _, ident, _) = param.pat.kind {
format!("`{ident}`")
} else {
"{unknown}".to_string()
}
})
.collect();
if !param_idents_matching.is_empty() {
spans.push_span_label(
generic_param.span,
format!(
"{} all reference this parameter {}",
display_list_with_comma_and(&param_idents_matching),
generic_param.name.ident().name,
),
);
}
}
err.span_note(spans, format!("{} defined here", self.tcx.def_descr(def_id)));
} else if let Some(hir::Node::Expr(e)) = self.tcx.hir().get_if_local(def_id)
&& let hir::ExprKind::Closure(hir::Closure { body, .. }) = &e.kind
@ -2535,74 +2553,77 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
return;
};
let params_with_generics = self.get_hir_params_with_generics(def_id, is_method);
if let Some(params_with_generics) = self.get_hir_params_with_generics(def_id, is_method) {
debug_assert_eq!(params_with_generics.len(), matched_inputs.len());
for (idx, (generic_param, _)) in params_with_generics.iter().enumerate() {
if matched_inputs[idx.into()].is_none() {
continue;
}
for (idx, (generic_param, _)) in params_with_generics.iter().enumerate() {
if matched_inputs[idx.into()].is_none() {
continue;
let Some((_, matched_arg_span)) = provided_arg_tys.get(idx.into()) else {
continue;
};
let Some(generic_param) = generic_param else {
continue;
};
let mut idxs_matched: Vec<usize> = vec![];
for (other_idx, (_, _)) in params_with_generics.iter().enumerate().filter(
|(other_idx, (other_generic_param, _))| {
if *other_idx == idx {
return false;
}
let Some(other_generic_param) = other_generic_param else {
return false;
};
if matched_inputs[(*other_idx).into()].is_some() {
return false;
}
other_generic_param.name.ident() == generic_param.name.ident()
},
) {
idxs_matched.push(other_idx);
}
if idxs_matched.is_empty() {
continue;
}
let expected_display_type = self
.resolve_vars_if_possible(formal_and_expected_inputs[idx.into()].1)
.sort_string(self.tcx);
let label = if idxs_matched.len() == params_with_generics.len() - 1 {
format!(
"expected all arguments to be this {} type because they need to match the type of this parameter",
expected_display_type
)
} else {
format!(
"expected some other arguments to be {} {} type to match the type of this parameter",
a_or_an(&expected_display_type),
expected_display_type,
)
};
err.span_label(*matched_arg_span, label);
}
let Some((_, matched_arg_span)) = provided_arg_tys.get(idx.into()) else {
continue;
};
let Some(generic_param) = generic_param else {
continue;
};
let mut idxs_matched: Vec<usize> = vec![];
for (other_idx, (_, _)) in params_with_generics.iter().enumerate().filter(
|(other_idx, (other_generic_param, _))| {
if *other_idx == idx {
return false;
}
let Some(other_generic_param) = other_generic_param else {
return false;
};
if matched_inputs[(*other_idx).into()].is_some() {
return false;
}
other_generic_param.name.ident() == generic_param.name.ident()
},
) {
idxs_matched.push(other_idx.into());
}
if idxs_matched.is_empty() {
continue;
}
let expected_display_type = self
.resolve_vars_if_possible(formal_and_expected_inputs[idx.into()].1)
.sort_string(self.tcx);
let label = if idxs_matched.len() == params_with_generics.len() - 1 {
format!(
"expected all arguments to be this {} type because they need to match the type of this parameter",
expected_display_type
)
} else {
format!(
"expected some other arguments to be {} {} type to match the type of this parameter",
a_or_an(&expected_display_type),
expected_display_type,
)
};
err.span_label(*matched_arg_span, label);
}
}
/// Returns the parameters of a function, with their generic parameters if those are the full
/// type of that parameter. Returns `None` if the function body is unavailable (eg is an instrinsic).
fn get_hir_params_with_generics(
&self,
def_id: DefId,
is_method: bool,
) -> Vec<(Option<&hir::GenericParam<'_>>, &hir::Param<'_>)> {
let fn_node = self.tcx.hir().get_if_local(def_id);
) -> Option<Vec<(Option<&hir::GenericParam<'_>>, &hir::Param<'_>)>> {
let fn_node = self.tcx.hir().get_if_local(def_id)?;
let generic_params: Vec<Option<&hir::GenericParam<'_>>> = fn_node
.and_then(|node| node.fn_decl())
.fn_decl()?
.inputs
.into_iter()
.flat_map(|decl| decl.inputs)
.skip(if is_method { 1 } else { 0 })
.map(|param| {
if let hir::TyKind::Path(QPath::Resolved(
@ -2611,7 +2632,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
)) = param.kind
{
fn_node
.and_then(|node| node.generics())
.generics()
.into_iter()
.flat_map(|generics| generics.params)
.find(|param| &param.def_id.to_def_id() == res_def_id)
@ -2621,14 +2642,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
})
.collect();
let params: Vec<&hir::Param<'_>> = fn_node
.and_then(|node| node.body_id())
let params: Vec<&hir::Param<'_>> = self
.tcx
.hir()
.body(fn_node.body_id()?)
.params
.into_iter()
.flat_map(|id| self.tcx.hir().body(id).params)
.skip(if is_method { 1 } else { 0 })
.collect();
generic_params.into_iter().zip(params).collect()
Some(generic_params.into_iter().zip_eq(params).collect())
}
}

View File

@ -158,14 +158,12 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> {
),
);
}
} else {
if !self.fcx.tcx.features().unsized_locals {
self.fcx.require_type_is_sized(
var_ty,
p.span,
ObligationCauseCode::VariableType(p.hir_id),
);
}
} else if !self.fcx.tcx.features().unsized_locals {
self.fcx.require_type_is_sized(
var_ty,
p.span,
ObligationCauseCode::VariableType(p.hir_id),
);
}
debug!(

View File

@ -1252,11 +1252,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&& suggested_bounds.contains(parent)
{
// We don't suggest `PartialEq` when we already suggest `Eq`.
} else if !suggested_bounds.contains(pred) {
if collect_type_param_suggestions(self_ty, *pred, &p) {
suggested = true;
suggested_bounds.insert(pred);
}
} else if !suggested_bounds.contains(pred)
&& collect_type_param_suggestions(self_ty, *pred, &p)
{
suggested = true;
suggested_bounds.insert(pred);
}
(
match parent_pred {
@ -1267,14 +1267,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if !suggested
&& !suggested_bounds.contains(pred)
&& !suggested_bounds.contains(parent_pred)
{
if collect_type_param_suggestions(
&& collect_type_param_suggestions(
self_ty,
*parent_pred,
&p,
) {
suggested_bounds.insert(pred);
}
)
{
suggested_bounds.insert(pred);
}
format!("`{p}`\nwhich is required by `{parent_p}`")
}

View File

@ -417,12 +417,10 @@ fn check_config(tcx: TyCtxt<'_>, attr: &Attribute) -> bool {
fn expect_associated_value(tcx: TyCtxt<'_>, item: &NestedMetaItem) -> Symbol {
if let Some(value) = item.value_str() {
value
} else if let Some(ident) = item.ident() {
tcx.dcx().emit_fatal(errors::AssociatedValueExpectedFor { span: item.span(), ident });
} else {
if let Some(ident) = item.ident() {
tcx.dcx().emit_fatal(errors::AssociatedValueExpectedFor { span: item.span(), ident });
} else {
tcx.dcx().emit_fatal(errors::AssociatedValueExpected { span: item.span() });
}
tcx.dcx().emit_fatal(errors::AssociatedValueExpected { span: item.span() });
}
}

View File

@ -808,7 +808,7 @@ fn test_unstable_options_tracking_hash() {
tracked!(mir_opt_level, Some(4));
tracked!(move_size_limit, Some(4096));
tracked!(mutable_noalias, false);
tracked!(next_solver, NextSolverConfig { coherence: true, globally: true });
tracked!(next_solver, Some(NextSolverConfig { coherence: true, globally: false }));
tracked!(no_generate_arange_section, true);
tracked!(no_jump_tables, true);
tracked!(no_link, true);
@ -847,6 +847,7 @@ fn test_unstable_options_tracking_hash() {
tracked!(share_generics, Some(true));
tracked!(show_span, Some(String::from("abc")));
tracked!(simulate_remapped_rust_src_base, Some(PathBuf::from("/rustc/abc")));
tracked!(small_data_threshold, Some(16));
tracked!(split_lto_unit, Some(true));
tracked!(src_hash_algorithm, Some(SourceFileHashAlgorithm::Sha1));
tracked!(stack_protector, StackProtector::All);

View File

@ -334,6 +334,11 @@ lint_identifier_uncommon_codepoints = identifier contains {$codepoints_len ->
*[other] {" "}{$identifier_type}
} Unicode general security profile
lint_if_let_rescope = `if let` assigns a shorter lifetime since Edition 2024
.label = this value has a significant drop implementation which may observe a major change in drop order and requires your discretion
.help = the value is now dropped here in Edition 2024
.suggestion = a `match` with a single arm can preserve the drop order up to Edition 2021
lint_ignored_unless_crate_specified = {$level}({$name}) is ignored unless specified at crate level
lint_ill_formed_attribute_input = {$num_suggestions ->

View File

@ -429,10 +429,8 @@ impl MissingDoc {
// Only check publicly-visible items, using the result from the privacy pass.
// It's an option so the crate root can also use this function (it doesn't
// have a `NodeId`).
if def_id != CRATE_DEF_ID {
if !cx.effective_visibilities.is_exported(def_id) {
return;
}
if def_id != CRATE_DEF_ID && !cx.effective_visibilities.is_exported(def_id) {
return;
}
let attrs = cx.tcx.hir().attrs(cx.tcx.local_def_id_to_hir_id(def_id));

View File

@ -3,8 +3,7 @@ use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_middle::query::Providers;
use rustc_middle::ty::layout::LayoutError;
use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
use rustc_middle::ty::{self, AdtDef, Instance, Ty, TyCtxt};
use rustc_session::declare_lint;
use rustc_span::{sym, Span, Symbol};
use rustc_target::abi::FIRST_VARIANT;
@ -212,7 +211,17 @@ fn structurally_same_type<'tcx>(
ckind: types::CItemKind,
) -> bool {
let mut seen_types = UnordSet::default();
structurally_same_type_impl(&mut seen_types, tcx, param_env, a, b, ckind)
let result = structurally_same_type_impl(&mut seen_types, tcx, param_env, a, b, ckind);
if cfg!(debug_assertions) && result {
// Sanity-check: must have same ABI, size and alignment.
// `extern` blocks cannot be generic, so we'll always get a layout here.
let a_layout = tcx.layout_of(param_env.and(a)).unwrap();
let b_layout = tcx.layout_of(param_env.and(b)).unwrap();
assert_eq!(a_layout.abi, b_layout.abi);
assert_eq!(a_layout.size, b_layout.size);
assert_eq!(a_layout.align, b_layout.align);
}
result
}
fn structurally_same_type_impl<'tcx>(
@ -266,30 +275,21 @@ fn structurally_same_type_impl<'tcx>(
// Do a full, depth-first comparison between the two.
use rustc_type_ir::TyKind::*;
let compare_layouts = |a, b| -> Result<bool, &'tcx LayoutError<'tcx>> {
debug!("compare_layouts({:?}, {:?})", a, b);
let a_layout = &tcx.layout_of(param_env.and(a))?.layout.abi();
let b_layout = &tcx.layout_of(param_env.and(b))?.layout.abi();
debug!(
"comparing layouts: {:?} == {:?} = {}",
a_layout,
b_layout,
a_layout == b_layout
);
Ok(a_layout == b_layout)
};
let is_primitive_or_pointer =
|ty: Ty<'tcx>| ty.is_primitive() || matches!(ty.kind(), RawPtr(..) | Ref(..));
ensure_sufficient_stack(|| {
match (a.kind(), b.kind()) {
(Adt(a_def, _), Adt(b_def, _)) => {
// We can immediately rule out these types as structurally same if
// their layouts differ.
match compare_layouts(a, b) {
Ok(false) => return false,
_ => (), // otherwise, continue onto the full, fields comparison
(&Adt(a_def, _), &Adt(b_def, _)) => {
// Only `repr(C)` types can be compared structurally.
if !(a_def.repr().c() && b_def.repr().c()) {
return false;
}
// If the types differ in their packed-ness, align, or simd-ness they conflict.
let repr_characteristica =
|def: AdtDef<'tcx>| (def.repr().pack, def.repr().align, def.repr().simd());
if repr_characteristica(a_def) != repr_characteristica(b_def) {
return false;
}
// Grab a flattened representation of all fields.
@ -311,9 +311,9 @@ fn structurally_same_type_impl<'tcx>(
},
)
}
(Array(a_ty, a_const), Array(b_ty, b_const)) => {
// For arrays, we also check the constness of the type.
a_const.kind() == b_const.kind()
(Array(a_ty, a_len), Array(b_ty, b_len)) => {
// For arrays, we also check the length.
a_len == b_len
&& structurally_same_type_impl(
seen_types, tcx, param_env, *a_ty, *b_ty, ckind,
)
@ -357,10 +357,9 @@ fn structurally_same_type_impl<'tcx>(
ckind,
)
}
(Tuple(a_args), Tuple(b_args)) => {
a_args.iter().eq_by(b_args.iter(), |a_ty, b_ty| {
structurally_same_type_impl(seen_types, tcx, param_env, a_ty, b_ty, ckind)
})
(Tuple(..), Tuple(..)) => {
// Tuples are not `repr(C)` so these cannot be compared structurally.
false
}
// For these, it's not quite as easy to define structural-sameness quite so easily.
// For the purposes of this lint, take the conservative approach and mark them as
@ -380,24 +379,21 @@ fn structurally_same_type_impl<'tcx>(
// An Adt and a primitive or pointer type. This can be FFI-safe if non-null
// enum layout optimisation is being applied.
(Adt(..), _) if is_primitive_or_pointer(b) => {
if let Some(ty) = types::repr_nullable_ptr(tcx, param_env, a, ckind) {
ty == b
if let Some(a_inner) = types::repr_nullable_ptr(tcx, param_env, a, ckind) {
a_inner == b
} else {
compare_layouts(a, b).unwrap_or(false)
false
}
}
(_, Adt(..)) if is_primitive_or_pointer(a) => {
if let Some(ty) = types::repr_nullable_ptr(tcx, param_env, b, ckind) {
ty == a
if let Some(b_inner) = types::repr_nullable_ptr(tcx, param_env, b, ckind) {
b_inner == a
} else {
compare_layouts(a, b).unwrap_or(false)
false
}
}
// Otherwise, just compare the layouts. This may fail to lint for some
// incompatible types, but at the very least, will stop reads into
// uninitialised memory.
_ => compare_layouts(a, b).unwrap_or(false),
_ => false,
}
})
}

View File

@ -0,0 +1,430 @@
use std::iter::repeat;
use std::ops::ControlFlow;
use hir::intravisit::Visitor;
use rustc_ast::Recovered;
use rustc_errors::{
Applicability, Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic, SuggestionStyle,
};
use rustc_hir::{self as hir, HirIdSet};
use rustc_macros::LintDiagnostic;
use rustc_middle::ty::TyCtxt;
use rustc_session::lint::{FutureIncompatibilityReason, Level};
use rustc_session::{declare_lint, impl_lint_pass};
use rustc_span::edition::Edition;
use rustc_span::Span;
use crate::{LateContext, LateLintPass};
declare_lint! {
/// The `if_let_rescope` lint detects cases where a temporary value with
/// significant drop is generated on the right hand side of `if let`
/// and suggests a rewrite into `match` when possible.
///
/// ### Example
///
/// ```rust,edition2021
/// #![feature(if_let_rescope)]
/// #![warn(if_let_rescope)]
/// #![allow(unused_variables)]
///
/// struct Droppy;
/// impl Drop for Droppy {
/// fn drop(&mut self) {
/// // Custom destructor, including this `drop` implementation, is considered
/// // significant.
/// // Rust does not check whether this destructor emits side-effects that can
/// // lead to observable change in program semantics, when the drop order changes.
/// // Rust biases to be on the safe side, so that you can apply discretion whether
/// // this change indeed breaches any contract or specification that your code needs
/// // to honour.
/// println!("dropped");
/// }
/// }
/// impl Droppy {
/// fn get(&self) -> Option<u8> {
/// None
/// }
/// }
///
/// fn main() {
/// if let Some(value) = Droppy.get() {
/// // do something
/// } else {
/// // do something else
/// }
/// }
/// ```
///
/// {{produces}}
///
/// ### Explanation
///
/// With Edition 2024, temporaries generated while evaluating `if let`s
/// will be dropped before the `else` block.
/// This lint captures a possible change in runtime behaviour due to
/// a change in sequence of calls to significant `Drop::drop` destructors.
///
/// A significant [`Drop::drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html)
/// destructor here refers to an explicit, arbitrary implementation of the `Drop` trait on the type
/// with exceptions including `Vec`, `Box`, `Rc`, `BTreeMap` and `HashMap`
/// that are marked by the compiler otherwise so long that the generic types have
/// no significant destructor recursively.
/// In other words, a type has a significant drop destructor when it has a `Drop` implementation
/// or its destructor invokes a significant destructor on a type.
/// Since we cannot completely reason about the change by just inspecting the existence of
/// a significant destructor, this lint remains only a suggestion and is set to `allow` by default.
///
/// Whenever possible, a rewrite into an equivalent `match` expression that
/// observe the same order of calls to such destructors is proposed by this lint.
/// Authors may take their own discretion whether the rewrite suggestion shall be
/// accepted, or rejected to continue the use of the `if let` expression.
pub IF_LET_RESCOPE,
Allow,
"`if let` assigns a shorter lifetime to temporary values being pattern-matched against in Edition 2024 and \
rewriting in `match` is an option to preserve the semantics up to Edition 2021",
@future_incompatible = FutureIncompatibleInfo {
reason: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2024),
reference: "issue #124085 <https://github.com/rust-lang/rust/issues/124085>",
};
}
/// Lint for potential change in program semantics of `if let`s
#[derive(Default)]
pub(crate) struct IfLetRescope {
skip: HirIdSet,
}
fn expr_parent_is_else(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
let Some((_, hir::Node::Expr(expr))) = tcx.hir().parent_iter(hir_id).next() else {
return false;
};
let hir::ExprKind::If(_cond, _conseq, Some(alt)) = expr.kind else { return false };
alt.hir_id == hir_id
}
fn expr_parent_is_stmt(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
let Some((_, hir::Node::Stmt(stmt))) = tcx.hir().parent_iter(hir_id).next() else {
return false;
};
let (hir::StmtKind::Semi(expr) | hir::StmtKind::Expr(expr)) = stmt.kind else { return false };
expr.hir_id == hir_id
}
fn match_head_needs_bracket(tcx: TyCtxt<'_>, expr: &hir::Expr<'_>) -> bool {
expr_parent_is_else(tcx, expr.hir_id) && matches!(expr.kind, hir::ExprKind::If(..))
}
impl IfLetRescope {
fn probe_if_cascade<'tcx>(&mut self, cx: &LateContext<'tcx>, mut expr: &'tcx hir::Expr<'tcx>) {
if self.skip.contains(&expr.hir_id) {
return;
}
let tcx = cx.tcx;
let source_map = tcx.sess.source_map();
let expr_end = expr.span.shrink_to_hi();
let mut add_bracket_to_match_head = match_head_needs_bracket(tcx, expr);
let mut significant_droppers = vec![];
let mut lifetime_ends = vec![];
let mut closing_brackets = 0;
let mut alt_heads = vec![];
let mut match_heads = vec![];
let mut consequent_heads = vec![];
let mut first_if_to_lint = None;
let mut first_if_to_rewrite = false;
let mut empty_alt = false;
while let hir::ExprKind::If(cond, conseq, alt) = expr.kind {
self.skip.insert(expr.hir_id);
// We are interested in `let` fragment of the condition.
// Otherwise, we probe into the `else` fragment.
if let hir::ExprKind::Let(&hir::LetExpr {
span,
pat,
init,
ty: ty_ascription,
recovered: Recovered::No,
}) = cond.kind
{
let if_let_pat = expr.span.shrink_to_lo().between(init.span);
// The consequent fragment is always a block.
let before_conseq = conseq.span.shrink_to_lo();
let lifetime_end = source_map.end_point(conseq.span);
if let ControlFlow::Break(significant_dropper) =
(FindSignificantDropper { cx }).visit_expr(init)
{
first_if_to_lint = first_if_to_lint.or_else(|| Some((span, expr.hir_id)));
significant_droppers.push(significant_dropper);
lifetime_ends.push(lifetime_end);
if ty_ascription.is_some()
|| !expr.span.can_be_used_for_suggestions()
|| !pat.span.can_be_used_for_suggestions()
{
// Our `match` rewrites does not support type ascription,
// so we just bail.
// Alternatively when the span comes from proc macro expansion,
// we will also bail.
// FIXME(#101728): change this when type ascription syntax is stabilized again
} else if let Ok(pat) = source_map.span_to_snippet(pat.span) {
let emit_suggestion = |alt_span| {
first_if_to_rewrite = true;
if add_bracket_to_match_head {
closing_brackets += 2;
match_heads.push(SingleArmMatchBegin::WithOpenBracket(if_let_pat));
} else {
// Sometimes, wrapping `match` into a block is undesirable,
// because the scrutinee temporary lifetime is shortened and
// the proposed fix will not work.
closing_brackets += 1;
match_heads
.push(SingleArmMatchBegin::WithoutOpenBracket(if_let_pat));
}
consequent_heads.push(ConsequentRewrite { span: before_conseq, pat });
if let Some(alt_span) = alt_span {
alt_heads.push(AltHead(alt_span));
}
};
if let Some(alt) = alt {
let alt_head = conseq.span.between(alt.span);
if alt_head.can_be_used_for_suggestions() {
// We lint only when the `else` span is user code, too.
emit_suggestion(Some(alt_head));
}
} else {
// This is the end of the `if .. else ..` cascade.
// We can stop here.
emit_suggestion(None);
empty_alt = true;
break;
}
}
}
}
// At this point, any `if let` fragment in the cascade is definitely preceeded by `else`,
// so a opening bracket is mandatory before each `match`.
add_bracket_to_match_head = true;
if let Some(alt) = alt {
expr = alt;
} else {
break;
}
}
if let Some((span, hir_id)) = first_if_to_lint {
tcx.emit_node_span_lint(
IF_LET_RESCOPE,
hir_id,
span,
IfLetRescopeLint {
significant_droppers,
lifetime_ends,
rewrite: first_if_to_rewrite.then_some(IfLetRescopeRewrite {
match_heads,
consequent_heads,
closing_brackets: ClosingBrackets {
span: expr_end,
count: closing_brackets,
empty_alt,
},
alt_heads,
}),
},
);
}
}
}
impl_lint_pass!(
IfLetRescope => [IF_LET_RESCOPE]
);
impl<'tcx> LateLintPass<'tcx> for IfLetRescope {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
if expr.span.edition().at_least_rust_2024() || !cx.tcx.features().if_let_rescope {
return;
}
if let (Level::Allow, _) = cx.tcx.lint_level_at_node(IF_LET_RESCOPE, expr.hir_id) {
return;
}
if expr_parent_is_stmt(cx.tcx, expr.hir_id)
&& matches!(expr.kind, hir::ExprKind::If(_cond, _conseq, None))
{
// `if let` statement without an `else` branch has no observable change
// so we can skip linting it
return;
}
self.probe_if_cascade(cx, expr);
}
}
#[derive(LintDiagnostic)]
#[diag(lint_if_let_rescope)]
struct IfLetRescopeLint {
#[label]
significant_droppers: Vec<Span>,
#[help]
lifetime_ends: Vec<Span>,
#[subdiagnostic]
rewrite: Option<IfLetRescopeRewrite>,
}
// #[derive(Subdiagnostic)]
struct IfLetRescopeRewrite {
match_heads: Vec<SingleArmMatchBegin>,
consequent_heads: Vec<ConsequentRewrite>,
closing_brackets: ClosingBrackets,
alt_heads: Vec<AltHead>,
}
impl Subdiagnostic for IfLetRescopeRewrite {
fn add_to_diag_with<G: EmissionGuarantee, F: SubdiagMessageOp<G>>(
self,
diag: &mut Diag<'_, G>,
f: &F,
) {
let mut suggestions = vec![];
for match_head in self.match_heads {
match match_head {
SingleArmMatchBegin::WithOpenBracket(span) => {
suggestions.push((span, "{ match ".into()))
}
SingleArmMatchBegin::WithoutOpenBracket(span) => {
suggestions.push((span, "match ".into()))
}
}
}
for ConsequentRewrite { span, pat } in self.consequent_heads {
suggestions.push((span, format!("{{ {pat} => ")));
}
for AltHead(span) in self.alt_heads {
suggestions.push((span, " _ => ".into()));
}
let closing_brackets = self.closing_brackets;
suggestions.push((
closing_brackets.span,
closing_brackets
.empty_alt
.then_some(" _ => {}".chars())
.into_iter()
.flatten()
.chain(repeat('}').take(closing_brackets.count))
.collect(),
));
let msg = f(diag, crate::fluent_generated::lint_suggestion.into());
diag.multipart_suggestion_with_style(
msg,
suggestions,
Applicability::MachineApplicable,
SuggestionStyle::ShowCode,
);
}
}
struct AltHead(Span);
struct ConsequentRewrite {
span: Span,
pat: String,
}
struct ClosingBrackets {
span: Span,
count: usize,
empty_alt: bool,
}
enum SingleArmMatchBegin {
WithOpenBracket(Span),
WithoutOpenBracket(Span),
}
struct FindSignificantDropper<'tcx, 'a> {
cx: &'a LateContext<'tcx>,
}
impl<'tcx, 'a> Visitor<'tcx> for FindSignificantDropper<'tcx, 'a> {
type Result = ControlFlow<Span>;
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
if self
.cx
.typeck_results()
.expr_ty(expr)
.has_significant_drop(self.cx.tcx, self.cx.param_env)
{
return ControlFlow::Break(expr.span);
}
match expr.kind {
hir::ExprKind::ConstBlock(_)
| hir::ExprKind::Lit(_)
| hir::ExprKind::Path(_)
| hir::ExprKind::Assign(_, _, _)
| hir::ExprKind::AssignOp(_, _, _)
| hir::ExprKind::Break(_, _)
| hir::ExprKind::Continue(_)
| hir::ExprKind::Ret(_)
| hir::ExprKind::Become(_)
| hir::ExprKind::InlineAsm(_)
| hir::ExprKind::OffsetOf(_, _)
| hir::ExprKind::Repeat(_, _)
| hir::ExprKind::Err(_)
| hir::ExprKind::Struct(_, _, _)
| hir::ExprKind::Closure(_)
| hir::ExprKind::Block(_, _)
| hir::ExprKind::DropTemps(_)
| hir::ExprKind::Loop(_, _, _, _) => ControlFlow::Continue(()),
hir::ExprKind::Tup(exprs) | hir::ExprKind::Array(exprs) => {
for expr in exprs {
self.visit_expr(expr)?;
}
ControlFlow::Continue(())
}
hir::ExprKind::Call(callee, args) => {
self.visit_expr(callee)?;
for expr in args {
self.visit_expr(expr)?;
}
ControlFlow::Continue(())
}
hir::ExprKind::MethodCall(_, receiver, args, _) => {
self.visit_expr(receiver)?;
for expr in args {
self.visit_expr(expr)?;
}
ControlFlow::Continue(())
}
hir::ExprKind::Index(left, right, _) | hir::ExprKind::Binary(_, left, right) => {
self.visit_expr(left)?;
self.visit_expr(right)
}
hir::ExprKind::Unary(_, expr)
| hir::ExprKind::Cast(expr, _)
| hir::ExprKind::Type(expr, _)
| hir::ExprKind::Yield(expr, _)
| hir::ExprKind::AddrOf(_, _, expr)
| hir::ExprKind::Match(expr, _, _)
| hir::ExprKind::Field(expr, _)
| hir::ExprKind::Let(&hir::LetExpr {
init: expr,
span: _,
pat: _,
ty: _,
recovered: Recovered::No,
}) => self.visit_expr(expr),
hir::ExprKind::Let(_) => ControlFlow::Continue(()),
hir::ExprKind::If(cond, _, _) => {
if let hir::ExprKind::Let(hir::LetExpr {
init,
span: _,
pat: _,
ty: _,
recovered: Recovered::No,
}) = cond.kind
{
self.visit_expr(init)?;
}
ControlFlow::Continue(())
}
}
}
}

View File

@ -56,6 +56,7 @@ mod expect;
mod for_loops_over_fallibles;
mod foreign_modules;
pub mod hidden_unicode_codepoints;
mod if_let_rescope;
mod impl_trait_overcaptures;
mod internal;
mod invalid_from_utf8;
@ -94,6 +95,7 @@ use drop_forget_useless::*;
use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
use for_loops_over_fallibles::*;
use hidden_unicode_codepoints::*;
use if_let_rescope::IfLetRescope;
use impl_trait_overcaptures::ImplTraitOvercaptures;
use internal::*;
use invalid_from_utf8::*;
@ -243,6 +245,7 @@ late_lint_methods!(
NonLocalDefinitions: NonLocalDefinitions::default(),
ImplTraitOvercaptures: ImplTraitOvercaptures,
TailExprDropOrder: TailExprDropOrder,
IfLetRescope: IfLetRescope::default(),
]
]
);

View File

@ -96,6 +96,7 @@ impl fmt::Debug for Scope {
ScopeData::Arguments => write!(fmt, "Arguments({:?})", self.id),
ScopeData::Destruction => write!(fmt, "Destruction({:?})", self.id),
ScopeData::IfThen => write!(fmt, "IfThen({:?})", self.id),
ScopeData::IfThenRescope => write!(fmt, "IfThen[edition2024]({:?})", self.id),
ScopeData::Remainder(fsi) => write!(
fmt,
"Remainder {{ block: {:?}, first_statement_index: {}}}",
@ -126,6 +127,11 @@ pub enum ScopeData {
/// Used for variables introduced in an if-let expression.
IfThen,
/// Scope of the condition and then block of an if expression
/// Used for variables introduced in an if-let expression,
/// whose lifetimes do not cross beyond this scope.
IfThenRescope,
/// Scope following a `let id = expr;` binding in a block.
Remainder(FirstStatementIndex),
}

View File

@ -444,10 +444,11 @@ impl<'tcx> TyCtxt<'tcx> {
// the `-Z force-unstable-if-unmarked` flag present (we're
// compiling a compiler crate), then let this missing feature
// annotation slide.
if feature == sym::rustc_private && issue == NonZero::new(27812) {
if self.sess.opts.unstable_opts.force_unstable_if_unmarked {
return EvalResult::Allow;
}
if feature == sym::rustc_private
&& issue == NonZero::new(27812)
&& self.sess.opts.unstable_opts.force_unstable_if_unmarked
{
return EvalResult::Allow;
}
if matches!(allow_unstable, AllowUnstable::Yes) {

View File

@ -448,22 +448,20 @@ impl<Prov: Provenance, Extra, Bytes: AllocBytes> Allocation<Prov, Extra, Bytes>
bad: uninit_range,
}))
})?;
if !Prov::OFFSET_IS_ADDR {
if !self.provenance.range_empty(range, cx) {
// Find the provenance.
let (offset, _prov) = self
.provenance
.range_get_ptrs(range, cx)
.first()
.copied()
.expect("there must be provenance somewhere here");
let start = offset.max(range.start); // the pointer might begin before `range`!
let end = (offset + cx.pointer_size()).min(range.end()); // the pointer might end after `range`!
return Err(AllocError::ReadPointerAsInt(Some(BadBytesAccess {
access: range,
bad: AllocRange::from(start..end),
})));
}
if !Prov::OFFSET_IS_ADDR && !self.provenance.range_empty(range, cx) {
// Find the provenance.
let (offset, _prov) = self
.provenance
.range_get_ptrs(range, cx)
.first()
.copied()
.expect("there must be provenance somewhere here");
let start = offset.max(range.start); // the pointer might begin before `range`!
let end = (offset + cx.pointer_size()).min(range.end()); // the pointer might end after `range`!
return Err(AllocError::ReadPointerAsInt(Some(BadBytesAccess {
access: range,
bad: AllocRange::from(start..end),
})));
}
Ok(self.get_bytes_unchecked(range))
}

View File

@ -1084,6 +1084,9 @@ pub enum LocalInfo<'tcx> {
/// (with no intervening statement context).
// FIXME(matthewjasper) Don't store in this in `Body`
BlockTailTemp(BlockTailInfo),
/// A temporary created during evaluating `if` predicate, possibly for pattern matching for `let`s,
/// and subject to Edition 2024 temporary lifetime rules
IfThenRescopeTemp { if_then: HirId },
/// A temporary created during the pass `Derefer` to avoid it's retagging
DerefTemp,
/// A temporary created for borrow checking.

View File

@ -208,12 +208,10 @@ fn dump_path<'tcx>(
let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
String::new()
} else if pass_num {
format!(".{:03}-{:03}", body.phase.phase_index(), body.pass_count)
} else {
if pass_num {
format!(".{:03}-{:03}", body.phase.phase_index(), body.pass_count)
} else {
".-------".to_string()
}
".-------".to_string()
};
let crate_name = tcx.crate_name(source.def_id().krate);

View File

@ -295,20 +295,12 @@ impl<'tcx> Const<'tcx> {
_ => expr,
};
if let hir::ExprKind::Path(
qpath @ hir::QPath::Resolved(
_,
&hir::Path { res: Res::Def(DefKind::ConstParam, _), .. },
),
) = expr.kind
if let hir::ExprKind::Path(hir::QPath::Resolved(
_,
&hir::Path { res: Res::Def(DefKind::ConstParam, _), .. },
)) = expr.kind
{
if tcx.features().const_arg_path {
span_bug!(
expr.span,
"try_from_lit: received const param which shouldn't be possible"
);
}
return Some(Const::from_param(tcx, qpath, expr.hir_id));
span_bug!(expr.span, "try_from_lit: received const param which shouldn't be possible");
};
let lit_input = match expr.kind {
@ -396,7 +388,7 @@ impl<'tcx> Const<'tcx> {
Ok((tcx.type_of(unevaluated.def).instantiate(tcx, unevaluated.args), c))
}
Ok(Err(bad_ty)) => Err(Either::Left(bad_ty)),
Err(err) => Err(Either::Right(err.into())),
Err(err) => Err(Either::Right(err)),
}
}
ConstKind::Value(ty, val) => Ok((ty, val)),

View File

@ -2606,33 +2606,31 @@ impl<'tcx> TyCtxt<'tcx> {
/// With `cfg(debug_assertions)`, assert that args are compatible with their generics,
/// and print out the args if not.
pub fn debug_assert_args_compatible(self, def_id: DefId, args: &'tcx [ty::GenericArg<'tcx>]) {
if cfg!(debug_assertions) {
if !self.check_args_compatible(def_id, args) {
if let DefKind::AssocTy = self.def_kind(def_id)
&& let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id))
{
bug!(
"args not compatible with generics for {}: args={:#?}, generics={:#?}",
self.def_path_str(def_id),
args,
// Make `[Self, GAT_ARGS...]` (this could be simplified)
self.mk_args_from_iter(
[self.types.self_param.into()].into_iter().chain(
self.generics_of(def_id)
.own_args(ty::GenericArgs::identity_for_item(self, def_id))
.iter()
.copied()
)
if cfg!(debug_assertions) && !self.check_args_compatible(def_id, args) {
if let DefKind::AssocTy = self.def_kind(def_id)
&& let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id))
{
bug!(
"args not compatible with generics for {}: args={:#?}, generics={:#?}",
self.def_path_str(def_id),
args,
// Make `[Self, GAT_ARGS...]` (this could be simplified)
self.mk_args_from_iter(
[self.types.self_param.into()].into_iter().chain(
self.generics_of(def_id)
.own_args(ty::GenericArgs::identity_for_item(self, def_id))
.iter()
.copied()
)
);
} else {
bug!(
"args not compatible with generics for {}: args={:#?}, generics={:#?}",
self.def_path_str(def_id),
args,
ty::GenericArgs::identity_for_item(self, def_id)
);
}
)
);
} else {
bug!(
"args not compatible with generics for {}: args={:#?}, generics={:#?}",
self.def_path_str(def_id),
args,
ty::GenericArgs::identity_for_item(self, def_id)
);
}
}
}
@ -3132,11 +3130,11 @@ impl<'tcx> TyCtxt<'tcx> {
}
pub fn next_trait_solver_globally(self) -> bool {
self.sess.opts.unstable_opts.next_solver.globally
self.sess.opts.unstable_opts.next_solver.map_or(false, |c| c.globally)
}
pub fn next_trait_solver_in_coherence(self) -> bool {
self.sess.opts.unstable_opts.next_solver.coherence
self.sess.opts.unstable_opts.next_solver.map_or(false, |c| c.coherence)
}
pub fn is_impl_trait_in_trait(self, def_id: DefId) -> bool {

View File

@ -1183,10 +1183,10 @@ pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: SpecAbi) ->
//
// This is not part of `codegen_fn_attrs` as it can differ between crates
// and therefore cannot be computed in core.
if tcx.sess.opts.unstable_opts.panic_in_drop == PanicStrategy::Abort {
if tcx.is_lang_item(did, LangItem::DropInPlace) {
return false;
}
if tcx.sess.opts.unstable_opts.panic_in_drop == PanicStrategy::Abort
&& tcx.is_lang_item(did, LangItem::DropInPlace)
{
return false;
}
}

View File

@ -1526,7 +1526,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
let precedence = |binop: rustc_middle::mir::BinOp| {
use rustc_ast::util::parser::AssocOp;
AssocOp::from_ast_binop(binop.to_hir_binop().into()).precedence()
AssocOp::from_ast_binop(binop.to_hir_binop()).precedence()
};
let op_precedence = precedence(op);
let formatted_op = op.to_hir_binop().as_str();
@ -3361,10 +3361,8 @@ pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
// name.
//
// Any stable ordering would be fine here though.
if *v.get() != symbol {
if v.get().as_str() > symbol.as_str() {
v.insert(symbol);
}
if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
v.insert(symbol);
}
}
Vacant(v) => {

View File

@ -41,7 +41,15 @@ impl RvalueScopes {
debug!("temporary_scope({expr_id:?}) = {id:?} [enclosing]");
return Some(id);
}
_ => id = p,
ScopeData::IfThenRescope => {
debug!("temporary_scope({expr_id:?}) = {p:?} [enclosing]");
return Some(p);
}
ScopeData::Node
| ScopeData::CallSite
| ScopeData::Arguments
| ScopeData::IfThen
| ScopeData::Remainder(_) => id = p,
}
}

View File

@ -268,10 +268,9 @@ impl Builder<'_, '_> {
pub(crate) fn mcdc_decrement_depth_if_enabled(&mut self) {
if let Some(coverage_info) = self.coverage_info.as_mut()
&& let Some(mcdc_info) = coverage_info.mcdc_info.as_mut()
&& mcdc_info.state.decision_ctx_stack.pop().is_none()
{
if mcdc_info.state.decision_ctx_stack.pop().is_none() {
bug!("Unexpected empty decision stack");
}
bug!("Unexpected empty decision stack");
};
}
}

View File

@ -1,7 +1,9 @@
//! See docs in build/expr/mod.rs
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir::HirId;
use rustc_middle::middle::region;
use rustc_middle::middle::region::{Scope, ScopeData};
use rustc_middle::mir::*;
use rustc_middle::thir::*;
use tracing::{debug, instrument};
@ -73,11 +75,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
_ if let Some(tail_info) = this.block_context.currently_in_block_tail() => {
LocalInfo::BlockTailTemp(tail_info)
}
_ if let Some(Scope { data: ScopeData::IfThenRescope, id }) = temp_lifetime => {
LocalInfo::IfThenRescopeTemp {
if_then: HirId { owner: this.hir_id.owner, local_id: id },
}
}
_ => LocalInfo::Boring,
};
**local_decl.local_info.as_mut().assert_crate_local() = local_info;
this.local_decls.push(local_decl)
};
debug!(?temp);
if deduplicate_temps {
this.fixed_temps.insert(expr_id, temp);
}

View File

@ -706,7 +706,13 @@ impl<'tcx> Cx<'tcx> {
hir::ExprKind::If(cond, then, else_opt) => ExprKind::If {
if_then_scope: region::Scope {
id: then.hir_id.local_id,
data: region::ScopeData::IfThen,
data: {
if expr.span.at_least_rust_2024() && tcx.features().if_let_rescope {
region::ScopeData::IfThenRescope
} else {
region::ScopeData::IfThen
}
},
},
cond: self.mirror_expr(cond),
then: self.mirror_expr(then),

View File

@ -42,14 +42,14 @@ pub trait Direction {
) where
A: GenKillAnalysis<'tcx>;
fn visit_results_in_block<'mir, 'tcx, F, R>(
state: &mut F,
fn visit_results_in_block<'mir, 'tcx, D, R>(
state: &mut D,
block: BasicBlock,
block_data: &'mir mir::BasicBlockData<'tcx>,
results: &mut R,
vis: &mut impl ResultsVisitor<'mir, 'tcx, R, FlowState = F>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, R, Domain = D>,
) where
R: ResultsVisitable<'tcx, FlowState = F>;
R: ResultsVisitable<'tcx, Domain = D>;
fn join_state_into_successors_of<'tcx, A>(
analysis: &mut A,
@ -186,14 +186,14 @@ impl Direction for Backward {
analysis.apply_statement_effect(state, statement, location);
}
fn visit_results_in_block<'mir, 'tcx, F, R>(
state: &mut F,
fn visit_results_in_block<'mir, 'tcx, D, R>(
state: &mut D,
block: BasicBlock,
block_data: &'mir mir::BasicBlockData<'tcx>,
results: &mut R,
vis: &mut impl ResultsVisitor<'mir, 'tcx, R, FlowState = F>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, R, Domain = D>,
) where
R: ResultsVisitable<'tcx, FlowState = F>,
R: ResultsVisitable<'tcx, Domain = D>,
{
results.reset_to_block_entry(state, block);
@ -444,9 +444,9 @@ impl Direction for Forward {
block: BasicBlock,
block_data: &'mir mir::BasicBlockData<'tcx>,
results: &mut R,
vis: &mut impl ResultsVisitor<'mir, 'tcx, R, FlowState = F>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, R, Domain = F>,
) where
R: ResultsVisitable<'tcx, FlowState = F>,
R: ResultsVisitable<'tcx, Domain = F>,
{
results.reset_to_block_entry(state, block);

View File

@ -57,7 +57,7 @@ where
&mut self,
body: &'mir mir::Body<'tcx>,
blocks: impl IntoIterator<Item = BasicBlock>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, Self, FlowState = A::Domain>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, Self, Domain = A::Domain>,
) {
visit_results(body, blocks, self, vis)
}
@ -65,7 +65,7 @@ where
pub fn visit_reachable_with<'mir>(
&mut self,
body: &'mir mir::Body<'tcx>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, Self, FlowState = A::Domain>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, Self, Domain = A::Domain>,
) {
let blocks = mir::traversal::reachable(body);
visit_results(body, blocks.map(|(bb, _)| bb), self, vis)

View File

@ -544,15 +544,15 @@ where
A: Analysis<'tcx>,
A::Domain: DebugWithContext<A>,
{
type FlowState = A::Domain;
type Domain = A::Domain;
fn visit_block_start(&mut self, state: &Self::FlowState) {
fn visit_block_start(&mut self, state: &Self::Domain) {
if A::Direction::IS_FORWARD {
self.prev_state.clone_from(state);
}
}
fn visit_block_end(&mut self, state: &Self::FlowState) {
fn visit_block_end(&mut self, state: &Self::Domain) {
if A::Direction::IS_BACKWARD {
self.prev_state.clone_from(state);
}
@ -561,7 +561,7 @@ where
fn visit_statement_before_primary_effect(
&mut self,
results: &mut Results<'tcx, A>,
state: &Self::FlowState,
state: &Self::Domain,
_statement: &mir::Statement<'tcx>,
_location: Location,
) {
@ -574,7 +574,7 @@ where
fn visit_statement_after_primary_effect(
&mut self,
results: &mut Results<'tcx, A>,
state: &Self::FlowState,
state: &Self::Domain,
_statement: &mir::Statement<'tcx>,
_location: Location,
) {
@ -585,7 +585,7 @@ where
fn visit_terminator_before_primary_effect(
&mut self,
results: &mut Results<'tcx, A>,
state: &Self::FlowState,
state: &Self::Domain,
_terminator: &mir::Terminator<'tcx>,
_location: Location,
) {
@ -598,7 +598,7 @@ where
fn visit_terminator_after_primary_effect(
&mut self,
results: &mut Results<'tcx, A>,
state: &Self::FlowState,
state: &Self::Domain,
_terminator: &mir::Terminator<'tcx>,
_location: Location,
) {

View File

@ -4,15 +4,15 @@ use super::{Analysis, Direction, Results};
/// Calls the corresponding method in `ResultsVisitor` for every location in a `mir::Body` with the
/// dataflow state at that location.
pub fn visit_results<'mir, 'tcx, F, R>(
pub fn visit_results<'mir, 'tcx, D, R>(
body: &'mir mir::Body<'tcx>,
blocks: impl IntoIterator<Item = BasicBlock>,
results: &mut R,
vis: &mut impl ResultsVisitor<'mir, 'tcx, R, FlowState = F>,
vis: &mut impl ResultsVisitor<'mir, 'tcx, R, Domain = D>,
) where
R: ResultsVisitable<'tcx, FlowState = F>,
R: ResultsVisitable<'tcx, Domain = D>,
{
let mut state = results.new_flow_state(body);
let mut state = results.bottom_value(body);
#[cfg(debug_assertions)]
let reachable_blocks = mir::traversal::reachable_as_bitset(body);
@ -29,16 +29,16 @@ pub fn visit_results<'mir, 'tcx, F, R>(
/// A visitor over the results of an `Analysis`. The type parameter `R` is the results type being
/// visited.
pub trait ResultsVisitor<'mir, 'tcx, R> {
type FlowState;
type Domain;
fn visit_block_start(&mut self, _state: &Self::FlowState) {}
fn visit_block_start(&mut self, _state: &Self::Domain) {}
/// Called with the `before_statement_effect` of the given statement applied to `state` but not
/// its `statement_effect`.
fn visit_statement_before_primary_effect(
&mut self,
_results: &mut R,
_state: &Self::FlowState,
_state: &Self::Domain,
_statement: &'mir mir::Statement<'tcx>,
_location: Location,
) {
@ -49,7 +49,7 @@ pub trait ResultsVisitor<'mir, 'tcx, R> {
fn visit_statement_after_primary_effect(
&mut self,
_results: &mut R,
_state: &Self::FlowState,
_state: &Self::Domain,
_statement: &'mir mir::Statement<'tcx>,
_location: Location,
) {
@ -60,7 +60,7 @@ pub trait ResultsVisitor<'mir, 'tcx, R> {
fn visit_terminator_before_primary_effect(
&mut self,
_results: &mut R,
_state: &Self::FlowState,
_state: &Self::Domain,
_terminator: &'mir mir::Terminator<'tcx>,
_location: Location,
) {
@ -73,13 +73,13 @@ pub trait ResultsVisitor<'mir, 'tcx, R> {
fn visit_terminator_after_primary_effect(
&mut self,
_results: &mut R,
_state: &Self::FlowState,
_state: &Self::Domain,
_terminator: &'mir mir::Terminator<'tcx>,
_location: Location,
) {
}
fn visit_block_end(&mut self, _state: &Self::FlowState) {}
fn visit_block_end(&mut self, _state: &Self::Domain) {}
}
/// Things that can be visited by a `ResultsVisitor`.
@ -88,40 +88,40 @@ pub trait ResultsVisitor<'mir, 'tcx, R> {
/// simultaneously.
pub trait ResultsVisitable<'tcx> {
type Direction: Direction;
type FlowState;
type Domain;
/// Creates an empty `FlowState` to hold the transient state for these dataflow results.
/// Creates an empty `Domain` to hold the transient state for these dataflow results.
///
/// The value of the newly created `FlowState` will be overwritten by `reset_to_block_entry`
/// The value of the newly created `Domain` will be overwritten by `reset_to_block_entry`
/// before it can be observed by a `ResultsVisitor`.
fn new_flow_state(&self, body: &mir::Body<'tcx>) -> Self::FlowState;
fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain;
fn reset_to_block_entry(&self, state: &mut Self::FlowState, block: BasicBlock);
fn reset_to_block_entry(&self, state: &mut Self::Domain, block: BasicBlock);
fn reconstruct_before_statement_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
statement: &mir::Statement<'tcx>,
location: Location,
);
fn reconstruct_statement_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
statement: &mir::Statement<'tcx>,
location: Location,
);
fn reconstruct_before_terminator_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
terminator: &mir::Terminator<'tcx>,
location: Location,
);
fn reconstruct_terminator_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
terminator: &mir::Terminator<'tcx>,
location: Location,
);
@ -131,21 +131,20 @@ impl<'tcx, A> ResultsVisitable<'tcx> for Results<'tcx, A>
where
A: Analysis<'tcx>,
{
type FlowState = A::Domain;
type Domain = A::Domain;
type Direction = A::Direction;
fn new_flow_state(&self, body: &mir::Body<'tcx>) -> Self::FlowState {
fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
self.analysis.bottom_value(body)
}
fn reset_to_block_entry(&self, state: &mut Self::FlowState, block: BasicBlock) {
fn reset_to_block_entry(&self, state: &mut Self::Domain, block: BasicBlock) {
state.clone_from(self.entry_set_for_block(block));
}
fn reconstruct_before_statement_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
stmt: &mir::Statement<'tcx>,
loc: Location,
) {
@ -154,7 +153,7 @@ where
fn reconstruct_statement_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
stmt: &mir::Statement<'tcx>,
loc: Location,
) {
@ -163,7 +162,7 @@ where
fn reconstruct_before_terminator_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
term: &mir::Terminator<'tcx>,
loc: Location,
) {
@ -172,7 +171,7 @@ where
fn reconstruct_terminator_effect(
&mut self,
state: &mut Self::FlowState,
state: &mut Self::Domain,
term: &mir::Terminator<'tcx>,
loc: Location,
) {

View File

@ -11,7 +11,7 @@ use crate::{AnalysisDomain, GenKill, GenKillAnalysis};
/// At present, this is used as a very limited form of alias analysis. For example,
/// `MaybeBorrowedLocals` is used to compute which locals are live during a yield expression for
/// immovable coroutines.
#[derive(Clone, Copy)]
#[derive(Clone)]
pub struct MaybeBorrowedLocals;
impl MaybeBorrowedLocals {

View File

@ -217,7 +217,6 @@ impl DefUse {
/// This is basically written for dead store elimination and nothing else.
///
/// All of the caveats of `MaybeLiveLocals` apply.
#[derive(Clone, Copy)]
pub struct MaybeTransitiveLiveLocals<'a> {
always_live: &'a BitSet<Local>,
}

View File

@ -7,7 +7,6 @@ use rustc_middle::mir::*;
use super::MaybeBorrowedLocals;
use crate::{GenKill, ResultsCursor};
#[derive(Clone)]
pub struct MaybeStorageLive<'a> {
always_live_locals: Cow<'a, BitSet<Local>>,
}
@ -80,7 +79,6 @@ impl<'tcx, 'a> crate::GenKillAnalysis<'tcx> for MaybeStorageLive<'a> {
}
}
#[derive(Clone)]
pub struct MaybeStorageDead<'a> {
always_live_locals: Cow<'a, BitSet<Local>>,
}

View File

@ -102,7 +102,7 @@ pub fn save_as_intervals<'tcx, N, R>(
) -> SparseIntervalMatrix<N, PointIndex>
where
N: Idx,
R: ResultsVisitable<'tcx, FlowState = BitSet<N>>,
R: ResultsVisitable<'tcx, Domain = BitSet<N>>,
{
let values = SparseIntervalMatrix::new(elements.num_points());
let mut visitor = Visitor { elements, values };
@ -124,12 +124,12 @@ impl<'mir, 'tcx, R, N> ResultsVisitor<'mir, 'tcx, R> for Visitor<'_, N>
where
N: Idx,
{
type FlowState = BitSet<N>;
type Domain = BitSet<N>;
fn visit_statement_after_primary_effect(
&mut self,
_results: &mut R,
state: &Self::FlowState,
state: &Self::Domain,
_statement: &'mir mir::Statement<'tcx>,
location: Location,
) {
@ -143,7 +143,7 @@ where
fn visit_terminator_after_primary_effect(
&mut self,
_results: &mut R,
state: &Self::FlowState,
state: &Self::Domain,
_terminator: &'mir mir::Terminator<'tcx>,
location: Location,
) {

View File

@ -229,7 +229,7 @@ trait RustcPeekAt<'tcx>: Analysis<'tcx> {
&self,
tcx: TyCtxt<'tcx>,
place: mir::Place<'tcx>,
flow_state: &Self::Domain,
state: &Self::Domain,
call: PeekCall,
);
}
@ -243,12 +243,12 @@ where
&self,
tcx: TyCtxt<'tcx>,
place: mir::Place<'tcx>,
flow_state: &Self::Domain,
state: &Self::Domain,
call: PeekCall,
) {
match self.move_data().rev_lookup.find(place.as_ref()) {
LookupResult::Exact(peek_mpi) => {
let bit_state = flow_state.contains(peek_mpi);
let bit_state = state.contains(peek_mpi);
debug!("rustc_peek({:?} = &{:?}) bit_state: {}", call.arg, place, bit_state);
if !bit_state {
tcx.dcx().emit_err(PeekBitNotSet { span: call.span });
@ -267,7 +267,7 @@ impl<'tcx> RustcPeekAt<'tcx> for MaybeLiveLocals {
&self,
tcx: TyCtxt<'tcx>,
place: mir::Place<'tcx>,
flow_state: &BitSet<Local>,
state: &BitSet<Local>,
call: PeekCall,
) {
info!(?place, "peek_at");
@ -276,7 +276,7 @@ impl<'tcx> RustcPeekAt<'tcx> for MaybeLiveLocals {
return;
};
if !flow_state.contains(local) {
if !state.contains(local) {
tcx.dcx().emit_err(PeekBitNotSet { span: call.span });
}
}

View File

@ -95,19 +95,19 @@ impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> {
// Check for assignment to fields of a constant
// Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
// so emitting a lint would be redundant.
if !lhs.projection.is_empty() {
if let Some(def_id) = self.is_const_item_without_destructor(lhs.local)
&& let Some((lint_root, span, item)) =
self.should_lint_const_item_usage(lhs, def_id, loc)
{
self.tcx.emit_node_span_lint(
CONST_ITEM_MUTATION,
lint_root,
span,
errors::ConstMutate::Modify { konst: item },
);
}
if !lhs.projection.is_empty()
&& let Some(def_id) = self.is_const_item_without_destructor(lhs.local)
&& let Some((lint_root, span, item)) =
self.should_lint_const_item_usage(lhs, def_id, loc)
{
self.tcx.emit_node_span_lint(
CONST_ITEM_MUTATION,
lint_root,
span,
errors::ConstMutate::Modify { konst: item },
);
}
// We are looking for MIR of the form:
//
// ```

View File

@ -885,12 +885,12 @@ struct StorageConflictVisitor<'a, 'tcx> {
impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
for StorageConflictVisitor<'a, 'tcx>
{
type FlowState = BitSet<Local>;
type Domain = BitSet<Local>;
fn visit_statement_before_primary_effect(
&mut self,
_results: &mut R,
state: &Self::FlowState,
state: &Self::Domain,
_statement: &'a Statement<'tcx>,
loc: Location,
) {
@ -900,7 +900,7 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
fn visit_terminator_before_primary_effect(
&mut self,
_results: &mut R,
state: &Self::FlowState,
state: &Self::Domain,
_terminator: &'a Terminator<'tcx>,
loc: Location,
) {
@ -909,13 +909,13 @@ impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
}
impl StorageConflictVisitor<'_, '_> {
fn apply_state(&mut self, flow_state: &BitSet<Local>, loc: Location) {
fn apply_state(&mut self, state: &BitSet<Local>, loc: Location) {
// Ignore unreachable blocks.
if let TerminatorKind::Unreachable = self.body.basic_blocks[loc.block].terminator().kind {
return;
}
self.eligible_storage_live.clone_from(flow_state);
self.eligible_storage_live.clone_from(state);
self.eligible_storage_live.intersect(&**self.saved_locals);
for local in self.eligible_storage_live.iter() {

View File

@ -155,12 +155,14 @@ impl CoverageCounters {
BcbCounter::Expression { id }
}
/// Variant of `make_expression` that makes `lhs` optional and assumes [`Op::Add`].
/// Creates a counter that is the sum of the given counters.
///
/// This is useful when using [`Iterator::fold`] to build an arbitrary-length sum.
fn make_sum_expression(&mut self, lhs: Option<BcbCounter>, rhs: BcbCounter) -> BcbCounter {
let Some(lhs) = lhs else { return rhs };
self.make_expression(lhs, Op::Add, rhs)
/// Returns `None` if the given list of counters was empty.
fn make_sum(&mut self, counters: &[BcbCounter]) -> Option<BcbCounter> {
counters
.iter()
.copied()
.reduce(|accum, counter| self.make_expression(accum, Op::Add, counter))
}
pub(super) fn num_counters(&self) -> usize {
@ -315,20 +317,17 @@ impl<'a> MakeBcbCounters<'a> {
// For each out-edge other than the one that was chosen to get an expression,
// ensure that it has a counter (existing counter/expression or a new counter),
// and accumulate the corresponding counters into a single sum expression.
let sum_of_all_other_out_edges: BcbCounter = {
let _span = debug_span!("sum_of_all_other_out_edges", ?expression_to_bcb).entered();
successors
.iter()
.copied()
// Skip the chosen edge, since we'll calculate its count from this sum.
.filter(|&to_bcb| to_bcb != expression_to_bcb)
.fold(None, |accum, to_bcb| {
let _span = debug_span!("to_bcb", ?accum, ?to_bcb).entered();
let edge_counter = self.get_or_make_edge_counter(from_bcb, to_bcb);
Some(self.coverage_counters.make_sum_expression(accum, edge_counter))
})
.expect("there must be at least one other out-edge")
};
let other_out_edge_counters = successors
.iter()
.copied()
// Skip the chosen edge, since we'll calculate its count from this sum.
.filter(|&to_bcb| to_bcb != expression_to_bcb)
.map(|to_bcb| self.get_or_make_edge_counter(from_bcb, to_bcb))
.collect::<Vec<_>>();
let sum_of_all_other_out_edges: BcbCounter = self
.coverage_counters
.make_sum(&other_out_edge_counters)
.expect("there must be at least one other out-edge");
// Now create an expression for the chosen edge, by taking the counter
// for its source node and subtracting the sum of its sibling out-edges.
@ -375,20 +374,15 @@ impl<'a> MakeBcbCounters<'a> {
// A BCB with multiple incoming edges can compute its count by ensuring that counters
// exist for each of those edges, and then adding them up to get a total count.
let sum_of_in_edges: BcbCounter = {
let _span = debug_span!("sum_of_in_edges", ?bcb).entered();
// We avoid calling `self.bcb_predecessors` here so that we can
// call methods on `&mut self` inside the fold.
self.basic_coverage_blocks.predecessors[bcb]
.iter()
.copied()
.fold(None, |accum, from_bcb| {
let _span = debug_span!("from_bcb", ?accum, ?from_bcb).entered();
let edge_counter = self.get_or_make_edge_counter(from_bcb, bcb);
Some(self.coverage_counters.make_sum_expression(accum, edge_counter))
})
.expect("there must be at least one in-edge")
};
let in_edge_counters = self.basic_coverage_blocks.predecessors[bcb]
.iter()
.copied()
.map(|from_bcb| self.get_or_make_edge_counter(from_bcb, bcb))
.collect::<Vec<_>>();
let sum_of_in_edges: BcbCounter = self
.coverage_counters
.make_sum(&in_edge_counters)
.expect("there must be at least one in-edge");
debug!("{bcb:?} gets a new counter (sum of predecessor counters): {sum_of_in_edges:?}");
self.coverage_counters.set_bcb_counter(bcb, sum_of_in_edges)

View File

@ -724,13 +724,13 @@ impl<'mir, 'tcx>
ResultsVisitor<'mir, 'tcx, Results<'tcx, ValueAnalysisWrapper<ConstAnalysis<'_, 'tcx>>>>
for Collector<'tcx, '_>
{
type FlowState = State<FlatSet<Scalar>>;
type Domain = State<FlatSet<Scalar>>;
#[instrument(level = "trace", skip(self, results, statement))]
fn visit_statement_before_primary_effect(
&mut self,
results: &mut Results<'tcx, ValueAnalysisWrapper<ConstAnalysis<'_, 'tcx>>>,
state: &Self::FlowState,
state: &Self::Domain,
statement: &'mir Statement<'tcx>,
location: Location,
) {
@ -752,7 +752,7 @@ impl<'mir, 'tcx>
fn visit_statement_after_primary_effect(
&mut self,
results: &mut Results<'tcx, ValueAnalysisWrapper<ConstAnalysis<'_, 'tcx>>>,
state: &Self::FlowState,
state: &Self::Domain,
statement: &'mir Statement<'tcx>,
location: Location,
) {
@ -777,7 +777,7 @@ impl<'mir, 'tcx>
fn visit_terminator_before_primary_effect(
&mut self,
results: &mut Results<'tcx, ValueAnalysisWrapper<ConstAnalysis<'_, 'tcx>>>,
state: &Self::FlowState,
state: &Self::Domain,
terminator: &'mir Terminator<'tcx>,
location: Location,
) {

View File

@ -168,17 +168,16 @@ pub(super) fn deduced_param_attrs<'tcx>(
// Codegen won't use this information for anything if all the function parameters are passed
// directly. Detect that and bail, for compilation speed.
let fn_ty = tcx.type_of(def_id).instantiate_identity();
if matches!(fn_ty.kind(), ty::FnDef(..)) {
if fn_ty
if matches!(fn_ty.kind(), ty::FnDef(..))
&& fn_ty
.fn_sig(tcx)
.inputs()
.skip_binder()
.iter()
.cloned()
.all(type_will_always_be_passed_directly)
{
return &[];
}
{
return &[];
}
// Don't deduce any attributes for functions that have no MIR.

View File

@ -378,19 +378,19 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
if let (Some(l), Some(r)) = (l, r)
&& l.layout.ty.is_integral()
&& op.is_overflowing()
{
if self.use_ecx(|this| {
&& self.use_ecx(|this| {
let (_res, overflow) = this.ecx.binary_op(op, &l, &r)?.to_scalar_pair();
overflow.to_bool()
})? {
self.report_assert_as_lint(
location,
AssertLintKind::ArithmeticOverflow,
AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
);
return None;
}
})?
{
self.report_assert_as_lint(
location,
AssertLintKind::ArithmeticOverflow,
AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
);
return None;
}
Some(())
}

View File

@ -42,7 +42,7 @@ fn to_profiler_name(type_name: &'static str) -> &'static str {
// const wrapper for `if let Some((_, tail)) = name.rsplit_once(':') { tail } else { name }`
const fn c_name(name: &'static str) -> &'static str {
// FIXME Simplify the implementation once more `str` methods get const-stable.
// FIXME(const-hack) Simplify the implementation once more `str` methods get const-stable.
// and inline into call site
let bytes = name.as_bytes();
let mut i = bytes.len();
@ -61,7 +61,7 @@ const fn c_name(name: &'static str) -> &'static str {
/// loop that goes over each available MIR and applies `run_pass`.
pub(super) trait MirPass<'tcx> {
fn name(&self) -> &'static str {
// FIXME Simplify the implementation once more `str` methods get const-stable.
// FIXME(const-hack) Simplify the implementation once more `str` methods get const-stable.
// See copypaste in `MirLint`
const {
let name = std::any::type_name::<Self>();
@ -89,7 +89,7 @@ pub(super) trait MirPass<'tcx> {
/// disabled (via the `Lint` adapter).
pub(super) trait MirLint<'tcx> {
fn name(&self) -> &'static str {
// FIXME Simplify the implementation once more `str` methods get const-stable.
// FIXME(const-hack) Simplify the implementation once more `str` methods get const-stable.
// See copypaste in `MirPass`
const {
let name = std::any::type_name::<Self>();

View File

@ -504,10 +504,8 @@ fn compute_inlined_overlap<'tcx>(cgu1: &CodegenUnit<'tcx>, cgu2: &CodegenUnit<'t
let mut overlap = 0;
for (item, data) in src_cgu.items().iter() {
if data.inlined {
if dst_cgu.items().contains_key(item) {
overlap += data.size_estimate;
}
if data.inlined && dst_cgu.items().contains_key(item) {
overlap += data.size_estimate;
}
}
overlap

View File

@ -185,10 +185,8 @@ impl<'a, D: SolverDelegate<Interner = I>, I: Interner> Canonicalizer<'a, D, I> {
for var in var_infos.iter_mut() {
// We simply put all regions from the input into the highest
// compressed universe, so we only deal with them at the end.
if !var.is_region() {
if is_existential == var.is_existential() {
update_uv(var, orig_uv, is_existential)
}
if !var.is_region() && is_existential == var.is_existential() {
update_uv(var, orig_uv, is_existential)
}
}
}

View File

@ -122,6 +122,21 @@ where
(certainty, NestedNormalizationGoals::empty())
};
if let Certainty::Maybe(cause @ MaybeCause::Overflow { .. }) = certainty {
// If we have overflow, it's probable that we're substituting a type
// into itself infinitely and any partial substitutions in the query
// response are probably not useful anyways, so just return an empty
// query response.
//
// This may prevent us from potentially useful inference, e.g.
// 2 candidates, one ambiguous and one overflow, which both
// have the same inference constraints.
//
// Changing this to retain some constraints in the future
// won't be a breaking change, so this is good enough for now.
return Ok(self.make_ambiguous_response_no_constraints(cause));
}
let external_constraints =
self.compute_external_query_constraints(certainty, normalization_nested_goals);
let (var_values, mut external_constraints) = (self.var_values, external_constraints)

View File

@ -17,7 +17,7 @@ use crate::delegate::SolverDelegate;
use crate::solve::inspect::{self, ProofTreeBuilder};
use crate::solve::search_graph::SearchGraph;
use crate::solve::{
CanonicalInput, CanonicalResponse, Certainty, Goal, GoalEvaluationKind, GoalSource, MaybeCause,
CanonicalInput, CanonicalResponse, Certainty, Goal, GoalEvaluationKind, GoalSource,
NestedNormalizationGoals, NoSolution, PredefinedOpaquesData, QueryResult, SolverMode,
FIXPOINT_STEP_LIMIT,
};
@ -370,7 +370,7 @@ where
canonical_goal,
&mut goal_evaluation,
);
let canonical_response = match canonical_response {
let response = match canonical_response {
Err(e) => {
self.inspect.goal_evaluation(goal_evaluation);
return Err(e);
@ -378,12 +378,11 @@ where
Ok(response) => response,
};
let (normalization_nested_goals, certainty, has_changed) = self
.instantiate_response_discarding_overflow(
goal.param_env,
orig_values,
canonical_response,
);
let has_changed = !response.value.var_values.is_identity_modulo_regions()
|| !response.value.external_constraints.opaque_types.is_empty();
let (normalization_nested_goals, certainty) =
self.instantiate_and_apply_query_response(goal.param_env, orig_values, response);
self.inspect.goal_evaluation(goal_evaluation);
// FIXME: We previously had an assert here that checked that recomputing
// a goal after applying its constraints did not change its response.
@ -398,24 +397,6 @@ where
Ok((normalization_nested_goals, has_changed, certainty))
}
fn instantiate_response_discarding_overflow(
&mut self,
param_env: I::ParamEnv,
original_values: Vec<I::GenericArg>,
response: CanonicalResponse<I>,
) -> (NestedNormalizationGoals<I>, Certainty, bool) {
if let Certainty::Maybe(MaybeCause::Overflow { .. }) = response.value.certainty {
return (NestedNormalizationGoals::empty(), response.value.certainty, false);
}
let has_changed = !response.value.var_values.is_identity_modulo_regions()
|| !response.value.external_constraints.opaque_types.is_empty();
let (normalization_nested_goals, certainty) =
self.instantiate_and_apply_query_response(param_env, original_values, response);
(normalization_nested_goals, certainty, has_changed)
}
fn compute_goal(&mut self, goal: Goal<I, I::Predicate>) -> QueryResult<I> {
let Goal { param_env, predicate } = goal;
let kind = predicate.kind();

Some files were not shown because too many files have changed in this diff Show More