Commit Graph

534 Commits

Author SHA1 Message Date
Nicholas Nethercote
2e93f2c92f Allow more deriving on packed structs.
Currently, deriving on packed structs has some non-trivial limitations,
related to the fact that taking references on unaligned fields is UB.

The current approach to field accesses in derived code:
- Normal case: `&self.0`
- In a packed struct that derives `Copy`: `&{self.0}`
- In a packed struct that doesn't derive `Copy`: `&self.0`

Plus, we disallow deriving any builtin traits other than `Default` for any
packed generic type, because it's possible that there might be
misaligned fields. This is a fairly broad restriction.

Plus, we disallow deriving any builtin traits other than `Default` for most
packed types that don't derive `Copy`. (The exceptions are those where the
alignments inherently satisfy the packing, e.g. in a type with
`repr(packed(N))` where all the fields have alignments of `N` or less
anyway. Such types are pretty strange, because the `packed` attribute is
not having any effect.)

This commit introduces a new, simpler approach to field accesses:
- Normal case: `&self.0`
- In a packed struct: `&{self.0}`

In the latter case, this requires that all fields impl `Copy`, which is
a new restriction. This means that the following example compiles under
the old approach and doesn't compile under the new approach.
```
 #[derive(Debug)]
 struct NonCopy(u8);

 #[derive(Debug)
 #[repr(packed)]
 struct MyType(NonCopy);
```
(Note that the old approach's support for cases like this was brittle.
Changing the `u8` to a `u16` would be enough to stop it working. So not
much capability is lost here.)

However, the other constraints from the old rules are removed. We can now
derive builtin traits for packed generic structs like this:
```
 trait Trait { type A; }

 #[derive(Hash)]
 #[repr(packed)]
 pub struct Foo<T: Trait>(T, T::A);
```
To allow this, we add a `T: Copy` bound in the derived impl and a `T::A:
Copy` bound in where clauses. So `T` and `T::A` must impl `Copy`.

We can now also derive builtin traits for packed structs that don't derive
`Copy`, so long as the fields impl `Copy`:
```
 #[derive(Hash)]
 #[repr(packed)]
 pub struct Foo(u32);
```
This includes types that hand-impl `Copy` rather than deriving it, such as the
following, that show up in winapi-0.2:
```
 #[derive(Clone)]
 #[repr(packed)]
 struct MyType(i32);

 impl Copy for MyType {}
```
The new approach is simpler to understand and implement, and it avoids
the need for the `unsafe_derive_on_repr_packed` check.

One exception is required for backwards-compatibility: we allow `[u8]`
fields for now. There is a new lint for this,
`byte_slice_in_packed_struct_with_derive`.
2023-01-30 12:00:42 +11:00
bors
9f82651a5f Auto merge of #103659 - clubby789:improve-partialord-derive, r=nagisa
Special-case deriving `PartialOrd` for enums with dataless variants

I was able to get slightly better codegen by flipping the derived `PartialOrd` logic for two-variant enums.  I also tried to document the implementation of the derive macro to make the special-case logic a little clearer.
```rs
#[derive(PartialEq, PartialOrd)]
pub enum A<T> {
    A,
    B(T)
}
```
```diff
impl<T: ::core::cmp::PartialOrd> ::core::cmp::PartialOrd for A<T> {
   #[inline]
   fn partial_cmp(
       &self,
       other: &A<T>,
   ) -> ::core::option::Option<::core::cmp::Ordering> {
       let __self_tag = ::core::intrinsics::discriminant_value(self);
       let __arg1_tag = ::core::intrinsics::discriminant_value(other);
-      match ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag) {
-          ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
-              match (self, other) {
-                  (A::B(__self_0), A::B(__arg1_0)) => {
-                      ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
-                  }
-                  _ => ::core::option::Option::Some(::core::cmp::Ordering::Equal),
-              }
+      match (self, other) {
+          (A::B(__self_0), A::B(__arg1_0)) => {
+              ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
           }
-          cmp => cmp,
+          _ => ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag),
       }
   }
}
```
Godbolt: [Current](https://godbolt.org/z/GYjEzG1T8), [New](https://godbolt.org/z/GoK78qx15)
I'm not sure how common a case comparing two enums like this (such as `Option`) is, and if it's worth the slowdown of adding a special case to the derive. If it causes overall regressions it might be worth just manually implementing this for `Option`.
2023-01-28 22:11:11 +00:00
Mara Bos
0abf8a0617 Replace format flags u32 by enums and bools. 2023-01-27 08:53:39 +01: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
bors
b22aa57fd5 Auto merge of #106884 - clubby789:fieldless-enum-debug, r=michaelwoerister
Simplify `derive(Debug)` output for fieldless enums

Fixes #106875
2023-01-21 07:49:09 +00:00
clubby789
95a824c02c Special case derive(Debug) for fieldless enums 2023-01-19 15:53:31 +00:00
clubby789
97cf1713d1 Add enum for fieldless unification 2023-01-19 15:41:11 +00:00
Maybe Waffle
6a28fb42a8 Remove double spaces after dots in comments 2023-01-17 08:09:33 +00:00
clubby789
2883148e60 Special case deriving PartialOrd for certain enum layouts 2023-01-15 01:35:48 +00:00
Mara Bos
56593104ac Update comment explaining format_args!() expansion. 2023-01-12 00:45:29 +01:00
Mara Bos
a4dbcb525b Expand format_args!() in rust_ast_lowering. 2023-01-12 00:25:45 +01:00
Gimbles
32ab2d95f1
Update format.rs 2023-01-02 15:51:54 +05:30
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
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
Matthias Krüger
3e58de240c
Rollup merge of #105978 - jyn514:unused_proc_macro_decl, r=tmiasko
Mark `proc_macro_decls_static` as always used

This would have avoided a bug in https://github.com/rust-lang/rust/pull/104860.

In practice this shouldn't matter since nothing uses the query other than the `dead_code` lint, but this isn't documented as an internal-only query so it seems nice for it to be accurate. I think for `dead_code` it doesn't matter because the relevant code is generated by `rustc_builtin_macros` and isn't linted.

I think `@tmiasko` or `@bjorn3` would be a good reviewer?

r? `@tmiasko`
2022-12-23 01:17:50 +01:00
Joshua Nelson
164e22109b Mark proc_macro_decls_static as always used
This would have avoided a bug in https://github.com/rust-lang/rust/pull/104860.

In practice this shouldn't matter since nothing uses the query other than the `dead_code` lint,
but this isn't documented as an internal-only query so it seems nice for it to be accurate.
I think for `dead_code` it doesn't matter because the relevant code is generated by `rustc_builtin_macros` and isn't linted.
2022-12-22 12:02:53 -06:00
Jeremy Stucki
3dde32ca97
rustc: Remove needless lifetimes 2022-12-20 22:10:40 +01:00
Matthias Krüger
8892698903
Rollup merge of #105870 - matthiaskrgr:useless_conv, r=oli-obk
avoid .into() conversion to identical types
2022-12-18 18:57:05 +01:00
Matthias Krüger
0aa4cde747 avoid .into() conversion to identical types 2022-12-18 16:20:32 +01:00
Matthias Krüger
1ade25491e remove redundant clone 2022-12-18 00:29:25 +01:00
Matthias Krüger
4069792d73
Rollup merge of #105620 - TaKO8Ki:remove-unnecessary-uses-of-clone, r=compiler-errors
Remove unnecessary uses of `clone`
2022-12-13 01:17:10 +01:00
Takayuki Maeda
ee40a67cd9 remove unnecessary uses of clone 2022-12-13 02:06:24 +09: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
Matthias Krüger
2daa3bcbc2
Rollup merge of #105537 - kadiwa4:remove_some_imports, r=fee1-dead
compiler: remove unnecessary imports and qualified paths

Some of these imports were necessary before Edition 2021, others were already in the prelude.

I hope it's fine that this PR is so spread-out across files :/
2022-12-11 09:51:57 +01:00
KaDiWa
9bc69925cb
compiler: remove unnecessary imports and qualified paths 2022-12-10 18:45:34 +01:00
nils
2f9f097cb8 Migrate parts of rustc_expand to session diagnostics
This migrates everything but the `mbe` and `proc_macro` modules. It also
contains a few cleanups and drive-by/accidental diagnostic improvements
which can be seen in the diff for the UI tests.
2022-12-10 11:02:41 +01:00
bors
0d5573e6da Auto merge of #105363 - WaffleLapkin:thin2win_box_next_argument, r=nnethercote
Shrink `rustc_parse_format::Piece`

This makes both variants closer together in size (previously they were different by 208 bytes -- 16 vs 224). This may make things worse, but it's worth a try.

r? `@nnethercote`
2022-12-09 21:27:35 +00:00
Maybe Waffle
700c095306 rustc_builtin_macros: remove ref patterns
... and other pattern matching improvements
2022-12-06 14:45:58 +00:00
Maybe Waffle
78060cb6de Box rustc_parse_format::Piece::NextArgument
This makes both variants closer together in size (previously they were
different by 208 bytes -- 16 vs 224). This may make things worse, but
it's worth a try.
2022-12-06 12:02:56 +00:00
Matthias Krüger
4fdc3eb176
Rollup merge of #104614 - Nilstrieb:type-ascribe!, r=TaKO8Ki
Add `type_ascribe!` macro as placeholder syntax for type ascription

This makes it still possible to test the internal semantics of type ascription even once the `:`-syntax is removed from the parser. The macro now gets used in a bunch of UI tests that test the semantics and not syntax of type ascription.

I might have forgotten a few tests but this should hopefully be most of them. The remaining ones will certainly be found once type ascription is removed from the parser altogether.

Part of #101728
2022-12-02 08:28:08 +01:00
bors
11663b1b48 Auto merge of #104963 - petrochenkov:noaddids2, r=cjgillot
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-02 04:24: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
Matthias Krüger
ee9eaa695c
Rollup merge of #105106 - jhpratt:issue-105101, r=TaKO8Ki
Fix ICE from #105101

Fixes #105101

Rather than comparing idents, compare spans, which should be unique to each variant.
2022-12-01 11:59:01 +01: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
Jacob Pratt
ab264ae612
Fix ICE from #105101 2022-11-30 21:18:31 +00:00
Nicholas Nethercote
bf4a62c381 Fix an ICE parsing a malformed literal in concat_bytes!.
Fixes #104769.
2022-11-30 12:19:07 +11: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
Nicholas Nethercote
a709f87be7 Avoid more unnecessary MetaItem/Attribute conversions.
In `Expander::expand` the code currently uses `mk_attr_outer` to convert
a `MetaItem` to an `Attribute`, and then follows that with
`meta_item_list` which converts back. This commit avoids the unnecessary
conversions.

There was one wrinkle: the existing conversions caused the bogus `<>` on
`Default<>` to be removed. With the conversion gone, we get a second
error message about the `<>`. This is a rare case, so I think it
probably doesn't matter much.
2022-11-29 12:54:45 +11:00
Nicholas Nethercote
c9ae38c71e Avoid unnecessary MetaItem/Attribute conversions.
`check_builtin_attribute` calls `parse_meta` to convert an `Attribute`
to a `MetaItem`, which it then checks. However, many callers of
`check_builtin_attribute` start with a `MetaItem`, and then convert it
to an `Attribute` by calling `cx.attribute(meta_item)`. This `MetaItem`
to `Attribute` to `MetaItem` conversion is silly.

This commit adds a new function `check_builtin_meta_item`, which can be
called instead from these call sites. `check_builtin_attribute` also now
calls it. The commit also renames `check_meta` as `check_attr` to better
match its arguments.
2022-11-29 12:08:57 +11:00
Nicholas Nethercote
a60e337c88 Rename NestedMetaItem::[Ll]iteral as NestedMetaItem::[Ll]it.
We already use a mix of `Literal` and `Lit`. The latter is better
because it is shorter without causing any ambiguity.
2022-11-28 15:18:53 +11:00
Nicholas Nethercote
e4a9150872 Rename ast::Lit as ast::MetaItemLit. 2022-11-28 15:18:49 +11:00
Maybe Waffle
1d42936b18 Prefer doc comments over //-comments in compiler 2022-11-27 11:19:04 +00:00
Matthias Krüger
5197ef66b7
Rollup merge of #103908 - estebank:consider-cloning, r=compiler-errors
Suggest `.clone()` or `ref binding` on E0382
2022-11-24 08:42:33 +01:00
bors
872631d0f0 Auto merge of #104507 - WaffleLapkin:asderefsyou, r=wesleywiser
Use `as_deref` in compiler (but only where it makes sense)

This simplifies some code :3

(there are some changes that are not exacly `as_deref`, but more like "clever `Option`/`Result` method use")
2022-11-24 00:17:35 +00:00
Esteban Küber
9e72e35ceb Suggest .clone() or ref binding on E0382 2022-11-23 12:17:47 -08:00
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
Nicholas Nethercote
a6e09a19fc Streamline deriving on packed structs.
The current approach to field accesses in derived code:
- Normal case: `&self.0`
- In a packed struct that derives `Copy`: `&{self.0}`
- In a packed struct that doesn't derive `Copy`: `let Self(ref x) = *self`

The `let` pattern used in the third case is equivalent to the simpler
field access in the first case. This commit changes the third case to
use a field access.

The commit also combines two boolean arguments (`is_packed` and
`always_copy`) into a single field (`copy_fields`) earlier, to save
passing both around.
2022-11-21 14:07:39 +11:00
Nilstrieb
6ee0dd97e3
Add unstable type_ascribe macro
This macro serves as a placeholder for future type ascription syntax to
make sure that the semantic implementation keeps working.
2022-11-19 22:16:42 +01:00