about summary refs log tree commit diff
path: root/compiler/rustc_mir_build/src/thir/pattern
AgeCommit message (Collapse)AuthorLines
2025-09-25usize/isize range matching error clarificationhelldawg-4/+4
2025-09-09erase_regions to erase_and_anonymize_regionsBoxy-3/+5
2025-08-14shrink TestBranch::Constant and PatRangeBoundary::FiniteRalf Jung-2/+3
2025-08-14use ty::Value instead of manual pairs of types and valtreesRalf Jung-7/+7
2025-08-14pattern testing: store constants as valtreesRalf Jung-10/+4
2025-08-14PatKind: store constants as valtreesRalf Jung-15/+14
2025-07-31remove rustc_attr_data_structuresJana Dönszelmann-1/+2
2025-07-28use let chains in hir, lint, mirKivooeo-7/+5
2025-07-14Auto merge of #143779 - JonathanBrouwer:automatically_derived_parser, r=oli-obkbors-2/+4
Port `#[automatically_derived]` to the new attribute parsing infrastructure Ports `#[automatically_derived]` to the new attribute parsing infrastructure for https://github.com/rust-lang/rust/issues/131229#issuecomment-2971351163 r? `@oli-obk` cc `@jdonszelmann`
2025-07-13Generalize TyCtxt::item_name.Camille GILLOT-1/+1
2025-07-12Port `#[automatically_derived]` to the new attribute parsing infrastructureJonathan Brouwer-2/+4
Signed-off-by: Jonathan Brouwer <jonathantbrouwer@gmail.com>
2025-07-04only check for mixed deref/normal constructors when neededdianne-0/+1
2025-07-04treat box patterns as deref patterns in THIR and usefulness analysisdianne-3/+4
This removes special-casing of boxes from `rustc_pattern_analysis`, as a first step in replacing `box_patterns` with `deref_patterns`. Incidentally, it fixes a bug caused by box patterns being represented as structs rather than pointers, where `exhaustive_patterns` could generate spurious `unreachable_patterns` lints on arms required for exhaustiveness; following the lint's advice would result in an error.
2025-07-03Rollup merge of #134006 - klensy:typos, r=nnethercoteJana Dönszelmann-2/+2
setup typos check in CI This allows to check typos in CI, currently for compiler only (to reduce commit size with fixes). With current setup, exclude list is quite short, so it worth trying? Also includes commits with actual typo fixes. MCP: https://github.com/rust-lang/compiler-team/issues/817 typos check currently turned for: * ./compiler * ./library * ./src/bootstrap * ./src/librustdoc After merging, PRs which enables checks for other crates (tools) can be implemented too. Found typos will **not break** other jobs immediately: (tests, building compiler for perf run). Job will be marked as red on completion in ~ 20 secs, so you will not forget to fix it whenever you want, before merging pr. Check typos: `python x.py test tidy --extra-checks=spellcheck` Apply typo fixes: `python x.py test tidy --extra-checks=spellcheck:fix` (in case if there only 1 suggestion of each typo) Current fail in this pr is expected and shows how typo errors emitted. Commit with error will be removed after r+.
2025-07-03setup CI and tidy to use typos for spellchecking and fix few typosklensy-2/+2
2025-07-01loop match: run exhaustiveness checkFolkert de Vries-1/+7
2025-06-30Introduce `ByteSymbol`.Nicholas Nethercote-1/+1
It's like `Symbol` but for byte strings. The interner is now used for both `Symbol` and `ByteSymbol`. E.g. if you intern `"dog"` and `b"dog"` you'll get a `Symbol` and a `ByteSymbol` with the same index and the characters will only be stored once. The motivation for this is to eliminate the `Arc`s in `ast::LitKind`, to make `ast::LitKind` impl `Copy`, and to avoid the need to arena-allocate `ast::LitKind` in HIR. The latter change reduces peak memory by a non-trivial amount on literal-heavy benchmarks such as `deep-vector` and `tuple-stress`. `Encoder`, `Decoder`, `SpanEncoder`, and `SpanDecoder` all get some changes so that they can handle normal strings and byte strings. This change does slow down compilation of programs that use `include_bytes!` on large files, because the contents of those files are now interned (hashed). This makes `include_bytes!` more similar to `include_str!`, though `include_bytes!` contents still aren't escaped, and hashing is still much cheaper than escaping.
2025-06-25Rollup merge of #142724 - xizheyin:avoid_overwrite_args, r=oli-obkJana Dönszelmann-2/+5
Add runtime check to avoid overwrite arg in `Diag` ## Origin PR description At first, I set up a `debug_assert` check for the arg method to make sure that `args` in `Diag` aren't easily overwritten, and I added the `remove_arg()` method, so that if you do need to overwrite an arg, then you can explicitly call `remove_arg()` to remove it first, then call `arg()` to overwrite it. For the code before the rust-lang/rust#142015 change, it won't compile because it will report an error ``` arg `instance`already exists. ``` This PR also modifies all diagnostics that fail the check to pass the check. There are two cases of check failure: 1. ~~Between *the parent diagnostic and the subdiagnostic*, or *between the subdiagnostics* have the same field between them. In this case, I renamed the conflicting fields.~~ 2. ~~For subdiagnostics stored in `Vec`, the rendering may iteratively write the same arg over and over again. In this case, I changed the auto-generation with `derive(SubDiagnostic)` to manually implementing `SubDiagnostic` and manually rendered it with `eagerly_translate()`, similar to https://github.com/rust-lang/rust/issues/142031#issuecomment-2984812090, and after rendering it I manually deleted useless arg with the newly added `remove_arg` method.~~ ## Final Decision After trying and discussing, we made a final decision. For `#[derive(Subdiagnostic)]`, This PR made two changes: 1. After the subdiagnostic is rendered, remove all args of this subdiagnostic, which allows for usage like `Vec<Subdiag>`. 2. Store `diag.args` before setting arguments, so that you can restore the contents of the main diagnostic after deleting the arguments after subdiagnostic is rendered, to avoid deleting the main diagnostic's arg when they have the same name args.
2025-06-25Add runtime check to avoid overwrite arg easily in diag and store and ↵xizheyin-2/+5
restore snapshot when set subdiag arg Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-06-23Add `#[loop_match]` for improved DFA codegenbjorn3-1/+6
Co-authored-by: Folkert de Vries <folkert@folkertdev.nl>
2025-06-05Replace some `Option<Span>` with `Span` and use DUMMY_SP instead of NoneOli Scherer-3/+4
2025-06-03Overhaul `UsePath`.Nicholas Nethercote-20/+15
`UsePath` contains a `SmallVec<[Res; 3]>`. This holds up to three `Res` results, one per namespace (type, value, or macro). `lower_import_res` takes a `PerNS<Option<Res<NodeId>>>` result and lowers it into the `SmallVec`. This is pretty weird. The input `PerNS` makes it clear which `Res` belongs to which namespace, but the `SmallVec` throws that information away. And code that operates on the `SmallVec` tends to use iteration (or even just grabbing the first entry!) without knowing which namespace the `Res` belongs to. Even weirder! Also, `SmallVec` is an overly flexible type to use here, because it can contain any number of elements (even though it's optimized for 3 in this case). This commit changes `UsePath` so it also contains a `PerNS<Option<Res<HirId>>>`. This type preserves more information and is more self-documenting. The commit also changes a lot of the use sites to access the result for a particular namespace. E.g. if you're looking up a trait, it will be in the `Res` for the type namespace if it's present; it's silly to look in the `Res` for the value namespace or macro namespace. Overall I find the new code much easier to understand. However, some use sites still iterate. These now use `present_items` because that filters out the `None` results. Also, `redundant_pub_crate.rs` gets a bigger change. A `UseKind:ListStem` item gets no `Res` results, which means the old `all` call in `is_not_macro_export` would succeed (because `all` succeeds on an empty iterator) and the `ListStem` would be ignored. This is what we want, but was more by luck than design. The new code detects `ListStem` explicitly. The commit generalizes the name of that function accordingly. Finally, the commit also removes the `use_path` arena, because `PerNS<Option<Res>>` impls `Copy` (unlike `SmallVec`) and it can be allocated in the arena shared by all `Copy` types.
2025-05-27Rename unpack to kindMichael Goulet-1/+1
2025-05-23Dont walk into unsafe binders when emiting error for non-structural type matchMichael Goulet-0/+3
2025-05-04Auto merge of #140549 - BoxyUwU:proper_const_norm, r=lcnrbors-0/+2
Set groundwork for proper const normalization r? lcnr Updates a lot of our normalization/alias infrastructure to be setup to handle mgca aliases and normalization once const items are represented more like aliases than bodies. Inherent associated consts are still super busted, I didn't update the assertions that IACs the right arg setup because that winds up being somewhat involved to do *before* proper support for normalizing const aliases is implemented. I dont *intend* for this to have any effect on stable. We continue normalizing via ctfe on stable and the codepaths in `project` for consts should only be reachable with mgca or ace.
2025-05-01Set groundwork for proper const normalizationBoxy-0/+2
2025-05-01User type annotations for free consts in pattern positionBoxy-2/+1
2025-04-24lower deref patterns on boxes using built-in derefsdianne-7/+4
This allows deref patterns to move out of boxes. Implementation-wise, I've opted to put the information of whether a deref pattern uses a built-in deref or a method call in the THIR. It'd be a bit less code to check `.is_box()` everywhere, but I think this way feels more robust (and we don't have a `mutability` field in the THIR that we ignore when the smart pointer's a box). I'm not sure about the naming (or using `ByRef`), though.
2025-04-22make `str` literal patterns usable in deref patternsdianne-0/+10
Specifically, this allows string literal patterns to be used where a `str` is expected when `deref_patterns` is enabled.
2025-04-16lower implicit deref patterns to THIRdianne-18/+24
Since this uses `pat_adjustments`, I've also tweaked the documentation to mention implicit deref patterns and made sure the pattern migration diagnostic logic accounts for it. I'll adjust `ExprUseVisitor` in a later commit and add some tests there for closure capture inference.
2025-04-12store the kind of pattern adjustments in `pat_adjustments`dianne-8/+9
This allows us to better distinguish builtin and overloaded implicit dereferences.
2025-04-07Rollup merge of #139108 - Nadrieril:simplify-expandedconstant, r=oli-obkStuart Cook-75/+82
Simplify `thir::PatKind::ExpandedConstant` I made it a bit less ad-hoc. In particular, I removed `is_inline: bool` that was just caching the output of `tcx.def_kind(def_id)`. This makes inline consts a tiny bit less special in patterns. r? `@oli-obk` cc `@Zalathar`
2025-04-07Rollup merge of #139035 - nnethercote:PatKind-Missing, r=oli-obkStuart Cook-0/+2
Add new `PatKind::Missing` variants To avoid some ugly uses of `kw::Empty` when handling "missing" patterns, e.g. in bare fn tys. Helps with #137978. Details in the individual commits. r? ``@oli-obk``
2025-04-06Reuse `parent_args`Nadrieril-12/+3
2025-04-06Add the inline const type annotation in pattern loweringNadrieril-2/+34
2025-04-06Tweak `lower_pat_expr`Nadrieril-35/+33
2025-04-06Remove the `is_inline` field from `PatKind::ExpandedConstant`Nadrieril-26/+15
2025-04-06Let `const_to_pat` handle the `ExpandedConstant` wrappingNadrieril-15/+12
2025-04-03Make LevelAndSource a structOli Scherer-1/+1
2025-04-02Auto merge of #139269 - matthiaskrgr:rollup-pk78gig, r=matthiaskrgrbors-34/+35
Rollup of 6 pull requests Successful merges: - #138992 (literal pattern lowering: use the pattern's type instead of the literal's in `const_to_pat`) - #139211 (interpret: add a version of run_for_validation for &self) - #139235 (`AstValidator` tweaks) - #139237 (Add a dep kind for use of the anon node with zero dependencies) - #139260 (Add dianqk to codegen reviewers) - #139264 (Fix two incorrect turbofish suggestions) r? `@ghost` `@rustbot` modify labels: rollup
2025-04-02Move methods from `Map` to `TyCtxt`, part 5.Nicholas Nethercote-1/+1
This eliminates all methods on `Map`. Actually removing `Map` will occur in a follow-up PR.
2025-03-28Add `{ast,hir,thir}::PatKind::Missing` variants.Nicholas Nethercote-0/+2
"Missing" patterns are possible in bare fn types (`fn f(u32)`) and similar places. Currently these are represented in the AST with `ast::PatKind::Ident` with no `by_ref`, no `mut`, an empty ident, and no sub-pattern. This flows through to `{hir,thir}::PatKind::Binding` for HIR and THIR. This is a bit nasty. It's very non-obvious, and easy to forget to check for the exceptional empty identifier case. This commit adds a new variant, `PatKind::Missing`, to do it properly. The process I followed: - Add a `Missing` variant to `{ast,hir,thir}::PatKind`. - Chang `parse_param_general` to produce `ast::PatKind::Missing` instead of `ast::PatKind::Missing`. - Look through `kw::Empty` occurrences to find functions where an existing empty ident check needs replacing with a `PatKind::Missing` check: `print_param`, `check_trait_item`, `is_named_param`. - Add a `PatKind::Missing => unreachable!(),` arm to every exhaustive match identified by the compiler. - Find which arms are actually reachable by running the test suite, changing them to something appropriate, usually by looking at what would happen to a `PatKind::Ident`/`PatKind::Binding` with no ref, no `mut`, an empty ident, and no subpattern. Quite a few of the `unreachable!()` arms were never reached. This makes sense because `PatKind::Missing` can't happen in every pattern, only in places like bare fn tys and trait fn decls. I also tried an alternative approach: modifying `ast::Param::pat` to hold an `Option<P<Pat>>` instead of a `P<Pat>`, but that quickly turned into a very large and painful change. Adding `PatKind::Missing` is much easier.
2025-03-26add a temporary workaround for `string_deref_patterns`dianne-2/+21
2025-03-26`lower_pat_expr`: use the pattern's type instead of the literal'sdianne-33/+15
This allows us to remove the field `treat_byte_string_as_slice` from `TypeckResults`, since the pattern's type contains everything necessary to get the correct lowering for byte string literal patterns. This leaves the implementation of `string_deref_patterns` broken, to be fixed in the next commit.
2025-03-18Move `hir::Item::ident` into `hir::ItemKind`.Nicholas Nethercote-3/+3
`hir::Item` has an `ident` field. - It's always non-empty for these item kinds: `ExternCrate`, `Static`, `Const`, `Fn`, `Macro`, `Mod`, `TyAlias`, `Enum`, `Struct`, `Union`, Trait`, TraitAalis`. - It's always empty for these item kinds: `ForeignMod`, `GlobalAsm`, `Impl`. - For `Use`, it is non-empty for `UseKind::Single` and empty for `UseKind::{Glob,ListStem}`. All of this is quite non-obvious; the only documentation is a single comment saying "The name might be a dummy name in case of anonymous items". Some sites that handle items check for an empty ident, some don't. This is a very C-like way of doing things, but this is Rust, we have sum types, we can do this properly and never forget to check for the exceptional case and never YOLO possibly empty identifiers (or possibly dummy spans) around and hope that things will work out. The commit is large but it's mostly obvious plumbing work. Some notable things. - A similar transformation makes sense for `ast::Item`, but this is already a big change. That can be done later. - Lots of assertions are added to item lowering to ensure that identifiers are empty/non-empty as expected. These will be removable when `ast::Item` is done later. - `ItemKind::Use` doesn't get an `Ident`, but `UseKind::Single` does. - `lower_use_tree` is significantly simpler. No more confusing `&mut Ident` to deal with. - `ItemKind::ident` is a new method, it returns an `Option<Ident>`. It's used with `unwrap` in a few places; sometimes it's hard to tell exactly which item kinds might occur. None of these unwraps fail on the test suite. It's conceivable that some might fail on alternative input. We can deal with those if/when they happen. - In `trait_path` the `find_map`/`if let` is replaced with a loop, and things end up much clearer that way. - `named_span` no longer checks for an empty name; instead the call site now checks for a missing identifier if necessary. - `maybe_inline_local` doesn't need the `glob` argument, it can be computed in-function from the `renamed` argument. - `arbitrary_source_item_ordering::check_mod` had a big `if` statement that was just getting the ident from the item kinds that had one. It could be mostly replaced by a single call to the new `ItemKind::ident` method. - `ItemKind` grows from 56 to 64 bytes, but `Item` stays the same size, and that's what matters, because `ItemKind` only occurs within `Item`.
2025-03-12Rollup merge of #137504 - nnethercote:remove-Map-4, r=ZalatharManish Goregaokar-1/+1
Move methods from Map to TyCtxt, part 4. A follow-up to https://github.com/rust-lang/rust/pull/137350. r? ```@Zalathar```
2025-03-12Move methods from `Map` to `TyCtxt`, part 4.Nicholas Nethercote-1/+1
Continuing the work from #137350. Removes the unused methods: `expect_variant`, `expect_field`, `expect_foreign_item`. Every method gains a `hir_` prefix.
2025-03-09Explain weird quirk in user type annotation loweringMichael Goulet-1/+1
2025-03-06Implement .use keyword as an alias of cloneSantiago Pastorino-0/+1
2025-02-25Teach structured errors to display short `Ty`Esteban Küber-5/+1
Make it so that every structured error annotated with `#[derive(Diagnostic)]` that has a field of type `Ty<'_>`, the printing of that value into a `String` will look at the thread-local storage `TyCtxt` in order to shorten to a length appropriate with the terminal width. When this happen, the resulting error will have a note with the file where the full type name was written to. ``` error[E0618]: expected function, found `((..., ..., ..., ...), ..., ..., ...)`` --> long.rs:7:5 | 6 | fn foo(x: D) { //~ `x` has type `(... | - `x` has type `((..., ..., ..., ...), ..., ..., ...)` 7 | x(); //~ ERROR expected function, found `(... | ^-- | | | call expression requires function | = note: the full name for the type has been written to 'long.long-type-14182675702747116984.txt' = note: consider using `--verbose` to print the full type name to the console ```