Question: Ok(()) } <del> fn is_legal_fragment_specifier(sess: &ParseSess, features: &Features, attrs: &[ast::Attribute], </del> <ins> fn is_legal_fragment_specifier(_sess: &ParseSess, _features: &Features, _attrs: &[ast::Attribute], </ins> frag_name: &str, <del> frag_span: Span) -> bool { </del> <ins> _frag_span: Span) -> bool { /* * If new fragment specifiers are invented in nightly, `_sess`, * `_features`, `_attrs`, and `_frag_span` will be useful here * for checking against feature gates. See past versions of * this function. */ </ins> match frag_name { "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" | <del> "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "" => true, "literal" => { if !features.macro_literal_matcher && !attr::contains_name(attrs, "allow_internal_unstable") { let explain = feature_gate::EXPLAIN_LITERAL_MATCHER; emit_feature_err(sess, "macro_literal_matcher", frag_span, GateIssue::Language, explain); } true }, </del> <ins> "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "literal" | "" => true, </ins> _ => false, } }

I dunno, maybe this is not such a good idea after all. Re-reading the RFC in a more skeptical light, I felt like the "Motivation" section could use some more concrete use cases. Maybe this is just failure of imagination on my part, though! I think the likelihood of this feature attracting people who really want constant expressions should be acknowledged as a drawback, too.
That's fine IMO. Personally I'd like it to match only explicit literals in code to distinguish, for example, between literal and identifier and produce different code for them. Right now this is not possible because all of , , are too broad and conflict with each other.
Hi All, I have implemented this feature in my fork of Rust over 1.25.0, under this branch: Following a quick review by a rustc mentor I may have the free time to provide a full pull request for this.
BTW label has the tooltip "implemented in nightly and unstable" but I did not see it there, i.e. commits & pull requests referencing this. Did I miss it?
The implementation that I worked on was merged, yay!
Is there anything stopping an FCP for this?
It's currently merged in unstable; do you mean an FCP to declare it stable?
Yes, an FCP to stabilise. Should have clarified.
Currently, it is not possible to pass a literal from a macro to another macro. . I think this is a bug.
Interesting! That is a bug. I opened to track it.
Agreed, this should be allowed just like passing any other node types.
Is there anything else preventing this from being stabilized? The issue above has been fixed.
This has baked for some time now and I believe it should be ready for stabilization. So let's start the review. merge The feature gate test is here: Unstable book: Tests defined here:
Team member has proposed to merge this. The next step is review by the rest of the tagged teams: [x] [x] [x] [x] [x] [ ] [x] [x] [x] [ ] No concerns currently listed. Once a majority of reviewers approve (and none object), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!


Question: Ok(()) } <del> fn is_legal_fragment_specifier(sess: &ParseSess, features: &Features, attrs: &[ast::Attribute], </del> <ins> fn is_legal_fragment_specifier(_sess: &ParseSess, _features: &Features, _attrs: &[ast::Attribute], </ins> frag_name: &str, <del> frag_span: Span) -> bool { </del> <ins> _frag_span: Span) -> bool { /* * If new fragment specifiers are invented in nightly, `_sess`, * `_features`, `_attrs`, and `_frag_span` will be useful here * for checking against feature gates. See past versions of * this function. */ </ins> match frag_name { "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" | <del> "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "" => true, "literal" => { if !features.macro_literal_matcher && !attr::contains_name(attrs, "allow_internal_unstable") { let explain = feature_gate::EXPLAIN_LITERAL_MATCHER; emit_feature_err(sess, "macro_literal_matcher", frag_span, GateIssue::Language, explain); } true }, </del> <ins> "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "literal" | "" => true, </ins> _ => false, } }

See for info about what commands tagged team members can give me.
Reading through the tests, I see that is a literal. While that makes sense to me, I remember hearing that it wasn't, but was instead a negation operator and a literal. Am I misremembering?
cc on
I agree that it makes sense. I would say that even if is interpreted as negation + a literal, I would probably still want the macro matcher to accept since that behavior seems more intuitive. In other words, I would see being more as an implementation detail than what a literal is in the mental model.
I think that the nuance with causes a bit of a problem, because I don't think it should be treated as a literal, but I also don't think that the current implementation of would allow detecting it either. You could naïvely allow but that would allow which is clearly wrong.
there are tests currently implemented that verify that is detected as a literal.
I worded that wrong; I meant that only having a matcher and not being able to distinguish strings and numbers means that you can't easily make not a literal.
for procedural macros the input as lexed by the compiler is (two tokens) but procedural macros can create tokens that are negatives (like ). In that sense matching for makes sense to me.
Are literals generated by the compiler counted as true literals? A quick example would be something like: This fails to match, as the expansion, I guess, happens after the selection. I just naively assumed that would have worked.
is not a literal generated by the compiler, it is an identifier followed by an exclamation mark followed by a set of parentheses containing some tokens. See for example: If you were to use it in expression position, it would be interpreted as an invocation of which expands to a string literal. In this case and in your macro though, it is never in a syntactic position where it would be treated as an expression.
I can understand semantically why it doesn't make sense, I just thought it would have, but that being said, I already changed it to , so there's no issue. It just made more sense to me as a literal, because according to the compiler, it could generate a literal from it. I guess it was more a question than an actual issue.
This is true, but there's more to it!


Question: Ok(()) } <del> fn is_legal_fragment_specifier(sess: &ParseSess, features: &Features, attrs: &[ast::Attribute], </del> <ins> fn is_legal_fragment_specifier(_sess: &ParseSess, _features: &Features, _attrs: &[ast::Attribute], </ins> frag_name: &str, <del> frag_span: Span) -> bool { </del> <ins> _frag_span: Span) -> bool { /* * If new fragment specifiers are invented in nightly, `_sess`, * `_features`, `_attrs`, and `_frag_span` will be useful here * for checking against feature gates. See past versions of * this function. */ </ins> match frag_name { "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" | <del> "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "" => true, "literal" => { if !features.macro_literal_matcher && !attr::contains_name(attrs, "allow_internal_unstable") { let explain = feature_gate::EXPLAIN_LITERAL_MATCHER; emit_feature_err(sess, "macro_literal_matcher", frag_span, GateIssue::Language, explain); } true }, </del> <ins> "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "literal" | "" => true, </ins> _ => false, } }

A few built-in macros can expand their arguments eagerly through ~m a g i c~, so they accept and likes even if they expect string literals: Fortunately (or not), this currently cannot be done in user-defined macros.
I actually just realised that I can't change it to , as it's used in . So, I've just had to manually unroll the macro. ! It doesn't look pretty. :( Ninja edit: I just tested what actually happens if you try to pass in a non-literal with . It rejects it the exact same way. Does the already make use of this feature? If not, the seems to propagate the required token. Oh, unless the compiler steps in... That's actually probably the case... I've reverted it back to the type.
:bell: This is now entering its final comment period, as per the . :bell:
The final comment period, with a disposition to merge, as per the , is now complete.
Since you implemented this, would you be willing to write up the stabilization PR?
sure
This appears to be missing from the Rust reference


Question: rustc_data_structures = { path = "../librustc_data_structures" } rustc_hir = { path = "../librustc_hir" } rustc_hir_pretty = { path = "../librustc_hir_pretty" } <del> rustc_parse = { path = "../librustc_parse" } </del> <ins> rustc_lexer = { path = "../librustc_lexer" } </ins> serde_json = "1" rustc_session = { path = "../librustc_session" } rustc_span = { path = "../librustc_span" }

contains a function, which allows to to, well, retokenize existing span: There's only caller of this function: And there's only one caller of that caller: In other words, the only reason why we need is to get the span of hir::Usewhich happens to be a glob import. ( rls needs to know the span of use foo:: with explicit list of imported items" code action. This was the first demoed code action and is still that is implemented ) I'd like to remove the function, as it is one of the few remaining things that requires to be public, and as it is very much a hack anyway. Additionally, I believe I've broken this function accidently a while ago: Rather than retokenizing a span, it retokenized file from the begining until the end of the span (whcih, as uses are usually on top, worked correctly most of the times by accident). What would be the best way to fix this? Add hir::Use-- this seem to be the "proper" solution here Move hack's implementation to where it belongs: in , just fetch the text of the file and look for ('') Remove the deglog functionlity from RLS? I don't like this option as it handicaps the RLS before we formally decided to deprecated it. But I don't completely disregard it either, as, as a whole, it seems to be a full-stack one off hack penetrating every layer of abstraction. WDYT?
I'd suggest the second alternative (move hack's implementation to in librutcsaveanalysis), save analysis is a home of many hacks already and one more until save analysis is deprecated in its entirety won't hurt. Adding span for would be ok if it were useful for anything else at least.


Question: <del> Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 </del> <ins> Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f </ins>

The AVR-Rust post continues to track AVR-LLVM, which is tracking upstream LLVM. That means we are running into changes from the future LLVM 4.0. I figured we could open up this issue now to track the changes required to stay compatible. This is the current list of upgrade hazards. Note that some of the text may be nonsensical as I don't truly grok all the internals of LLVM so some changes are wild stabs in the dark. It's also possible that some failed fix for earlier problems actually caused later problems: [x] DIDescriptorFlags became a real C++ enum and not a bitset () [x] An EH personality is required for every function that can unwind () [x] pass changed header and constructor name () [x] changed API () [x] Bitcode/ReaderWriter.h has been renamed / API changed () () [x] changed API () [x] changed API () [x] prefers over () [x] string type changes () [x] is not guaranteed to be null terminated () [x] changed return types () [x] Archive support changed error handling types () [x] Teach Rust about an LLVM 4.0 API change for creating debug info for global variables () [x] Check all errors in LLVMRustArchiveIterator API () [x] Upgrade emscripten (kripken/emscripten-fastcomp, kripken/emscripten-fastcomp-clang) [x] Alignment now represented with 32 bits instead of 64 () [x] API changed again () [x] now takes an instead of a and () [x] Symbol lookup error when linking dylibs () [x] Undefined behavior in tests () [x] Unoptimised builds of compilerbuiltins on ARM have references to () A WIP PR that performs the upgrade! Some issues whose resolution is believed to be blocked on LLVM 4.0: [ ]
Next time we do this upgrade we'll need emscripten to do it to. It would be good if we could pull in a working llvm wasm backend in the same upgrade, but that may not be ready before the end of the year.
For the record, I am also working with a fork of LLVM that is tracking upstream (not AVR-LLVM but similar in spirit) and am starting to work on this now.


Question: <del> Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 </del> <ins> Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f </ins>

I'm looking through the AVR-Rust commits and I'd love to coordinate --- feel free to ping me on IRC () or via mail!
Note that there is a regression reported against llvm 4.0 regarding the powi intrinsic on armhf targets: I'm explicitly mentioning this here, because there were previously problems with it, see and related issues. Also cc rust-lang-nursery/compiler-builtins, an issue about the same problem in the compiler-rt rust port.
To clarify what I think the is referring to (correct me if I'm wrong) In LLVM 3.9 and before, the calling convention LLVM used with the powidf2 and powisf2 intrinsics was basically the C calling convention In LLVM 4.0, the backend was corrected to expect these intrinsics to have the aapcs calling convention One person that aapcs is expected for powis2f and powid2f, while another a claiming that the normal C calling convention should be used. So it seems that if the LLVM change is not reverted (expected powisf2 to be aapcs) then we need to update our definition. This is going to be a huge PITA for supporting multiple LLVM versions as well. We need to select the calling convention depending on the LLVM version as well...
Any objections to doing that coordination here on GitHub, or on one of our forks?
I don't have strong preferences for the communication channel.
should address what is listed as API changes" above (the core of the change is in how attributes are represented).
I would prefer to upstream LLVM 4.0 compatibility patches sooner rather than later. That includes my own work obviously, but I'm also looking at the commits I cherry-picked from AVR-Rust. In particular, looks like a reasonable simplification even independent of LLVM 4.0 compatibility, and looks like a nice little self-contained fix. Could you create PRs for those? (If you don't have the time but are otherwise fine with upstreaming, I'd be happy to manage that, giving proper credit of course.)
Absolutely! I wasn't really sure how much we could expect LLVM 4 to change as it goes towards stable / how much churn the Rust maintainers would want to put up with. I'll get those pulled out and submitted soon. I think I'm also starting to understand some of the silly error handling that the new LLVM does.


Question: <del> Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 </del> <ins> Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f </ins>

Awesome, thanks in advance!
BTW the PR reference for "llvm::AttrBuilder changed API" is wrong, it points at this issue instead of
Does anyone have ETA? I'd like to know when I can use AVR. :)
You should follow along at avr-rust/rust for the AVR-specific issues. Upgrading to LLVM 4 will not magically yield AVR support.
Ok, thank you!
I've created for the API change.
I've also created for another debug info API change.
After putting all of those patches on top of master, was successfully built. I got several undefined references, most likely due to my local LLVM setup.
I think the next step after all those patches land is to allow LLVM 4.0 in the configure/rustbuild scripts and then actually update the submodule.
We'll also need to fix that AAPCS bug first, I just noticed it
Don't forget : I think that means that the Rust fork of LLVM is following the Emscripten fork of LLVM, thus Emscripten needs to upgrade to LLVM 4.0 / master before Rust can.
And I'm hoping to supersede it with
I just ran into which changed the alignment from u64 to u32. Will think about a proper fix later, unless someone beats me to it (but should merge first to avoid further conflicts).
And it says So, that will be "exciting".
Is there much left blocking an upgrade?
This: Has to be done too but I don't know if it's currently being worked on. Any info on that ^?
No nobody is actively working on an emscripten upgrade. Since even when that is done it will probably take a lot of work to land an LLVM upgrade, there's probably more we can do to prepare. Once we decide we want to do it, somebody can prepare a patch to throw at the bots. It seems likely stuff will not work and it will be a slog to fix it all, which will give us time. We don't need emcc to generate wasm stds, just a fairly small patch on our LLVM branch that will hopefully port without much difficulty. So if somebody feels motivated, it's not too soon to start going after it. As to the emscripten upgrade, we should at least let know that we're starting to think seriously about doing the upgrade, and need emscripten to upgrade LLVM too.


Question: <del> Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 </del> <ins> Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f </ins>

It seems like that could be a big effort. Another alternative is to use the LLVM wasm backend, but I still have not heard that it is generally usable yet. cc
I can look into the effort needed to update emscripten's fastcomp LLVM version, but I need to know a commit to aim for. Sounds like the goal here is 4.0, which hasn't released yet, so I guess I have to wait on that?
So far as AVR is concerned, any commit within the last month will do. There will likely be a few more months until 4.0 is actually tagged (every ~6 months a new release is made). It is quite common for projects to track LLVM master, which I'm personally a fan of.
But is it common to release snapshots from LLVM master? When LLVM itself only releases every 6 months, it seems incongruous for Rust to pick arbitrary snapshots in its 6-week release cycle.
LLVM 4.0 will branch in a week and the final release will happen in late feburary (schedule says 21st for final tag, but this is flexible IIRC).
From the llvm-dev mailing list:
branch has happened
An update on the "powidf2 / powisf2 calling convention changed" situation: The regression has been fixed on llvm master () however from what I can tell the fixes are not yet in the 4.0 branch, although the fix may be backported ().
I've started working on updating emscripten kripken/emscripten-fastcomp kripken/emscripten-fastcomp-clang I've also created a new bug requesting that the regression fix be merged into 4.0 .
says the emcc LLVM upgrade is ready to go. or are we prepared to begin the Rust LLVM upgrade? I think what needs to happen is to submit the Rust PR and start throwing it against the bots. Once it looks like that is close to landing then we'll have to coordinate both project's upgrades to minimize the breakage window where rustc and emcc have different backends. I'm not sure how best to do that - we might just try to upgrade as simultaneously as possible and accept up to a few days of breakage, or we might ask emscripten to stage their build such that they can swap their incoming branch right after we land to master.


Question: <del> Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 </del> <ins> Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f </ins>

needs to know the exact LLVM commit we're moving to as well, and that will become clear once the PR starts working through the queue. The stars are aligning. Let's make this happen. Thanks for doing the fastcomp upgrade.
We are not fully compatible with LLVM 4.0. I have heard from at least one person (on IRC) that building against stock LLVM 4.0 (RC) does not work. I haven't personally inspected all failures, but there's at least two things still missing: (and possibly ). It shouldn't be a conceptually difficult patch to apply the equivalent changes to rustc, but possibly a big diff. I haven't digested the implications yet, but it might be a relatively simple change localized to the function in that currently calls .
The fix has been merged into the 4.0 release (). I'm going to try and build Rust against stock LLVM 4.0 and figure out what needs modifying.
On top of what mentioned: now takes an instead of a and ()
I've got a half-baked patch to use the new signature for I'm not familiar enough with Rust internals to finish it off. I ran into a problem in as it is given a but in order to use we need a . We need to call in order to build an instance of .
I've opened for the change that mentioned. I've also opened for the 32-bit alignment change. I believe that is the only thing we need to update aside from these two PRs in order to get the compiler to successfully be built with LLVM 4.0.
So to summarize where we are with LLVM 4 (correct me if I'm wrong): 4.0 will be released in about 1 week (2/21). are no known issues with supporting LLVM 4.0, but there are probably issues that will be discovered once we try to use it in nightlies. runs on in-tree LLVM + LLVM 3.7 (so PRs haven't actually been tested on LLVM 4.0 yet). support LLVM back to ~3.6(?


Question: <del> Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 </del> <ins> Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f </ins>

)~ 3.7 and will continue to support it until either: a. It's so old that it can be removed without bothering package maintainers b. We need at least version X in order to fix an important bug c. The API is so different from version Y that it's a huge pain to support will open a PR to update the submodule shortly after release but it will take a month to land due to: a. Waiting for emscripten ( -) b. Bugs in upstream c. Missed LLVM API changes d. Making bors happy e. All of the above
Thanks for the summary The only correction I'd make is that in your point (4) you can s/3.6/3.7/, but otherwise it's accurate :) If you'd like to start preparing a PR to update to LLVM 4.0 I don't think we need to block waiting for LLVM itself to release 4.0. Currently only one Travis builder runs on each PR but we could temporarily allow more builders running on an LLVM 4.0 PR to start weeding out bugs before it hits
I gave it a go but I don't think my git-fu (or patience) is strong enough to handle a big merge like this. What I can do is try to run rustc with upstream LLVM and file/fix issues as I find them. There is at least one issue remaining as of (details to come).
Whoever ends up doing the LLVM upgrade, please also upgrade the compiler-rt submodule so that the sanitizer related LLVM passes don't diverge from what the sanitizer runtimes expect.
In fact, if you upgrade before the release, they usually mention your project in the release notes. :)
So whats the next issue(s) to subscribe to in the race-to-AVR? :)
As says on , we can integrate the latest Rust master into the avr-rust compiler. After that, we can spend some time getting compiling for AVR. Once that is working, we could then start looking into upstreaming the AVR target to Rust.
AVR-specific issues can be raised / tracked in For example, there are two that I'm aware of right now:
has been closed, so that can be checked off in the top post.


Question: h3.impl, h3.method, h3.type { margin-top: 15px; } <del> h1, h2, h3, h4, .sidebar, a.source, .search-input, .content table :not(code)>a, .collapse-toggle { </del> <ins> h1, h2, h3, h4, .sidebar, a.source, .search-input, .content table :not(code)>a, .collapse-toggle, ul.item-list > li > .out-of-band { </ins> font-family: "Fira Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; }

It should work a bit like IDE's feature that finds everything that implements a given interface.
This should be a fairly small change (the most annoying part has already been done) so i'll open this up as a mentored issue. The bit that writes out the "Implementors" section is in . This is where the known implementors for a given trait are pulled out of the global context and listed out onto the rendered page. The bit that's responsible for creating links is , implemented on a local type. This kind of Item is easily made from the kind of Item that's otherwise worked on in , but there's a catch: The entries in the Implementors list aren't s. They're s, which are only a subset of the things you get on an Item. This is the "most annoying part" i mentioned earlier. Fortunately, i ran into this when creating the "Implementations on Foreign Types" section, so if you scroll up a little in , you can see so i could render the full impl block for them. The task for anyone who wants to take this on is to pull that up a little so that it's used for all the implementors, not just the foreign ones. With a in hand, combine it with the Context to create a and call to generate the link. ( This also helpfully includes the extra HTML bits that will flush the link to the right edge, which is really the final step.) And... that's it! The link should probably go between the and the where clause underneath it, so that it's aligned with the impl line and not the where clause. You may need to also close/open the that's wrapping the whole line to make sure the link itself isn't monospace. If you have any questions, let me know! Either comment here, or hop onto IRC in , or the impl period Gitter under .


Question: format!("{}-apple-macosx{}.{}.0", arch, major, minor) } <del> pub fn macos_link_env(arch: &str) -> Vec<(String, String)> { // Use the default deployment target for linking just as with the LLVM target if not // specified via MACOSX_DEPLOYMENT_TARGET, otherwise the system linker would use its // default which varies with Xcode version. if env::var("MACOSX_DEPLOYMENT_TARGET").is_err() { let default = macos_default_deployment_target(arch); vec![("MACOSX_DEPLOYMENT_TARGET".to_string(), format!("{}.{}", default.0, default.1))] } else { vec![] } } </del> pub fn macos_link_env_remove() -> Vec<String> { let mut env_remove = Vec::with_capacity(2); // Remove the `SDKROOT` environment variable if it's clearly set for the wrong platform, which

<!-- Thank you for filing a bug report! Please provide a short summary of the bug, along with any information you feel relevant to replicating the bug. --This used to work on Rust : is present in the framework (on macOS +10.13; on lower versions, in the framework). The framework uses internally, so the symbol is available through that (I think). Linking like this worked previously, but since Rust it started failing. This is . <!-- If you're using the stable version of the compiler, you should also check if the bug also exists in the beta or nightly versions. --OS: macOS Mojave 10.14.6. : <!-- Include a backtrace in the code block by setting in your environment. E.g. . --<details<summaryBacktrace</summary<p</p</details<!-- TRIAGEBOTSTART --<!-- TRIAGEBOTASSIGNSTART --<!-- TRIAGEBOTASSIGNDATASTARTTRIAGEBOTASSIGNDATAEND --<!-- TRIAGEBOTASSIGNEND --<!-- TRIAGEBOTEND --
Sorry if the issue is not very well explained, I'm very inexperienced with how linking works
This is affecting  as well from what I can tell.
This appears to have regressed via , cc As a temporary workaround, you can try setting the environment variable to something like .
With Rust sets to 10.7 for the linker, if not set, to match what we are passing to LLVM. Setting it to 10.8 or above get rids of the linker failure. I will look into this more.
Can you elaborate on that? Building it locally with worked fine for me on an M1.
I can confirm that using gets rid of the linker failure in . For , is required. You need to build a binary, so that the linker is actually invoked. Try building an example (e.g. ).
I can clarify this a little more: If you were building a Rust program for an Apple platform that linked to APIs with availability somewhere between 10.7+ and 12.0+, and you weren't setting your own deployment target, has revealed a bug in your build process. Your binaries were only ever going to run on recent OS releases, but you would have been unaware without testing.


Question: format!("{}-apple-macosx{}.{}.0", arch, major, minor) } <del> pub fn macos_link_env(arch: &str) -> Vec<(String, String)> { // Use the default deployment target for linking just as with the LLVM target if not // specified via MACOSX_DEPLOYMENT_TARGET, otherwise the system linker would use its // default which varies with Xcode version. if env::var("MACOSX_DEPLOYMENT_TARGET").is_err() { let default = macos_default_deployment_target(arch); vec![("MACOSX_DEPLOYMENT_TARGET".to_string(), format!("{}.{}", default.0, default.1))] } else { vec![] } } </del> pub fn macos_link_env_remove() -> Vec<String> { let mut env_remove = Vec::with_capacity(2); // Remove the `SDKROOT` environment variable if it's clearly set for the wrong platform, which

For coreaudio, if it really requires APIs from 11.0+, that seems a bit recent/limiting for a library that's existed since forever on macOS. If the authors were unaware of this, has revealed that they need to do more work to attain backwards compatibility. There will be more breakage like it, but it is the good kind, because anyone using newer Apple APIs should be aware of their minimum platform requirement, just as Xcode forces you to be.
Hmm, this change had more impact than I thought. to determine which minimum Macos version to pass as part of the target triple to LLVM and to ld via by looking at the various command line options and environment variables that have accumulated over the years. If nothing is specified, it apparently defaults to the minimum of the specified in the SDKROOTs and the host Macos version . I think ideally we should probably try to mimic this behavior somewhat so we don't confront users with having to set , while they don't have to do it using clang. Not sure how we can easily accomplish this though.
Actually, that makes a lot of sense, thanks! I fully agree that it's better to catch these issues when developing (instead of later, when users complain that the application doesn't work on their older system)! I've opened to fix the linking in , and would fix the linking in .
Note that this is a breaking change for macOS users, before, they didn't have to specify , now they do. Furthermore, they have no easy way to find out that they need to (they just get a confusing linker error)! Additionally, the affected crates (that we know about) are quite widely used (at least half of all Rust games depend on and/or ), and have not yet fixed the issue, nor yet released updated versions which includes these fixes. And even when this has been done, it will take time before users have run and received working versions (can probably be helped along by yanking the affected versions). I don't really know the procedure for this, but I would like to propose reverting (at least from the current beta) to give the affected crates more time to update. Again, I really do agree with the change, I just also want to minimize the breakage macOS users will experience from upgrading Rust.


Question: format!("{}-apple-macosx{}.{}.0", arch, major, minor) } <del> pub fn macos_link_env(arch: &str) -> Vec<(String, String)> { // Use the default deployment target for linking just as with the LLVM target if not // specified via MACOSX_DEPLOYMENT_TARGET, otherwise the system linker would use its // default which varies with Xcode version. if env::var("MACOSX_DEPLOYMENT_TARGET").is_err() { let default = macos_default_deployment_target(arch); vec![("MACOSX_DEPLOYMENT_TARGET".to_string(), format!("{}.{}", default.0, default.1))] } else { vec![] } } </del> pub fn macos_link_env_remove() -> Vec<String> { let mut env_remove = Vec::with_capacity(2); // Remove the `SDKROOT` environment variable if it's clearly set for the wrong platform, which

Like I wrote I think ideally we should match clang's behavior and thus fall back to the default of the currently configured Macos SDK. That would mean looking at the property of the in the currently configured SDK. Unfortunately I don't really see a reliable way to do get the path to that without running .
I think we should revert the change until you find a way to do this - it seems to be causing a lot of breakage and my understanding is the goal was just to turn a runtime error into a link time error.
Oh sure. I am not against a revert until that is sorted out. I will open a PR. claim
reopening as this is a beta-regression, and we keep those open until beta fix lands (or we explicitly decline to fix).
Backport merged.
Just for reference, the linking in the noted crates have since been fixed: , ,
I root-caused this a little bit more today, sharing my findings: The problem can be reproduced with and the following file: Weirdly enough, if you remove the linking to , everything links fine. I think this is actually a bug in , it seems like: The linker is reading the symbol tables from and to try to figure out where comes from. When reading , it sees that it has a few "", which includes , which is where the symbol actually comes from (well, nowadays from , but that is re-exported from ). But when reading , it finds the symbol , which is intended to indicate that "when linking on older platforms, use instead" But instead, it ends up making it seem like is actually the real , and does not expose , so the linking fails. Again, I believe this to be a linker bug because the problem does not happen with (try passing ).


Question: && !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..))) // Check that we're in fact trying to clone into the expected type && self.can_coerce(*pointee_ty, expected_ty) <ins> && let trait_ref = ty::Binder::dummy(self.tcx.mk_trait_ref(clone_trait_did, [expected_ty])) </ins> // And the expected type doesn't implement `Clone` && !self.predicate_must_hold_considering_regions(&traits::Obligation::new( self.tcx, traits::ObligationCause::dummy(), self.param_env, <del> ty::Binder::dummy(self.tcx.mk_trait_ref( clone_trait_did, [expected_ty], )), </del> <ins> trait_ref, </ins> )) { diag.span_note(

This gives the very unintuitive error: You expect to return , i.e. a . It mysteriously returns an instead. Because has a clone impl, it too, can be cloned (really, copied), returning a reference of the same lifetime. This is an operation you rarely want to do explicitly, except when dealing with generics. This error can crop up when you've forgotten to implement on , and have a reference (which could have been silently inserted using , as in the code above). However, it's not very obvious what's happening here. It can also crop up We should hint that itself isn't cloneable and thus we fell back to cloning here. This could be a lint on hitting the clone impl for references, but lints run too late. I'm not sure how this can be implemented, since we need to see the source of a value and that's a bit tricky.
cc
Interesting. This does seem like it would require some pretty special-case code to achieve, but I agree it'd be a nice case to capture.
A relatively easy way to catch most instances of this is to Pick up the expression which has a type error like this If it is a method call, check if that method call is a clone() call resolving to If it is a variable, find the variable's def If the def is a local def, look at the init expr, check if it's a bad clone This will miss things, but I think the majority of such bugs will be due to this. As it stands this feels like an incredibly easy case to hit (we've all forgotten to decorate structs).
cc
CC
As reported in : This reports:
Current output is even worse for the original report: The last comment's code is marginally different:
Current output: The last case should suggest constraining . Edit: that was easier than I thought (we already had the suggestion machinery): <img width="511" alt="Screen Shot 2022-12-13 at 6 41 23 PM" src="https://user-"


Question: <ins> // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This test makes sure that just changing a definition's location in the // source file also changes its incr. comp. hash, if debuginfo is enabled. // revisions:rpass1 rpass2 // compile-flags: -C overflow-checks=on #![feature(rustc_attrs)] #[cfg(rpass1)] pub fn main() { let _ = 0u8 + 1; } #[cfg(rpass2)] #[rustc_clean(label="Hir", cfg="rpass2")] #[rustc_dirty(label="HirBody", cfg="rpass2")] pub fn main() { let _ = 0u8 + 1; } </ins>

Found via rust-icci: https://travis- The commit history of the regex crate contains on changeset that only adds a comment which in turn leads to the body of a function being moved. This results in the update of the source location pointed to by a potential overflow panic message. This message is not updated properly in incremental mode: I have not found out yet why the change is not detected. HIR fingerprinting has special treatment of operations that can trigger overflows: There must be some kind of mismatch between when HIR fingerprinting thinks that an operation can panic and when we actually emit panic messages. This is another span-related papercut cc
Full IR files for reference:


Question: serialized_hashes.index_map.len()); } <ins> fn process_edges<'a, 'tcx, 'edges>( tcx: TyCtxt<'a, 'tcx, 'tcx>, source: &'edges DepNode<DefPathIndex>, target: &'edges DepNode<DefPathIndex>, edges: &'edges FxHashMap<DepNode<DefPathIndex>, Vec<DepNode<DefPathIndex>>>, directory: &DefIdDirectory, retraced: &RetracedDefIdDirectory, dirty_raw_nodes: &DirtyNodes, clean_work_products: &mut FxHashSet<Arc<WorkProductId>>, dirty_work_products: &mut FxHashSet<Arc<WorkProductId>>, extra_edges: &mut Vec<(&'edges DepNode<DefPathIndex>, &'edges DepNode<DefPathIndex>)>) { // If the target is dirty, skip the edge. If this is an edge // that targets a work-product, we can print the blame // information now. if let Some(blame) = dirty_raw_nodes.get(target) { if let DepNode::WorkProduct(ref wp) = *target { if tcx.sess.opts.debugging_opts.incremental_info { if dirty_work_products.insert(wp.clone()) { // It'd be nice to pretty-print these paths better than just // using the `Debug` impls, but wev. println!("incremental: module {:?} is dirty because {:?}  changed or was removed", wp, blame.map_def(|&index| { Some(directory.def_path_string(tcx, index)) }).unwrap()); } } } return; } // If the source is dirty, the target will be dirty. assert!(!dirty_raw_nodes.contains_key(source)); // Retrace the source -> target edges to def-ids and then create // an edge in the graph. Retracing may yield none if some of the // data happens to have been removed. if let Some(source_node) = retraced.map(source) { if let Some(target_node) = retraced.map(target) { let _task = tcx.dep_graph.in_task(target_node); tcx.dep_graph.read(source_node); if let DepNode::WorkProduct(ref wp) = *target { clean_work_products.insert(wp.clone()); } } else { // As discussed in `decode_dep_graph` above, sometimes the // target cannot be recreated again, in which case we add // edges to go from `source` to the targets of `target`. extra_edges.extend( edges[target].iter().map(|t| (source, t))); } } else { // It's also possible that the source can't be created! But we // can ignore such cases, because (a) if `source` is a HIR // node, it would be considered dirty; and (b) in other cases, // there must be some input to this node that is clean, and so // we'll re-create the edges over in the case where target is // undefined. } } </ins>

Today, nightly crashed on me when compiling my code: https://travis- I don't know what part of the code () is causing this and I don't know how to search for it. Compilation locally works correctly, with yesterday's or today's nightly. I'm trying that new feature. I managed to get this version info from travis in another job: I guess that travis log contains all the relevant information, but if not, please tell me what you need to know.
most likely the cause is . Can you remove the target directory and rebuild without it?
That seems to have helped… I to the job specification and now it passes. I didn't know travis keeps the directories intact between builds. The new log is https://travis- But I guess that makes it even harder to find out what is wrong.
Thanks for the bug report. This seems to be a problem with our new dependency graph reduction algorithm introduced in
I believe this was fixed -- can you verify?
I couldn't reproduce it reliably, it only crashed from time to time, so I have no way to explicitly verify it's fixed. But I haven't seen it crash for quite some time now, so I'd say it's probably solved.
OK, thanks! :)


Question: <ins> pub type Archived<T> = <m::Alias as n::Trait>::Archived; //~^ ERROR failed to resolve: use of undeclared crate or module `m` //~| ERROR failed to resolve: use of undeclared crate or module `n` fn main() {} </ins>

<!-- ICE: Rustc '' 'thread 'rustc' panicked at 'assertion failed: ().haserrors().issome()'', 'thread 'rustc' panicked at 'assertion failed: ().haserrors().issome()'' File: --auto-reduced (treereduce-rust): original: Version information ` Command: <!-- Include a backtrace in the code block by setting in your environment. E.g. . --<details<summary<strongProgram output</strong</summary<p</p</details<!-- query stack: [checkwellformed] checking that is well-formed [checkmodtype_wf] checking that types are well-formed in top-level module [analysis] running analysis passes on this crate --
cc
in 'ish ICEs, I am seeing ice now, im wondering if that also relates to somehow :thinking:
Quite likely, I'll take a look.
I can reproduce this. It's Saturday morning here, I might get to it today, if not I'll look on Monday morning.
Fixing this is really easy, I just need to adjust the assertion a tiny bit. The hard part is deciding where to put the test. is the obvious place, but then I get complaining that there are too many files in that directory. Suggestions?
just bump the limit by one like everybody else? :upsidedownface: :seenoevil:
I ended up putting the test in , because it happens during type checking.


Question: let ty = field.ty(tcx, args); try_visit!(visitor.visit(span, ty)); } <del> for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { </del> <ins> for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { </ins> try_visit!(visitor.visit(span, pred)); } }

https://crater-
searched nightlies: from nightly-2024-02-01 to nightly-2024-03-20 regressed nightly: nightly-2024-02-10 searched commit range: regressed commit: <details<summarybisected with <a href=''cargo-bisect-rustc</av0.6.8</summaryHost triple: x86_64-unknown-linux-gnu Reproduce with: </detailsprobably
WG-prioritization assigning priority (). label -I-prioritize +P-high
MCVE


Question: //  E0300, // unexpanded macro //  E0304, // expected signed integer constant //  E0305, // expected constant <del> E0313, // lifetime of borrowed pointer outlives lifetime of captured // variable </del> <ins> //  E0313, // removed: found unreachable </ins> //  E0314, // closure outlives stack frame //  E0315, // cannot invoke closure outside of its lifetime //  E0319, // trait impls for defaulted traits allowed just for structs/enums

This issue is a proposal for the deprecation of error code . I opened a PR () as part of an effort to add long error explanations for error codes that didn't have one (). I chose and for my erroneous code example, I used the example from . I quickly realized, through running the example and other code that would also raise and through the CI failure message, that was not being raised. I went back to consult the issue I received the original code example from and noticed comments about not occurring anymore with . The issue was eventually labeled with . But, looking at the current contents of the file, can still be emitted even while it isn't: also doesn't have any UI tests as it is part of the error codes in . Since , is no longer actually emitted (although it is in code that it could) thanks to , I believe it should be deprecated. I would be happy to help deprecate the error code, if it is decided that it should happen. I would just need to know the proper steps to take to deprecate an error code. If there are reasons for why it is still an error code, I would love to be enlightened. claim <!-- TRIAGEBOTSTART --<!-- TRIAGEBOTASSIGNSTART --<!-- TRIAGEBOTASSIGNDATASTARTTRIAGEBOTASSIGNDATAEND --<!-- TRIAGEBOTASSIGNEND --<!-- TRIAGEBOTEND --
If is not emitted anymore then it can be removed immediately. A crater run can also be done to ensure that this is the case. I'm also happy to do this if you want.
Sure, that sounds good.
Sorry just for clarification, do you want me to do the PR or you?


Question: *x } <ins> async fn async_fn_with_borrow_named_lifetime<'a>(x: &'a u8) -> u8 { await!(wake_and_yield_once()); *x } fn async_fn_with_impl_future_named_lifetime<'a>(x: &'a u8) -> impl Future<Output = u8> + 'a { async move { await!(wake_and_yield_once()); *x } } async fn async_fn_with_named_lifetime_multiple_args<'a>(x: &'a u8, _y: &'a u8) -> u8 { await!(wake_and_yield_once()); *x } </ins> fn async_fn_with_internal_borrow(y: u8) -> impl Future<Output = u8> { async move { await!(async_fn_with_borrow(&y))

suggested this is because when we lower the async function, we add `), whereas it should be parented as something outside of the impl trait context (as that is how such an expression would be parented, if it actually existing in the AST). I have a bit of code where I'd like to use a reference with a lifetime in an "async" function, which panics the compiler. I tried this code: I expected to see this happen: My understanding was that async functions are allowed to take references as parameters. helped to debug this a little bit and there is a suspicion that named lifetimes are somehow not properly propagated. I stumbled into this because I wanted to have 2 args with references, but if the lifetimes are elided the compiler asks for them to be . Adding them ICEs the compiler. Instead, this happened: I got a compiler panic. Backtrace:
suggested might be related
It would appear one can workaround this by using async blocks manually: I still need to test this does what I expect.
why do you need the immediately invoked closure there,
Yeah, just noticed. I think I also had some other issue / ICE, but I don't remember exactly what it was. Gonna have to check it again. Also, I don't think I knew that on blocks was a thing.
I didn't quite understand why I needed the move. I am trying to fix the original ICE, I think I got some time today tomorrow, hopefully, will make some progress. But compiler newbie, so might not work out.
You need to move to avoid the closure borrowing the references locally. It's the same situation as with I just removed all immeditaly invoked functions from eval :wink:
I am playing around with similar types of borrowing patterns, namely using StreamObj to carry a stream around inside of a struct. I can't seem to use the posted work-arounds: I am taking this working code and I'm refactoring it. Starts as: this works, compiles and runs. Then I try my hand at refactoring to move the stream out of the same scope as the await code pulling out values.


Question: *x } <ins> async fn async_fn_with_borrow_named_lifetime<'a>(x: &'a u8) -> u8 { await!(wake_and_yield_once()); *x } fn async_fn_with_impl_future_named_lifetime<'a>(x: &'a u8) -> impl Future<Output = u8> + 'a { async move { await!(wake_and_yield_once()); *x } } async fn async_fn_with_named_lifetime_multiple_args<'a>(x: &'a u8, _y: &'a u8) -> u8 { await!(wake_and_yield_once()); *x } </ins> fn async_fn_with_internal_borrow(y: u8) -> impl Future<Output = u8> { async move { await!(async_fn_with_borrow(&y))

Now I can get the same ICE as this ticket: ICE: full backtrace: Then I try some of your posted workarounds and they don't do the trick, here's my best try: but this fails to compile due to an ownership issue I can't figure out:
your final borrow error is because Fahrenheit while your contains a local stack borrow. You could try using  instead of Fahrenheit.
Alternatively to what suggested, you could move the code in to an async fn:


Question: <ins> #!/usr/bin/env python # ignore-tidy-linelength # This is a small script that we use on CI to collect CPU usage statistics of # our builders. By seeing graphs of CPU usage over time we hope to correlate # that with possible improvements to Rust's own build system, ideally diagnosing # that either builders are always fully using their CPU resources or they're # idle for long stretches of time. # # This script is relatively simple, but it's platform specific. Each platform # (OSX/Windows/Linux) has a different way of calculating the current state of # CPU at a point in time. We then compare two captured states to determine the # percentage of time spent in one state versus another. The state capturing is # all platform-specific but the loop at the bottom is the cross platform part # that executes everywhere. # # # Viewing statistics # # All builders will upload their CPU statistics as CSV files to our S3 buckets. # These URLS look like: # #   https://$bucket.s3.amazonaws.com/rustc-builds/$commit/cpu-$builder.csv # # for example # #   https://rust-lang-ci2.s3.amazonaws.com/rustc-builds/68baada19cd5340f05f0db15a3e16d6671609bcc/cpu-x86_64-apple.csv # # Each CSV file has two columns. The first is the timestamp of the measurement # and the second column is the % of idle cpu time in that time slice. Ideally # the second column is always zero. # # Once you've downloaded a file there's various ways to plot it and visualize # it. For command line usage you can use a script like so: # #      set timefmt '%Y-%m-%dT%H:%M:%S' #      set xdata time #      set ylabel "Idle CPU %" #      set xlabel "Time" #      set datafile sep ',' #      set term png #      set output "printme.png" #      set grid #      builder = "i686-apple" #      plot "cpu-".builder.".csv" using 1:2 with lines title builder # # Executed as `gnuplot < ./foo.plot` it will generate a graph called # `printme.png` which you can then open up. If you know how to improve this # script or the viewing process that would be much appreciated :) (or even if # you know how to automate it!) import datetime import sys import time if sys.platform == 'linux2': class State: def __init__(self): with open('/proc/stat', 'r') as file: data = file.readline().split() if data[0] != 'cpu': raise Exception('did not start with "cpu"') self.user = int(data[1]) self.nice = int(data[2]) self.system = int(data[3]) self.idle = int(data[4]) self.iowait = int(data[5]) self.irq = int(data[6]) self.softirq = int(data[7]) self.steal = int(data[8]) self.guest = int(data[9]) self.guest_nice = int(data[10]) def idle_since(self, prev): user = self.user - prev.user nice = self.nice - prev.nice system = self.system - prev.system idle = self.idle - prev.idle iowait = self.iowait - prev.iowait irq = self.irq - prev.irq softirq = self.softirq - prev.softirq steal = self.steal - prev.steal guest = self.guest - prev.guest guest_nice = self.guest_nice - prev.guest_nice total = user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice return float(idle) / float(total) * 100 elif sys.platform == 'win32': from ctypes.wintypes import DWORD from ctypes import Structure, windll, WinError, GetLastError, byref class FILETIME(Structure): _fields_ = [ ("dwLowDateTime", DWORD), ("dwHighDateTime", DWORD), ] class State: def __init__(self): idle, kernel, user = FILETIME(), FILETIME(), FILETIME() success = windll.kernel32.GetSystemTimes( byref(idle), byref(kernel), byref(user), ) assert success, WinError(GetLastError())[1] self.idle = (idle.dwHighDateTime << 32) | idle.dwLowDateTime self.kernel = (kernel.dwHighDateTime << 32) | kernel.dwLowDateTime self.user = (user.dwHighDateTime << 32) | user.dwLowDateTime def idle_since(self, prev): idle = self.idle - prev.idle user = self.user - prev.user kernel = self.kernel - prev.kernel return float(idle) / float(user + kernel) * 100 elif sys.platform == 'darwin': from ctypes import * libc = cdll.LoadLibrary('/usr/lib/libc.dylib') PROESSOR_CPU_LOAD_INFO = c_int(2) CPU_STATE_USER = 0 CPU_STATE_SYSTEM = 1 CPU_STATE_IDLE = 2 CPU_STATE_NICE = 3 c_int_p = POINTER(c_int) class State: def __init__(self): num_cpus_u = c_uint(0) cpu_info = c_int_p() cpu_info_cnt = c_int(0) err = libc.host_processor_info( libc.mach_host_self(), PROESSOR_CPU_LOAD_INFO, byref(num_cpus_u), byref(cpu_info), byref(cpu_info_cnt), ) assert err == 0 self.user = 0 self.system = 0 self.idle = 0 self.nice = 0 cur = 0 while cur < cpu_info_cnt.value: self.user += cpu_info[cur + CPU_STATE_USER] self.system += cpu_info[cur + CPU_STATE_SYSTEM] self.idle += cpu_info[cur + CPU_STATE_IDLE] self.nice += cpu_info[cur + CPU_STATE_NICE] cur += num_cpus_u.value def idle_since(self, prev): user = self.user - prev.user system = self.system - prev.system idle = self.idle - prev.idle nice = self.nice - prev.nice return float(idle) / float(user + system + idle + nice) * 100.0 else: print('unknown platform', sys.platform) sys.exit(1) cur_state = State(); print("Time,Idle") while True: time.sleep(1); next_state = State(); now = datetime.datetime.utcnow().isoformat() idle = next_state.idle_since(cur_state) print("%s,%s" % (now, idle)) sys.stdout.flush() cur_state = next_state </ins>

One of the easiest ways to make CI faster is to make things parallel and simply use the hardware we have available to us. Unfortunately though we don't have a lot of data about how parallel our build is. Are there steps we think are parallel but actually aren't? Are we pegged to one core for long durations when there's other work we could be doing? The general idea here is that we'd spin up a daemon at the very start of the build which would sample CPU utilization every so often. This daemon would then update a file that's either displayed or uploaded at the end of the build. Hopefully we could then use these logs to get a better view into how the builders are working during the build, diagnose non-parallel portions of the build, and implement fixes to use all the cpus we've got. cc
On Windows this can be done by taking advantage of job objects. If the entire build is wrapped in a job object then we can call with to get a bunch of useful data.
I made script that will print output into the travis log every 30 seconds , . Some findings: Cloning submodules jemalloc, libcompilerbuildtins and liblibc alone takes 30 seconds. While building bootstrap, compiling serdederive, serdejson and bootstrap crates seems to take 30 seconds (total build time: 47 seconds). stage0: Compiling tidy crate seems to take around 30 seconds. Compiling rustcerrors takes at least 2 minutes, only one codegen-unit is used Compiling syntaxext takes 9 minutes, only one CGU used stage0 codegen artifacts: Compiling rustcllvm takes 1,5 minutes, one CGU During stage1, rustcerrors and syntaxext builds are approximately as slow as during stage0, rustc_plugins 2 minutes, one CGU. stage2: rustdoc took 2 minutes to build, one CGU compiletest suite=run-make mode=run-make: It looks like there is a single test that takes around 3 minutes to complete and has no parallelization. Testing alloc stage1: building liballoc takes around a minute Testing syntax stage1: building syntax takes 1.5 minutes, one CGU Notes: When the load average dropped towards 1, I assumed only one codegen unit was active.


Question: <ins> #!/usr/bin/env python # ignore-tidy-linelength # This is a small script that we use on CI to collect CPU usage statistics of # our builders. By seeing graphs of CPU usage over time we hope to correlate # that with possible improvements to Rust's own build system, ideally diagnosing # that either builders are always fully using their CPU resources or they're # idle for long stretches of time. # # This script is relatively simple, but it's platform specific. Each platform # (OSX/Windows/Linux) has a different way of calculating the current state of # CPU at a point in time. We then compare two captured states to determine the # percentage of time spent in one state versus another. The state capturing is # all platform-specific but the loop at the bottom is the cross platform part # that executes everywhere. # # # Viewing statistics # # All builders will upload their CPU statistics as CSV files to our S3 buckets. # These URLS look like: # #   https://$bucket.s3.amazonaws.com/rustc-builds/$commit/cpu-$builder.csv # # for example # #   https://rust-lang-ci2.s3.amazonaws.com/rustc-builds/68baada19cd5340f05f0db15a3e16d6671609bcc/cpu-x86_64-apple.csv # # Each CSV file has two columns. The first is the timestamp of the measurement # and the second column is the % of idle cpu time in that time slice. Ideally # the second column is always zero. # # Once you've downloaded a file there's various ways to plot it and visualize # it. For command line usage you can use a script like so: # #      set timefmt '%Y-%m-%dT%H:%M:%S' #      set xdata time #      set ylabel "Idle CPU %" #      set xlabel "Time" #      set datafile sep ',' #      set term png #      set output "printme.png" #      set grid #      builder = "i686-apple" #      plot "cpu-".builder.".csv" using 1:2 with lines title builder # # Executed as `gnuplot < ./foo.plot` it will generate a graph called # `printme.png` which you can then open up. If you know how to improve this # script or the viewing process that would be much appreciated :) (or even if # you know how to automate it!) import datetime import sys import time if sys.platform == 'linux2': class State: def __init__(self): with open('/proc/stat', 'r') as file: data = file.readline().split() if data[0] != 'cpu': raise Exception('did not start with "cpu"') self.user = int(data[1]) self.nice = int(data[2]) self.system = int(data[3]) self.idle = int(data[4]) self.iowait = int(data[5]) self.irq = int(data[6]) self.softirq = int(data[7]) self.steal = int(data[8]) self.guest = int(data[9]) self.guest_nice = int(data[10]) def idle_since(self, prev): user = self.user - prev.user nice = self.nice - prev.nice system = self.system - prev.system idle = self.idle - prev.idle iowait = self.iowait - prev.iowait irq = self.irq - prev.irq softirq = self.softirq - prev.softirq steal = self.steal - prev.steal guest = self.guest - prev.guest guest_nice = self.guest_nice - prev.guest_nice total = user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice return float(idle) / float(total) * 100 elif sys.platform == 'win32': from ctypes.wintypes import DWORD from ctypes import Structure, windll, WinError, GetLastError, byref class FILETIME(Structure): _fields_ = [ ("dwLowDateTime", DWORD), ("dwHighDateTime", DWORD), ] class State: def __init__(self): idle, kernel, user = FILETIME(), FILETIME(), FILETIME() success = windll.kernel32.GetSystemTimes( byref(idle), byref(kernel), byref(user), ) assert success, WinError(GetLastError())[1] self.idle = (idle.dwHighDateTime << 32) | idle.dwLowDateTime self.kernel = (kernel.dwHighDateTime << 32) | kernel.dwLowDateTime self.user = (user.dwHighDateTime << 32) | user.dwLowDateTime def idle_since(self, prev): idle = self.idle - prev.idle user = self.user - prev.user kernel = self.kernel - prev.kernel return float(idle) / float(user + kernel) * 100 elif sys.platform == 'darwin': from ctypes import * libc = cdll.LoadLibrary('/usr/lib/libc.dylib') PROESSOR_CPU_LOAD_INFO = c_int(2) CPU_STATE_USER = 0 CPU_STATE_SYSTEM = 1 CPU_STATE_IDLE = 2 CPU_STATE_NICE = 3 c_int_p = POINTER(c_int) class State: def __init__(self): num_cpus_u = c_uint(0) cpu_info = c_int_p() cpu_info_cnt = c_int(0) err = libc.host_processor_info( libc.mach_host_self(), PROESSOR_CPU_LOAD_INFO, byref(num_cpus_u), byref(cpu_info), byref(cpu_info_cnt), ) assert err == 0 self.user = 0 self.system = 0 self.idle = 0 self.nice = 0 cur = 0 while cur < cpu_info_cnt.value: self.user += cpu_info[cur + CPU_STATE_USER] self.system += cpu_info[cur + CPU_STATE_SYSTEM] self.idle += cpu_info[cur + CPU_STATE_IDLE] self.nice += cpu_info[cur + CPU_STATE_NICE] cur += num_cpus_u.value def idle_since(self, prev): user = self.user - prev.user system = self.system - prev.system idle = self.idle - prev.idle nice = self.nice - prev.nice return float(idle) / float(user + system + idle + nice) * 100.0 else: print('unknown platform', sys.platform) sys.exit(1) cur_state = State(); print("Time,Idle") while True: time.sleep(1); next_state = State(); now = datetime.datetime.utcnow().isoformat() idle = next_state.idle_since(cur_state) print("%s,%s" % (now, idle)) sys.stdout.flush() cur_state = next_state </ins>

The script was only applied to the default pullrequest travis-ci configuration.
As shown in , the CPUs assigned to each job may have some performance difference: Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz Intel(R) Xeon(R) CPU E5-2680 v3 @ 2.50GHz The clock-rate 2.4 GHz vs 2.5 GHz shouldn't make any noticeable difference though (this would at most slow down by 7.2 minutes out of 3 hours if everything is CPU-bound). It is not enough to explain the timeout in .
I was working on recently for this where it periodically prints out the CPU usage as a percentage for the whole system (aka 1 core on a 4 core machine is 25%). I only got Linux/OSX working though and was unable to figure out a good way to do it on Windows. My thinking for how we'd do this is probably download a binary near the beginning of the build (or set up some script). We'd then run just before we run . That way we could correlate the two timestamps of each log (the main log and the to similar moments in time. Initially I was also thinking we'd just at the end of the build and scrape it later if need be.


Question: <ins> // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(associated_consts)] #![deny(dead_code)] // use different types / traits to test all combinations trait Const { const C: (); } trait StaticFn { fn sfn(); } struct ConstStruct; struct StaticFnStruct; enum ConstEnum {} enum StaticFnEnum {} struct AliasedConstStruct; struct AliasedStaticFnStruct; enum AliasedConstEnum {} enum AliasedStaticFnEnum {} type AliasConstStruct    = AliasedConstStruct; type AliasStaticFnStruct = AliasedStaticFnStruct; type AliasConstEnum      = AliasedConstEnum; type AliasStaticFnEnum   = AliasedStaticFnEnum; macro_rules! impl_Const {($($T:ident),*) => {$( impl Const for $T { const C: () = (); } )*}} macro_rules! impl_StaticFn {($($T:ident),*) => {$( impl StaticFn for $T { fn sfn() {} } )*}} impl_Const!(ConstStruct, ConstEnum, AliasedConstStruct, AliasedConstEnum); impl_StaticFn!(StaticFnStruct, StaticFnEnum, AliasedStaticFnStruct, AliasedStaticFnEnum); fn main() { let _ = ConstStruct::C; let _ = ConstEnum::C; StaticFnStruct::sfn(); StaticFnEnum::sfn(); let _ = AliasConstStruct::C; let _ = AliasConstEnum::C; AliasStaticFnStruct::sfn(); AliasStaticFnEnum::sfn(); } </ins>

Warning:
By the way, the warning goes away if you explicitly specify the trait who's static method you are calling, like so:


Question: "`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead" ), ); <ins> let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id); if let ty::Param(param) = expected_ty.kind() && let Some(generics) = self.tcx.hir().get_generics(owner) { suggest_constraining_type_params( self.tcx, generics, diag, vec![(param.name.as_str(), "Clone", Some(clone_trait_did))].into_iter(), ); } else { self.suggest_derive(diag, &[(trait_ref.to_predicate(self.tcx), None, None)]); } </ins> } }


Question: macro_rules! mac { ($ ($ tt : tt) *) => () } mac! { <del> struct S { field1 : u8 , field2 : u16 , } impl Clone for S </del> <ins> struct S { field1 : u8, field2 : u16, } impl Clone for S </ins> { fn clone () -> S {

proc-macro derive panicked All of the 62 regressions are due to old versions of having an assert expecting instead of . So this is again a consequence of whitespace changes in pretty-printing (). I think we should be able to fix this by special casing the comma token during token stream pretty-printing and not printing the space before it.
Fixed in
Just FYI, we discussed this in the meeting. We felt like the action here was appropriate -- while in general we do not guarantee stability of pretty printing, it makes sense to be judicious, and in this particular case not having a leading space before just looks better anyway.


Question: //! Unicode string slices. //! <ins> //! The `&str` type is one of the two main string types, the other being `String`. //! Unlike its `String` counterpart, its contents are borrowed. //! //! # Basic Usage //! //! A basic string declaration of `&str` type: //! //! ``` //! let hello_world = "Hello, World!"; //! ``` //! //! Here we have declared a string literal, also known as a string slice. //! String literals have a static lifetime, which means the string `hello_world` //! is guaranteed to be valid for the duration of the entire program. //! We can explicitly specify `hello_world`'s lifetime as well: //! //! ``` //! let hello_world: &'static str = "Hello, world!"; //! ``` //! </ins> //! *[See also the `str` primitive type](../../std/primitive.str.html).* #![stable(feature = "rust1", since = "1.0.0")] // Many of the usings in this module are only used in the test configuration.

Part of Here's what needs to be done to close out this issue: is fine, but should point out why and the primitive type are different. should use the same boilerplate as  has the same issue. has the same issue. has the same issue. should link to the method it comes from. should use the same boilerplate as . should link to those functions. should have an example of implementing it. should link the types it mentions. should link that .
As shown in , there's a lot of junk there that could be in instead.
I am happy to mentor anyone who wants to tackle this issue.
Hello! I'd like to give this issue a try.
that'd be great! this issue is very general, so any improvements would be welcome. Let me know if you need any help!
Shouldn't this remain open? 3 points have been hit on, but the rest of the bullets need to be addressed
Yes, whoops! That was an auto-close from a PR message; gotta be careful with that!
Can you explain what you mean by "the same boilerplate" in points 2-5? Boilerplate as in the description text or the struct line, or something else? Getting some clarification could get those knocked out in short order
Yes, absolutely! is the main set of iterators, for . When I did these docs, I took care to make them all consistent: etc. and etc don't use this; when I wrote it, I was thinking that would be the right way to go; but looks like is slightly different than the ones. So we should change all of these to look like the ones in . Make sense?
Ahhh, so for , it should be something along the lines of: An iterator over the lines of a string, as string slices. With the proper links to and as well, yes? I could run through each of those structs, format them like that, with a commit for each and then do one big pull request for the lot of them if that would be convenient
Exactly. Sure thing! That'd be great.
I think the last two PRs should take care of the remaining bits of the task list. When they're merged, I think we'll be good to close this issue out!


Question: //! Unicode string slices. //! <ins> //! The `&str` type is one of the two main string types, the other being `String`. //! Unlike its `String` counterpart, its contents are borrowed. //! //! # Basic Usage //! //! A basic string declaration of `&str` type: //! //! ``` //! let hello_world = "Hello, World!"; //! ``` //! //! Here we have declared a string literal, also known as a string slice. //! String literals have a static lifetime, which means the string `hello_world` //! is guaranteed to be valid for the duration of the entire program. //! We can explicitly specify `hello_world`'s lifetime as well: //! //! ``` //! let hello_world: &'static str = "Hello, world!"; //! ``` //! </ins> //! *[See also the `str` primitive type](../../std/primitive.str.html).* #![stable(feature = "rust1", since = "1.0.0")] // Many of the usings in this module are only used in the test configuration.

Module documentation () Bytes should use the same boilerplate as Lines () CharIndices has the same issue. () Chars has the same issue. () EncodeUtf16 has the same issue. () ParseBoolError should link to the method it comes from. () SplitWhitespace should use the same boilerplate as Lines. () Utf8Error should link to those functions. () FromStr should have an example of implementing it. () fromutf8 should link the types it mentions. () fromutf8_unchecked should link that &str. ()
Everything's merged! Good to close
Yes! Thank you for all the help!


Question: #[allow(unused)] pub fn doctest_runner(bin: &std::path::Path, test_nb: usize) -> Result<(), String> {{ let out = std::process::Command::new(bin) <del> .arg(self::RUN_OPTION) .arg(test_nb.to_string()) </del> <ins> .env(self::RUN_OPTION, test_nb.to_string()) .args(std::env::args().skip(1).collect::<Vec<_>>()) </ins> .output() .expect("failed to run command"); if !out.status.success() {{

The crater run for merged doctests () detected a large number of regressions due to tests examining the process arguments. (I don't have an exact number, but let's say ~50 projects.) Previously, there were no arguments, but now it gets arguments like which the user's CLI parsing code isn't expecting. For example, using something like  will now fail. It seems to be fairly common to have objects whose default constructor will parse the arguments from the command line. I'm not sure if or how we should resolve that. One idea is to use a different mechanism for passing in the test information (like via an environment variable).
I vaguely remember that using environment variables was discussed but can't find anything except mentioning it . Maybe it'd be a better approach indeed. Let me send a PR so we can make a crater run on it.


Question: let attrs = self.parse_outer_attributes()?; let lo = self.token.span; <del> Ok(Some(if self.eat_keyword(kw::Let) { Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Local(self.parse_local(attrs.into())?), span: lo.to(self.prev_span), } } else if let Some(macro_def) = self.eat_macro_def( &attrs, &respan(lo, VisibilityKind::Inherited), lo, )? { Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Item(macro_def), span: lo.to(self.prev_span), } </del> <ins> if self.eat_keyword(kw::Let) { let local = self.parse_local(attrs.into())?; return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local)))); } let mac_vis = respan(lo, VisibilityKind::Inherited); if let Some(macro_def) = self.eat_macro_def(&attrs, &mac_vis, lo)? { return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Item(macro_def)))); } </ins> // Starts like a simple path, being careful to avoid contextual keywords // such as a union items, item with `crate` visibility or auto trait items. // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts // like a path (1 token), but it fact not a path. <del> // `union::b::c` - path, `union U { ... }` - not a path. // `crate::b::c` - path, `crate struct S;` - not a path. } else if self.token.is_path_start() && !self.token.is_qpath_start() && !self.is_union_item() && !self.is_crate_vis() && !self.is_auto_trait_item() && !self.is_async_fn() { </del> <ins> if self.token.is_path_start() && !self.token.is_qpath_start() && !self.is_union_item() // `union::b::c` - path, `union U { ... }` - not a path. && !self.is_crate_vis() // `crate::b::c` - path, `crate struct S;` - not a path. && !self.is_auto_trait_item() && !self.is_async_fn() { </ins> let path = self.parse_path(PathStyle::Expr)?; <del> if !self.eat(&token::Not) { let expr = if self.check(&token::OpenDelim(token::Brace)) { self.parse_struct_expr(lo, path, ThinVec::new())? } else { let hi = self.prev_span; self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()) }; let expr = self.with_res(Restrictions::STMT_EXPR, |this| { let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?; this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) })?; return Ok(Some(Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Expr(expr), span: lo.to(self.prev_span), })); </del> <ins> if self.eat(&token::Not) { return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings); </ins> } <del> let args = self.parse_mac_args()?; let delim = args.delim(); let hi = self.prev_span; let style = if delim == token::Brace { MacStmtStyle::Braces </del> <ins> let expr = if self.check(&token::OpenDelim(token::Brace)) { self.parse_struct_expr(lo, path, ThinVec::new())? </ins> } else { <del> MacStmtStyle::NoBraces </del> <ins> let hi = self.prev_span; self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()) </ins> }; <del> let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription, }; let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof { StmtKind::Mac(P((mac, style, attrs.into()))) } // We used to incorrectly stop parsing macro-expanded statements here. // If the next token will be an error anyway but could have parsed with the // earlier behavior, stop parsing here and emit a warning to avoid breakage. else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token.kind { // These can continue an expression, so we can't stop parsing and warn. token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | token::BinOp(token::Minus) | token::BinOp(token::Star) | token::BinOp(token::And) | token::BinOp(token::Or) | token::AndAnd | token::OrOr | token::DotDot | token::DotDotDot | token::DotDotEq => false, _ => true, } { self.warn_missing_semicolon(); StmtKind::Mac(P((mac, style, attrs.into()))) } else { let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new()); let e = self.maybe_recover_from_bad_qpath(e, true)?; let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?; let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; StmtKind::Expr(e) }; Stmt { id: DUMMY_NODE_ID, span: lo.to(hi), kind, </del> <ins> let expr = self.with_res(Restrictions::STMT_EXPR, |this| { let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?; this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) })?; return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr)))); } // FIXME: Bad copy of attrs let old_directory_ownership = mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); let item = self.parse_item_(attrs.clone(), false, true)?; self.directory.ownership = old_directory_ownership; if let Some(item) = item { return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item)))); } // Do not attempt to parse an expression if we're done here. if self.token == token::Semi { self.error_outer_attrs(&attrs); self.bump(); let mut last_semi = lo; while self.token == token::Semi { last_semi = self.token.span; self.bump(); </ins> } <ins> // We are encoding a string of semicolons as an an empty tuple that spans // the excess semicolons to preserve this info until the lint stage. let kind = StmtKind::Semi(self.mk_expr( lo.to(last_semi), ExprKind::Tup(Vec::new()), ThinVec::new() )); return Ok(Some(self.mk_stmt(lo.to(last_semi), kind))); } if self.token == token::CloseDelim(token::Brace) { self.error_outer_attrs(&attrs); return Ok(None); } // Remainder are line-expr stmts. let e = self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?; Ok(Some(self.mk_stmt(lo.to(e.span), StmtKind::Expr(e)))) } /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`. /// At this point, the `!` token after the path has already been eaten. fn parse_stmt_mac( &mut self, lo: Span, attrs: ThinVec<Attribute>, path: ast::Path, legacy_warnings: bool, ) -> PResult<'a, Option<Stmt>> { let args = self.parse_mac_args()?; let delim = args.delim(); let hi = self.prev_span; let style = if delim == token::Brace { MacStmtStyle::Braces </ins> } else { <del> // FIXME: Bad copy of attrs let old_directory_ownership = mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); let item = self.parse_item_(attrs.clone(), false, true)?; self.directory.ownership = old_directory_ownership; match item { Some(i) => Stmt { id: DUMMY_NODE_ID, span: lo.to(i.span), kind: StmtKind::Item(i), }, None => { let unused_attrs = |attrs: &[Attribute], s: &mut Self| { if !attrs.is_empty() { if s.prev_token_kind == PrevTokenKind::DocComment { s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit(); } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { s.span_err( s.token.span, "expected statement after outer attribute" ); } } }; // Do not attempt to parse an expression if we're done here. if self.token == token::Semi { unused_attrs(&attrs, self); self.bump(); let mut last_semi = lo; while self.token == token::Semi { last_semi = self.token.span; self.bump(); } // We are encoding a string of semicolons as an // an empty tuple that spans the excess semicolons // to preserve this info until the lint stage return Ok(Some(Stmt { id: DUMMY_NODE_ID, span: lo.to(last_semi), kind: StmtKind::Semi(self.mk_expr(lo.to(last_semi), ExprKind::Tup(Vec::new()), ThinVec::new() )), })); } </del> <ins> MacStmtStyle::NoBraces }; </ins> <del> if self.token == token::CloseDelim(token::Brace) { unused_attrs(&attrs, self); return Ok(None); } </del> <ins> let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription, }; </ins> <del> // Remainder are line-expr stmts. let e = self.parse_expr_res( Restrictions::STMT_EXPR, Some(attrs.into()))?; Stmt { id: DUMMY_NODE_ID, span: lo.to(e.span), kind: StmtKind::Expr(e), } } </del> <ins> let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof { StmtKind::Mac(P((mac, style, attrs.into()))) } // We used to incorrectly stop parsing macro-expanded statements here. // If the next token will be an error anyway but could have parsed with the // earlier behavior, stop parsing here and emit a warning to avoid breakage. else if legacy_warnings && self.token.can_begin_expr() && match self.token.kind { // These can continue an expression, so we can't stop parsing and warn. token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | token::BinOp(token::Minus) | token::BinOp(token::Star) | token::BinOp(token::And) | token::BinOp(token::Or) | token::AndAnd | token::OrOr | token::DotDot | token::DotDotDot | token::DotDotEq => false, _ => true, </ins> } <del> })) </del> <ins> { self.warn_missing_semicolon(); StmtKind::Mac(P((mac, style, attrs))) } else { // Since none of the above applied, this is an expression statement macro. let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new()); let e = self.maybe_recover_from_bad_qpath(e, true)?; let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?; let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; StmtKind::Expr(e) }; Ok(Some(self.mk_stmt(lo.to(hi), kind))) } /// Error on outer attributes in this context. /// Also error if the previous token was a doc comment. fn error_outer_attrs(&self, attrs: &[Attribute]) { if !attrs.is_empty() { if self.prev_token_kind == PrevTokenKind::DocComment { self.span_fatal_err(self.prev_span, Error::UselessDocComment).emit(); } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { self.span_err(self.token.span, "expected statement after outer attribute"); } } </ins> } /// Parses a local variable declaration.

The idea of shortening to has been discussed many times before, and the general consensus always ends up being that it is not a good idea. I would like to propose something a bit different, so please hear me out. I propose that instead of aliasing to , we instead just make expand into when in the context of a variable declaration. For example: This solves the problems (readability, more concise) that people have with , whilst not causing the issues that people have (pattern matching and consistancy). The most common issue people have with aliasing to is that it doesn't fit well with patterns, like . However, gets rid of this problem, because you wouldn't write if you were trying to pattern match, so why would someone want to write ? You wouldn't do that, and it wouldn't compile. This would be optional, of course. would still work fine, and people would just have to option of removing the to let it be implied. There are a lot of other abbreviations used in rust (, , ) that all serve the purpose of writing less. It just doesn't feel right that one of the most commonly used keywords is so long. :heart::crab: <!-- TRIAGEBOTSTART --<!-- TRIAGEBOTASSIGNSTART --<!-- TRIAGEBOTASSIGNDATASTARTTRIAGEBOTASSIGNDATAEND --<!-- TRIAGEBOTASSIGNEND --<!-- TRIAGEBOTEND --
Rust wants to make to make you think when you try and use mutation, even if only a little bit, because mutation can be difficult to reason about. Shortening to doesn't fit this philosophy. Also, this makes mutation just as easy as no mutation. This will lead people to choose mutation because it will give them less compiler errors in the short term, and in doing so open themselves up to some weird bugs that could have been prevented with the syntactic salt that is . tldr: wasn't rejected because of the name , but because it allowed easy mutation, which runs counter to Rust's philosophy.
I politely disagree. In fact, it is actually the other way around. Using unnecessarily will cause compiler warnings, discouraging the use of unneeded mutability. The compiler doesn't warn when the use of is actually needed.
The fact that people will choose in the face of compiler warnings has been shown in practice, across many projects.


Question: let attrs = self.parse_outer_attributes()?; let lo = self.token.span; <del> Ok(Some(if self.eat_keyword(kw::Let) { Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Local(self.parse_local(attrs.into())?), span: lo.to(self.prev_span), } } else if let Some(macro_def) = self.eat_macro_def( &attrs, &respan(lo, VisibilityKind::Inherited), lo, )? { Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Item(macro_def), span: lo.to(self.prev_span), } </del> <ins> if self.eat_keyword(kw::Let) { let local = self.parse_local(attrs.into())?; return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local)))); } let mac_vis = respan(lo, VisibilityKind::Inherited); if let Some(macro_def) = self.eat_macro_def(&attrs, &mac_vis, lo)? { return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Item(macro_def)))); } </ins> // Starts like a simple path, being careful to avoid contextual keywords // such as a union items, item with `crate` visibility or auto trait items. // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts // like a path (1 token), but it fact not a path. <del> // `union::b::c` - path, `union U { ... }` - not a path. // `crate::b::c` - path, `crate struct S;` - not a path. } else if self.token.is_path_start() && !self.token.is_qpath_start() && !self.is_union_item() && !self.is_crate_vis() && !self.is_auto_trait_item() && !self.is_async_fn() { </del> <ins> if self.token.is_path_start() && !self.token.is_qpath_start() && !self.is_union_item() // `union::b::c` - path, `union U { ... }` - not a path. && !self.is_crate_vis() // `crate::b::c` - path, `crate struct S;` - not a path. && !self.is_auto_trait_item() && !self.is_async_fn() { </ins> let path = self.parse_path(PathStyle::Expr)?; <del> if !self.eat(&token::Not) { let expr = if self.check(&token::OpenDelim(token::Brace)) { self.parse_struct_expr(lo, path, ThinVec::new())? } else { let hi = self.prev_span; self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()) }; let expr = self.with_res(Restrictions::STMT_EXPR, |this| { let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?; this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) })?; return Ok(Some(Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Expr(expr), span: lo.to(self.prev_span), })); </del> <ins> if self.eat(&token::Not) { return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings); </ins> } <del> let args = self.parse_mac_args()?; let delim = args.delim(); let hi = self.prev_span; let style = if delim == token::Brace { MacStmtStyle::Braces </del> <ins> let expr = if self.check(&token::OpenDelim(token::Brace)) { self.parse_struct_expr(lo, path, ThinVec::new())? </ins> } else { <del> MacStmtStyle::NoBraces </del> <ins> let hi = self.prev_span; self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()) </ins> }; <del> let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription, }; let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof { StmtKind::Mac(P((mac, style, attrs.into()))) } // We used to incorrectly stop parsing macro-expanded statements here. // If the next token will be an error anyway but could have parsed with the // earlier behavior, stop parsing here and emit a warning to avoid breakage. else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token.kind { // These can continue an expression, so we can't stop parsing and warn. token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | token::BinOp(token::Minus) | token::BinOp(token::Star) | token::BinOp(token::And) | token::BinOp(token::Or) | token::AndAnd | token::OrOr | token::DotDot | token::DotDotDot | token::DotDotEq => false, _ => true, } { self.warn_missing_semicolon(); StmtKind::Mac(P((mac, style, attrs.into()))) } else { let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new()); let e = self.maybe_recover_from_bad_qpath(e, true)?; let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?; let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; StmtKind::Expr(e) }; Stmt { id: DUMMY_NODE_ID, span: lo.to(hi), kind, </del> <ins> let expr = self.with_res(Restrictions::STMT_EXPR, |this| { let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?; this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) })?; return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr)))); } // FIXME: Bad copy of attrs let old_directory_ownership = mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); let item = self.parse_item_(attrs.clone(), false, true)?; self.directory.ownership = old_directory_ownership; if let Some(item) = item { return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item)))); } // Do not attempt to parse an expression if we're done here. if self.token == token::Semi { self.error_outer_attrs(&attrs); self.bump(); let mut last_semi = lo; while self.token == token::Semi { last_semi = self.token.span; self.bump(); </ins> } <ins> // We are encoding a string of semicolons as an an empty tuple that spans // the excess semicolons to preserve this info until the lint stage. let kind = StmtKind::Semi(self.mk_expr( lo.to(last_semi), ExprKind::Tup(Vec::new()), ThinVec::new() )); return Ok(Some(self.mk_stmt(lo.to(last_semi), kind))); } if self.token == token::CloseDelim(token::Brace) { self.error_outer_attrs(&attrs); return Ok(None); } // Remainder are line-expr stmts. let e = self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?; Ok(Some(self.mk_stmt(lo.to(e.span), StmtKind::Expr(e)))) } /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`. /// At this point, the `!` token after the path has already been eaten. fn parse_stmt_mac( &mut self, lo: Span, attrs: ThinVec<Attribute>, path: ast::Path, legacy_warnings: bool, ) -> PResult<'a, Option<Stmt>> { let args = self.parse_mac_args()?; let delim = args.delim(); let hi = self.prev_span; let style = if delim == token::Brace { MacStmtStyle::Braces </ins> } else { <del> // FIXME: Bad copy of attrs let old_directory_ownership = mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); let item = self.parse_item_(attrs.clone(), false, true)?; self.directory.ownership = old_directory_ownership; match item { Some(i) => Stmt { id: DUMMY_NODE_ID, span: lo.to(i.span), kind: StmtKind::Item(i), }, None => { let unused_attrs = |attrs: &[Attribute], s: &mut Self| { if !attrs.is_empty() { if s.prev_token_kind == PrevTokenKind::DocComment { s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit(); } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { s.span_err( s.token.span, "expected statement after outer attribute" ); } } }; // Do not attempt to parse an expression if we're done here. if self.token == token::Semi { unused_attrs(&attrs, self); self.bump(); let mut last_semi = lo; while self.token == token::Semi { last_semi = self.token.span; self.bump(); } // We are encoding a string of semicolons as an // an empty tuple that spans the excess semicolons // to preserve this info until the lint stage return Ok(Some(Stmt { id: DUMMY_NODE_ID, span: lo.to(last_semi), kind: StmtKind::Semi(self.mk_expr(lo.to(last_semi), ExprKind::Tup(Vec::new()), ThinVec::new() )), })); } </del> <ins> MacStmtStyle::NoBraces }; </ins> <del> if self.token == token::CloseDelim(token::Brace) { unused_attrs(&attrs, self); return Ok(None); } </del> <ins> let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription, }; </ins> <del> // Remainder are line-expr stmts. let e = self.parse_expr_res( Restrictions::STMT_EXPR, Some(attrs.into()))?; Stmt { id: DUMMY_NODE_ID, span: lo.to(e.span), kind: StmtKind::Expr(e), } } </del> <ins> let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof { StmtKind::Mac(P((mac, style, attrs.into()))) } // We used to incorrectly stop parsing macro-expanded statements here. // If the next token will be an error anyway but could have parsed with the // earlier behavior, stop parsing here and emit a warning to avoid breakage. else if legacy_warnings && self.token.can_begin_expr() && match self.token.kind { // These can continue an expression, so we can't stop parsing and warn. token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | token::BinOp(token::Minus) | token::BinOp(token::Star) | token::BinOp(token::And) | token::BinOp(token::Or) | token::AndAnd | token::OrOr | token::DotDot | token::DotDotDot | token::DotDotEq => false, _ => true, </ins> } <del> })) </del> <ins> { self.warn_missing_semicolon(); StmtKind::Mac(P((mac, style, attrs))) } else { // Since none of the above applied, this is an expression statement macro. let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new()); let e = self.maybe_recover_from_bad_qpath(e, true)?; let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?; let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; StmtKind::Expr(e) }; Ok(Some(self.mk_stmt(lo.to(hi), kind))) } /// Error on outer attributes in this context. /// Also error if the previous token was a doc comment. fn error_outer_attrs(&self, attrs: &[Attribute]) { if !attrs.is_empty() { if self.prev_token_kind == PrevTokenKind::DocComment { self.span_fatal_err(self.prev_span, Error::UselessDocComment).emit(); } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { self.span_err(self.token.span, "expected statement after outer attribute"); } } </ins> } /// Parses a local variable declaration.

Also, the problem isn't that people may choose to put just for the heck of it, but that they will unintentionally mutate something that was supposed to be immutable. And because it is being mutated, there is no warning, and they used because it is their default, it is their default because it gets rid of compiler errors that say they were trying to mutate things that are immutable even though they weren't supposed to mutate them in the first place. They will use because it is just as easy as making it immutable. So the problem is a bit more subtle than you seem to think.
Incorrect. Extreme brevity harms readability. See Perl. lol Readers would ignore the vs distinction far more often that vs , partially due to length difference, but works even better than say . It's true boilerplate often harms readability, but boilerplate requires some complexity be repeated, not merely the in . It harms readability even further if also works for , especially when you consider code readers need not actually know Rust. Rust syntax was designed largely to reduce cognitive load, not to reduce typing. We use , , and , not any shorter alternatives. And delegation RFCs have kinda given up the short syntaxes. I think Rust's omission of is now considered a mistake, but presumably helps C programmers. Rust has short keywords only really for fundamental "items" used repeatedly by basically every module. It's similar cognitive load if you write , , or , but actually just writing the shorter bare increases cognitive load. I think invokes the minor linguistic subtlety that variable means mutable binding, while acts like a common term for binding, which makes very slightly clearer.
The statement would be orthogonal to the current language in some sense though. is not a special syntax, but is composed of statement + pattern. It is in line with other places expects a pattern, where you can write , , or .
It seems unlikely to me that we would support as a short-hand. I'm personally opposed to it both because it adds unnecessary compiler complexity, stylistic schisms, and for the reasons outlined by However, I've taken the liberty of reusing this issue towards improved diagnostics: The idea here is to check . The idea here is to check: The relevant code is here: cc
claim
Error: Parsing assign command in failed: claim :)... Please let know if you're having trouble with this bot.