feat: Display the value of enum variant on hover
fixes#12955
This PR adds const eval support for enums, as well as showing their value on hover, just as consts currently have.
I developed these two things at the same time, but I've realized now that they are separate. However since the hover is just a 10 line change (not including tests), I figured I may as well put them in the same PR. Though if you want them split up into "enum const eval support" and "show enum variant value on hover", I think that's reasonable too.
Since this adds const eval support for enums this also allows consts that reference enums to have their values computed now too.
The const evaluation itself is quite rudimentary, it doesn't keep track of the actual type of the enum, but it turns out that Rust doesn't actually either, and `E::A as u8` is valid regardless of the `repr` on `E`.
It also doesn't really care about what expression the enum variant contains, it could for example be a string, despite that not being allowed, but I guess it's up to the `cargo check` diagnostics to inform of such issues anyway?
fixup: remove unnecessary `Option`
Fixup for #13223, two things:
- `normalize_projection_query()` (and consequently `HirDatabase::normalize_projection()`) never returns `None` (well, it used to when I first wrote it...), so just return `Ty` instead of `Option<Ty>`
- When chalk cannot normalize projection uniquely, `normalize_trait_assoc_type()` used to return `None` before #13223, but not anymore because of the first point. I restored the behavior so its callers work as before.
fix: handle lifetime variables in projection normalization
Fixes#12674
The problem is that we've been skipping the binders of normalized projections assuming they should be empty, but the assumption is unfortunately wrong. We may get back lifetime variables and should handle them before returning them as normalized projections. For those who are curious why we get those even though we treat all lifetimes as 'static, [this comment in chalk](d875af0ff1/chalk-solve/src/infer/unify.rs (L888-L908)) may be interesting.
I thought using `InferenceTable` would be cleaner than the other ways as it already has the methods for canonicalization, normalizing projection, and resolving variables, so moved goal building and trait solving logic to a new `HirDatabase` query. I made it transparent query as the query itself doesn't do much work but the eventual call to `HirDatabase::trait_solve_query()` does.
This hir expression isn't needed and only existed as it was simpler to
deal with at first as it gave us a direct mapping for the ast version of
the same construct. This PR removes it, properly handling the statements
that are introduced by macro call expressions.
internal: Record all macro definitions in ItemScope
Fixes https://github.com/rust-lang/rust-analyzer/issues/12100
Doesn't resolve the shadowing issues though, fixing those is gonna be really tricky I believe unless we can come up with a nice scheme to "order" item tree items (using syntax ranges and file ids would be a pain and also a bad idea since that'll require us to potentially reparse files in collection).
This change attempts to resolve issue #7636: Extract into Function does not
create a generic function with constraints when extracting generic code.
In `FunctionBody::analyze_container`, we now traverse the `ancestors` in search
of `AnyHasGenericParams`, and attach any `GenericParamList`s and `WhereClause`s
we find to the `ContainerInfo`.
Later, in `format_function`, we collect all the `GenericParam`s and
`WherePred`s from the container, and filter them to keep only types matching
`TypeParam`s used within the newly extracted function body or param list. We
can then include the new `GenericParamList` and `WhereClause` in the new
function definition.
This change only impacts `TypeParam`s. `LifetimeParam`s and `ConstParam`s are
out of scope for this change.
feat: Show witnesses of non-exhaustiveness in `missing-match-arm` diagnostic
Shamelessly copied from rustc. Thus reporting format is same.
This extends public api `hir::diagnostics::MissingMatchArms` with `uncovered_patterns: String` field. It does not expose data for implementing a quick fix yet.
-----
Worth to note: current implementation does not give a comprehensive list of missing patterns. Also mentioned in [paper](http://moscova.inria.fr/~maranget/papers/warn/warn.pdf):
> One may think that algorithm I should make an additional effort to provide more
> non-matching values, by systematically computing recursive calls on specialized
> matrices when possible, and by returning a list of all pattern vectors returned by
> recursive calls. We can first observe that it is not possible in general to supply the
> users with all non-matching values, since the signature of integers is (potentially)
> infinite.
Distinguish between
- there is no build data (for some reason?)
- there is build data, but the cargo package didn't build a proc macro dylib
- there is a proc macro dylib, but it didn't contain the proc macro we expected
- the name did not resolve to any macro (this is now an
unresolved_macro_call even for attributes)
I changed the handling of disabled attribute macro expansion to
immediately ignore the macro and report an unresolved_proc_macro,
because otherwise they would now result in loud unresolved_macro_call
errors. I hope this doesn't break anything.
Also try to improve error ranges for unresolved_macro_call / macro_error
by reusing the code for unresolved_proc_macro. It's not perfect but
probably better than before.
- remove Valid, it serves no purpose and just obscures the diff
- rename some things
- don't use is_valid_candidate when searching for impl, it's not necessary
fix: doc url link type
fix: #12033
I did some debugging and found the cause looks like to be some doc links' `LinkType` are kept as `Shortcut` which don't make sense for url links.
This PR should resolve both problems in the origin issue, but aside this PR, more work are needed for doc_links.
about `LinkType`: f29bd1e228/src/lib.rs (L191-L210)
11925: internal: Add and use `HirFormatter::write_{str,char}` r=Veykril a=lnicola
Saves slightly over 3 KB of `text`, but comparing the total with that from two weeks ago in #11776, this is a losing battle (we're 951 KB larger).
```
text data bss dec hex filename
24693512 1542704 4424 26240640 1906680 rust-analyzer-baseline
24690216 1542112 4424 26236752 1905750 rust-analyzer-pr
```
Co-authored-by: Laurențiu Nicola <lnicola@dend.ro>
While we don't support const args in type inference yet, we can at least
make use of the fallback path resolution to resolve paths in const args
in the IDE layer to enable some features for them.
11774: feat: Tag macro calls as unsafe if they expand to unsafe expressions r=Veykril a=Veykril
as long as they aren't inside an unsafe block inside the macro that is.
Co-authored-by: Lukas Wirth <lukastw97@gmail.com>
11660: Insert dummy values for const generics in subst r=flodiebold a=HKalbasi
fix#11659
This is a band-aid until proper const generic support.
Co-authored-by: hkalbasi <hamidrezakalbasi@protonmail.com>
- don't return the receiver type from method resolution; instead just
return the autorefs/autoderefs that happened and repeat them. This
ensures all the effects like trait obligations and whatever we learned
about type variables from derefing them are actually applied. Also, it
allows us to get rid of `decanonicalize_ty`, which was just wrong in
principle.
- Autoderef itself now directly works with an inference table. Sadly
this has the effect of making it harder to use as an iterator, often
requiring manual `while let` loops. (rustc works around this by using
inner mutability in the inference context, so that things like unifying
types don't require a unique reference.)
- We now record the adjustments (autoref/deref) for method receivers
and index expressions, which we didn't before.
- Removed the redundant crate parameter from method resolution, since
the trait_env contains the crate as well.
- in the HIR API, the methods now take a scope to determine the trait env.
`Type` carries a trait env, but I think that's probably a bad decision
because it's easy to create it with the wrong env, e.g. by using
`Adt::ty`. This mostly didn't matter so far because
`iterate_method_candidates` took a crate parameter and ignored
`self.krate`, but the trait env would still have been wrong in those
cases, which I think would give some wrong results in some edge cases.
Fixes#10058.
In code like this:
```rust
impl<T> Option<T> {
fn as_deref(&self) -> T::Target where T: Deref {}
}
```
when trying to resolve the associated type `T::Target`, we were only
looking at the bounds on the impl (where the type parameter is defined),
but the method can add additional bounds that can also be used to refer
to associated types. Hence, when resolving such an associated type, it's
not enough to just know the type parameter T, we also need to know
exactly where we are currently.
This fixes#11364 (beta apparently switched some bounds around).
11145: feat: add config to use reasonable default expression instead of todo! when filling missing fields r=Veykril a=bnjjj
Use `Default::default()` in struct fields when we ask to fill it instead of putting `todo!()` for every fields
before:
```rust
pub enum Other {
One,
Two,
}
pub struct Test {
text: String,
num: usize,
other: Other,
}
fn t_test() {
let test = Test {<|>};
}
```
after:
```rust
pub enum Other {
One,
Two,
}
pub struct Test {
text: String,
num: usize,
other: Other,
}
fn t_test() {
let test = Test {
text: String::new(),
num: 0,
other: todo!(),
};
}
```
Co-authored-by: Benjamin Coenen <5719034+bnjjj@users.noreply.github.com>
Co-authored-by: Coenen Benjamin <benjamin.coenen@hotmail.com>
10872: ide_db: build symbol index from crate def map r=Veykril a=jhgg
fixes#4842, #10764
Is this looking correct? 👀
- [x] build the symbol index based upon the CrateDefMap for the given crate in `crate_symbols`
- [x] make it multi threaded again, and figure out how to cache each moduleid's symbol index in salsa.
- [x] NavigationTarget for names in macros is wrong, need to figure out how to compute a text range in the original file id?
- [x] cleanup some duped code
- [x] collect macros from `ItemScope.declared_macros()` into symbol index.
- [x] store declared macros in `ItemScope` so we can figure out where macros were defined for the index.
- [x] do something about `SymbolIndex::for_files` - ideally it should use the new module symbol index stuff.
- [x] delete `source_file_to_file_symbols` & co...
- [x] figure out what to do about `library_symbols`
- [x] maybe... speed up the new `library_symbols` - the new impl is probably much slower, and definitely much less parallel. **deciding to do nothing here, we can optimize later if necerssary.**
- [x] fix failing test: `navigation_target::tests::test_nav_for_symbol` - notably the crate def map doesn't seem to find declarations inside function.
- [x] now a bunch of other tests are failing around auto_import & qualify_path handlers. :(
- [x] need to assoc items in traits and impls
Co-authored-by: Jake Heinz <jh@discordapp.com>