Commit Graph

1155 Commits

Author SHA1 Message Date
Deadbeef
f441fa08da Remove constness from ImplSource::Param 2023-08-14 02:17:30 +00:00
Matthias Krüger
a12c329b35
Rollup merge of #114667 - compiler-errors:issue-114664, r=davidtwco
Record binder for bare trait object in LifetimeCollectVisitor

The `LifetimeCollectVisitor` had a bug where it was not recording the binder of bate trait objects. This was uncovered in #114487, when I changed opaque type lowering to ICE if it encountered a captured fresh lifetime with no def-id to map back to: https://github.com/rust-lang/rust/pull/114487/files#diff-ad0c15bbde97a607d4758ec7eaf88248be5d6b8ae084dfc84127f81e3f7a9bb4R1585

Fixes #114664
2023-08-12 12:06:36 +02:00
Michael Goulet
94533d924e
Rollup merge of #114622 - petrochenkov:noplugin, r=oli-obk
rustc: Move `crate_types` and `stable_crate_id` from `Session` to `GlobalCtxt`

Removes two pieces of mutable state.
Follow up to https://github.com/rust-lang/rust/pull/114578.
2023-08-10 21:17:07 -07:00
Michael Goulet
bbe7a96bec Record binder for bare trait object in LifetimeCollectVisitor 2023-08-11 03:15:41 +00:00
Vadim Petrochenkov
0b89aac08d rustc: Move crate_types from Session to GlobalCtxt
Removes a piece of mutable state.
Follow up to #114578.
2023-08-09 14:17:54 +08:00
Seth Pellegrino
897c7bb23b feat: riscv-interrupt-{m,s} calling conventions
Similar to prior support added for the mips430, avr, and x86 targets
this change implements the rough equivalent of clang's
[`__attribute__((interrupt))`][clang-attr] for riscv targets, enabling
e.g.

```rust
static mut CNT: usize = 0;

pub extern "riscv-interrupt-m" fn isr_m() {
    unsafe {
        CNT += 1;
    }
}
```

to produce highly effective assembly like:

```asm
pub extern "riscv-interrupt-m" fn isr_m() {
420003a0:       1141                    addi    sp,sp,-16
    unsafe {
        CNT += 1;
420003a2:       c62a                    sw      a0,12(sp)
420003a4:       c42e                    sw      a1,8(sp)
420003a6:       3fc80537                lui     a0,0x3fc80
420003aa:       63c52583                lw      a1,1596(a0) # 3fc8063c <_ZN12esp_riscv_rt3CNT17hcec3e3a214887d53E.0>
420003ae:       0585                    addi    a1,a1,1
420003b0:       62b52e23                sw      a1,1596(a0)
    }
}
420003b4:       4532                    lw      a0,12(sp)
420003b6:       45a2                    lw      a1,8(sp)
420003b8:       0141                    addi    sp,sp,16
420003ba:       30200073                mret
```

(disassembly via `riscv64-unknown-elf-objdump -C -S --disassemble ./esp32c3-hal/target/riscv32imc-unknown-none-elf/release/examples/gpio_interrupt`)

This outcome is superior to hand-coded interrupt routines which, lacking
visibility into any non-assembly body of the interrupt handler, have to
be very conservative and save the [entire CPU state to the stack
frame][full-frame-save]. By instead asking LLVM to only save the
registers that it uses, we defer the decision to the tool with the best
context: it can more accurately account for the cost of spills if it
knows that every additional register used is already at the cost of an
implicit spill.

At the LLVM level, this is apparently [implemented by] marking every
register as "[callee-save]," matching the semantics of an interrupt
handler nicely (it has to leave the CPU state just as it found it after
its `{m|s}ret`).

This approach is not suitable for every interrupt handler, as it makes
no attempt to e.g. save the state in a user-accessible stack frame. For
a full discussion of those challenges and tradeoffs, please refer to
[the interrupt calling conventions RFC][rfc].

Inside rustc, this implementation differs from prior art because LLVM
does not expose the "all-saved" function flavor as a calling convention
directly, instead preferring to use an attribute that allows for
differentiating between "machine-mode" and "superivsor-mode" interrupts.

Finally, some effort has been made to guide those who may not yet be
aware of the differences between machine-mode and supervisor-mode
interrupts as to why no `riscv-interrupt` calling convention is exposed
through rustc, and similarly for why `riscv-interrupt-u` makes no
appearance (as it would complicate future LLVM upgrades).

[clang-attr]: https://clang.llvm.org/docs/AttributeReference.html#interrupt-risc-v
[full-frame-save]: 9281af2ecf/src/lib.rs (L440-L469)
[implemented by]: b7fb2a3fec/llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp (L61-L67)
[callee-save]: 973f1fe7a8/llvm/lib/Target/RISCV/RISCVCallingConv.td (L30-L37)
[rfc]: https://github.com/rust-lang/rfcs/pull/3246
2023-08-08 18:09:56 -07:00
bors
f88a8b71ce Auto merge of #114545 - fee1-dead-contrib:lower-impl-effect, r=oli-obk
correctly lower `impl const` to bind to host effect param

r? `@oli-obk`
2023-08-08 19:23:41 +00:00
Michael Goulet
8dcb8e0759 Unconditionally record lifetime mapping 2023-08-08 03:16:04 +00:00
Deadbeef
057be381c6 Fix ICE 2023-08-07 17:16:10 +00:00
Deadbeef
92f4c59e48 lower impl const to bind to host effect param 2023-08-06 13:34:53 +00:00
Michael Goulet
57a96893f6 Consolidate opaque ty and async fn lowering code 2023-08-05 16:53:13 +00:00
bors
e173a8e663 Auto merge of #112117 - bryangarza:track-caller-feature-gate, r=compiler-errors
Add separate feature gate for async fn track caller

This patch adds a feature gate `async_fn_track_caller` that is separate from `closure_track_caller`. This is to allow enabling `async_fn_track_caller` separately.

Fixes #110009
2023-08-04 22:17:59 +00:00
Nilstrieb
5706be1854 Improve spans for indexing expressions
Indexing is similar to method calls in having an arbitrary
left-hand-side and then something on the right, which is the main part
of the expression. Method calls already have a span for that right part,
but indexing does not. This means that long method chains that use
indexing have really bad spans, especially when the indexing panics and
that span in coverted into a panic location.

This does the same thing as method calls for the AST and HIR, storing an
extra span which is then put into the `fn_span` field in THIR.
2023-08-04 13:17:39 +02:00
Bryan Garza
673ab17c7f Add separate feature gate for async fn track caller
This patch adds a feature gate `async_fn_track_caller` that is separate from `closure_track_caller`. This is to allow enabling `async_fn_track_caller` separately.

Fixes #110009
2023-08-02 14:18:21 -07:00
León Orell Valerian Liehr
9213aec762
Lower generic const items to HIR 2023-07-28 22:21:40 +02:00
Matthias Krüger
af2b370100 more clippy::style fixes:
get_first
single_char_add_str
unnecessary_mut_passed
manual_map
manual_is_ascii_check
2023-07-23 23:39:04 +02:00
bors
c06b2b9117 Auto merge of #113847 - SparrowLii:path_clone, r=cjgillot
avoid clone path prefix when lowering to hir

Found this while trying to parallelize `lower_to_hir`.

When lowering to hir, `Nested` paths in `ast` will be split and the prefix segments will be cloned. This could be omited, since the only consequence is that the prefix segments in `Path`s in hir will have the same `HirId`s, and it seems harmless.

This simplifies the process of lowering to hir and avoids re-modification of `ResolverAstLowering`.

r? `@Aaron1011`
cc #99292
2023-07-21 11:02:47 +00:00
SparrowLii
0377945157 add comment for lower_use_tree
Signed-off-by: SparrowLii <liyuan179@huawei.com>
2023-07-19 16:48:33 +08:00
SparrowLii
c6f0a7c3c3 avoid clone path prefix when lowering to hir
Signed-off-by: SparrowLii <liyuan179@huawei.com>
2023-07-19 11:19:33 +08:00
Michael Goulet
603fd426df Properly document lifetime_mapping in OpaqueTy 2023-07-17 14:56:33 +00:00
Mark Rousskov
cc907f80b9 Re-format let-else per rustfmt update 2023-07-12 21:49:27 -04:00
Deadbeef
58c105af04 include host_effect_index in Generics 2023-07-04 17:21:52 +00:00
Deadbeef
1c837cb6f7 Add effects during lowering for ~const bounds 2023-07-04 11:47:45 +00:00
Santiago Pastorino
6f4a51e80e
Do not generate lifetime_mapping for RPIT no in_trait 2023-06-29 14:26:28 -03:00
Santiago Pastorino
4925b57782
Add bidirectional where clauses on RPITIT synthesized GATs 2023-06-29 14:26:26 -03:00
Santiago Pastorino
d70deac161
Intern OpaqueTy on ItemKind::OpaqueTy 2023-06-29 14:05:10 -03:00
Santiago Pastorino
72a32583d1
Reorganize opaque lowering code 2023-06-29 14:04:37 -03:00
Maybe Waffle
ccb71ff424 hir: Add Become expression kind 2023-06-26 08:56:32 +00:00
Maybe Waffle
d7713feb99 Syntatically accept become expressions 2023-06-19 12:54:34 +00:00
Camille GILLOT
ca4d0d4c24 Separate AnonConst from ConstBlock in HIR. 2023-06-02 21:25:18 +00:00
bors
498553fc04 Auto merge of #111235 - loongarch-rs:stabilize-asm, r=Amanieu
Stabilize inline asm for LoongArch64

This PR is used to tracking for stabilize `inline asm` for LoongArch64.

**Status**

- [x] https://github.com/rust-lang/rust/pull/111237
- [x] https://github.com/rust-lang/rust/pull/111332
- [ ] https://github.com/rust-lang/reference/pull/1357

Any others I missed?

r? `@Amanieu`
2023-05-29 13:31:53 +00:00
bors
c86212f9bc Auto merge of #111858 - clubby789:fluent-alphabetical, r=jyn514,compiler-errors
Ensure Fluent messages are in alphabetical order

Fixes #111847

This adds a tidy check to ensure Fluent messages are in alphabetical order, as well as sorting all existing messages. I think the error could be worded better, would appreciate suggestions.

<details>
<summary>Script used to sort files</summary>

```py
import sys
import re

fn = sys.argv[1]
with open(fn, 'r') as f:
    data = f.read().split("\n")

chunks = []
cur = ""
for line in data:
    if re.match(r"^([a-zA-Z0-9_]+)\s*=\s*", line):
        chunks.append(cur)
        cur = ""
    cur += line + "\n"
chunks.append(cur)
chunks.sort()

with open(fn, 'w') as f:
    f.write(''.join(chunks).strip("\n\n") + "\n")
```
</details>
2023-05-26 03:31:04 +00:00
clubby789
f97fddab91 Ensure Fluent messages are in alphabetical order 2023-05-25 23:49:35 +00:00
Michael Goulet
4692375389 Don't print newlines in APITs 2023-05-25 02:45:14 +00:00
Michael Woerister
a7d48800f9 Turn debugger_visualizers from feed- into regular query. 2023-05-16 18:50:36 +02:00
Oli Scherer
f08b517597 Require impl Trait in associated types to appear in method signatures 2023-05-12 10:24:03 +00:00
Matthias Krüger
363d158cd8
Rollup merge of #111215 - BoxyUwU:resolve_anon_consts_differently, r=cjgillot
Various changes to name resolution of anon consts

Sorry this PR is kind of all over the place ^^'

Fixes #111012

- Rewrites anon const nameres to all go through `fn resolve_anon_const` explicitly instead of `visit_anon_const` to ensure that we do not accidentally resolve anon consts as if they are allowed to use generics when they aren't. Also means that we dont have bits of code for resolving anon consts that will get out of sync (i.e. legacy const generics and resolving path consts that were parsed as type arguments)
- Renames two of the `LifetimeRibKind`, `AnonConst -> ConcreteAnonConst` and `ConstGeneric -> ConstParamTy`
- Noticed while doing this that under `generic_const_exprs` all lifetimes currently get resolved to errors without any error being emitted which was causing a bunch of tests to pass without their bugs having been fixed, incidentally fixed that in this PR and marked those tests as `// known-bug:`. I'm fine to break those since `generic_const_exprs` is a very unstable incomplete feature and this PR _does_ make generic_const_exprs "less broken" as a whole, also I can't be assed to figure out what the underlying causes of all of them are. This PR reopens #77357 #83993
- Changed `generics_of` to stop providing generics and predicates to enum variant discriminant anon consts since those are not allowed to use generic parameters
- Updated the error for non 'static lifetime in const arguments and the error for non 'static lifetime in const param tys to use `derive(Diagnostic)`

I have a vague idea why const-arg-in-const-arg.rs, in-closure.rs and simple.rs have started failing which is unfortunate since these were deliberately made to work, I think lifetime resolution being broken just means this regressed at some point and nobody noticed because the tests were not testing anything :( I'm fine breaking these too for the same reason as the tests for #77357 #83993. I couldn't get `// known-bug` to work for these ICEs and just kept getting different stderr between CI and local `--bless` so I just removed them and will create an issue to track re-adding (and fixing) the bugs if this PR lands.

r? `@cjgillot` cc `@compiler-errors`
2023-05-09 20:49:32 +02:00
Mara Bos
d5843ddaf1 Limit lifetime of format_args!() with inlined args. 2023-05-09 16:08:40 +02:00
WANG Rui
46252ef401 asm: Stabilize loongarch64 2023-05-08 23:46:48 +08:00
bors
ea0c22ea4f Auto merge of #106621 - ozkanonur:enable-elided-lifetimes-for-doctests, r=Mark-Simulacrum
enable `rust_2018_idioms` lint group for doctests

With this change, `rust_2018_idioms` lint group will be enabled for compiler/libstd doctests.

Resolves #106086
Resolves #99144

Signed-off-by: ozkanonur <work@onurozkan.dev>
2023-05-08 04:50:28 +00:00
ozkanonur
4e7c14fe9f enable rust_2018_idioms for doctests
Signed-off-by: ozkanonur <work@onurozkan.dev>
2023-05-07 00:12:29 +03:00
Boxy
442617c046 misc nameres changes for anon consts 2023-05-05 21:31:35 +01:00
Dylan DPC
80df4ab403
Rollup merge of #110791 - compiler-errors:negative-bounds, r=oli-obk
Implement negative bounds for internal testing purposes

Implements partial support the `!` negative polarity on trait bounds. This is incomplete, but should allow us to at least be able to play with the feature.

Not even gonna consider them as a public-facing feature, but I'm implementing them because would've been nice to have in UI tests, for example in #110671.
2023-05-04 00:17:23 +05:30
Nicholas Nethercote
6b62f37402 Restrict From<S> for {D,Subd}iagnosticMessage.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.

This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.

As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-05-03 08:44:39 +10:00
Michael Goulet
6e01e910cb Implement negative bounds 2023-05-02 22:36:24 +00:00
Matthias Krüger
1b262b8b56
Rollup merge of #110823 - compiler-errors:tweak-await-span, r=b-naber
Tweak await span to not contain dot

Fixes a discrepancy between method calls and await expressions where the latter are desugared to have a span that *contains* the dot (i.e. `.await`) but method call identifiers don't contain the dot. This leads to weird suggestions suggestions in borrowck -- see linked issue.

Fixes #110761

This mostly touches a bunch of tests to tighten their `await` span.
2023-05-01 01:09:47 +02:00
Matthias Krüger
cf911ac757
Rollup merge of #110766 - m-ou-se:fmt-rt, r=jyn514
More core::fmt::rt cleanup.

- Removes the `V1` suffix from the `Argument` and `Flag` types.

- Moves more of the format_args lang items into the `core::fmt::rt` module. (The only remaining lang item in `core::fmt` is `Arguments` itself, which is a public type.)

Part of https://github.com/rust-lang/rust/issues/99012

Follow-up to https://github.com/rust-lang/rust/pull/110616
2023-04-28 07:34:02 +02:00
Michael Goulet
6d6c904431 Make async removal span more resilient to macro expansions 2023-04-27 18:25:07 +00:00
Michael Goulet
f0fc4f9acf Tweak await span 2023-04-27 17:18:11 +00:00
Michael Goulet
c18e7b765f IntoFuture::into_future is no longer unstable 2023-04-26 22:44:18 +00:00
Mara Bos
0a28977740 Restructure std::fmt::rt a bit.
This moves more of the internal/lang items into the private rt module.
2023-04-24 16:16:14 +02:00
Mara Bos
5cf3cbf3b7 Remove "V1" from ArgumentsV1 and FlagsV1. 2023-04-24 16:16:14 +02:00
Maybe Waffle
e496fbec92 Split {Idx, IndexVec, IndexSlice} into their own modules 2023-04-24 13:53:35 +00:00
Nilstrieb
74e31ec64c Also arena-allocate ast::MacroDef to make Item: Copy 2023-04-22 23:00:38 +02:00
DrMeepster
511e457c4b offset_of 2023-04-21 02:14:02 -07:00
Mara Bos
441682cca9 Update comments in format args lowering.
These lang items have been moved/renamed.
2023-04-20 18:09:32 +02:00
bors
d7f9e81650 Auto merge of #110407 - Nilstrieb:fluent-macro, r=davidtwco
Add `rustc_fluent_macro` to decouple fluent from `rustc_macros`

Fluent, with all the icu4x it brings in, takes quite some time to compile. `fluent_messages!` is only needed in further downstream rustc crates, but is blocking more upstream crates like `rustc_index`. By splitting it out, we allow `rustc_macros` to be compiled earlier, which speeds up `x check compiler` by about 5 seconds (and even more after the needless dependency on `serde_json` is removed from `rustc_data_structures`).
2023-04-19 08:26:47 +00:00
Matthias Krüger
a184557d1d
Rollup merge of #110451 - WaffleLapkin:ensure_return_elem, r=scottmcm
Minor changes to `IndexVec::ensure_contains_elem` & related methods

r? `@scottmcm`
2023-04-19 06:35:34 +02:00
Nilstrieb
b5d3d970fa Add rustc_fluent_macro to decouple fluent from rustc_macros
Fluent, with all the icu4x it brings in, takes quite some time to
compile. `fluent_messages!` is only needed in further downstream rustc
crates, but is blocking more upstream crates like `rustc_index`. By
splitting it out, we allow `rustc_macros` to be compiled earlier, which
speeds up `x check compiler` by about 5 seconds (and even more after the
needless dependency on `serde_json` is removed from
`rustc_data_structures`).
2023-04-18 18:56:22 +00:00
Maybe Waffle
9534541dd4 Use Item::expect_* and ImplItem::expect_* more 2023-04-17 18:00:27 +00:00
Maybe Waffle
e1cd99f6ff Make IndexVec::ensure_contains_elem return a reference to the element 2023-04-17 14:23:46 +00:00
bors
53ac4f8e2f Auto merge of #109588 - Nilstrieb:dropless-expr, r=compiler-errors
Alloc `hir::Lit` in an arena to remove the destructor from `Expr`

This allows allocating `Expr`s into a dropless arena, which is useful for using length prefixed thing slices in HIR, since these can only be allocated in the dropless arena and not in a typed arena.
2023-04-17 05:12:12 +00:00
Nilstrieb
34ed5c3efc Alloc hir::Lit in an arena to remove the destructor from Expr
This allows allocating `Expr`s into a dropless arena, which is useful
for using length prefixed thing slices in HIR, since these can only be
allocated in the dropless arena and not in a typed arena. This is
something I'm working on.
2023-04-16 15:35:51 +00:00
Matthias Krüger
bcc15bba95 use matches! macro in more places 2023-04-16 12:08:30 +02:00
Matthias Krüger
a34bcd70b2
Rollup merge of #110203 - compiler-errors:rtn-dots, r=eholk
Remove `..` from return type notation

`@nikomatsakis` and I decided that using `..` in the return-type notation syntax is probably overkill.

r? `@eholk` since you reviewed the last one

Since this is piggybacking now totally off of a pre-existing syntax (parenthesized generics), let me know if you need any explanation of the logic here, since it's a bit more complicated now.
2023-04-12 20:56:22 +02:00
Michael Goulet
24cbf81b85 Remove .. from return type notation 2023-04-10 22:19:46 +00:00
DaniPopes
677357d32b
Fix typos in compiler 2023-04-10 22:02:52 +02:00
Oli Scherer
373807a95c Rename ast::Static to ast::StaticItem to match ast::ConstItem 2023-04-04 15:34:40 +00:00
Oli Scherer
4bebdd7104 box a bunch of large types 2023-04-04 13:58:50 +00:00
Oli Scherer
ec74653652 Split out ast::ItemKind::Const into its own struct 2023-04-04 09:44:50 +00:00
Oli Scherer
e3828777a6 rust-analyzer guided tuple field to named field 2023-04-04 09:44:50 +00:00
Oli Scherer
b08a557f80 rust-analyzer guided enum variant structification 2023-04-04 09:44:45 +00:00
Scott McMurray
a2ee7592d6 Use &IndexSlice instead of &IndexVec where possible
All the same reasons as for `[T]`: more general, less pointer chasing, and `&mut IndexSlice` emphasizes that it doesn't change *length*.
2023-04-02 17:35:37 -07:00
bors
7402519c63 Auto merge of #109010 - compiler-errors:rtn, r=eholk
Initial support for return type notation (RTN)

See: https://smallcultfollowing.com/babysteps/blog/2023/02/13/return-type-notation-send-bounds-part-2/

1. Only supports `T: Trait<method(): Send>` style bounds, not `<T as Trait>::method(): Send`. Checking validity and injecting an implicit binder for all of the late-bound method generics is harder to do for the latter.
    * I'd add this in a follow-up.
3. ~Doesn't support RTN in general type position, i.e. no `let x: <T as Trait>::method() = ...`~
    * I don't think we actually want this.
5. Doesn't add syntax for "eliding" the function args -- i.e. for now, we write `method(): Send` instead of `method(..): Send`.
    * May be a hazard if we try to add it in the future. I'll probably add it in a follow-up later, with a structured suggestion to change `method()` to `method(..)` once we add it.
7. ~I'm not in love with the feature gate name 😺~
    * I renamed it to `return_type_notation` ✔️

Follow-up PRs will probably add support for `where T::method(): Send` bounds. I'm not sure if we ever want to support return-type-notation in arbitrary type positions. I may also make the bounds require `..` in the args list later.

r? `@ghost`
2023-03-31 18:04:12 +00:00
Dylan DPC
a3eb2f0f22
Rollup merge of #109664 - m-ou-se:format-args-placeholder-span, r=oli-obk
Use span of placeholders in format_args!() expansion.

`format_args!("{}", x)` expands to something that contains `Argument::new_display(&x)`. That entire expression was generated with the span of `x`.

After this PR, `&x` uses the span of `x`, but the `new_display` call uses the span of the `{}` placeholder within the format string. If an implicitly captured argument was used like in `format_args!("{x}")`, both use the span of the `{x}` placeholder.

This fixes https://github.com/rust-lang/rust/issues/109576, and also allows for more improvements to similar diagnostics in the future, since the usage of `x` can now be traced to the exact `{}` placeholder that required it to be `Display` (or `Debug` etc.)
2023-03-29 14:07:28 +05:30
Michael Goulet
8b592db27a Add (..) syntax for RTN 2023-03-28 01:14:28 +00:00
Michael Goulet
104aacb49f Add tests and error messages 2023-03-28 01:02:15 +00:00
Michael Goulet
773e8a5ad1 RTN 2023-03-28 01:02:15 +00:00
Michael Goulet
f50c1e1f05 ParenthesizedGenericArgs::{Ok -> ParenSugar} 2023-03-28 01:02:15 +00:00
Guillaume Gomez
b1e8be783f
Rollup merge of #109354 - Swatinem:rm-closureid, r=compiler-errors
Remove the `NodeId` of `ast::ExprKind::Async`

This is a followup to https://github.com/rust-lang/rust/pull/104833#pullrequestreview-1314537416.

In my original attempt, I was using `LoweringContext::expr`, which was not correct as it creates a fresh `DefId`.
It now uses the correct `DefId` for the wrapping `Expr`, and also makes forwarding `#[track_caller]` attributes more explicit.
2023-03-27 18:56:19 +02:00
Mara Bos
1b3fda4978 Use span of placeholders in format_args!() expansion. 2023-03-27 14:53:48 +02:00
Vadim Petrochenkov
67a2c5bec8 rustc: Remove unused Session argument from some attribute functions 2023-03-22 13:55:55 +04:00
Arpad Borsos
c8ead2e693
Remove the NodeId of ast::ExprKind::Async 2023-03-19 19:01:31 +01:00
Mara Bos
995e57b89e Gate fmt args flattening behind -Zflatten-format-args. 2023-03-16 11:21:50 +01:00
Mara Bos
f2f6bcc499 Don't allow new const panic through format flattening.
panic!("a {}", "b") is still not allowed in const,
even if the hir flattens to panic!("a b").
2023-03-16 11:21:50 +01:00
Mara Bos
6a535dfff4 Also inline integer literals into format_args!(). 2023-03-16 11:21:50 +01:00
Mara Bos
df8c14ca61 Check all arg indexes before removing inlined format args. 2023-03-16 11:21:50 +01:00
Mara Bos
0554401fcc Remove unreachable branch in format_args ast lowering. 2023-03-16 11:21:48 +01:00
Mara Bos
b6c988b041 Fix argument index remapping in format_args flattening. 2023-03-16 11:19:31 +01:00
Mara Bos
b7678d48b8 Only inline {} string literals in format_args.
Placeholders like {:123} would incorrectly get inlined.
2023-03-16 11:19:31 +01:00
Mara Bos
caa6ba9e86 Support flattening/inlining format_args through & and ().
E.g. format_args!("{}", &(format_args!("abc"))).
2023-03-16 11:19:31 +01:00
Mara Bos
85ef2f0cfe Inline string literals into format_args!(). 2023-03-16 11:19:31 +01:00
Mara Bos
94ad7e881d Coalesce adjacent literal pieces in expand_format_args. 2023-03-16 11:19:31 +01:00
Mara Bos
a769b30a93 Flatten nested format_args!() into one. 2023-03-16 11:19:30 +01:00
bors
669e751639 Auto merge of #104833 - Swatinem:async-identity-future, r=compiler-errors
Remove `identity_future` indirection

This was previously needed because the indirection used to hide some unexplained lifetime errors, which it turned out were related to the `min_choice` algorithm.

Removing the indirection also solves a couple of cycle errors, large moves and makes async blocks support the `#[track_caller]`annotation.

Fixes https://github.com/rust-lang/rust/issues/104826.
2023-03-14 10:12:58 +00:00
bors
f1b1ed7e18 Auto merge of #108471 - clubby789:unbox-the-syntax, r=Nilstrieb,est31
Remove `box_syntax`

r? `@Nilstrieb`

This removes the feature `box_syntax`, which allows the use of `box <expr>` to create a Box, and finalises removing use of the feature from the compiler. `box_patterns` (allowing the use of `box <pat>` in a pattern) is unaffected.
It also removes `ast::ExprKind::Box` - the only way to create a 'box' expression now is with the rustc-internal `#[rustc_box]` attribute.
As a temporary measure to help users move away, `box <expr>` now parses the inner expression, and emits a `MachineApplicable` lint to replace it with `Box::new`

Closes #49733
2023-03-13 10:41:50 +00:00
bors
f41927f309 Auto merge of #108820 - cjgillot:ensure-on-disk, r=oli-obk
Ensure value is on the on-disk cache before returning from `ensure()`.

The current logic for `ensure()` a query just checks that the node is green in the dependency graph.
However, a lot of places use `ensure()` to prevent the query from being called later. This is the case before stealing a query result.

If the query is actually green but the value is not available in the on-disk cache, `ensure` would return, but a subsequent call to the full query would run the code, and attempt to read from a stolen value.

This PR conforms the query system to the usage by checking whether the queried value is loadable from disk before returning.

Sadly, I can't manage to craft a proper test...

Should fix all instances of "attempted to read from stolen value".
2023-03-12 14:00:28 +00:00
clubby789
0932452fa4 Remove box_syntax from AST and use in tools 2023-03-12 13:19:46 +00:00
bors
150cb38147 Auto merge of #108794 - nnethercote:avoid-unnecessary-hashing, r=cjgillot
Avoid unnecessary hashing

I noticed some stable hashing being done in a non-incremental build. It turns out that some of this is necessary to compute the crate hash, but some of it is not. Removing the unnecessary hashing is a perf win.

r? `@cjgillot`
2023-03-12 06:48:30 +00:00
Camille GILLOT
e955ec0908 Use ensure_with_value in a few more places. 2023-03-11 22:42:13 +00:00
est31
7e2ecb3cd8 Simplify message paths
This makes it easier to open the messages file while developing on features.

The commit was the result of automatted changes:

for p in compiler/rustc_*; do mv $p/locales/en-US.ftl $p/messages.ftl; rmdir $p/locales; done

for p in compiler/rustc_*; do sed -i "s#\.\./locales/en-US.ftl#../messages.ftl#" $p/src/lib.rs; done
2023-03-11 22:51:57 +01:00
Matthias Krüger
df50001c7d
Rollup merge of #108806 - cjgillot:query-lints, r=davidtwco
Querify register_tools and post-expansion early lints

The 2 extra queries correspond to code that happen before and after macro expansion, and don't need the resolver to exist.
2023-03-11 15:43:15 +01:00
Arpad Borsos
9f03cfc207
Remove identity_future indirection
This was previously needed because the indirection used to hide some unexplained lifetime errors, which it turned out were related to the `min_choice` algorithm.

Removing the indirection also solves a couple of cycle errors, large moves and makes async blocks support the `#[track_caller]` annotation.
2023-03-08 15:37:14 +01:00
Nicholas Nethercote
9570023ce1 Only compute the crate hash when necessary.
The crate hash is needed:
- if debug assertions are enabled, or
- if incr. comp. is enabled, or
- if metadata is being generated, or
- if `-C instrumentation-coverage` is enabled.

This commit avoids computing the crate hash when these conditions are
all false, such as when doing a release build of a binary crate.

It uses `Option` to store the hashes when needed, rather than
computing them on demand, because some of them are needed in multiple
places and computing them on demand would make compilation slower.

The commit also removes `Owner::hash_without_bodies`. There is no
benefit to pre-computing that one, it can just be done in the normal
fashion.
2023-03-08 09:30:22 +11:00
Camille GILLOT
c90fc105cb Querify early_lint_checks. 2023-03-06 11:26:29 +00:00
bors
0d439f8181 Auto merge of #108351 - petrochenkov:rmdit, r=cjgillot
rustc_middle: Remove trait `DefIdTree`

This trait was a way to generalize over both `TyCtxt` and `Resolver`, but now `Resolver` has access to `TyCtxt`, so this trait is no longer necessary.
2023-03-05 10:37:02 +00:00
est31
ff2c609d66 Match unmatched backticks in compiler/ that are part of rustdoc 2023-03-03 08:39:00 +01:00
Vadim Petrochenkov
c83553da31 rustc_middle: Remove trait DefIdTree
This trait was a way to generalize over both `TyCtxt` and `Resolver`, but now `Resolver` has access to `TyCtxt`, so this trait is no longer necessary.
2023-03-02 23:46:44 +04:00
Matthias Krüger
c9c9283c6a
Rollup merge of #108516 - clubby789:rustc-box-restrict, r=compiler-errors
Restrict `#[rustc_box]` to `Box::new` calls

Currently, `#[rustc_box]` can be applied to any call expression with a single argument. This PR only allows it to be applied to calls to `Box::new`
2023-03-02 07:24:00 +01:00
clubby789
d845769557 Restrict #[rustc_box] to Box::new calls 2023-03-02 02:42:19 +00:00
Michael Goulet
f851a8aefa Only look for param in generics if it actually comes from generics 2023-02-28 06:27:56 +00:00
Michael Goulet
c0e58c3420 Add ErrorGuaranteed to HIR ExprKind::Err 2023-02-25 19:46:36 +00:00
Michael Goulet
a772a6fc2a Add ErrorGuaranteed to HIR TyKind::Err 2023-02-25 19:46:36 +00:00
Michael Goulet
b14eb0c497 pluralize stuff 2023-02-22 21:52:26 +00:00
Michael Goulet
deb135748d Suppress duplicated errors for associated type bounds in object types 2023-02-22 21:52:26 +00:00
Michael Goulet
e7c490892f Move associated type bounds check to ast lowering
This makes the check for when associated type bounds more accurate
2023-02-22 20:18:14 +00:00
David Wood
d1fcf61117 errors: generate typed identifiers in each crate
Instead of loading the Fluent resources for every crate in
`rustc_error_messages`, each crate generates typed identifiers for its
own diagnostics and creates a static which are pulled together in the
`rustc_driver` crate and provided to the diagnostic emitter.

Signed-off-by: David Wood <david.wood@huawei.com>
2023-02-22 09:15:53 +00:00
Nicholas Nethercote
1807027248 Use ThinVec in ast::AngleBracketedArgs. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote
4143b101f9 Use ThinVec in various AST types.
This commit changes the sequence parsers to produce `ThinVec`, which
triggers numerous conversions.
2023-02-21 11:51:56 +11:00
Nicholas Nethercote
dd7aff5cc5 Use ThinVec in ast::Generics and related types. 2023-02-21 11:51:55 +11:00
Nicholas Nethercote
06228d6e93 Upgrade thin-vec from 0.2.9 to 0.2.12.
Because 0.2.10 added supports for `ThinVec::splice`, and 0.2.12 is the
latest release.
2023-02-21 11:51:55 +11:00
Jacob Pratt
378c4ab9ab
Make public API, docs algorithm-agnostic 2023-02-19 04:11:10 +00:00
Michael Goulet
3f80017f03 Better label for illegal impl trait types 2023-02-14 23:12:27 +00:00
klensy
4f5f9f0a13 remove unused imports 2023-02-06 17:40:18 +03:00
Camille GILLOT
15d6325747 Remove HirId -> LocalDefId map from HIR. 2023-01-28 09:55:26 +00:00
Camille GILLOT
3175d03d3b Take a LocalDefId in hir::Visitor::visit_fn. 2023-01-28 09:51:50 +00:00
Mara Bos
21cf9dbc85 Destructure format_options in make_format_spec. 2023-01-27 11:43:38 +01:00
Mara Bos
0abf8a0617 Replace format flags u32 by enums and bools. 2023-01-27 08:53:39 +01:00
bors
d7948c843d Auto merge of #106812 - oli-obk:output_filenames, r=petrochenkov
make `output_filenames` a real query

part of #105462

This may be a perf regression and is not obviously the right way forward. We may store this information in the resolver after freezing it for example.
2023-01-26 20:32:28 +00:00
bors
3e97763872 Auto merge of #106745 - m-ou-se:format-args-ast, r=oli-obk
Move format_args!() into AST (and expand it during AST lowering)

Implements https://github.com/rust-lang/compiler-team/issues/541

This moves FormatArgs from rustc_builtin_macros to rustc_ast_lowering. For now, the end result is the same. But this allows for future changes to do smarter things with format_args!(). It also allows Clippy to directly access the ast::FormatArgs, making things a lot easier.

This change turns the format args types into lang items. The builtin macro used to refer to them by their path. After this change, the path is no longer relevant, making it easier to make changes in `core`.

This updates clippy to use the new language items, but this doesn't yet make clippy use the ast::FormatArgs structure that's now available. That should be done after this is merged.
2023-01-26 12:44:47 +00:00
Oli Scherer
d924a8ca59 Evaluate output_filenames before one of its dependencies gets stolen 2023-01-23 14:22:33 +00:00
Matthias Krüger
68f12338af
Rollup merge of #104505 - WaffleLapkin:no-double-spaces-in-comments, r=jackh726
Remove double spaces after dots in comments

Most of the comments do not have double spaces, so I assume these are typos.
2023-01-17 20:21:25 +01:00
Maybe Waffle
6a28fb42a8 Remove double spaces after dots in comments 2023-01-17 08:09:33 +00:00
Mara Bos
9f2ba59647 Change not-so-permanent link to a more permanent link. 2023-01-13 22:23:59 +01:00
bors
0b90256ada Auto merge of #106776 - oli-obk:om_nom_nom_nom_nom, r=cjgillot
Feed a bunch of queries instead of tracking fields on TyCtxt

r? `@cjgillot`

pulled out of https://github.com/rust-lang/rust/pull/105462
2023-01-13 13:57:21 +00:00
Mara Bos
cd8ec6c787 Add note on optimization in format args ast lowering. 2023-01-12 20:14:31 +01:00
Mara Bos
8a23ad17f8 Update comments in rustc_ast_lowering/src/format.rs. 2023-01-12 20:06:38 +01:00
Mara Bos
298e160dc8 Assume there are no macros left in ast lowering. 2023-01-12 19:58:49 +01:00
Oli Scherer
33b6a7790e Remove untracked_crate field and instead pass it along with the resolver. 2023-01-12 17:14:17 +00:00
Deadbeef
4fb10c0ce4 parse const closures 2023-01-12 02:28:37 +00:00
Mara Bos
bcf388f4ac Update outdated comment. 2023-01-12 00:39:46 +01:00
Mara Bos
a4dbcb525b Expand format_args!() in rust_ast_lowering. 2023-01-12 00:25:45 +01:00
Mara Bos
3c45176592 Expose some LoweringContext methods. 2023-01-11 21:44:19 +01:00
Mara Bos
43105c10d2 Add some helper functions to LoweringContext. 2023-01-11 21:44:19 +01:00
Albert Larsan
40ba0e84d5
Change src/test to tests in source files, fix tidy and tests 2023-01-11 09:32:13 +00:00
nils
fd7a159710 Fix uninlined_format_args for some compiler crates
Convert all the crates that have had their diagnostic migration
completed (except save_analysis because that will be deleted soon and
apfloat because of the licensing problem).
2023-01-05 19:01:12 +01:00
bors
fb9dfa8cef Auto merge of #84762 - cjgillot:resolve-span-opt, r=petrochenkov
Encode spans relative to the enclosing item -- enable on nightly

Follow-up to #84373 with the flag `-Zincremental-relative-spans` set by default.

This PR seeks to remove one of the main shortcomings of incremental: the handling of spans.
Changing the contents of a function may require redoing part of the compilation process for another function in another file because of span information is changed.
Within one file: all the spans in HIR change, so typechecking had to be re-done.
Between files: spans of associated types/consts/functions change, so type-based resolution needs to be re-done (hygiene information is stored in the span).

The flag `-Zincremental-relative-spans` encodes local spans relative to the span of an item, stored inside the `source_span` query.

Trap: stashed diagnostics are referenced by the "raw" span, so stealing them requires to remove the span's parent.

In order to avoid too much traffic in the span interner, span encoding uses the `ctxt_or_tag` field to encode:
- the parent when the `SyntaxContext` is 0;
- the `SyntaxContext` when the parent is `None`.
Even with this, the PR creates a lot of traffic to the Span interner, when a Span has both a LocalDefId parent and a non-root SyntaxContext. They appear in lowering, when we add a parent to all spans, including those which come from macros, and during inlining when we mark inlined spans.

The last commit changes how queries of `LocalDefId` manage their cache. I can put this in a separate PR if required.

Possible future directions:
- validate that all spans are marked in HIR validation;
- mark macro-expanded spans relative to the def-site and not the use-site.
2023-01-02 13:10:16 +00:00
Matthias Krüger
c610aeb592
Rollup merge of #106221 - Nilstrieb:rptr-more-like-ref-actually, r=compiler-errors
Rename `Rptr` to `Ref` in AST and HIR

The name makes a lot more sense, and `ty::TyKind` calls it `Ref` already as well.
2022-12-29 13:16:04 +01:00
Nilstrieb
9067e4417e Rename Rptr to Ref in AST and HIR
The name makes a lot more sense, and `ty::TyKind` calls it `Ref` already
as well.
2022-12-28 18:52:36 +01:00
Michael Goulet
18bf19c3a9
Rollup merge of #106064 - lukas-code:outlives-macro, r=cjgillot
Partially fix `explicit_outlives_requirements` lint in macros

Show the suggestion if and only if the bounds are from the same source context.

fixes https://github.com/rust-lang/rust/issues/106044
fixes https://github.com/rust-lang/rust/issues/106063
2022-12-27 12:33:35 -08:00
Lukas Markeffsky
1eba6c404f address review comments + better tests 2022-12-26 16:35:21 +01:00
Matthias Krüger
23967a9990
Rollup merge of #106137 - matthiaskrgr:clippy_style, r=jyn514
fix more clippy::style findings

match_result_ok
obfuscated_if_else
single_char_add
writeln_empty_string
collapsible_match
iter_cloned_collect
unnecessary_mut_passed

r? `@compiler-errors`
2022-12-25 22:15:00 +01:00
Matthias Krüger
44065e4184
Rollup merge of #105375 - WaffleLapkin:docfix, r=cjgillot
Fix an outdated comment mentioning parameter that doesn't exist anymore

I'm not too familiar with the code in question, but from what I see I think the new comment makes sense.

r? `@cjgillot` (you touched these arguments lately https://github.com/rust-lang/rust/pull/91557/files#diff-ad0c15bbde97a607d4758ec7eaf88248be5d6b8ae084dfc84127f81e3f7a9bb4L1702, https://github.com/rust-lang/rust/pull/104048/files#diff-ad0c15bbde97a607d4758ec7eaf88248be5d6b8ae084dfc84127f81e3f7a9bb4L1682)
2022-12-25 22:14:59 +01:00
Camille GILLOT
40c8165395 Only enable relative span hashing on nightly. 2022-12-25 18:48:36 +00:00
Camille GILLOT
65f342daea Enable relative span hashing. 2022-12-25 18:48:31 +00:00
Matthias Krüger
d8874f259a fix more clippy::style findings
match_result_ok
obfuscated_if_else
single_char_add
writeln_empty_string
collapsible_match
iter_cloned_collect
unnecessary_mut_passed
2022-12-25 17:32:26 +01:00
Matthias Krüger
d23cb738d2
Rollup merge of #105975 - jeremystucki:rustc-remove-needless-lifetimes, r=eholk
rustc: Remove needless lifetimes
2022-12-24 00:31:41 +01:00
Lukas Markeffsky
94d6245003 Fix explicit_outlives_requirements lint in macros
Show the suggestion if and only if the bounds are from the same source context.
2022-12-22 22:04:40 +01:00
Bryan Garza
ccbba0a60e Update track_caller tests; run fmt 2022-12-21 23:25:08 +00:00
Bryan Garza
9650a4168f Improve code based on feedback.
This patch improves the readability of some of the code by using
if-let-chains. Also, make use of the `add_feature_diagnostics` function.
2022-12-21 03:47:27 +00:00
Bryan Garza
2d060034f0 Update track_caller logic/lint after rebase 2022-12-21 03:39:33 +00:00
Jeremy Stucki
3dde32ca97
rustc: Remove needless lifetimes 2022-12-20 22:10:40 +01:00
Andrew Pollack
8441ca5d81
Revert "Replace usage of ResumeTy in async lowering with Context" 2022-12-19 11:24:59 -08:00
Dylan DPC
a9005b6cc0
Rollup merge of #105864 - matthiaskrgr:compl, r=Nilstrieb
clippy::complexity fixes

filter_next
needless_question_mark
bind_instead_of_map
manual_find
derivable_impls
map_identity
redundant_slicing
skip_while_next
unnecessary_unwrap
needless_bool

r? `@compiler-errors`
2022-12-19 14:41:35 +05:30
Matthias Krüger
1da4a49912 clippy::complexity fixes
filter_next
needless_question_mark
bind_instead_of_map
manual_find
derivable_impls
map_identity
redundant_slicing
skip_while_next
unnecessary_unwrap
needless_bool
2022-12-19 00:04:28 +01:00
Nilstrieb
d59a2ac2bc Revert "Introduce lowering_arena to avoid creating AST nodes on the fly"
This reverts commit d9a1faaa9c.

This was originally part of a larger PR that has now been closed as a
different approach is taken now.
2022-12-18 20:28:59 +01:00
Matthias Krüger
5e38e702aa
Rollup merge of #105464 - nbdd0121:hir, r=compiler-errors
Support #[track_caller] on async closures

Follow up on #105180

r? ```@compiler-errors```
cc ```@cjgillot```
2022-12-13 19:57:10 +01:00
bors
2cd2070af7 Auto merge of #105160 - nnethercote:rm-Lit-token_lit, r=petrochenkov
Remove `token::Lit` from `ast::MetaItemLit`.

Currently `ast::MetaItemLit` represents the literal kind twice. This PR removes that redundancy. Best reviewed one commit at a time.

r? `@petrochenkov`
2022-12-12 05:16:50 +00:00
KaDiWa
9bc69925cb
compiler: remove unnecessary imports and qualified paths 2022-12-10 18:45:34 +01:00
Gary Guo
6275b045d7 Move paren expr and loop HIR lowering 2022-12-08 17:28:21 +00:00
Gary Guo
0c0fb226bb Support #[track_caller] on async closures 2022-12-08 17:23:44 +00:00
Matthias Krüger
2fbde2b028
Rollup merge of #105408 - cuviper:help-rpitirpit, r=compiler-errors
Add help for `#![feature(impl_trait_in_fn_trait_return)]`

This adds a new variant `ImplTraitContext::FeatureGated`, so we can
generalize the help for `return_position_impl_trait_in_trait` to also
work for `impl_trait_in_fn_trait_return`.

cc #99697
2022-12-08 12:57:31 +01:00
Matthias Krüger
95da525982
Rollup merge of #105343 - nbdd0121:hir, r=fee1-dead
Simplify attribute handling in rustc_ast_lowering

Given that attributes is stored in a separate BTreeMap, it's not necessary to pass it in when constructing `hir::Expr`. We can just construct `hir::Expr` and then call `self.lower_attrs` later if it needs attributes.

As most desugaring code don't use attributes, this allows some code cleanup.
2022-12-07 15:39:07 +01:00
Josh Stone
e9dd59131b Add help for #![feature(impl_trait_in_fn_trait_return)]
This adds a new variant `ImplTraitContext::FeatureGated`, so we can
generalize the help for `return_position_impl_trait_in_trait` to also
work for `impl_trait_in_fn_trait_return`.
2022-12-06 17:53:50 -08:00
Maybe Waffle
d87a8349ee Fix an outdated comment mentioning parameter that doesn't exist anymore 2022-12-06 14:32:14 +00:00
Arpad Borsos
cf031a3355
Replace usage of ResumeTy in async lowering with Context
Replaces using `ResumeTy` / `get_context` in favor of using `&'static mut Context<'_>`.

Usage of the `'static` lifetime here is technically "cheating", and replaces
the raw pointer in `ResumeTy` and the `get_context` fn that pulls the
correct lifetimes out of thin air.
2022-12-06 10:16:23 +01:00
Gary Guo
c559cf62c2 Simplify attribute handling in rustc_ast_lowering
Given that attributes is stored in a separate BTreeMap, it's not necessary
to pass it in when constructing `hir::Expr`. We can just construct
`hir::Expr` and then call `self.lower_attrs` later if it needs attributes.

As most desugaring code don't use attributes, this allows some code cleanup.
2022-12-06 01:05:17 +00:00
Matthias Krüger
78cf0b916a
Rollup merge of #105180 - nbdd0121:async_track_caller, r=compiler-errors
Use proper HirId for async track_caller attribute check

Fix #105134
2022-12-05 20:43:42 +01:00
Gary Guo
34c377335b Add fixme note 2022-12-05 03:18:26 +00:00
Matthias Krüger
c89bff29e5
Rollup merge of #104199 - SarthakSingh31:issue-97417-1, r=cjgillot
Keep track of the start of the argument block of a closure

This removes a call to `tcx.sess.source_map()` from [compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs](https://github.com/rust-lang/rust/compare/master...SarthakSingh31:issue-97417-1?expand=1#diff-8406bbc0d0b43d84c91b1933305df896ecdba0d1f9269e6744f13d87a2ab268a) as required by #97417.

VsCode automatically applied `rustfmt` to the files I edited under `src/tools`. I can undo that if its a problem.

r? `@cjgillot`
2022-12-03 17:37:41 +01:00
bors
703d95e183 Auto merge of #105133 - oli-obk:promoted_def_ids, r=cjgillot
Ensure query backtraces work for `DefId`s created after ast lowering

r? `@cjgillot`
2022-12-03 08:17:46 +00:00
Gary Guo
ec4080b236 Fix async track caller for assoc fn and trait impl fn 2022-12-02 16:47:57 +00:00
Gary Guo
4c73b64632 Use proper HirId for async track_caller attribute check 2022-12-02 16:47:57 +00:00
Nicholas Nethercote
2fd364acff Remove token::Lit from ast::MetaItemLit.
`token::Lit` contains a `kind` field that indicates what kind of literal
it is. `ast::MetaItemLit` currently wraps a `token::Lit` but also has
its own `kind` field. This means that `ast::MetaItemLit` encodes the
literal kind in two different ways.

This commit changes `ast::MetaItemLit` so it no longer wraps
`token::Lit`. It now contains the `symbol` and `suffix` fields from
`token::Lit`, but not the `kind` field, eliminating the redundancy.
2022-12-02 13:49:19 +11:00
Nicholas Nethercote
a7f35c42d4 Add StrStyle to ast::LitKind::ByteStr.
This is required to distinguish between cooked and raw byte string
literals in an `ast::LitKind`, without referring to an adjacent
`token::Lit`. It's a prerequisite for the next commit.
2022-12-02 10:38:58 +11:00
Vadim Petrochenkov
b32a4edb20 rustc_ast_lowering: Stop lowering imports into multiple items
Lower them into a single item with multiple resolutions instead.
This also allows to remove additional `NodId`s and `DefId`s related to those additional items.
2022-12-01 18:51:20 +03:00
Vadim Petrochenkov
1f259ae679 rustc_hir: Change representation of import paths to support multiple resolutions 2022-12-01 18:51:05 +03:00
Oli Scherer
ab75d777de Fill in def_span when creating def ids.
This makes sure that ICEing because of def ids created outside of ast lowering will be able to produce a query backtrace and not cause a double panic because of trying to call the  `def_span` query
2022-12-01 10:33:28 +00:00
bors
d6c4de0fb2 Auto merge of #104861 - nnethercote:attr-cleanups, r=petrochenkov
Attribute cleanups

Best reviewed one commit at a time.

r? `@petrochenkov`
2022-12-01 07:13:45 +00:00
Camille GILLOT
6477fd8fc3 Make TyCtxtFeed::def_id private. 2022-11-29 18:50:29 +00:00
Camille GILLOT
731c002b27 Only allow feeding a value to newly created definitions. 2022-11-29 18:43:00 +00:00
bors
c372b14701 Auto merge of #104947 - cjgillot:verify-hir-nest, r=oli-obk
Verify that HIR parenting and Def parenting match.

This relationship is relied upon for `tcx.hir_owner_parent` query to return an accurate result.
2022-11-29 10:34:19 +00:00
Nicholas Nethercote
ba1751a201 Avoid more MetaItem-to-Attribute conversions.
There is code for converting `Attribute` (syntactic) to `MetaItem`
(semantic). There is also code for the reverse direction. The reverse
direction isn't really necessary; it's currently only used when
generating attributes, e.g. in `derive` code.

This commit adds some new functions for creating `Attributes`s directly,
without involving `MetaItem`s: `mk_attr_word`, `mk_attr_name_value_str`,
`mk_attr_nested_word`, and
`ExtCtxt::attr_{word,name_value_str,nested_word}`.

These new methods replace the old functions for creating `Attribute`s:
`mk_attr_inner`, `mk_attr_outer`, and `ExtCtxt::attribute`. Those
functions took `MetaItem`s as input, and relied on many other functions
that created `MetaItems`, which are also removed: `mk_name_value_item`,
`mk_list_item`, `mk_word_item`, `mk_nested_word_item`,
`{MetaItem,MetaItemKind,NestedMetaItem}::token_trees`,
`MetaItemKind::attr_args`, `MetaItemLit::{from_lit_kind,to_token}`,
`ExtCtxt::meta_word`.

Overall this cuts more than 100 lines of code and makes thing simpler.
2022-11-29 18:43:53 +11:00
Sarthak Singh
8f705e2425 Keep track of the start of the argument block of a closure 2022-11-28 14:09:00 +05:30
Nicholas Nethercote
e4a9150872 Rename ast::Lit as ast::MetaItemLit. 2022-11-28 15:18:49 +11:00
Nicholas Nethercote
aa10aad1ac Factor out a repeated expression in lower_attr_args. 2022-11-28 15:17:45 +11:00
bors
454784afba Auto merge of #104048 - cjgillot:split-lifetime, r=compiler-errors
Separate lifetime ident from lifetime resolution in HIR

Drive-by: change how suggested generic args are computed.
Fixes https://github.com/rust-lang/rust/issues/103815

I recommend reviewing commit-by-commit.
2022-11-27 14:30:19 +00:00
Camille GILLOT
b22418eac3 Verify that HIR parenting and Def parenting match. 2022-11-26 17:28:59 +00:00
Guillaume Gomez
a2e485c25c
Rollup merge of #104786 - WaffleLapkin:amp-mut-help, r=compiler-errors
Use the power of adding helper function to simplify code w/ `Mutability`

r? `@compiler-errors`
2022-11-26 17:47:23 +01:00
Maybe Waffle
e143fa2156 nested-match mutability (proposed by the reviewer) 2022-11-24 18:18:45 +00:00
Camille GILLOT
1c737d6997 Use kw::Empty for elided lifetimes in path. 2022-11-24 17:48:59 +00:00
Camille GILLOT
5f5e7a8eec Record in HIR whether lifetime elision was succesful. 2022-11-24 17:48:27 +00:00
bors
5dfb4b0afa Auto merge of #104321 - Swatinem:async-gen, r=oli-obk
Avoid `GenFuture` shim when compiling async constructs

Previously, async constructs would be lowered to "normal" generators, with an additional `from_generator` / `GenFuture` shim in between to convert from `Generator` to `Future`.

The compiler will now special-case these generators internally so that async constructs will *directly* implement `Future` without the need to go through the `from_generator` / `GenFuture` shim.

The primary motivation for this change was hiding this implementation detail in stack traces and debuginfo, but it can in theory also help the optimizer as there is less abstractions to see through.

---

Given this demo code:

```rust
pub async fn a(arg: u32) -> Backtrace {
    let bt = b().await;
    let _arg = arg;
    bt
}

pub async fn b() -> Backtrace {
    Backtrace::force_capture()
}
```

I would get the following with the latest stable compiler (on Windows):

```
   4: async_codegen:🅱️:async_fn$0
             at .\src\lib.rs:10
   5: core::future::from_generator::impl$1::poll<enum2$<async_codegen:🅱️:async_fn_env$0> >
             at /rustc/897e37553bba8b42751c67658967889d11ecd120\library\core\src\future\mod.rs:91
   6: async_codegen:🅰️:async_fn$0
             at .\src\lib.rs:4
   7: core::future::from_generator::impl$1::poll<enum2$<async_codegen:🅰️:async_fn_env$0> >
             at /rustc/897e37553bba8b42751c67658967889d11ecd120\library\core\src\future\mod.rs:91
```

whereas now I get a much cleaner stack trace:

```
   3: async_codegen:🅱️:async_fn$0
             at .\src\lib.rs:10
   4: async_codegen:🅰️:async_fn$0
             at .\src\lib.rs:4
```
2022-11-24 17:14:42 +00:00
Arpad Borsos
9f36f988ad
Avoid GenFuture shim when compiling async constructs
Previously, async constructs would be lowered to "normal" generators,
with an additional `from_generator` / `GenFuture` shim in between to
convert from `Generator` to `Future`.

The compiler will now special-case these generators internally so that
async constructs will *directly* implement `Future` without the need
to go through the `from_generator` / `GenFuture` shim.

The primary motivation for this change was hiding this implementation
detail in stack traces and debuginfo, but it can in theory also help
the optimizer as there is less abstractions to see through.
2022-11-24 10:04:27 +01:00
Esteban Küber
78b8d126db Fix rebase 2022-11-23 13:06:27 -08:00
Maybe Waffle
da40965300 Add Mutability::{is_mut,is_not} 2022-11-23 20:26:31 +00:00
Esteban Küber
9e72e35ceb Suggest .clone() or ref binding on E0382 2022-11-23 12:17:47 -08:00
Camille GILLOT
fb7d25e978 Separate lifetime ident from resolution in HIR. 2022-11-23 19:33:06 +00:00
Dylan DPC
c03026a7c6
Rollup merge of #104721 - WaffleLapkin:deref-harder, r=oli-obk
Remove more `ref` patterns from the compiler

r? `@oli-obk`
Previous PR: https://github.com/rust-lang/rust/pull/104500
2022-11-23 20:32:37 +05:30
Manish Goregaokar
36815c6e3b
Rollup merge of #104612 - Swatinem:async-ret-y, r=estebank
Lower return type outside async block creation

This allows feeding a different output type to async blocks with a different `ImplTraitContext`. Spotted this while working on #104321
2022-11-22 22:54:39 -05:00
Maybe Waffle
b97ec3924d rustc_ast_lowering: remove ref patterns 2022-11-22 18:49:29 +00:00
Dylan DPC
88542a3150
Rollup merge of #104615 - spastorino:create-async-def-id-in-lowering, r=compiler-errors
Create def_id for async fns during lowering

r? `@compiler-errors`
2022-11-22 16:36:37 +05:30
Nicholas Nethercote
3e3a4192d8 Split MacArgs in two.
`MacArgs` is an enum with three variants: `Empty`, `Delimited`, and `Eq`. It's
used in two ways:
- For representing attribute macro arguments (e.g. in `AttrItem`), where all
  three variants are used.
- For representing function-like macros (e.g. in `MacCall` and `MacroDef`),
  where only the `Delimited` variant is used.

In other words, `MacArgs` is used in two quite different places due to them
having partial overlap. I find this makes the code hard to read. It also leads
to various unreachable code paths, and allows invalid values (such as
accidentally using `MacArgs::Empty` in a `MacCall`).

This commit splits `MacArgs` in two:
- `DelimArgs` is a new struct just for the "delimited arguments" case. It is
  now used in `MacCall` and `MacroDef`.
- `AttrArgs` is a renaming of the old `MacArgs` enum for the attribute macro
  case. Its `Delimited` variant now contains a `DelimArgs`.

Various other related things are renamed as well.

These changes make the code clearer, avoids several unreachable paths, and
disallows the invalid values.
2022-11-22 09:04:15 +11:00
bors
7fe6f36224 Auto merge of #103491 - cjgillot:self-rpit, r=oli-obk
Support using `Self` or projections inside an RPIT/async fn

I reuse the same idea as https://github.com/rust-lang/rust/pull/103449 to use variances to encode whether a lifetime parameter is captured by impl-trait.

The current implementation of async and RPIT replace all lifetimes from the parent generics by `'static`.  This PR changes the scheme
```rust
impl<'a> Foo<'a> {
    fn foo<'b, T>() -> impl Into<Self> + 'b { ... }
}

opaque Foo::<'_a>::foo::<'_b, T>::opaque<'b>: Into<Foo<'_a>> + 'b;
impl<'a> Foo<'a> {
    // OLD
    fn foo<'b, T>() -> Foo::<'static>::foo::<'static, T>::opaque::<'b> { ... }
                             ^^^^^^^ the `Self` becomes `Foo<'static>`

    // NEW
    fn foo<'b, T>() -> Foo::<'a>::foo::<'b, T>::opaque::<'b> { ... }
                             ^^ the `Self` stays `Foo<'a>`
}
```

There is the same issue with projections. In the example, substitute `Self` by `<T as Trait<'b>>::Assoc` in the sugared version, and `Foo<'_a>` by `<T as Trait<'_b>>::Assoc` in the desugared one.

This allows to support `Self` in impl-trait, since we do not replace lifetimes by `'static` any more.  The same trick allows to use projections like `T::Assoc` where `Self` is allowed.  The feature is gated behind a `impl_trait_projections` feature gate.

The implementation relies on 2 tweaking rules for opaques in 2 places:
- we only relate substs that correspond to captured lifetimes during TypeRelation;
- we only list captured lifetimes in choice region computation.

For simplicity, I encoded the "capturedness" of lifetimes as a variance, `Bivariant` vs `Invariant` for unused vs captured lifetimes. The `variances_of` query used to ICE for opaques.

Impl-trait that do not reference `Self` or projections will have their variances as:
- `o` (invariant) for each parent type or const;
- `*` (bivariant) for each parent lifetime --> will not participate in borrowck;
- `o` (invariant) for each own lifetime.

Impl-trait that does reference `Self` and/or projections will have some parent lifetimes marked as `o` (as the example above), and participate in type relation and borrowck.  In the example above, `variances_of(opaque) = ['_a: o, '_b: *, T: o, 'b: o]`.

r? types
cc `@compiler-errors` , as you asked about the issue with `Self` and projections.
2022-11-21 12:17:03 +00:00
Santiago Pastorino
520fafe5c2
Create def_id for async fns during lowering 2022-11-19 19:17:14 -03:00
Arpad Borsos
b59090ebe3
Lower return type outside async block creation
This allows feeding a different output type to async blocks with a
different `ImplTraitContext`.
2022-11-19 18:23:32 +01:00
bors
70fe5f08ff Auto merge of #101562 - nnethercote:shrink-ast-Expr-harder, r=petrochenkov
Shrink `ast::Expr` harder

r? `@ghost`
2022-11-18 16:56:12 +00:00
bors
fd3bfb3551 Auto merge of #104330 - CastilloDel:ast_lowering, r=cjgillot
Remove allow(rustc::potential_query_instability) from rustc_ast_lowering

Related to https://github.com/rust-lang/rust/issues/84447.

`@cjgillot` Thanks for helping me!
2022-11-18 13:12:18 +00:00
bors
b6097f2e1b Auto merge of #104219 - bryangarza:async-track-caller-dup, r=eholk
Support `#[track_caller]` on async fns

Adds `#[track_caller]` to the generator that is created when we desugar the async fn.

Fixes #78840

Open questions:
- What is the performance impact of adding `#[track_caller]` to every `GenFuture`'s `poll(...)` function, even if it's unused (i.e., the parent span does not set `#[track_caller]`)? We might need to set it only conditionally, if the indirection causes overhead we don't want.
2022-11-17 13:47:03 +00:00
bors
7c75fe4c85 Auto merge of #104170 - cjgillot:hir-def-id, r=fee1-dead
Record `LocalDefId` in HIR nodes instead of a side table

This is part of an attempt to remove the `HirId -> LocalDefId` table from HIR.
This attempt is a prerequisite to creation of `LocalDefId` after HIR lowering (https://github.com/rust-lang/rust/pull/96840), by controlling how `def_id` information is accessed.

This first part adds the information to HIR nodes themselves instead of a table.
The second part is https://github.com/rust-lang/rust/pull/103902
The third part will be to make `hir::Visitor::visit_fn` take a `LocalDefId` as last parameter.
The fourth part will be to completely remove the side table.
2022-11-17 07:42:27 +00:00
Nicholas Nethercote
67d5cc0462 Use ThinVec in ast::Path. 2022-11-17 13:56:38 +11:00
Nicholas Nethercote
6b7ca2fcf2 Box ExprKind::{Closure,MethodCall}, and QSelf in expressions, types, and patterns. 2022-11-17 13:45:59 +11:00
Nicholas Nethercote
358a603f11 Use token::Lit in ast::ExprKind::Lit.
Instead of `ast::Lit`.

Literal lowering now happens at two different times. Expression literals
are lowered when HIR is crated. Attribute literals are lowered during
parsing.

This commit changes the language very slightly. Some programs that used
to not compile now will compile. This is because some invalid literals
that are removed by `cfg` or attribute macros will no longer trigger
errors. See this comment for more details:
https://github.com/rust-lang/rust/pull/102944#issuecomment-1277476773
2022-11-16 09:41:28 +11:00
Daniel del Castillo
557226348f Update compiler/rustc_ast_lowering/src/item.rs
Co-authored-by: Camille Gillot <gillot.camille@gmail.com>
2022-11-15 13:57:25 +01:00
CastilloDel
fdb5fe2ed8 Change LoweringContext.children to Vec 2022-11-15 13:57:24 +01:00
CastilloDel
d1eab51f47 Make clobber_abis use an FxIndexMap
It seems to be used more for lookup than iteration, so this could be a
perf hit
2022-11-15 13:57:24 +01:00
CastilloDel
769cc733b1 Remove allow(rustc::potential_query_instability) from rustc_ast_lowering 2022-11-15 13:57:24 +01:00
Camille GILLOT
9d20aca983 Store a LocalDefId in hir::Variant & hir::Field. 2022-11-13 14:06:51 +00:00
Camille GILLOT
607d0c2a14 Store a LocalDefId in hir::AnonConst. 2022-11-13 14:06:11 +00:00
Camille GILLOT
18482f7b23 Store a LocalDefId in hir::GenericParam. 2022-11-13 14:05:30 +00:00
Camille GILLOT
290f0781b4 Store LocalDefId in hir::Closure. 2022-11-13 14:04:02 +00:00
Camille GILLOT
c5949c8bee Create bidirectional bounds between original and duplicated parameters. 2022-11-13 09:01:29 +00:00
clubby789
b2da155a9a Introduce ExprKind::IncludedBytes 2022-11-11 16:31:32 +00:00
Bryan Garza
509b9478f5 Refactor nested for-loops into find() calls 2022-11-10 00:13:48 +00:00
Bryan Garza
fa99cb8269 Allow and add track_caller to generators
This patch allows the usage of the `track_caller` annotation on
generators, as well as sets them conditionally if the parent also has
`track_caller` set.

Also add this annotation on the `GenFuture`'s `poll()` function.
2022-11-09 23:27:14 +00:00
Michael Howell
03968a802c rustdoc: use ThinVec for cleaned generics 2022-11-02 16:17:22 -07:00
Manish Goregaokar
69e705564d
Rollup merge of #103575 - Xiretza:suggestions-style-attr, r=davidtwco
Change #[suggestion_*] attributes to use style="..."

As discussed [on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20tool_only_span_suggestion), this changes `#[(multipart_)suggestion_{short,verbose,hidden}(...)]` attributes to plain `#[(multipart_)suggestion(...)]` attributes with a `style = "{short,verbose,hidden}"` parameter.

It also adds a new style, `tool-only`, that corresponds to `tool_only_span_suggestion`/`tool_only_multipart_suggestion` and causes the suggestion to not be shown in human-readable output at all.

Best reviewed commit-by-commit, there's a bit of noise in there.

cc #100717 `@compiler-errors`
r? `@davidtwco`
2022-11-01 20:00:38 -04:00
Dylan DPC
b4cf523cb5
Rollup merge of #93582 - WaffleLapkin:rpitirpit, r=compiler-errors
Allow `impl Fn() -> impl Trait` in return position

_This was originally proposed as part of #93082 which was [closed](https://github.com/rust-lang/rust/pull/93082#issuecomment-1027225715) due to allowing `impl Fn() -> impl Trait` in argument position._

This allows writing the following function signatures:
```rust
fn f0() -> impl Fn() -> impl Trait;
fn f3() -> &'static dyn Fn() -> impl Trait;
```

These signatures were already allowed for common traits and associated types, there is no reason why `Fn*` traits should be special in this regard.

`impl Trait` in both `f0` and `f3` means "new existential type", just like with `-> impl Iterator<Item = impl Trait>` and such.

Arrow in `impl Fn() ->` is right-associative and binds from right to left, it's tested by [this test](a819fecb8d/src/test/ui/impl-trait/impl_fn_associativity.rs).

There even is a test that `f0` compiles:
2f004d2d40/src/test/ui/impl-trait/nested_impl_trait.rs (L25-L28)

But it was changed in [PR 48084 (lines)](https://github.com/rust-lang/rust/pull/48084/files#diff-ccecca938872d65ffe8cd1c3ef1956e309fac83bcda547d8b16b89257e53a437R37)  to test the opposite, probably unintentionally given [PR 48084 (lines)](https://github.com/rust-lang/rust/pull/48084/files#diff-5a02f1ed43debed1fd24f7aad72490064f795b9420f15d847bac822aa4621a1cR476-R477).

r? `@nikomatsakis`

----

This limitation is especially annoying with async code, since it forces one to write this:
```rust
trait AsyncFn3<A, B, C>: Fn(A, B, C) -> <Self as AsyncFn3<A, B, C>>::Future {
    type Future: Future<Output = Self::Out>;

    type Out;
}

impl<A, B, C, Fut, F> AsyncFn3<A, B, C> for F
where
    F: Fn(A, B, C) -> Fut,
    Fut: Future,
{
    type Future = Fut;

    type Out = Fut::Output;
}

fn async_closure() -> impl AsyncFn3<i32, i32, i32, Out = u32> {
    |a, b, c| async move { (a + b + c) as u32 }
}
```
Instead of:
```rust
fn async_closure() -> impl Fn(i32, i32, i32) -> impl Future<Output = u32> {
    |a, b, c| async move { (a + b + c) as u32 }
}
```
2022-10-30 11:50:26 +05:30
Nicholas Nethercote
c8c25ce5a1 Rename some OwnerId fields.
spastorino noticed some silly expressions like `item_id.def_id.def_id`.

This commit renames several `def_id: OwnerId` fields as `owner_id`, so
those expressions become `item_id.owner_id.def_id`.

`item_id.owner_id.local_def_id` would be even clearer, but the use of
`def_id` for values of type `LocalDefId` is *very* widespread, so I left
that alone.
2022-10-29 20:28:38 +11:00
Xiretza
cd621be782 Convert all #[suggestion_*] attributes to #[suggestion(style = "...")]
Using the following command:

find compiler/ -type f -name '*.rs' -exec perl -i -gpe \
    's/(#\[\w*suggestion)_(short|verbose|hidden)\(\s*(\S+,)?/\1(\3style = "\2",/g' \
    '{}' +
2022-10-26 15:04:09 +02:00
Maybe Waffle
e93982a78f adopt to compiler changes 2022-10-25 13:47:43 +00:00
Maybe Waffle
cc752f5665 Feature gate impl_trait_in_fn_trait_return 2022-10-25 13:25:52 +00:00
Maybe Waffle
8b494f427c Allow impl Fn() -> impl Trait in return position
This allows writing the following function signatures:
```rust
fn f0() -> impl Fn() -> impl Trait;
fn f3() -> &'static dyn Fn() -> impl Trait;
```

These signatures were already allowed for common traits and associated
types, there is no reason why `Fn*` traits should be special in this
regard.
2022-10-25 13:25:51 +00:00
Nilstrieb
c65ebae221
Migrate all diagnostics 2022-10-23 10:09:44 +02:00
Dylan DPC
e11511dfa6
Rollup merge of #103051 - davidtwco:translation-tidying-up, r=compiler-errors
translation: doc comments with derives, subdiagnostic-less enum variants, more derive use

- Adds support for `doc` attributes in the diagnostic derives so that documentation comments don't result in the derive failing.
- Adds support for enum variants in the subdiagnostic derive to not actually correspond to an addition to a diagnostic.
- Made use of the derive in more places in the `rustc_ast_lowering`, `rustc_ast_passes`, `rustc_lint`, `rustc_session`, `rustc_infer` - taking advantage of recent additions like eager subdiagnostics, multispan suggestions, etc.

cc #100717
2022-10-21 17:29:58 +05:30
Santiago Pastorino
49ce8a22b0
Do anonymous lifetimes remapping correctly for nested rpits 2022-10-19 16:49:39 -03:00
Santiago Pastorino
fb5475887f
Extract orig_opt_local_def_id as a function 2022-10-19 16:49:39 -03:00
Yuki Okushi
6e7d206a7b
Rollup merge of #103168 - Amanieu:stable_asm_sym, r=davidtwco
Stabilize asm_sym

Tracking issue #93333

Reference PR: https://github.com/rust-lang/reference/pull/1270
2022-10-18 21:21:32 +09:00
Amanieu d'Antras
430bd6200d Stabilize asm_sym 2022-10-17 22:38:37 +01:00
David Wood
2a4b587a68 ast_lowering: use derive more
Signed-off-by: David Wood <david.wood@huawei.com>
2022-10-17 09:54:24 +01:00