The length of byte strings containing escaped newlines is displayed two
bytes longer when the first escaped character is a newline.
This is due to a small bug in handling the first escaped newline in
string literals.
Closes#13567
Feat: extracted method from trait impl is placed in existing impl
**Before**
https://user-images.githubusercontent.com/1759192/183872883-3b0eafd2-d1dc-440e-9e66-38e3372f8b64.mp4
**After**
https://user-images.githubusercontent.com/1759192/183875769-87f34c7d-52f0-4dfc-9766-f591ee738ebb.mp4
Previously, when triggering a method extraction from within an impl trait block, then this would always create a new impl block for
the struct, even if there already is one. Now, if there is already an existing trait-less impl block, then it'll put the extracted method in there.
**Caveats**:
- It currently requires the target impl block to be non-empty. This limitation is because the current architecture takes a `node_to_insert_after` as reference for where to insert the extracted function. An empty impl block doesn't have such a reference node, since it's empty. It seems that supporting this requires a much larger and more complex change.
- This is my first contribution in rust, so apologies for any beginner mistakes.
internal: Migrate `ide_assists::utils` and `ide_assists::handlers` to use format arg captures (part 1)
This not only serves as making future migration to mutable syntax trees easier, it also finds out what needs to be migrated in the first place.
~~Aside from the first commit, subsequent commits are structured to only deal with one file/handler at a time.~~
This is the first of 3 PRs, migrating:
Utils:
- `gen_trait_fn_body`
- `render_snippet`
- `ReferenceConversion`
- `convert_type`
- `getter`
Handlers:
- `add_explicit_type`
- `add_return_type`
- `add_turbo_fish`
- `apply_demorgan`
- `auto_import`
- `convert_comment_block`
- `convert_integer_literal`
- `convert_into_to_from`
- `convert_iter_for_each_to_for`
- `convert_let_else_to_match`
- `convert_tuple_struct_to_named_struct`
- `convert_two_arm_bool_match_to_matches_macro`
- `destructure_tuple_binding`
- `extract_function`
- `extract_module`
- `extract_struct_from_enum_variant`
- `extract_type_alias`
- `extract_variable`
- `fix_visibility`
scip: Generate symbols for local crates.
Consider something like:
```
// a.rs
pub struct Foo { .. } // Foo is "local 1"
fn something() {
crate:🅱️:Bar::new() // Bar is "local 1", but of "b.rs"
}
// b.rs
pub struct Bar { .. } // "local 1"
```
Without this there's no way to disambiguate whether "local 1" references "Bar" or "Foo".
feat: add config for inserting must_use in `generate_enum_as_method`
Should fix#13312
Didn't add a test because I was not sure on how to add test for a specific configuration option, tried to look for the usages for other `AssistConfig` variants but couldn't find any in `tests`. If there is a way to test this, do point me towards it.
I tried to extract the formatting string as a common `template_string` and only have if-else for that, but it didn't compile :(
Also it seems these tests are failing:
```
test config::tests::generate_config_documentation ... FAILED
test config::tests::generate_package_json_config ... FAILED
```
Can you also point me to how to correct these 😅 ( I guess there is some command to automatically generate these? )
fix: make custom expr prefix completions to understand refs
Possible fix of #7929
While reviewing the postfix completion code I saw that while calling `add_custom_postfix_completions` we were doing it under the part where reference was not taken into consideration, but as we are only adding postfix completions with `Expr` scope ( [source](ba28e19b78/crates/ide-completion/src/completions/postfix.rs (L272)) )
I shifted the `add_custom_postfix_completions` call to part where references are considered
I am not sure if this is the correct fix or I am understanding the problem exactly but this small move seemed to have fixed the issue :)
feat: show signature help when calling generic types implementing `FnOnce`
This queries chalk for the `FnOnce` impl of callees and takes argument and return types from there, making generic `Callable`s available to the IDE. This makes signature help work for them, and potentially allows other features to take generic callables into account in the future.
fix: disregard type variable expectation for if expressions
Fixes#13522
As [the comment](8142d1f606/crates/hir-ty/src/infer.rs (L1087-L1090)) on `Expectation::adjust_for_branches` explains:
> If the expected type is just a type variable, then don't use an expected type. Otherwise, we might write parts of the type when checking the 'then' block which are incompatible with the 'else' branch.
Note that we already use it in match expressions. I've added tests for them too nevertheless.
Switch to upstream `positionEncoding`
Closes#13481
This drops support for the custom extension, but that's probably fine.
Draft because it's not tested yet.
fix: Test all generic args for trait when finding matching impl
Addresses https://github.com/rust-lang/rust-analyzer/pull/13463#issuecomment-1287816680
When finding matching impl for a trait method, we've been testing the unifiability of self type. However, there can be multiple impl of a trait for the same type with different generic arguments for the trait. This patch takes it into account and tests the unifiability of all type arguments for the trait (the first being the self type) thus enables rust-analyzer to find the correct impl even in such cases.
Support const generics for builtin derive macro
Fixes#13121
We have been treating every generic parameter as type parameter during builtin derive macro expansion. This patch adds support for const generics in such expansions.
feat: add multiple getters mode in `generate_getter`
This commit adds two modes to generate_getter action.
First, the plain old working on single fields.
Second, working on a selected range of fields.
Should partially solve #13246
If this gets approved will create a separate PR for setters version of the same
### Points to help in review:
- `generate_getter_from_record_info` contains code which is mostly taken from assist before refactor
- Same goes for `parse_record_fields`
- There are changes in other assists, as one of the methods in utils named `find_struct_impl` is changed, before it used to accept a single `fn_name`, now it takes a list of function names to check against. All old impls are updated to create a small list to pass their single element.
### Assumptions:
- If any of the fields have an implementation, the action will quit.
Implement invocation strategy config
Fixes https://github.com/rust-lang/rust-analyzer/issues/10793
This allows to change how we run build scripts (and `checkOnSave`), exposing two configs:
- `once`: run the specified command once in the project root (the working dir of the server)
- `per_workspace`: run the specified command per workspace in the corresponding workspace
This also applies to `checkOnSave` likewise, though `once_in_root` is useless there currently, due to https://github.com/rust-lang/cargo/issues/11007
The reason for that was that we were calculating the crate defmaps
of the file we are saving by accident causing us to get stuck waiting
on their expensive computation, while we only need the relevant crate
id.
feat: Diagnose some incorrect usages of the question mark operator
Trying to figure out how the type stuff in r-a works some more, I think I am doing this correct here but I am not quite sure :)
Bump chalk
There's a bug in current chalk that prevents us from properly supporting GATs, which is supposed to be fixed in v0.86. Note the following:
- v0.86 is only going to be released next Sunday so I'll keep this PR as draft until then.
- This doesn't compile without https://github.com/rust-lang/chalk/pull/779, which I hope will be included in v0.86. I confirmed this compiles with it locally.
Two breaking changes from v0.84:
- `TypeFolder` has been split into `TypeFolder` and `FallibleTypeFolder` (https://github.com/rust-lang/chalk/pull/772)
- `ProjectionTy::self_type_parameter()` has been removed (https://github.com/rust-lang/chalk/pull/778)
Two breaking changes:
- `TypeFolder` has been split into `TypeFolder` and `FallibleTypeFolder`
- `ProjectionTy::self_type_parameter()` has been removed
feat: Autocomplete Cargo-defined env vars in `env!` and `option_env!` (#12448)
Closes#12448
Important to know:
- Variables are taken from https://doc.rust-lang.org/cargo/reference/environment-variables.html and hardcoded as a const array.
- For the sake of simplicity I didn't include the autocompletion of `CARGO_BIN_EXE_<name>` and `OUT_DIR` since it would require information about build.rs and binary name. If somebody knows an easy way of obtaining them I can add those vars as well :)
fix: reorder dyn bounds on render
Fixes#13368#13192 changed the order of dyn bounds, violating the [contract](3a69435af7/crates/hir-ty/src/display.rs (L896-L901)) with `write_bounds_like_dyn_trait()` on render. The projection bounds are expected to come right after the trait bound they are accompanied with.
Although the reordering procedure can be made a bit more efficient, I opted for relying only on the [invariants](3a69435af7/crates/hir-ty/src/lower.rs (L995-L998)) currently documented in `lower_dyn_trait()`. It's not the hottest path and dyn bounds tend to be short so I believe it shouldn't hurt performance noticeably.
Use $crate instead of std for panic builtin_fn_macro
This should be closer to the expected output and gets rid of a few type mismatches in rustc/library
Refactor completions expansion
Depends on https://github.com/rust-lang/rust-analyzer/pull/13384
Diff is unfortunately massive as I changed the functions in the analysis module from associated ones to standalone (unfortunately without an extra commit)
Don't report build-scripts and proc-macros as metadata progress
Seems somewhat confusing to me, given `metadata` is already the step we do for workspace loading
Expand unmatched mbe fragments to reasonable default token trees
Currently we expand unmatched fragments by not replacing them at all, leaving us with `$ident`. This trips up the parser or subsequent macro calls. Instead it makes more sense to replace these with some reasonable default depending on the fragment kind which should make more recursive macro calls work better for completions.
Currently we expand unmatched fragments by not replacing them at all,
leaving us with `$ident`. This trips up the parser or subsequent macro
calls. Instead it makes more sense to replace these with some reasonable
default depending on the fragment kind which should make more recursive
macro calls work better for completions.
Add convert_named_struct_to_tuple_struct assist
Closes#11643, since the assist for converting in the other direction is already there (I based most of the implementation and all of the tests on it).
internal: Add `GenericParamList::to_generic_args` and `{TypeParam,ConstParam}::remove_default` APIs
Also fixes `generate_impl` not removing the default const param value, though it seems that no one has encountered or reported that issue yet 😅
This initially started out as refactoring `utils::generate_impl_text_inner` to understand it better (which was the reason for adding `{TypeParam,ConstParam}::remove_default`), but ended up also finding another place that needed `GenericParamList::to_generic_args`, hence its addition in here.
The main change here should be that flags are not inhereted, so
$ rust-analyzer analysis-stats . -v -v
would do what it should do
We also no longer Don\'t
fix: use `BoundVar`s from current generic scope
Fixup for #13335, addresses https://github.com/rust-lang/rust-analyzer/pull/13339#issuecomment-1266654607
Before the change in generic parameter order, `BoundVar`s for trait reference didn't change whether you are in an impl's scope or in an associated item's scope. Now that item's generic params come before its parent's, we need to shift their indices when we are in an associated item's scope.
fix: treat enum variants as generic item on their own
Fixup for #13335
It turns out I tried to merge two procedures into one utility function without noticing the incompatibility.
This time I *did* run analysis-stats on the four crates and confirmed it doesn't crash and this patch doesn't cause regression.
internal: change generic parameter order
tl;dr: This PR changes the `Substitution` for trait items and methods like so:
```rust
trait Trait<TP, const CP: usize> { // note the implicit Self as first parameter
type Type<TC, const CC: usize>;
fn f<TC, const CC: usize>() {}
}
impl<TP, const CP: usize> S {
fn f<TC, const CC: usize>() {}
}
```
- before this PR: `[Self, TP, CP, TC, CC]` for each trait item, `[TP, CP, TC, CC]` for `S::f`
- after this PR: `[TC, CC, Self, TP, CP]` for each trait item, `[TC, CC, TP, CP]` for `S::f`
---
This PR "inverts" the generic parameters/arguments of an item and its parent. This is to fulfill [chalk's expectation](d875af0ff1/chalk-solve/src/rust_ir.rs (L498-L502)) on the order of generic arguments in `Substitution`s for generic associated types and it's one step forward for GATs support (hopefully). Although chalk doesn't put any constraint for other items, it feels more natural to get everything aligned than special casing GATs.
One complication is that `TyBuilder` now demands its users to pass in parent's `Substitution` upon construction unless it's obvious that the the item has no parent (e.g. an ADT never has parent). All users *should* already know the parent of the item in question, and without this, it cannot be easily reasoned about whether we're pushing the argument for the item or for its parent.
Some additional notes:
- f8f5a5ea57: This isn't related to the change, but I felt it's nicer.
- 78977cd86c: There's one major change here other than the generic param order: Default arguments are now bound by the same `Binder` as the item in question rather than a `Binder` limited to parameters they can refer to (i.e. arguments that syntactically appear before them). Now that the order of generic parameters is changed, it would be somewhat complicated to make such `Binder`s as before, and the "full" `Binder`s shouldn't be a problem because we already make sure that the default arguments don't refer to the generic arguments after them with `fallback_bound_vars()`.
- 7556f74b16: This is split from 4385d3dcd0 to make it easy to revert if it turns out that the GATs with const generics panic is actually not resolved with this PR. cc #11878#11957
This fixes a typo first appearing in #94624
in which test-macro diagnostic uses "a" article twice.
Since I searched sources for " a a " sequences,
I also fixed the same issue in a few source files where I found it.
Signed-off-by: Petr Portnov <gh@progrm-jarvis.ru>
This commit "inverts" the order of generic parameters/arguments of an
item and its parent. This is to fulfill chalk's expectation on the
order of `Substitution` for generic associated types and it's one step
forward for their support (hopefully).
Although chalk doesn't put any constraint on the order of `Substitution`
for other items, it feels natural to get everything aligned rather than
special casing GATs.
One complication is that `TyBuilder` now demands its users to pass in
parent's `Substitution` upon construction unless it's obvious that the
the item has no parent (e.g. an ADT never has parent). All users
*should* already know the parent of the item in question, and without
this, it cannot be easily reasoned about whether we're pushing the
argument for the item or for its parent.
Quick comparison of how this commit changes `Substitution`:
```rust
trait Trait<TP, const CP: usize> {
type Type<TC, const CC: usize> = ();
fn f<TC, const CC: usize>() {}
}
```
- before this commit: `[Self, TP, CP, TC, CC]` for each trait item
- after this commit: `[TC, CC, Self, TP, CP]` for each trait item
Amalgamate file changes for the same file ids in process_changes
When receiving multiple change events for a single file id where the last change is a delete the server panics, as it tries to access the file contents of a deleted file. This occurs due to the VFS changes and the in memory file contents being updated immediately, while `process_changes` processes the events afterwards in sequence which no longer works as it will only observe the final file contents. By folding these events together, we will no longer try to process these intermediate changes, as they aren't relevant anyways.
Potentially fixes https://github.com/rust-lang/rust-analyzer/issues/13236
When receiving multiple change events for a single file id where the
last change is a delete the server panics, as it tries to access the
file contents of a deleted file. This occurs due to the VFS changes and
the in memory file contents being updated immediately, while
`process_changes` processes the events afterwards in sequence which no
longer works as it will only observe the final file contents. By
folding these events together, we will no longer try to process these
intermediate changes, as they aren't relevant anyways.
Potentially fixes https://github.com/rust-lang/rust-analyzer/issues/13236
Feature: Add assist to unwrap tuple declarations
> Implement #12923 for only tuples.
>
> Does not implement unwrapping for structs, as mentioned in the issue.
Add assist to unwrap tuples declarations to separate declarations.
```rust
fn main() {
$0let (foo, bar, baz) = (1.0, "example", String::new())
}
```
becomes:
```rust
fn main() {
let foo = 1.0;
let bar = "example";
let baz = String::new();
}
```
## Changelog
### Feature
- Added assist to unwrap tuple declarations.
feat: type inference for generators
This PR implements basic type inference for generator and yield expressions.
Things not included in this PR:
- Generator upvars and generator witnesses are not implemented. They are only used to determine auto trait impls, so basic type inference should be fine without them, but method resolutions with auto trait bounds may not be resolved correctly.
Open questions:
- I haven't (yet) implemented `HirDisplay` for `TyKind::Generator`, so generator types are just shown as "{{generator}}" (in tests, inlay hints, hovers, etc.), which is not really nice. How should we show them?
- I added moderate amount of stuffs to minicore. I especially didn't want to add `impl<T> Deref for &T` and `impl<T> Deref for &mut T` exclusively for tests for generators; should I move them into the test fixtures or can they be placed in minicore?
cc #4309
proc-macro ABI breakage still affects the tests when a new stable version
releases. Ideally we'd still be able to run the tests on the rust-analyzer
repo without having to update the proc-macro ABI, but for now just to
unblock CI we will ignore them here, as they are still run in upstream.
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?
Add a new configuration settings to set env vars when running cargo, rustc, etc. commands: cargo.extraEnv and checkOnSave.extraEnv
It can be extremely useful to be able to set environment variables when rust-analyzer is running various cargo or rustc commands (such as `cargo check`, `cargo --print cfg` or `cargo metadata`): users may want to set custom `RUSTFLAGS`, change `PATH` to use a custom toolchain or set a different `CARGO_HOME`.
There is the existing `server.extraEnv` setting that allows env vars to be set when the rust-analyzer server is launched, but using this as the recommended mechanism to also configure cargo/rust has some drawbacks:
- It convolutes configuring the rust-analyzer server with configuring cargo/rustc (one may want to change the `PATH` for cargo/rustc without affecting the rust-analyzer server).
- The name `server.extraEnv` doesn't indicate that cargo/rustc will be affected but renaming it to `cargo.extraEnv` doesn't indicate that the rust-analyzer server would be affected.
- To make the setting useful, it needs to be dynamically reloaded without requiring that the entire extension is reloaded. It might be possible to do this, but it would require the client communicating to the server what the overwritten env vars were at first launch, which isn't easy to do.
This change adds two new configuration settings: `cargo.extraEnv` and `checkOnSave.extraEnv` that can be used to change the environment for the rust-analyzer server after launch (thus affecting any process that rust-analyzer invokes) and the `cargo check` command respectively. `cargo.extraEnv` supports dynamic changes by keeping track of the pre-change values of environment variables, thus it can undo changes made previously before applying the new configuration (and then requesting a workspace reload).
Fix add reference action on macros.
Before we were using the range of the corresponding expression node in the macro expanded file, which is obviously incorrect as we are setting the text in the original source.
For some reason, the test I added is failing and I haven't found a way to fix it. Does anyone know why `check_fix` wouldn't work with macros? Getting this error:
```text
thread 'handlers::type_mismatch::tests::test_add_reference_to_macro_call' panicked at 'no diagnostics', crates/ide-diagnostics/src/handlers/type_mismatch.rs:317:9
```
closes#13219
Use memmem when searching for usages in ide-db
We already have this dependency, so there is no reason not to use it as it is generally faster than std in our use case.