1
Fork 0

Auto merge of #100626 - Dylan-DPC:rollup-mwbm7kj, r=Dylan-DPC

Rollup of 6 pull requests

Successful merges:

 - #99942 (Fix nonsense non-tupled `Fn` trait error)
 - #100609 (Extend invalid floating point literal suffix suggestion)
 - #100610 (Ast and parser tweaks)
 - #100613 (compiletest: fix typo in runtest.rs)
 - #100616 (⬆️ rust-analyzer)
 - #100622 (Support 128-bit atomics on all aarch64 targets)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2022-08-16 18:07:02 +00:00
commit 5746c752f4
139 changed files with 5986 additions and 5190 deletions

View file

@ -497,7 +497,6 @@ pub struct WhereRegionPredicate {
/// E.g., `T = int`.
#[derive(Clone, Encodable, Decodable, Debug)]
pub struct WhereEqPredicate {
pub id: NodeId,
pub span: Span,
pub lhs_ty: P<Ty>,
pub rhs_ty: P<Ty>,
@ -3042,6 +3041,7 @@ mod size_asserts {
static_assert_size!(Attribute, 32);
static_assert_size!(Block, 48);
static_assert_size!(Expr, 104);
static_assert_size!(ExprKind, 72);
static_assert_size!(Fn, 192);
static_assert_size!(ForeignItem, 160);
static_assert_size!(ForeignItemKind, 72);
@ -3051,9 +3051,13 @@ mod size_asserts {
static_assert_size!(Item, 200);
static_assert_size!(ItemKind, 112);
static_assert_size!(Lit, 48);
static_assert_size!(LitKind, 24);
static_assert_size!(Pat, 120);
static_assert_size!(PatKind, 96);
static_assert_size!(Path, 40);
static_assert_size!(PathSegment, 24);
static_assert_size!(Stmt, 32);
static_assert_size!(StmtKind, 16);
static_assert_size!(Ty, 96);
static_assert_size!(TyKind, 72);
}

View file

@ -935,8 +935,7 @@ pub fn noop_visit_where_predicate<T: MutVisitor>(pred: &mut WherePredicate, vis:
visit_vec(bounds, |bound| noop_visit_param_bound(bound, vis));
}
WherePredicate::EqPredicate(ep) => {
let WhereEqPredicate { id, span, lhs_ty, rhs_ty } = ep;
vis.visit_id(id);
let WhereEqPredicate { span, lhs_ty, rhs_ty } = ep;
vis.visit_span(span);
vis.visit_ty(lhs_ty);
vis.visit_ty(rhs_ty);

View file

@ -1498,9 +1498,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
),
in_where_clause: true,
}),
WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => {
WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, span }) => {
hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
hir_id: self.lower_node_id(id),
lhs_ty: self
.lower_ty(lhs_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
rhs_ty: self

View file

@ -640,11 +640,7 @@ impl<'a> TraitDef<'a> {
}
ast::WherePredicate::EqPredicate(we) => {
let span = we.span.with_ctxt(ctxt);
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
id: ast::DUMMY_NODE_ID,
span,
..we.clone()
})
ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { span, ..we.clone() })
}
}
}));

View file

@ -778,7 +778,6 @@ impl<'hir> WhereRegionPredicate<'hir> {
/// An equality predicate (e.g., `T = int`); currently unsupported.
#[derive(Debug, HashStable_Generic)]
pub struct WhereEqPredicate<'hir> {
pub hir_id: HirId,
pub span: Span,
pub lhs_ty: &'hir Ty<'hir>,
pub rhs_ty: &'hir Ty<'hir>,

View file

@ -876,10 +876,7 @@ pub fn walk_where_predicate<'v, V: Visitor<'v>>(
visitor.visit_lifetime(lifetime);
walk_list!(visitor, visit_param_bound, bounds);
}
WherePredicate::EqPredicate(WhereEqPredicate {
hir_id, ref lhs_ty, ref rhs_ty, ..
}) => {
visitor.visit_id(hir_id);
WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, .. }) => {
visitor.visit_ty(lhs_ty);
visitor.visit_ty(rhs_ty);
}

View file

@ -1750,6 +1750,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
&& let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
&& let Some(def_id) = def_id.as_local()
&& terr.involves_regions()
{
let span = self.tcx.def_span(def_id);
diag.span_note(span, "this closure does not fulfill the lifetime requirements");

View file

@ -1935,6 +1935,18 @@ impl<'tcx> TypeTrace<'tcx> {
}
}
pub fn poly_trait_refs(
cause: &ObligationCause<'tcx>,
a_is_expected: bool,
a: ty::PolyTraitRef<'tcx>,
b: ty::PolyTraitRef<'tcx>,
) -> TypeTrace<'tcx> {
TypeTrace {
cause: cause.clone(),
values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a.into(), b.into())),
}
}
pub fn consts(
cause: &ObligationCause<'tcx>,
a_is_expected: bool,

View file

@ -74,6 +74,18 @@ pub enum TypeError<'tcx> {
TargetFeatureCast(DefId),
}
impl TypeError<'_> {
pub fn involves_regions(self) -> bool {
match self {
TypeError::RegionsDoesNotOutlive(_, _)
| TypeError::RegionsInsufficientlyPolymorphic(_, _)
| TypeError::RegionsOverlyPolymorphic(_, _)
| TypeError::RegionsPlaceholderMismatch => true,
_ => false,
}
}
}
/// Explains the source of a type err in a short, human readable way. This is meant to be placed
/// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
/// afterwards to present additional details, particularly when it comes to lifetime-related

View file

@ -314,7 +314,6 @@ impl<'a> Parser<'a> {
span: lo.to(self.prev_token.span),
lhs_ty: ty,
rhs_ty,
id: ast::DUMMY_NODE_ID,
}))
} else {
self.maybe_recover_bounds_doubled_colon(&ty)?;

View file

@ -527,7 +527,7 @@ impl<'a> Parser<'a> {
Ok(ident_gen_args) => ident_gen_args,
Err(()) => return Ok(Some(AngleBracketedArg::Arg(arg))),
};
if binder.is_some() {
if binder {
// FIXME(compiler-errors): this could be improved by suggesting lifting
// this up to the trait, at least before this becomes real syntax.
// e.g. `Trait<for<'a> Assoc = Ty>` -> `for<'a> Trait<Assoc = Ty>`
@ -720,28 +720,24 @@ impl<'a> Parser<'a> {
/// Given a arg inside of generics, we try to destructure it as if it were the LHS in
/// `LHS = ...`, i.e. an associated type binding.
/// This returns (optionally, if they are present) any `for<'a, 'b>` binder args, the
/// This returns a bool indicating if there are any `for<'a, 'b>` binder args, the
/// identifier, and any GAT arguments.
fn get_ident_from_generic_arg(
&self,
gen_arg: &GenericArg,
) -> Result<(Option<Vec<ast::GenericParam>>, Ident, Option<GenericArgs>), ()> {
) -> Result<(bool, Ident, Option<GenericArgs>), ()> {
if let GenericArg::Type(ty) = gen_arg {
if let ast::TyKind::Path(qself, path) = &ty.kind
&& qself.is_none()
&& let [seg] = path.segments.as_slice()
{
return Ok((None, seg.ident, seg.args.as_deref().cloned()));
return Ok((false, seg.ident, seg.args.as_deref().cloned()));
} else if let ast::TyKind::TraitObject(bounds, ast::TraitObjectSyntax::None) = &ty.kind
&& let [ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None)] =
bounds.as_slice()
&& let [seg] = trait_ref.trait_ref.path.segments.as_slice()
{
return Ok((
Some(trait_ref.bound_generic_params.clone()),
seg.ident,
seg.args.as_deref().cloned(),
));
return Ok((true, seg.ident, seg.args.as_deref().cloned()));
}
}
Err(())

View file

@ -2,7 +2,7 @@ use crate::spec::Target;
pub fn target() -> Target {
let mut base = super::windows_gnullvm_base::opts();
base.max_atomic_width = Some(64);
base.max_atomic_width = Some(128);
base.features = "+neon,+fp-armv8".into();
base.linker = Some("aarch64-w64-mingw32-clang".into());

View file

@ -2,7 +2,7 @@ use crate::spec::Target;
pub fn target() -> Target {
let mut base = super::windows_msvc_base::opts();
base.max_atomic_width = Some(64);
base.max_atomic_width = Some(128);
base.features = "+neon,+fp-armv8".into();
Target {

View file

@ -7,7 +7,7 @@ use crate::spec::{LinkerFlavor, Target};
pub fn target() -> Target {
let mut base = uefi_msvc_base::opts();
base.max_atomic_width = Some(64);
base.max_atomic_width = Some(128);
base.add_pre_link_args(LinkerFlavor::Msvc, &["/machine:arm64"]);
Target {

View file

@ -2,7 +2,7 @@ use crate::spec::Target;
pub fn target() -> Target {
let mut base = super::windows_uwp_msvc_base::opts();
base.max_atomic_width = Some(64);
base.max_atomic_width = Some(128);
Target {
llvm_target: "aarch64-pc-windows-msvc".into(),

View file

@ -10,7 +10,7 @@ pub fn target() -> Target {
arch: "aarch64".into(),
options: TargetOptions {
features: "+neon,+fp-armv8,+apple-a7".into(),
max_atomic_width: Some(64),
max_atomic_width: Some(128),
forces_embed_bitcode: true,
// These arguments are not actually invoked - they just have
// to look right to pass App Store validation.

View file

@ -22,6 +22,7 @@ use rustc_hir::intravisit::Visitor;
use rustc_hir::GenericParam;
use rustc_hir::Item;
use rustc_hir::Node;
use rustc_infer::infer::TypeTrace;
use rustc_infer::traits::TraitEngine;
use rustc_middle::traits::select::OverflowError;
use rustc_middle::ty::abstract_const::NotConstEvaluatable;
@ -941,9 +942,14 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
self.reported_closure_mismatch.borrow_mut().insert((span, found_span));
let mut not_tupled = false;
let found = match found_trait_ref.skip_binder().substs.type_at(1).kind() {
ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
_ => vec![ArgKind::empty()],
_ => {
not_tupled = true;
vec![ArgKind::empty()]
}
};
let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
@ -951,10 +957,28 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
ty::Tuple(ref tys) => {
tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
}
_ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
_ => {
not_tupled = true;
vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
}
};
if found.len() == expected.len() {
// If this is a `Fn` family trait and either the expected or found
// is not tupled, then fall back to just a regular mismatch error.
// This shouldn't be common unless manually implementing one of the
// traits manually, but don't make it more confusing when it does
// happen.
if Some(expected_trait_ref.def_id()) != tcx.lang_items().gen_trait() && not_tupled {
self.report_and_explain_type_error(
TypeTrace::poly_trait_refs(
&obligation.cause,
true,
expected_trait_ref,
found_trait_ref,
),
ty::error::TypeError::Mismatch,
)
} else if found.len() == expected.len() {
self.report_closure_arg_mismatch(
span,
found_span,

View file

@ -2193,7 +2193,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
E0610,
"`{expr_t}` is a primitive type and therefore doesn't have fields",
);
let is_valid_suffix = |field: String| {
let is_valid_suffix = |field: &str| {
if field == "f32" || field == "f64" {
return true;
}
@ -2218,20 +2218,39 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let suffix = chars.collect::<String>();
suffix.is_empty() || suffix == "f32" || suffix == "f64"
};
let maybe_partial_suffix = |field: &str| -> Option<&str> {
let first_chars = ['f', 'l'];
if field.len() >= 1
&& field.to_lowercase().starts_with(first_chars)
&& field[1..].chars().all(|c| c.is_ascii_digit())
{
if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
} else {
None
}
};
if let ty::Infer(ty::IntVar(_)) = expr_t.kind()
&& let ExprKind::Lit(Spanned {
node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
..
}) = base.kind
&& !base.span.from_expansion()
&& is_valid_suffix(field_name)
{
err.span_suggestion_verbose(
field.span.shrink_to_lo(),
"If the number is meant to be a floating point number, consider adding a `0` after the period",
'0',
Applicability::MaybeIncorrect,
);
if is_valid_suffix(&field_name) {
err.span_suggestion_verbose(
field.span.shrink_to_lo(),
"if intended to be a floating point literal, consider adding a `0` after the period",
'0',
Applicability::MaybeIncorrect,
);
} else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
err.span_suggestion_verbose(
field.span,
format!("if intended to be a floating point literal, consider adding a `0` after the period and a `{correct_suffix}` suffix"),
format!("0{correct_suffix}"),
Applicability::MaybeIncorrect,
);
}
}
err.emit();
}

View file

@ -3,4 +3,8 @@ fn main() {
let x = 0;
let _ = x.foo; //~ `{integer}` is a primitive type and therefore doesn't have fields [E0610]
let _ = x.bar; //~ `{integer}` is a primitive type and therefore doesn't have fields [E0610]
let _ = 0.f; //~ `{integer}` is a primitive type and therefore doesn't have fields [E0610]
let _ = 2.l; //~ `{integer}` is a primitive type and therefore doesn't have fields [E0610]
let _ = 12.F; //~ `{integer}` is a primitive type and therefore doesn't have fields [E0610]
let _ = 34.L; //~ `{integer}` is a primitive type and therefore doesn't have fields [E0610]
}

View file

@ -10,6 +10,50 @@ error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
LL | let _ = x.bar;
| ^^^
error: aborting due to 2 previous errors
error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
--> $DIR/attempted-access-non-fatal.rs:6:15
|
LL | let _ = 0.f;
| ^
|
help: if intended to be a floating point literal, consider adding a `0` after the period and a `f32` suffix
|
LL | let _ = 0.0f32;
| ~~~~
error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
--> $DIR/attempted-access-non-fatal.rs:7:15
|
LL | let _ = 2.l;
| ^
|
help: if intended to be a floating point literal, consider adding a `0` after the period and a `f64` suffix
|
LL | let _ = 2.0f64;
| ~~~~
error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
--> $DIR/attempted-access-non-fatal.rs:8:16
|
LL | let _ = 12.F;
| ^
|
help: if intended to be a floating point literal, consider adding a `0` after the period and a `f32` suffix
|
LL | let _ = 12.0f32;
| ~~~~
error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
--> $DIR/attempted-access-non-fatal.rs:9:16
|
LL | let _ = 34.L;
| ^
|
help: if intended to be a floating point literal, consider adding a `0` after the period and a `f64` suffix
|
LL | let _ = 34.0f64;
| ~~~~
error: aborting due to 6 previous errors
For more information about this error, try `rustc --explain E0610`.

View file

@ -1,7 +1,7 @@
#![feature(unboxed_closures)]
fn foo<F: Fn(usize)>(_: F) {}
fn bar<F: Fn<usize>>(_: F) {}
fn bar<F: Fn<(usize,)>>(_: F) {}
fn main() {
fn f(_: u64) {}
foo(|_: isize| {}); //~ ERROR type mismatch

View file

@ -27,8 +27,8 @@ LL | bar(|_: isize| {});
note: required by a bound in `bar`
--> $DIR/E0631.rs:4:11
|
LL | fn bar<F: Fn<usize>>(_: F) {}
| ^^^^^^^^^ required by this bound in `bar`
LL | fn bar<F: Fn<(usize,)>>(_: F) {}
| ^^^^^^^^^^^^ required by this bound in `bar`
error[E0631]: type mismatch in function arguments
--> $DIR/E0631.rs:9:9
@ -65,8 +65,8 @@ LL | bar(f);
note: required by a bound in `bar`
--> $DIR/E0631.rs:4:11
|
LL | fn bar<F: Fn<usize>>(_: F) {}
| ^^^^^^^^^ required by this bound in `bar`
LL | fn bar<F: Fn<(usize,)>>(_: F) {}
| ^^^^^^^^^^^^ required by this bound in `bar`
error: aborting due to 4 previous errors

View file

@ -1,6 +1,6 @@
#![feature(unboxed_closures)]
fn f<F: Fn<usize>>(_: F) {}
fn f<F: Fn<(usize,)>>(_: F) {}
fn main() {
[1, 2, 3].sort_by(|| panic!());
//~^ ERROR closure is expected to take

View file

@ -56,8 +56,8 @@ LL | f(|| panic!());
note: required by a bound in `f`
--> $DIR/closure-arg-count.rs:3:9
|
LL | fn f<F: Fn<usize>>(_: F) {}
| ^^^^^^^^^ required by this bound in `f`
LL | fn f<F: Fn<(usize,)>>(_: F) {}
| ^^^^^^^^^^^^ required by this bound in `f`
help: consider changing the closure to take and ignore the expected argument
|
LL | f(|_| panic!());
@ -74,8 +74,8 @@ LL | f( move || panic!());
note: required by a bound in `f`
--> $DIR/closure-arg-count.rs:3:9
|
LL | fn f<F: Fn<usize>>(_: F) {}
| ^^^^^^^^^ required by this bound in `f`
LL | fn f<F: Fn<(usize,)>>(_: F) {}
| ^^^^^^^^^^^^ required by this bound in `f`
help: consider changing the closure to take and ignore the expected argument
|
LL | f( move |_| panic!());

View file

@ -4,7 +4,7 @@ error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
LL | 2.e1;
| ^^
|
help: If the number is meant to be a floating point number, consider adding a `0` after the period
help: if intended to be a floating point literal, consider adding a `0` after the period
|
LL | 2.0e1;
| +
@ -15,7 +15,7 @@ error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
LL | 2.E1;
| ^^
|
help: If the number is meant to be a floating point number, consider adding a `0` after the period
help: if intended to be a floating point literal, consider adding a `0` after the period
|
LL | 2.0E1;
| +
@ -26,7 +26,7 @@ error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
LL | 2.f32;
| ^^^
|
help: If the number is meant to be a floating point number, consider adding a `0` after the period
help: if intended to be a floating point literal, consider adding a `0` after the period
|
LL | 2.0f32;
| +
@ -37,7 +37,7 @@ error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
LL | 2.f64;
| ^^^
|
help: If the number is meant to be a floating point number, consider adding a `0` after the period
help: if intended to be a floating point literal, consider adding a `0` after the period
|
LL | 2.0f64;
| +
@ -48,7 +48,7 @@ error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
LL | 2.e+12;
| ^
|
help: If the number is meant to be a floating point number, consider adding a `0` after the period
help: if intended to be a floating point literal, consider adding a `0` after the period
|
LL | 2.0e+12;
| +
@ -59,7 +59,7 @@ error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
LL | 2.e-12;
| ^
|
help: If the number is meant to be a floating point number, consider adding a `0` after the period
help: if intended to be a floating point literal, consider adding a `0` after the period
|
LL | 2.0e-12;
| +
@ -70,7 +70,7 @@ error[E0610]: `{integer}` is a primitive type and therefore doesn't have fields
LL | 2.e1f32;
| ^^^^^
|
help: If the number is meant to be a floating point number, consider adding a `0` after the period
help: if intended to be a floating point literal, consider adding a `0` after the period
|
LL | 2.0e1f32;
| +

View file

@ -0,0 +1,8 @@
#![feature(unboxed_closures)]
fn a<F: Fn<usize>>(f: F) {}
fn main() {
a(|_: usize| {});
//~^ ERROR mismatched types
}

View file

@ -0,0 +1,17 @@
error[E0308]: mismatched types
--> $DIR/non-tupled-arg-mismatch.rs:6:5
|
LL | a(|_: usize| {});
| ^ types differ
|
= note: expected trait `Fn<usize>`
found trait `Fn<(usize,)>`
note: required by a bound in `a`
--> $DIR/non-tupled-arg-mismatch.rs:3:9
|
LL | fn a<F: Fn<usize>>(f: F) {}
| ^^^^^^^^^ required by this bound in `a`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.

View file

@ -3761,7 +3761,7 @@ impl<'test> TestCx<'test> {
fn delete_file(&self, file: &PathBuf) {
if !file.exists() {
// Deleting a nonexistant file would error.
// Deleting a nonexistent file would error.
return;
}
if let Err(e) = fs::remove_file(file) {

View file

@ -101,7 +101,7 @@ jobs:
- name: Install Nodejs
uses: actions/setup-node@v1
with:
node-version: 14.x
node-version: 16.x
- name: Install xvfb
if: matrix.os == 'ubuntu-latest'

View file

@ -68,7 +68,7 @@ jobs:
- name: Install Node.js
uses: actions/setup-node@v1
with:
node-version: 14.x
node-version: 16.x
- name: Update apt repositories
if: matrix.target == 'aarch64-unknown-linux-gnu' || matrix.target == 'arm-unknown-linux-gnueabihf'
@ -133,7 +133,7 @@ jobs:
container:
image: rust:alpine
volumes:
- /usr/local/cargo/registry
- /usr/local/cargo/registry:/usr/local/cargo/registry
steps:
- name: Install dependencies
@ -176,7 +176,7 @@ jobs:
- name: Install Nodejs
uses: actions/setup-node@v1
with:
node-version: 14.x
node-version: 16.x
- run: echo "TAG=$(date --iso -u)" >> $GITHUB_ENV
if: github.ref == 'refs/heads/release'
@ -253,9 +253,9 @@ jobs:
- name: Publish Extension (Code Marketplace, nightly)
if: github.ref != 'refs/heads/release' && (github.repository == 'rust-analyzer/rust-analyzer' || github.repository == 'rust-lang/rust-analyzer')
working-directory: ./editors/code
run: npx vsce publish --pat ${{ secrets.MARKETPLACE_TOKEN }} --packagePath ../../dist/rust-analyzer-*.vsix --pre-release
run: npx vsce publish --pat ${{ secrets.MARKETPLACE_TOKEN }} --packagePath ../../dist/rust-analyzer-*.vsix
- name: Publish Extension (OpenVSX, nightly)
if: github.ref != 'refs/heads/release' && (github.repository == 'rust-analyzer/rust-analyzer' || github.repository == 'rust-lang/rust-analyzer')
working-directory: ./editors/code
run: npx ovsx publish --pat ${{ secrets.OPENVSX_TOKEN }} --packagePath ../../dist/rust-analyzer-*.vsix --pre-release
run: npx ovsx publish --pat ${{ secrets.OPENVSX_TOKEN }} --packagePath ../../dist/rust-analyzer-*.vsix

View file

@ -78,7 +78,7 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--disable-extension", "matklad.rust-analyzer",
"--disable-extension", "rust-lang.rust-analyzer",
"--extensionDevelopmentPath=${workspaceFolder}/editors/code"
],
"outFiles": [

View file

@ -710,6 +710,7 @@ dependencies = [
"ide-db",
"itertools",
"profile",
"serde_json",
"sourcegen",
"stdx",
"syntax",

View file

@ -6,7 +6,7 @@
//! actual IO. See `vfs` and `project_model` in the `rust-analyzer` crate for how
//! actual IO is done and lowered to input.
use std::{fmt, iter::FromIterator, ops, panic::RefUnwindSafe, str::FromStr, sync::Arc};
use std::{fmt, ops, panic::RefUnwindSafe, str::FromStr, sync::Arc};
use cfg::CfgOptions;
use rustc_hash::{FxHashMap, FxHashSet};

View file

@ -295,13 +295,13 @@ fn test_concat_expand() {
#[rustc_builtin_macro]
macro_rules! concat {}
fn main() { concat!("foo", "r", 0, r#"bar"#, "\n", false); }
fn main() { concat!("foo", "r", 0, r#"bar"#, "\n", false, '"', '\0'); }
"##,
expect![[r##"
#[rustc_builtin_macro]
macro_rules! concat {}
fn main() { "foor0bar\nfalse"; }
fn main() { "foor0bar\nfalse\"\u{0}"; }
"##]],
);
}

View file

@ -885,7 +885,7 @@ macro_rules! m {
($t:ty) => ( fn bar() -> $ t {} )
}
fn bar() -> & 'a Baz<u8> {}
fn bar() -> &'a Baz<u8> {}
fn bar() -> extern "Rust"fn() -> Ret {}
"#]],
@ -1578,7 +1578,7 @@ macro_rules !register_methods {
($$($val: expr), *) = > {
struct Foo;
impl Foo {
$(fn $method()-> & 'static[u32] {
$(fn $method()-> &'static[u32] {
&[$$($$val), *]
}
)*
@ -1591,10 +1591,10 @@ macro_rules !implement_methods {
($($val: expr), *) = > {
struct Foo;
impl Foo {
fn alpha()-> & 'static[u32] {
fn alpha()-> &'static[u32] {
&[$($val), *]
}
fn beta()-> & 'static[u32] {
fn beta()-> &'static[u32] {
&[$($val), *]
}
}
@ -1602,10 +1602,10 @@ macro_rules !implement_methods {
}
struct Foo;
impl Foo {
fn alpha() -> & 'static[u32] {
fn alpha() -> &'static[u32] {
&[1, 2, 3]
}
fn beta() -> & 'static[u32] {
fn beta() -> &'static[u32] {
&[1, 2, 3]
}
}

View file

@ -166,7 +166,7 @@ macro_rules! int_base {
}
}
#[stable(feature = "rust1", since = "1.0.0")] impl fmt::Binary for isize {
fn fmt(&self , f: &mut fmt::Formatter< '_>) -> fmt::Result {
fn fmt(&self , f: &mut fmt::Formatter<'_>) -> fmt::Result {
Binary.fmt_int(*self as usize, f)
}
}
@ -724,7 +724,7 @@ macro_rules! delegate_impl {
}
}
}
impl <> Data for & 'amut G where G: Data {}
impl <> Data for &'amut G where G: Data {}
"##]],
);
}

View file

@ -78,7 +78,7 @@ m!(static bar: &'static str = "hello";);
macro_rules! m {
($($t:tt)*) => { $($t)*}
}
static bar: & 'static str = "hello";
static bar: &'static str = "hello";
"#]],
);
}

View file

@ -87,7 +87,7 @@ fn foo() { bar.; blub }
fn foo() { bar.; blub }
fn foo() {
bar. ;
bar.;
blub
}"##]],
);

View file

@ -73,10 +73,12 @@ impl ModDir {
candidate_files.push(self.dir_path.join_attr(attr_path, self.root_non_dir_owner))
}
None if file_id.is_include_macro(db.upcast()) => {
let name = name.unescaped();
candidate_files.push(format!("{}.rs", name));
candidate_files.push(format!("{}/mod.rs", name));
}
None => {
let name = name.unescaped();
candidate_files.push(format!("{}{}.rs", self.dir_path.0, name));
candidate_files.push(format!("{}{}/mod.rs", self.dir_path.0, name));
}

View file

@ -132,9 +132,9 @@ pub struct Bar;
expect![[r#"
crate
Bar: t v
async: t
r#async: t
crate::async
crate::r#async
Bar: t v
"#]],
);

View file

@ -251,9 +251,13 @@ fn format_args_expand(
}
for arg in &mut args {
// Remove `key =`.
if matches!(arg.token_trees.get(1), Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p))) if p.char == '=' && p.spacing != tt::Spacing::Joint)
if matches!(arg.token_trees.get(1), Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p))) if p.char == '=')
{
arg.token_trees.drain(..2);
// but not with `==`
if !matches!(arg.token_trees.get(2), Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p))) if p.char == '=' )
{
arg.token_trees.drain(..2);
}
}
}
let _format_string = args.remove(0);
@ -357,6 +361,12 @@ fn unquote_str(lit: &tt::Literal) -> Option<String> {
token.value().map(|it| it.into_owned())
}
fn unquote_char(lit: &tt::Literal) -> Option<char> {
let lit = ast::make::tokens::literal(&lit.to_string());
let token = ast::Char::cast(lit)?;
token.value()
}
fn unquote_byte_string(lit: &tt::Literal) -> Option<Vec<u8>> {
let lit = ast::make::tokens::literal(&lit.to_string());
let token = ast::ByteString::cast(lit)?;
@ -408,8 +418,12 @@ fn concat_expand(
// concat works with string and char literals, so remove any quotes.
// It also works with integer, float and boolean literals, so just use the rest
// as-is.
let component = unquote_str(it).unwrap_or_else(|| it.text.to_string());
text.push_str(&component);
if let Some(c) = unquote_char(it) {
text.push(c);
} else {
let component = unquote_str(it).unwrap_or_else(|| it.text.to_string());
text.push_str(&component);
}
}
// handle boolean literals
tt::TokenTree::Leaf(tt::Leaf::Ident(id))

View file

@ -67,7 +67,6 @@ pub(crate) fn fixup_syntax(node: &SyntaxNode) -> SyntaxFixups {
preorder.skip_subtree();
continue;
}
// In some other situations, we can fix things by just appending some tokens.
let end_range = TextRange::empty(node.text_range().end());
match_ast! {
@ -194,7 +193,75 @@ pub(crate) fn fixup_syntax(node: &SyntaxNode) -> SyntaxFixups {
}
},
// FIXME: foo::
// FIXME: for, match etc.
ast::MatchExpr(it) => {
if it.expr().is_none() {
let match_token = match it.match_token() {
Some(t) => t,
None => continue
};
append.insert(match_token.into(), vec![
SyntheticToken {
kind: SyntaxKind::IDENT,
text: "__ra_fixup".into(),
range: end_range,
id: EMPTY_ID
},
]);
}
if it.match_arm_list().is_none() {
// No match arms
append.insert(node.clone().into(), vec![
SyntheticToken {
kind: SyntaxKind::L_CURLY,
text: "{".into(),
range: end_range,
id: EMPTY_ID,
},
SyntheticToken {
kind: SyntaxKind::R_CURLY,
text: "}".into(),
range: end_range,
id: EMPTY_ID,
},
]);
}
},
ast::ForExpr(it) => {
let for_token = match it.for_token() {
Some(token) => token,
None => continue
};
let [pat, in_token, iter] = [
(SyntaxKind::UNDERSCORE, "_"),
(SyntaxKind::IN_KW, "in"),
(SyntaxKind::IDENT, "__ra_fixup")
].map(|(kind, text)| SyntheticToken { kind, text: text.into(), range: end_range, id: EMPTY_ID});
if it.pat().is_none() && it.in_token().is_none() && it.iterable().is_none() {
append.insert(for_token.into(), vec![pat, in_token, iter]);
// does something funky -- see test case for_no_pat
} else if it.pat().is_none() {
append.insert(for_token.into(), vec![pat]);
}
if it.loop_body().is_none() {
append.insert(node.clone().into(), vec![
SyntheticToken {
kind: SyntaxKind::L_CURLY,
text: "{".into(),
range: end_range,
id: EMPTY_ID,
},
SyntheticToken {
kind: SyntaxKind::R_CURLY,
text: "}".into(),
range: end_range,
id: EMPTY_ID,
},
]);
}
},
_ => (),
}
}
@ -287,6 +354,111 @@ mod tests {
assert_eq!(tt.to_string(), original_as_tt.to_string());
}
#[test]
fn just_for_token() {
check(
r#"
fn foo() {
for
}
"#,
expect![[r#"
fn foo () {for _ in __ra_fixup {}}
"#]],
)
}
#[test]
fn for_no_iter_pattern() {
check(
r#"
fn foo() {
for {}
}
"#,
expect![[r#"
fn foo () {for _ in __ra_fixup {}}
"#]],
)
}
#[test]
fn for_no_body() {
check(
r#"
fn foo() {
for bar in qux
}
"#,
expect![[r#"
fn foo () {for bar in qux {}}
"#]],
)
}
// FIXME: https://github.com/rust-lang/rust-analyzer/pull/12937#discussion_r937633695
#[test]
fn for_no_pat() {
check(
r#"
fn foo() {
for in qux {
}
}
"#,
expect![[r#"
fn foo () {__ra_fixup}
"#]],
)
}
#[test]
fn match_no_expr_no_arms() {
check(
r#"
fn foo() {
match
}
"#,
expect![[r#"
fn foo () {match __ra_fixup {}}
"#]],
)
}
#[test]
fn match_expr_no_arms() {
check(
r#"
fn foo() {
match x {
}
}
"#,
expect![[r#"
fn foo () {match x {}}
"#]],
)
}
#[test]
fn match_no_expr() {
check(
r#"
fn foo() {
match {
_ => {}
}
}
"#,
expect![[r#"
fn foo () {match __ra_fixup {}}
"#]],
)
}
#[test]
fn incomplete_field_expr_1() {
check(
@ -296,7 +468,7 @@ fn foo() {
}
"#,
expect![[r#"
fn foo () {a . __ra_fixup}
fn foo () {a .__ra_fixup}
"#]],
)
}
@ -306,11 +478,11 @@ fn foo () {a . __ra_fixup}
check(
r#"
fn foo() {
a. ;
a.;
}
"#,
expect![[r#"
fn foo () {a . __ra_fixup ;}
fn foo () {a .__ra_fixup ;}
"#]],
)
}
@ -320,12 +492,12 @@ fn foo () {a . __ra_fixup ;}
check(
r#"
fn foo() {
a. ;
a.;
bar();
}
"#,
expect![[r#"
fn foo () {a . __ra_fixup ; bar () ;}
fn foo () {a .__ra_fixup ; bar () ;}
"#]],
)
}
@ -353,7 +525,7 @@ fn foo() {
}
"#,
expect![[r#"
fn foo () {let x = a . __ra_fixup ;}
fn foo () {let x = a .__ra_fixup ;}
"#]],
)
}
@ -369,7 +541,7 @@ fn foo() {
}
"#,
expect![[r#"
fn foo () {a . b ; bar () ;}
fn foo () {a .b ; bar () ;}
"#]],
)
}

View file

@ -22,7 +22,7 @@ pub struct ModPath {
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EscapedModPath<'a>(&'a ModPath);
pub struct UnescapedModPath<'a>(&'a ModPath);
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PathKind {
@ -102,8 +102,8 @@ impl ModPath {
}
}
pub fn escaped(&self) -> EscapedModPath<'_> {
EscapedModPath(self)
pub fn unescaped(&self) -> UnescapedModPath<'_> {
UnescapedModPath(self)
}
fn _fmt(&self, f: &mut fmt::Formatter<'_>, escaped: bool) -> fmt::Result {
@ -134,9 +134,9 @@ impl ModPath {
}
first_segment = false;
if escaped {
segment.escaped().fmt(f)?
} else {
segment.fmt(f)?
} else {
segment.unescaped().fmt(f)?
};
}
Ok(())
@ -145,13 +145,13 @@ impl ModPath {
impl Display for ModPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self._fmt(f, false)
self._fmt(f, true)
}
}
impl<'a> Display for EscapedModPath<'a> {
impl<'a> Display for UnescapedModPath<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0._fmt(f, true)
self.0._fmt(f, false)
}
}

View file

@ -7,12 +7,16 @@ use syntax::{ast, SmolStr, SyntaxKind};
/// `Name` is a wrapper around string, which is used in hir for both references
/// and declarations. In theory, names should also carry hygiene info, but we are
/// not there yet!
///
/// Note that `Name` holds and prints escaped name i.e. prefixed with "r#" when it
/// is a raw identifier. Use [`unescaped()`][Name::unescaped] when you need the
/// name without "r#".
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Name(Repr);
/// `EscapedName` will add a prefix "r#" to the wrapped `Name` when it is a raw identifier
/// Wrapper of `Name` to print the name without "r#" even when it is a raw identifier.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EscapedName<'a>(&'a Name);
pub struct UnescapedName<'a>(&'a Name);
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum Repr {
@ -34,37 +38,26 @@ fn is_raw_identifier(name: &str) -> bool {
is_keyword && !matches!(name, "self" | "crate" | "super" | "Self")
}
impl<'a> fmt::Display for EscapedName<'a> {
impl<'a> fmt::Display for UnescapedName<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 .0 {
Repr::Text(text) => {
if is_raw_identifier(text) {
write!(f, "r#{}", &text)
} else {
fmt::Display::fmt(&text, f)
}
let text = text.strip_prefix("r#").unwrap_or(text);
fmt::Display::fmt(&text, f)
}
Repr::TupleField(idx) => fmt::Display::fmt(&idx, f),
}
}
}
impl<'a> EscapedName<'a> {
pub fn is_escaped(&self) -> bool {
match &self.0 .0 {
Repr::Text(it) => is_raw_identifier(&it),
Repr::TupleField(_) => false,
}
}
/// Returns the textual representation of this name as a [`SmolStr`].
/// Prefer using this over [`ToString::to_string`] if possible as this conversion is cheaper in
/// the general case.
impl<'a> UnescapedName<'a> {
/// Returns the textual representation of this name as a [`SmolStr`]. Prefer using this over
/// [`ToString::to_string`] if possible as this conversion is cheaper in the general case.
pub fn to_smol_str(&self) -> SmolStr {
match &self.0 .0 {
Repr::Text(it) => {
if is_raw_identifier(&it) {
SmolStr::from_iter(["r#", &it])
if let Some(stripped) = it.strip_prefix("r#") {
SmolStr::new(stripped)
} else {
it.clone()
}
@ -97,9 +90,11 @@ impl Name {
/// Resolve a name from the text of token.
fn resolve(raw_text: &str) -> Name {
// When `raw_text` starts with "r#" but the name does not coincide with any
// keyword, we never need the prefix so we strip it.
match raw_text.strip_prefix("r#") {
Some(text) => Name::new_text(SmolStr::new(text)),
None => Name::new_text(raw_text.into()),
Some(text) if !is_raw_identifier(text) => Name::new_text(SmolStr::new(text)),
_ => Name::new_text(raw_text.into()),
}
}
@ -142,8 +137,15 @@ impl Name {
}
}
pub fn escaped(&self) -> EscapedName<'_> {
EscapedName(self)
pub fn unescaped(&self) -> UnescapedName<'_> {
UnescapedName(self)
}
pub fn is_escaped(&self) -> bool {
match &self.0 {
Repr::Text(it) => it.starts_with("r#"),
Repr::TupleField(_) => false,
}
}
}

View file

@ -196,8 +196,8 @@ impl_to_to_tokentrees! {
tt::Literal => self { self };
tt::Ident => self { self };
tt::Punct => self { self };
&str => self { tt::Literal{text: format!("\"{}\"", self.escape_debug()).into(), id: tt::TokenId::unspecified()}};
String => self { tt::Literal{text: format!("\"{}\"", self.escape_debug()).into(), id: tt::TokenId::unspecified()}}
&str => self { tt::Literal{text: format!("\"{}\"", self.escape_default()).into(), id: tt::TokenId::unspecified()}};
String => self { tt::Literal{text: format!("\"{}\"", self.escape_default()).into(), id: tt::TokenId::unspecified()}}
}
#[cfg(test)]

View file

@ -2,7 +2,6 @@
use std::{
collections::HashMap,
convert::TryInto,
fmt::{Display, Write},
};

View file

@ -14,8 +14,9 @@ use crate::{
consteval::intern_const_scalar,
infer::{BindingMode, Expectation, InferenceContext, TypeMismatch},
lower::lower_to_chalk_mutability,
static_lifetime, ConcreteConst, ConstValue, Interner, Substitution, Ty, TyBuilder, TyExt,
TyKind,
primitive::UintTy,
static_lifetime, ConcreteConst, ConstValue, Interner, Scalar, Substitution, Ty, TyBuilder,
TyExt, TyKind,
};
use super::PatLike;
@ -294,7 +295,29 @@ impl<'a> InferenceContext<'a> {
let start_ty = self.infer_expr(*start, &Expectation::has_type(expected.clone()));
self.infer_expr(*end, &Expectation::has_type(start_ty))
}
Pat::Lit(expr) => self.infer_expr(*expr, &Expectation::has_type(expected.clone())),
&Pat::Lit(expr) => {
// FIXME: using `Option` here is a workaround until we can use if-let chains in stable.
let mut pat_ty = None;
// Like slice patterns, byte string patterns can denote both `&[u8; N]` and `&[u8]`.
if let Expr::Literal(Literal::ByteString(_)) = self.body[expr] {
if let Some((inner, ..)) = expected.as_reference() {
let inner = self.resolve_ty_shallow(inner);
if matches!(inner.kind(Interner), TyKind::Slice(_)) {
let elem_ty = TyKind::Scalar(Scalar::Uint(UintTy::U8)).intern(Interner);
let slice_ty = TyKind::Slice(elem_ty).intern(Interner);
let ty = TyKind::Ref(Mutability::Not, static_lifetime(), slice_ty)
.intern(Interner);
self.write_expr_ty(expr, ty.clone());
pat_ty = Some(ty);
}
}
}
pat_ty.unwrap_or_else(|| {
self.infer_expr(expr, &Expectation::has_type(expected.clone()))
})
}
Pat::Box { inner } => match self.resolve_boxed_box() {
Some(box_adt) => {
let (inner_ty, alloc_ty) = match expected.as_adt() {
@ -343,7 +366,9 @@ fn is_non_ref_pat(body: &hir_def::body::Body, pat: PatId) -> bool {
// FIXME: ConstBlock/Path/Lit might actually evaluate to ref, but inference is unimplemented.
Pat::Path(..) => true,
Pat::ConstBlock(..) => true,
Pat::Lit(expr) => !matches!(body[*expr], Expr::Literal(Literal::String(..))),
Pat::Lit(expr) => {
!matches!(body[*expr], Expr::Literal(Literal::String(..) | Literal::ByteString(..)))
}
Pat::Bind {
mode: BindingAnnotation::Mutable | BindingAnnotation::Unannotated,
subpat: Some(subpat),

View file

@ -315,6 +315,51 @@ fn infer_pattern_match_string_literal() {
);
}
#[test]
fn infer_pattern_match_byte_string_literal() {
check_infer_with_mismatches(
r#"
//- minicore: index
struct S;
impl<T, const N: usize> core::ops::Index<S> for [T; N] {
type Output = [u8];
fn index(&self, index: core::ops::RangeFull) -> &Self::Output {
loop {}
}
}
fn test(v: [u8; 3]) {
if let b"foo" = &v[S] {}
if let b"foo" = &v {}
}
"#,
expect![[r#"
105..109 'self': &[T; N]
111..116 'index': {unknown}
157..180 '{ ... }': &[u8]
167..174 'loop {}': !
172..174 '{}': ()
191..192 'v': [u8; 3]
203..261 '{ ...v {} }': ()
209..233 'if let...[S] {}': ()
212..230 'let b"... &v[S]': bool
216..222 'b"foo"': &[u8]
216..222 'b"foo"': &[u8]
225..230 '&v[S]': &[u8]
226..227 'v': [u8; 3]
226..230 'v[S]': [u8]
228..229 'S': S
231..233 '{}': ()
238..259 'if let... &v {}': ()
241..256 'let b"foo" = &v': bool
245..251 'b"foo"': &[u8; 3]
245..251 'b"foo"': &[u8; 3]
254..256 '&v': &[u8; 3]
255..256 'v': [u8; 3]
257..259 '{}': ()
"#]],
);
}
#[test]
fn infer_pattern_match_or() {
check_infer_with_mismatches(

View file

@ -14,6 +14,7 @@ use crate::{MacroKind, Type};
macro_rules! diagnostics {
($($diag:ident,)*) => {
#[derive(Debug)]
pub enum AnyDiagnostic {$(
$diag(Box<$diag>),
)*}

View file

@ -368,6 +368,7 @@ impl SourceAnalyzer {
let local = if field.name_ref().is_some() {
None
} else {
// Shorthand syntax, resolve to the local
let path = ModPath::from_segments(PathKind::Plain, once(local_name.clone()));
match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
Some(ValueNs::LocalBinding(pat_id)) => {

View file

@ -1,28 +1,20 @@
//! See [`AssistContext`].
use std::mem;
use hir::Semantics;
use ide_db::{
base_db::{AnchoredPathBuf, FileId, FileRange},
SnippetCap,
};
use ide_db::{
label::Label,
source_change::{FileSystemEdit, SourceChange},
RootDatabase,
};
use ide_db::base_db::{FileId, FileRange};
use ide_db::{label::Label, RootDatabase};
use syntax::{
algo::{self, find_node_at_offset, find_node_at_range},
AstNode, AstToken, Direction, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxNodePtr,
SyntaxToken, TextRange, TextSize, TokenAtOffset,
AstNode, AstToken, Direction, SourceFile, SyntaxElement, SyntaxKind, SyntaxToken, TextRange,
TextSize, TokenAtOffset,
};
use text_edit::{TextEdit, TextEditBuilder};
use crate::{
assist_config::AssistConfig, Assist, AssistId, AssistKind, AssistResolveStrategy, GroupLabel,
};
pub(crate) use ide_db::source_change::{SourceChangeBuilder, TreeMutator};
/// `AssistContext` allows to apply an assist or check if it could be applied.
///
/// Assists use a somewhat over-engineered approach, given the current needs.
@ -163,7 +155,7 @@ impl Assists {
id: AssistId,
label: impl Into<String>,
target: TextRange,
f: impl FnOnce(&mut AssistBuilder),
f: impl FnOnce(&mut SourceChangeBuilder),
) -> Option<()> {
let mut f = Some(f);
self.add_impl(None, id, label.into(), target, &mut |it| f.take().unwrap()(it))
@ -175,7 +167,7 @@ impl Assists {
id: AssistId,
label: impl Into<String>,
target: TextRange,
f: impl FnOnce(&mut AssistBuilder),
f: impl FnOnce(&mut SourceChangeBuilder),
) -> Option<()> {
let mut f = Some(f);
self.add_impl(Some(group), id, label.into(), target, &mut |it| f.take().unwrap()(it))
@ -187,7 +179,7 @@ impl Assists {
id: AssistId,
label: String,
target: TextRange,
f: &mut dyn FnMut(&mut AssistBuilder),
f: &mut dyn FnMut(&mut SourceChangeBuilder),
) -> Option<()> {
if !self.is_allowed(&id) {
return None;
@ -195,7 +187,7 @@ impl Assists {
let mut trigger_signature_help = false;
let source_change = if self.resolve.should_resolve(&id) {
let mut builder = AssistBuilder::new(self.file);
let mut builder = SourceChangeBuilder::new(self.file);
f(&mut builder);
trigger_signature_help = builder.trigger_signature_help;
Some(builder.finish())
@ -216,132 +208,3 @@ impl Assists {
}
}
}
pub(crate) struct AssistBuilder {
edit: TextEditBuilder,
file_id: FileId,
source_change: SourceChange,
trigger_signature_help: bool,
/// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
mutated_tree: Option<TreeMutator>,
}
pub(crate) struct TreeMutator {
immutable: SyntaxNode,
mutable_clone: SyntaxNode,
}
impl TreeMutator {
pub(crate) fn new(immutable: &SyntaxNode) -> TreeMutator {
let immutable = immutable.ancestors().last().unwrap();
let mutable_clone = immutable.clone_for_update();
TreeMutator { immutable, mutable_clone }
}
pub(crate) fn make_mut<N: AstNode>(&self, node: &N) -> N {
N::cast(self.make_syntax_mut(node.syntax())).unwrap()
}
pub(crate) fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
let ptr = SyntaxNodePtr::new(node);
ptr.to_node(&self.mutable_clone)
}
}
impl AssistBuilder {
pub(crate) fn new(file_id: FileId) -> AssistBuilder {
AssistBuilder {
edit: TextEdit::builder(),
file_id,
source_change: SourceChange::default(),
trigger_signature_help: false,
mutated_tree: None,
}
}
pub(crate) fn edit_file(&mut self, file_id: FileId) {
self.commit();
self.file_id = file_id;
}
fn commit(&mut self) {
if let Some(tm) = self.mutated_tree.take() {
algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
}
let edit = mem::take(&mut self.edit).finish();
if !edit.is_empty() {
self.source_change.insert_source_edit(self.file_id, edit);
}
}
pub(crate) fn make_mut<N: AstNode>(&mut self, node: N) -> N {
self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
}
/// Returns a copy of the `node`, suitable for mutation.
///
/// Syntax trees in rust-analyzer are typically immutable, and mutating
/// operations panic at runtime. However, it is possible to make a copy of
/// the tree and mutate the copy freely. Mutation is based on interior
/// mutability, and different nodes in the same tree see the same mutations.
///
/// The typical pattern for an assist is to find specific nodes in the read
/// phase, and then get their mutable couterparts using `make_mut` in the
/// mutable state.
pub(crate) fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
}
/// Remove specified `range` of text.
pub(crate) fn delete(&mut self, range: TextRange) {
self.edit.delete(range)
}
/// Append specified `text` at the given `offset`
pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
self.edit.insert(offset, text.into())
}
/// Append specified `snippet` at the given `offset`
pub(crate) fn insert_snippet(
&mut self,
_cap: SnippetCap,
offset: TextSize,
snippet: impl Into<String>,
) {
self.source_change.is_snippet = true;
self.insert(offset, snippet);
}
/// Replaces specified `range` of text with a given string.
pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
self.edit.replace(range, replace_with.into())
}
/// Replaces specified `range` of text with a given `snippet`.
pub(crate) fn replace_snippet(
&mut self,
_cap: SnippetCap,
range: TextRange,
snippet: impl Into<String>,
) {
self.source_change.is_snippet = true;
self.replace(range, snippet);
}
pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
}
pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
self.source_change.push_file_system_edit(file_system_edit);
}
pub(crate) fn move_file(&mut self, src: FileId, dst: AnchoredPathBuf) {
let file_system_edit = FileSystemEdit::MoveFile { src, dst };
self.source_change.push_file_system_edit(file_system_edit);
}
pub(crate) fn trigger_signature_help(&mut self) {
self.trigger_signature_help = true;
}
fn finish(mut self) -> SourceChange {
self.commit();
mem::take(&mut self.source_change)
}
}

View file

@ -944,7 +944,7 @@ foo!();
struct Foo(usize);
impl FooB for Foo {
$0fn foo< 'lt>(& 'lt self){}
$0fn foo<'lt>(&'lt self){}
}
"#,
)

View file

@ -5,7 +5,7 @@ use syntax::{
match_ast, SyntaxNode,
};
use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
use crate::{assist_context::SourceChangeBuilder, AssistContext, AssistId, AssistKind, Assists};
// Assist: convert_tuple_struct_to_named_struct
//
@ -80,7 +80,7 @@ pub(crate) fn convert_tuple_struct_to_named_struct(
fn edit_struct_def(
ctx: &AssistContext<'_>,
edit: &mut AssistBuilder,
edit: &mut SourceChangeBuilder,
strukt: &Either<ast::Struct, ast::Variant>,
tuple_fields: ast::TupleFieldList,
names: Vec<ast::Name>,
@ -122,7 +122,7 @@ fn edit_struct_def(
fn edit_struct_references(
ctx: &AssistContext<'_>,
edit: &mut AssistBuilder,
edit: &mut SourceChangeBuilder,
strukt: Either<hir::Struct, hir::Variant>,
names: &[ast::Name],
) {
@ -132,7 +132,7 @@ fn edit_struct_references(
};
let usages = strukt_def.usages(&ctx.sema).include_self_refs().all();
let edit_node = |edit: &mut AssistBuilder, node: SyntaxNode| -> Option<()> {
let edit_node = |edit: &mut SourceChangeBuilder, node: SyntaxNode| -> Option<()> {
match_ast! {
match node {
ast::TupleStructPat(tuple_struct_pat) => {
@ -203,7 +203,7 @@ fn edit_struct_references(
fn edit_field_references(
ctx: &AssistContext<'_>,
edit: &mut AssistBuilder,
edit: &mut SourceChangeBuilder,
fields: impl Iterator<Item = ast::TupleField>,
names: &[ast::Name],
) {

View file

@ -8,7 +8,7 @@ use syntax::{
TextRange,
};
use crate::assist_context::{AssistBuilder, AssistContext, Assists};
use crate::assist_context::{AssistContext, Assists, SourceChangeBuilder};
// Assist: destructure_tuple_binding
//
@ -151,7 +151,7 @@ struct TupleData {
}
fn edit_tuple_assignment(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
data: &TupleData,
in_sub_pattern: bool,
) {
@ -195,7 +195,7 @@ fn edit_tuple_assignment(
fn edit_tuple_usages(
data: &TupleData,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
ctx: &AssistContext<'_>,
in_sub_pattern: bool,
) {
@ -211,7 +211,7 @@ fn edit_tuple_usages(
}
fn edit_tuple_usage(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
usage: &FileReference,
data: &TupleData,
in_sub_pattern: bool,
@ -239,7 +239,7 @@ fn edit_tuple_usage(
fn edit_tuple_field_usage(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
data: &TupleData,
index: TupleIndex,
) {

View file

@ -20,7 +20,7 @@ use syntax::{
SyntaxNode, T,
};
use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
use crate::{assist_context::SourceChangeBuilder, AssistContext, AssistId, AssistKind, Assists};
// Assist: extract_struct_from_enum_variant
//
@ -374,7 +374,7 @@ fn apply_references(
fn process_references(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
visited_modules: &mut FxHashSet<Module>,
enum_module_def: &ModuleDef,
variant_hir_name: &Name,

View file

@ -8,7 +8,7 @@ use syntax::{
};
use crate::{
assist_context::{AssistBuilder, AssistContext, Assists},
assist_context::{AssistContext, Assists, SourceChangeBuilder},
utils::generate_trait_impl_text,
AssistId, AssistKind,
};
@ -120,7 +120,7 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
}
fn generate_edit(
edit: &mut AssistBuilder,
edit: &mut SourceChangeBuilder,
strukt: ast::Struct,
field_type_syntax: &SyntaxNode,
field_name: impl Display,

View file

@ -5,7 +5,7 @@ use syntax::{
AstNode, TextRange,
};
use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
use crate::{assist_context::SourceChangeBuilder, AssistContext, AssistId, AssistKind, Assists};
static ASSIST_NAME: &str = "introduce_named_lifetime";
static ASSIST_LABEL: &str = "Introduce named lifetime";
@ -140,7 +140,7 @@ enum NeedsLifetime {
}
impl NeedsLifetime {
fn make_mut(self, builder: &mut AssistBuilder) -> Self {
fn make_mut(self, builder: &mut SourceChangeBuilder) -> Self {
match self {
Self::SelfParam(it) => Self::SelfParam(builder.make_mut(it)),
Self::RefType(it) => Self::RefType(builder.make_mut(it)),

View file

@ -8,7 +8,8 @@ use syntax::{
use SyntaxKind::WHITESPACE;
use crate::{
assist_context::AssistBuilder, utils::next_prev, AssistContext, AssistId, AssistKind, Assists,
assist_context::SourceChangeBuilder, utils::next_prev, AssistContext, AssistId, AssistKind,
Assists,
};
// Assist: remove_unused_param
@ -88,7 +89,7 @@ pub(crate) fn remove_unused_param(acc: &mut Assists, ctx: &AssistContext<'_>) ->
fn process_usages(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
file_id: FileId,
references: Vec<FileReference>,
arg_to_remove: usize,

View file

@ -10,7 +10,7 @@ use syntax::{
};
use crate::{
assist_context::{AssistBuilder, AssistContext, Assists},
assist_context::{AssistContext, Assists, SourceChangeBuilder},
utils::{
add_trait_assoc_items_to_impl, filter_assoc_items, gen_trait_fn_body,
generate_trait_impl_text, render_snippet, Cursor, DefaultMethods,
@ -224,7 +224,7 @@ fn impl_def_from_trait(
}
fn update_attribute(
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
old_derives: &[ast::Path],
old_tree: &ast::TokenTree,
old_trait_path: &ast::Path,

View file

@ -20,7 +20,7 @@ use syntax::{
SyntaxNode, TextRange, TextSize, T,
};
use crate::assist_context::{AssistBuilder, AssistContext};
use crate::assist_context::{AssistContext, SourceChangeBuilder};
pub(crate) mod suggest_name;
mod gen_trait_fn_body;
@ -484,7 +484,7 @@ fn generate_impl_text_inner(adt: &ast::Adt, trait_text: Option<&str>, code: &str
}
pub(crate) fn add_method_to_adt(
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
adt: &ast::Adt,
impl_def: Option<ast::Impl>,
method: &str,

View file

@ -617,7 +617,6 @@ pub(super) fn complete_name_ref(
dot::complete_undotted_self(acc, ctx, path_ctx, expr_ctx);
item_list::complete_item_list_in_expr(acc, ctx, path_ctx, expr_ctx);
record::complete_record_expr_func_update(acc, ctx, path_ctx, expr_ctx);
snippet::complete_expr_snippet(acc, ctx, path_ctx, expr_ctx);
}
PathKind::Type { location } => {

View file

@ -1,8 +1,10 @@
//! Completion of names from the current scope in expression position.
use hir::ScopeDef;
use syntax::ast;
use crate::{
completions::record::add_default_update,
context::{ExprCtx, PathCompletionCtx, Qualified},
CompletionContext, Completions,
};
@ -219,60 +221,78 @@ pub(crate) fn complete_expr_path(
_ => (),
});
if is_func_update.is_none() {
let mut add_keyword =
|kw, snippet| acc.add_keyword_snippet_expr(ctx, incomplete_let, kw, snippet);
match is_func_update {
Some(record_expr) => {
let ty = ctx.sema.type_of_expr(&ast::Expr::RecordExpr(record_expr.clone()));
if !in_block_expr {
add_keyword("unsafe", "unsafe {\n $0\n}");
match ty.as_ref().and_then(|t| t.original.as_adt()) {
Some(hir::Adt::Union(_)) => (),
_ => {
cov_mark::hit!(functional_update);
let missing_fields =
ctx.sema.record_literal_missing_fields(record_expr);
if !missing_fields.is_empty() {
add_default_update(acc, ctx, ty);
}
}
};
}
add_keyword("match", "match $1 {\n $0\n}");
add_keyword("while", "while $1 {\n $0\n}");
add_keyword("while let", "while let $1 = $2 {\n $0\n}");
add_keyword("loop", "loop {\n $0\n}");
if in_match_guard {
add_keyword("if", "if $0");
} else {
add_keyword("if", "if $1 {\n $0\n}");
}
add_keyword("if let", "if let $1 = $2 {\n $0\n}");
add_keyword("for", "for $1 in $2 {\n $0\n}");
add_keyword("true", "true");
add_keyword("false", "false");
None => {
let mut add_keyword = |kw, snippet| {
acc.add_keyword_snippet_expr(ctx, incomplete_let, kw, snippet)
};
if in_condition || in_block_expr {
add_keyword("let", "let");
}
if after_if_expr {
add_keyword("else", "else {\n $0\n}");
add_keyword("else if", "else if $1 {\n $0\n}");
}
if wants_mut_token {
add_keyword("mut", "mut ");
}
if in_loop_body {
if in_block_expr {
add_keyword("continue", "continue;");
add_keyword("break", "break;");
} else {
add_keyword("continue", "continue");
add_keyword("break", "break");
if !in_block_expr {
add_keyword("unsafe", "unsafe {\n $0\n}");
}
}
add_keyword("match", "match $1 {\n $0\n}");
add_keyword("while", "while $1 {\n $0\n}");
add_keyword("while let", "while let $1 = $2 {\n $0\n}");
add_keyword("loop", "loop {\n $0\n}");
if in_match_guard {
add_keyword("if", "if $0");
} else {
add_keyword("if", "if $1 {\n $0\n}");
}
add_keyword("if let", "if let $1 = $2 {\n $0\n}");
add_keyword("for", "for $1 in $2 {\n $0\n}");
add_keyword("true", "true");
add_keyword("false", "false");
if let Some(ty) = innermost_ret_ty {
add_keyword(
"return",
match (in_block_expr, ty.is_unit()) {
(true, true) => "return ;",
(true, false) => "return;",
(false, true) => "return $0",
(false, false) => "return",
},
);
if in_condition || in_block_expr {
add_keyword("let", "let");
}
if after_if_expr {
add_keyword("else", "else {\n $0\n}");
add_keyword("else if", "else if $1 {\n $0\n}");
}
if wants_mut_token {
add_keyword("mut", "mut ");
}
if in_loop_body {
if in_block_expr {
add_keyword("continue", "continue;");
add_keyword("break", "break;");
} else {
add_keyword("continue", "continue");
add_keyword("break", "break");
}
}
if let Some(ty) = innermost_ret_ty {
add_keyword(
"return",
match (in_block_expr, ty.is_unit()) {
(true, true) => "return ;",
(true, false) => "return;",
(false, true) => "return $0",
(false, false) => "return",
},
);
}
}
}
}

View file

@ -233,7 +233,8 @@ fn add_type_alias_impl(
type_alias: hir::TypeAlias,
) {
let alias_name = type_alias.name(ctx.db);
let (alias_name, escaped_name) = (alias_name.to_smol_str(), alias_name.escaped().to_smol_str());
let (alias_name, escaped_name) =
(alias_name.unescaped().to_smol_str(), alias_name.to_smol_str());
let label = format!("type {} =", alias_name);
let replacement = format!("type {} = ", escaped_name);

View file

@ -3,7 +3,7 @@ use ide_db::SymbolKind;
use syntax::ast::{self, Expr};
use crate::{
context::{DotAccess, DotAccessKind, ExprCtx, PathCompletionCtx, PatternContext, Qualified},
context::{DotAccess, DotAccessKind, PatternContext},
CompletionContext, CompletionItem, CompletionItemKind, CompletionRelevance,
CompletionRelevancePostfixMatch, Completions,
};
@ -14,7 +14,24 @@ pub(crate) fn complete_record_pattern_fields(
pattern_ctx: &PatternContext,
) {
if let PatternContext { record_pat: Some(record_pat), .. } = pattern_ctx {
complete_fields(acc, ctx, ctx.sema.record_pattern_missing_fields(record_pat));
let ty = ctx.sema.type_of_pat(&ast::Pat::RecordPat(record_pat.clone()));
let missing_fields = match ty.as_ref().and_then(|t| t.original.as_adt()) {
Some(hir::Adt::Union(un)) => {
// ctx.sema.record_pat_missing_fields will always return
// an empty Vec on a union literal. This is normally
// reasonable, but here we'd like to present the full list
// of fields if the literal is empty.
let were_fields_specified =
record_pat.record_pat_field_list().and_then(|fl| fl.fields().next()).is_some();
match were_fields_specified {
false => un.fields(ctx.db).into_iter().map(|f| (f, f.ty(ctx.db))).collect(),
true => return,
}
}
_ => ctx.sema.record_pattern_missing_fields(record_pat),
};
complete_fields(acc, ctx, missing_fields);
}
}
@ -42,8 +59,13 @@ pub(crate) fn complete_record_expr_fields(
}
_ => {
let missing_fields = ctx.sema.record_literal_missing_fields(record_expr);
add_default_update(acc, ctx, ty, &missing_fields);
if !missing_fields.is_empty() {
cov_mark::hit!(functional_update_field);
add_default_update(acc, ctx, ty);
}
if dot_prefix {
cov_mark::hit!(functional_update_one_dot);
let mut item =
CompletionItem::new(CompletionItemKind::Snippet, ctx.source_range(), "..");
item.insert_text(".");
@ -56,41 +78,18 @@ pub(crate) fn complete_record_expr_fields(
complete_fields(acc, ctx, missing_fields);
}
// FIXME: This should probably be part of complete_path_expr
pub(crate) fn complete_record_expr_func_update(
acc: &mut Completions,
ctx: &CompletionContext<'_>,
path_ctx: &PathCompletionCtx,
expr_ctx: &ExprCtx,
) {
if !matches!(path_ctx.qualified, Qualified::No) {
return;
}
if let ExprCtx { is_func_update: Some(record_expr), .. } = expr_ctx {
let ty = ctx.sema.type_of_expr(&Expr::RecordExpr(record_expr.clone()));
match ty.as_ref().and_then(|t| t.original.as_adt()) {
Some(hir::Adt::Union(_)) => (),
_ => {
let missing_fields = ctx.sema.record_literal_missing_fields(record_expr);
add_default_update(acc, ctx, ty, &missing_fields);
}
};
}
}
fn add_default_update(
pub(crate) fn add_default_update(
acc: &mut Completions,
ctx: &CompletionContext<'_>,
ty: Option<hir::TypeInfo>,
missing_fields: &[(hir::Field, hir::Type)],
) {
let default_trait = ctx.famous_defs().core_default_Default();
let impl_default_trait = default_trait
let impls_default_trait = default_trait
.zip(ty.as_ref())
.map_or(false, |(default_trait, ty)| ty.original.impls_trait(ctx.db, default_trait, &[]));
if impl_default_trait && !missing_fields.is_empty() {
if impls_default_trait {
// FIXME: This should make use of scope_def like completions so we get all the other goodies
// that is we should handle this like actually completing the default function
let completion_text = "..Default::default()";
let mut item = CompletionItem::new(SymbolKind::Field, ctx.source_range(), completion_text);
let completion_text =

View file

@ -134,6 +134,7 @@ pub(crate) struct ExprCtx {
pub(crate) in_condition: bool,
pub(crate) incomplete_let: bool,
pub(crate) ref_expr_parent: Option<ast::RefExpr>,
/// The surrounding RecordExpression we are completing a functional update
pub(crate) is_func_update: Option<ast::RecordExpr>,
pub(crate) self_param: Option<hir::SelfParam>,
pub(crate) innermost_ret_ty: Option<hir::Type>,

View file

@ -117,7 +117,7 @@ pub(crate) fn render_field(
) -> CompletionItem {
let is_deprecated = ctx.is_deprecated(field);
let name = field.name(ctx.db());
let (name, escaped_name) = (name.to_smol_str(), name.escaped().to_smol_str());
let (name, escaped_name) = (name.unescaped().to_smol_str(), name.to_smol_str());
let mut item = CompletionItem::new(
SymbolKind::Field,
ctx.source_range(),
@ -283,8 +283,8 @@ fn render_resolution_path(
let name = local_name.to_smol_str();
let mut item = render_resolution_simple_(ctx, &local_name, import_to_add, resolution);
if local_name.escaped().is_escaped() {
item.insert_text(local_name.escaped().to_smol_str());
if local_name.is_escaped() {
item.insert_text(local_name.to_smol_str());
}
// Add `<>` for generic types
let type_path_no_ty_args = matches!(
@ -306,7 +306,7 @@ fn render_resolution_path(
item.lookup_by(name.clone())
.label(SmolStr::from_iter([&name, "<…>"]))
.trigger_call_info()
.insert_snippet(cap, format!("{}<$0>", local_name.escaped()));
.insert_snippet(cap, format!("{}<$0>", local_name));
}
}
}
@ -342,7 +342,8 @@ fn render_resolution_simple_(
let ctx = ctx.import_to_add(import_to_add);
let kind = res_to_kind(resolution);
let mut item = CompletionItem::new(kind, ctx.source_range(), local_name.to_smol_str());
let mut item =
CompletionItem::new(kind, ctx.source_range(), local_name.unescaped().to_smol_str());
item.set_relevance(ctx.completion_relevance())
.set_documentation(scope_def_docs(db, resolution))
.set_deprecated(scope_def_is_deprecated(&ctx, resolution));

View file

@ -13,7 +13,7 @@ pub(crate) fn render_const(ctx: RenderContext<'_>, const_: hir::Const) -> Option
fn render(ctx: RenderContext<'_>, const_: hir::Const) -> Option<CompletionItem> {
let db = ctx.db();
let name = const_.name(db)?;
let (name, escaped_name) = (name.to_smol_str(), name.escaped().to_smol_str());
let (name, escaped_name) = (name.unescaped().to_smol_str(), name.to_smol_str());
let detail = const_.display(db).to_string();
let mut item = CompletionItem::new(SymbolKind::Const, ctx.source_range(), name.clone());

View file

@ -52,10 +52,10 @@ fn render(
let (call, escaped_call) = match &func_kind {
FuncKind::Method(_, Some(receiver)) => (
format!("{}.{}", receiver, &name).into(),
format!("{}.{}", receiver.escaped(), name.escaped()).into(),
format!("{}.{}", receiver.unescaped(), name.unescaped()).into(),
format!("{}.{}", receiver, name).into(),
),
_ => (name.to_smol_str(), name.escaped().to_smol_str()),
_ => (name.unescaped().to_smol_str(), name.to_smol_str()),
};
let mut item = CompletionItem::new(
if func.self_param(db).is_some() {
@ -96,7 +96,7 @@ fn render(
item.set_documentation(ctx.docs(func))
.set_deprecated(ctx.is_deprecated(func) || ctx.is_deprecated_assoc_item(func))
.detail(detail(db, func))
.lookup_by(name.to_smol_str());
.lookup_by(name.unescaped().to_smol_str());
match ctx.completion.config.snippet_cap {
Some(cap) => {

View file

@ -73,7 +73,7 @@ fn render(
None => (name.clone().into(), name.into(), false),
};
let (qualified_name, escaped_qualified_name) =
(qualified_name.to_string(), qualified_name.escaped().to_string());
(qualified_name.unescaped().to_string(), qualified_name.to_string());
let snippet_cap = ctx.snippet_cap();
let mut rendered = match kind {

View file

@ -46,7 +46,7 @@ fn render(
ctx.source_range()
};
let (name, escaped_name) = (name.to_smol_str(), name.escaped().to_smol_str());
let (name, escaped_name) = (name.unescaped().to_smol_str(), name.to_smol_str());
let docs = ctx.docs(macro_);
let docs_str = docs.as_ref().map(Documentation::as_str).unwrap_or_default();
let is_fn_like = macro_.is_fn_like(completion.db);

View file

@ -31,7 +31,7 @@ pub(crate) fn render_struct_pat(
}
let name = local_name.unwrap_or_else(|| strukt.name(ctx.db()));
let (name, escaped_name) = (name.to_smol_str(), name.escaped().to_smol_str());
let (name, escaped_name) = (name.unescaped().to_smol_str(), name.to_smol_str());
let kind = strukt.kind(ctx.db());
let label = format_literal_label(name.as_str(), kind);
let pat = render_pat(&ctx, pattern_ctx, &escaped_name, kind, &visible_fields, fields_omitted)?;
@ -53,10 +53,10 @@ pub(crate) fn render_variant_pat(
let (visible_fields, fields_omitted) = visible_fields(ctx.completion, &fields, variant)?;
let (name, escaped_name) = match path {
Some(path) => (path.to_string().into(), path.escaped().to_string().into()),
Some(path) => (path.unescaped().to_string().into(), path.to_string().into()),
None => {
let name = local_name.unwrap_or_else(|| variant.name(ctx.db()));
(name.to_smol_str(), name.escaped().to_smol_str())
(name.unescaped().to_smol_str(), name.to_smol_str())
}
};
@ -146,7 +146,7 @@ fn render_record_as_pat(
format!(
"{name} {{ {}{} }}",
fields.enumerate().format_with(", ", |(idx, field), f| {
f(&format_args!("{}${}", field.name(db).escaped(), idx + 1))
f(&format_args!("{}${}", field.name(db), idx + 1))
}),
if fields_omitted { ", .." } else { "" },
name = name
@ -155,7 +155,7 @@ fn render_record_as_pat(
None => {
format!(
"{name} {{ {}{} }}",
fields.map(|field| field.name(db).escaped().to_smol_str()).format(", "),
fields.map(|field| field.name(db).to_smol_str()).format(", "),
if fields_omitted { ", .." } else { "" },
name = name
)

View file

@ -32,11 +32,11 @@ fn render(
let name = type_alias.name(db);
let (name, escaped_name) = if with_eq {
(
SmolStr::from_iter([&name.unescaped().to_smol_str(), " = "]),
SmolStr::from_iter([&name.to_smol_str(), " = "]),
SmolStr::from_iter([&name.escaped().to_smol_str(), " = "]),
)
} else {
(name.to_smol_str(), name.escaped().to_smol_str())
(name.unescaped().to_smol_str(), name.to_smol_str())
};
let detail = type_alias.display(db).to_string();

View file

@ -21,8 +21,8 @@ pub(crate) fn render_union_literal(
let name = local_name.unwrap_or_else(|| un.name(ctx.db()));
let (qualified_name, escaped_qualified_name) = match path {
Some(p) => (p.to_string(), p.escaped().to_string()),
None => (name.to_string(), name.escaped().to_string()),
Some(p) => (p.unescaped().to_string(), p.to_string()),
None => (name.unescaped().to_string(), name.to_string()),
};
let mut item = CompletionItem::new(
@ -42,15 +42,15 @@ pub(crate) fn render_union_literal(
format!(
"{} {{ ${{1|{}|}}: ${{2:()}} }}$0",
escaped_qualified_name,
fields.iter().map(|field| field.name(ctx.db()).escaped().to_smol_str()).format(",")
fields.iter().map(|field| field.name(ctx.db()).to_smol_str()).format(",")
)
} else {
format!(
"{} {{ {} }}",
escaped_qualified_name,
fields.iter().format_with(", ", |field, f| {
f(&format_args!("{}: ()", field.name(ctx.db()).escaped()))
})
fields
.iter()
.format_with(", ", |field, f| { f(&format_args!("{}: ()", field.name(ctx.db()))) })
)
};

View file

@ -24,9 +24,9 @@ pub(crate) fn render_record_lit(
) -> RenderedLiteral {
let completions = fields.iter().enumerate().format_with(", ", |(idx, field), f| {
if snippet_cap.is_some() {
f(&format_args!("{}: ${{{}:()}}", field.name(db).escaped(), idx + 1))
f(&format_args!("{}: ${{{}:()}}", field.name(db), idx + 1))
} else {
f(&format_args!("{}: ()", field.name(db).escaped()))
f(&format_args!("{}: ()", field.name(db)))
}
});

View file

@ -103,47 +103,9 @@ fn foo(f: Struct) {
}
#[test]
fn functional_update() {
// FIXME: This should filter out all completions that do not have the type `Foo`
check(
r#"
//- minicore:default
struct Foo { foo1: u32, foo2: u32 }
impl Default for Foo {
fn default() -> Self { loop {} }
}
fn in_functional_update() {
cov_mark::check!(functional_update);
fn main() {
let thing = 1;
let foo = Foo { foo1: 0, foo2: 0 };
let foo2 = Foo { thing, $0 }
}
"#,
expect![[r#"
fd ..Default::default()
fd foo1 u32
fd foo2 u32
"#]],
);
check(
r#"
//- minicore:default
struct Foo { foo1: u32, foo2: u32 }
impl Default for Foo {
fn default() -> Self { loop {} }
}
fn main() {
let thing = 1;
let foo = Foo { foo1: 0, foo2: 0 };
let foo2 = Foo { thing, .$0 }
}
"#,
expect![[r#"
fd ..Default::default()
sn ..
"#]],
);
check(
r#"
//- minicore:default
@ -192,6 +154,56 @@ fn main() {
);
}
#[test]
fn functional_update_no_dot() {
cov_mark::check!(functional_update_field);
// FIXME: This should filter out all completions that do not have the type `Foo`
check(
r#"
//- minicore:default
struct Foo { foo1: u32, foo2: u32 }
impl Default for Foo {
fn default() -> Self { loop {} }
}
fn main() {
let thing = 1;
let foo = Foo { foo1: 0, foo2: 0 };
let foo2 = Foo { thing, $0 }
}
"#,
expect![[r#"
fd ..Default::default()
fd foo1 u32
fd foo2 u32
"#]],
);
}
#[test]
fn functional_update_one_dot() {
cov_mark::check!(functional_update_one_dot);
check(
r#"
//- minicore:default
struct Foo { foo1: u32, foo2: u32 }
impl Default for Foo {
fn default() -> Self { loop {} }
}
fn main() {
let thing = 1;
let foo = Foo { foo1: 0, foo2: 0 };
let foo2 = Foo { thing, .$0 }
}
"#,
expect![[r#"
fd ..Default::default()
sn ..
"#]],
);
}
#[test]
fn empty_union_literal() {
check(

View file

@ -4,7 +4,7 @@
//! get a super-set of matches. Then, we we confirm each match using precise
//! name resolution.
use std::{convert::TryInto, mem, sync::Arc};
use std::{mem, sync::Arc};
use base_db::{FileId, FileRange, SourceDatabase, SourceDatabaseExt};
use hir::{DefWithBody, HasAttrs, HasSource, InFile, ModuleSource, Semantics, Visibility};

View file

@ -3,12 +3,15 @@
//!
//! It can be viewed as a dual for `Change`.
use std::{collections::hash_map::Entry, iter};
use std::{collections::hash_map::Entry, iter, mem};
use base_db::{AnchoredPathBuf, FileId};
use rustc_hash::FxHashMap;
use stdx::never;
use text_edit::TextEdit;
use syntax::{algo, AstNode, SyntaxNode, SyntaxNodePtr, TextRange, TextSize};
use text_edit::{TextEdit, TextEditBuilder};
use crate::SnippetCap;
#[derive(Default, Debug, Clone)]
pub struct SourceChange {
@ -81,6 +84,135 @@ impl From<FxHashMap<FileId, TextEdit>> for SourceChange {
}
}
pub struct SourceChangeBuilder {
pub edit: TextEditBuilder,
pub file_id: FileId,
pub source_change: SourceChange,
pub trigger_signature_help: bool,
/// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
pub mutated_tree: Option<TreeMutator>,
}
pub struct TreeMutator {
immutable: SyntaxNode,
mutable_clone: SyntaxNode,
}
impl TreeMutator {
pub fn new(immutable: &SyntaxNode) -> TreeMutator {
let immutable = immutable.ancestors().last().unwrap();
let mutable_clone = immutable.clone_for_update();
TreeMutator { immutable, mutable_clone }
}
pub fn make_mut<N: AstNode>(&self, node: &N) -> N {
N::cast(self.make_syntax_mut(node.syntax())).unwrap()
}
pub fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
let ptr = SyntaxNodePtr::new(node);
ptr.to_node(&self.mutable_clone)
}
}
impl SourceChangeBuilder {
pub fn new(file_id: FileId) -> SourceChangeBuilder {
SourceChangeBuilder {
edit: TextEdit::builder(),
file_id,
source_change: SourceChange::default(),
trigger_signature_help: false,
mutated_tree: None,
}
}
pub fn edit_file(&mut self, file_id: FileId) {
self.commit();
self.file_id = file_id;
}
fn commit(&mut self) {
if let Some(tm) = self.mutated_tree.take() {
algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
}
let edit = mem::take(&mut self.edit).finish();
if !edit.is_empty() {
self.source_change.insert_source_edit(self.file_id, edit);
}
}
pub fn make_mut<N: AstNode>(&mut self, node: N) -> N {
self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
}
/// Returns a copy of the `node`, suitable for mutation.
///
/// Syntax trees in rust-analyzer are typically immutable, and mutating
/// operations panic at runtime. However, it is possible to make a copy of
/// the tree and mutate the copy freely. Mutation is based on interior
/// mutability, and different nodes in the same tree see the same mutations.
///
/// The typical pattern for an assist is to find specific nodes in the read
/// phase, and then get their mutable couterparts using `make_mut` in the
/// mutable state.
pub fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
}
/// Remove specified `range` of text.
pub fn delete(&mut self, range: TextRange) {
self.edit.delete(range)
}
/// Append specified `text` at the given `offset`
pub fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
self.edit.insert(offset, text.into())
}
/// Append specified `snippet` at the given `offset`
pub fn insert_snippet(
&mut self,
_cap: SnippetCap,
offset: TextSize,
snippet: impl Into<String>,
) {
self.source_change.is_snippet = true;
self.insert(offset, snippet);
}
/// Replaces specified `range` of text with a given string.
pub fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
self.edit.replace(range, replace_with.into())
}
/// Replaces specified `range` of text with a given `snippet`.
pub fn replace_snippet(
&mut self,
_cap: SnippetCap,
range: TextRange,
snippet: impl Into<String>,
) {
self.source_change.is_snippet = true;
self.replace(range, snippet);
}
pub fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
}
pub fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
self.source_change.push_file_system_edit(file_system_edit);
}
pub fn move_file(&mut self, src: FileId, dst: AnchoredPathBuf) {
let file_system_edit = FileSystemEdit::MoveFile { src, dst };
self.source_change.push_file_system_edit(file_system_edit);
}
pub fn trigger_signature_help(&mut self) {
self.trigger_signature_help = true;
}
pub fn finish(mut self) -> SourceChange {
self.commit();
mem::take(&mut self.source_change)
}
}
#[derive(Debug, Clone)]
pub enum FileSystemEdit {
CreateFile { dst: AnchoredPathBuf, initial_contents: String },

View file

@ -15,6 +15,7 @@ itertools = "0.10.3"
either = "1.7.0"
serde_json = "1.0.82"
profile = { path = "../profile", version = "0.0.0" }
stdx = { path = "../stdx", version = "0.0.0" }

View file

@ -43,7 +43,7 @@ mod tests {
use crate::{tests::check_diagnostics_with_config, DiagnosticsConfig};
pub(crate) fn check(ra_fixture: &str) {
let config = DiagnosticsConfig::default();
let config = DiagnosticsConfig::test_sample();
check_diagnostics_with_config(config, ra_fixture)
}

View file

@ -0,0 +1,310 @@
//! This diagnostic provides an assist for creating a struct definition from a JSON
//! example.
use hir::{PathResolution, Semantics};
use ide_db::{
base_db::FileId,
helpers::mod_path_to_ast,
imports::insert_use::{insert_use, ImportScope},
source_change::SourceChangeBuilder,
RootDatabase,
};
use itertools::Itertools;
use stdx::{format_to, never};
use syntax::{
ast::{self, make},
SyntaxKind, SyntaxNode,
};
use text_edit::TextEdit;
use crate::{fix, Diagnostic, DiagnosticsConfig, Severity};
#[derive(Default)]
struct State {
result: String,
struct_counts: usize,
has_serialize: bool,
has_deserialize: bool,
}
impl State {
fn generate_new_name(&mut self) -> ast::Name {
self.struct_counts += 1;
make::name(&format!("Struct{}", self.struct_counts))
}
fn serde_derive(&self) -> String {
let mut v = vec![];
if self.has_serialize {
v.push("Serialize");
}
if self.has_deserialize {
v.push("Deserialize");
}
match v.as_slice() {
[] => "".to_string(),
[x] => format!("#[derive({x})]\n"),
[x, y] => format!("#[derive({x}, {y})]\n"),
_ => {
never!();
"".to_string()
}
}
}
fn build_struct(&mut self, value: &serde_json::Map<String, serde_json::Value>) -> ast::Type {
let name = self.generate_new_name();
let ty = make::ty(&name.to_string());
let strukt = make::struct_(
None,
name,
None,
make::record_field_list(value.iter().sorted_unstable_by_key(|x| x.0).map(
|(name, value)| make::record_field(None, make::name(name), self.type_of(value)),
))
.into(),
);
format_to!(self.result, "{}{}\n", self.serde_derive(), strukt);
ty
}
fn type_of(&mut self, value: &serde_json::Value) -> ast::Type {
match value {
serde_json::Value::Null => make::ty_unit(),
serde_json::Value::Bool(_) => make::ty("bool"),
serde_json::Value::Number(it) => make::ty(if it.is_i64() { "i64" } else { "f64" }),
serde_json::Value::String(_) => make::ty("String"),
serde_json::Value::Array(it) => {
let ty = match it.iter().next() {
Some(x) => self.type_of(x),
None => make::ty_placeholder(),
};
make::ty(&format!("Vec<{ty}>"))
}
serde_json::Value::Object(x) => self.build_struct(x),
}
}
}
pub(crate) fn json_in_items(
sema: &Semantics<'_, RootDatabase>,
acc: &mut Vec<Diagnostic>,
file_id: FileId,
node: &SyntaxNode,
config: &DiagnosticsConfig,
) {
(|| {
if node.kind() == SyntaxKind::ERROR
&& node.first_token().map(|x| x.kind()) == Some(SyntaxKind::L_CURLY)
&& node.last_token().map(|x| x.kind()) == Some(SyntaxKind::R_CURLY)
{
let node_string = node.to_string();
if let Ok(it) = serde_json::from_str(&node_string) {
if let serde_json::Value::Object(it) = it {
let import_scope = ImportScope::find_insert_use_container(node, sema)?;
let range = node.text_range();
let mut edit = TextEdit::builder();
edit.delete(range);
let mut state = State::default();
let semantics_scope = sema.scope(node)?;
let scope_resolve =
|it| semantics_scope.speculative_resolve(&make::path_from_text(it));
let scope_has = |it| scope_resolve(it).is_some();
let deserialize_resolved = scope_resolve("::serde::Deserialize");
let serialize_resolved = scope_resolve("::serde::Serialize");
state.has_deserialize = deserialize_resolved.is_some();
state.has_serialize = serialize_resolved.is_some();
state.build_struct(&it);
edit.insert(range.start(), state.result);
acc.push(
Diagnostic::new(
"json-is-not-rust",
"JSON syntax is not valid as a Rust item",
range,
)
.severity(Severity::WeakWarning)
.with_fixes(Some(vec![{
let mut scb = SourceChangeBuilder::new(file_id);
let scope = match import_scope.clone() {
ImportScope::File(it) => ImportScope::File(scb.make_mut(it)),
ImportScope::Module(it) => ImportScope::Module(scb.make_mut(it)),
ImportScope::Block(it) => ImportScope::Block(scb.make_mut(it)),
};
let current_module = semantics_scope.module();
if !scope_has("Serialize") {
if let Some(PathResolution::Def(it)) = serialize_resolved {
if let Some(it) = current_module.find_use_path_prefixed(
sema.db,
it,
config.insert_use.prefix_kind,
) {
insert_use(
&scope,
mod_path_to_ast(&it),
&config.insert_use,
);
}
}
}
if !scope_has("Deserialize") {
if let Some(PathResolution::Def(it)) = deserialize_resolved {
if let Some(it) = current_module.find_use_path_prefixed(
sema.db,
it,
config.insert_use.prefix_kind,
) {
insert_use(
&scope,
mod_path_to_ast(&it),
&config.insert_use,
);
}
}
}
let mut sc = scb.finish();
sc.insert_source_edit(file_id, edit.finish());
fix("convert_json_to_struct", "Convert JSON to struct", sc, range)
}])),
);
}
}
}
Some(())
})();
}
#[cfg(test)]
mod tests {
use crate::{
tests::{check_diagnostics_with_config, check_fix, check_no_fix},
DiagnosticsConfig,
};
#[test]
fn diagnostic_for_simple_case() {
let mut config = DiagnosticsConfig::test_sample();
config.disabled.insert("syntax-error".to_string());
check_diagnostics_with_config(
config,
r#"
{ "foo": "bar" }
// ^^^^^^^^^^^^^^^^ 💡 weak: JSON syntax is not valid as a Rust item
"#,
);
}
#[test]
fn types_of_primitives() {
check_fix(
r#"
//- /lib.rs crate:lib deps:serde
use serde::Serialize;
fn some_garbage() {
}
{$0
"foo": "bar",
"bar": 2.3,
"baz": null,
"bay": 57,
"box": true
}
//- /serde.rs crate:serde
pub trait Serialize {
fn serialize() -> u8;
}
"#,
r#"
use serde::Serialize;
fn some_garbage() {
}
#[derive(Serialize)]
struct Struct1{ bar: f64, bay: i64, baz: (), r#box: bool, foo: String }
"#,
);
}
#[test]
fn nested_structs() {
check_fix(
r#"
{$0
"foo": "bar",
"bar": {
"kind": "Object",
"value": {}
}
}
"#,
r#"
struct Struct3{ }
struct Struct2{ kind: String, value: Struct3 }
struct Struct1{ bar: Struct2, foo: String }
"#,
);
}
#[test]
fn arrays() {
check_fix(
r#"
//- /lib.rs crate:lib deps:serde
{
"of_string": ["foo", "2", "x"], $0
"of_object": [{
"x": 10,
"y": 20
}, {
"x": 10,
"y": 20
}],
"nested": [[[2]]],
"empty": []
}
//- /serde.rs crate:serde
pub trait Serialize {
fn serialize() -> u8;
}
pub trait Deserialize {
fn deserialize() -> u8;
}
"#,
r#"
use serde::Serialize;
use serde::Deserialize;
#[derive(Serialize, Deserialize)]
struct Struct2{ x: i64, y: i64 }
#[derive(Serialize, Deserialize)]
struct Struct1{ empty: Vec<_>, nested: Vec<Vec<Vec<i64>>>, of_object: Vec<Struct2>, of_string: Vec<String> }
"#,
);
}
#[test]
fn no_emit_outside_of_item_position() {
check_no_fix(
r#"
fn foo() {
let json = {$0
"foo": "bar",
"bar": {
"kind": "Object",
"value": {}
}
};
}
"#,
);
}
}

View file

@ -79,7 +79,7 @@ pub macro panic {
#[test]
fn include_macro_should_allow_empty_content() {
let mut config = DiagnosticsConfig::default();
let mut config = DiagnosticsConfig::test_sample();
// FIXME: This is a false-positive, the file is actually linked in via
// `include!` macro

View file

@ -68,7 +68,7 @@ fn missing_record_expr_field_fixes(
}
let new_field = make::record_field(
None,
make::name(&record_expr_field.field_name()?.text()),
make::name(&record_expr_field.field_name()?.ident_token()?.text()),
make::ty(&new_field_type.display_source_code(sema.db, module.into()).ok()?),
);
@ -109,7 +109,7 @@ fn missing_record_expr_field_fixes(
#[cfg(test)]
mod tests {
use crate::tests::{check_diagnostics, check_fix};
use crate::tests::{check_diagnostics, check_fix, check_no_fix};
#[test]
fn no_such_field_diagnostics() {
@ -277,6 +277,20 @@ struct Foo {
bar: i32,
pub(crate) baz: bool
}
"#,
)
}
#[test]
fn test_tuple_field_on_record_struct() {
check_no_fix(
r#"
struct Struct {}
fn main() {
Struct {
0$0: 0
}
}
"#,
)
}

View file

@ -50,6 +50,7 @@ mod handlers {
pub(crate) mod field_shorthand;
pub(crate) mod useless_braces;
pub(crate) mod unlinked_file;
pub(crate) mod json_is_not_rust;
}
#[cfg(test)]
@ -59,6 +60,7 @@ use hir::{diagnostics::AnyDiagnostic, InFile, Semantics};
use ide_db::{
assists::{Assist, AssistId, AssistKind, AssistResolveStrategy},
base_db::{FileId, FileRange, SourceDatabase},
imports::insert_use::InsertUseConfig,
label::Label,
source_change::SourceChange,
FxHashSet, RootDatabase,
@ -139,13 +141,37 @@ impl Default for ExprFillDefaultMode {
}
}
#[derive(Default, Debug, Clone)]
#[derive(Debug, Clone)]
pub struct DiagnosticsConfig {
pub proc_macros_enabled: bool,
pub proc_attr_macros_enabled: bool,
pub disable_experimental: bool,
pub disabled: FxHashSet<String>,
pub expr_fill_default: ExprFillDefaultMode,
// FIXME: We may want to include a whole `AssistConfig` here
pub insert_use: InsertUseConfig,
}
impl DiagnosticsConfig {
pub fn test_sample() -> Self {
use hir::PrefixKind;
use ide_db::imports::insert_use::ImportGranularity;
Self {
proc_macros_enabled: Default::default(),
proc_attr_macros_enabled: Default::default(),
disable_experimental: Default::default(),
disabled: Default::default(),
expr_fill_default: Default::default(),
insert_use: InsertUseConfig {
granularity: ImportGranularity::Preserve,
enforce_granularity: false,
prefix_kind: PrefixKind::Plain,
group: false,
skip_glob_imports: false,
},
}
}
}
struct DiagnosticsContext<'a> {
@ -172,9 +198,12 @@ pub fn diagnostics(
}),
);
for node in parse.tree().syntax().descendants() {
let parse = sema.parse(file_id);
for node in parse.syntax().descendants() {
handlers::useless_braces::useless_braces(&mut res, file_id, &node);
handlers::field_shorthand::field_shorthand(&mut res, file_id, &node);
handlers::json_is_not_rust::json_in_items(&sema, &mut res, file_id, &node, &config);
}
let module = sema.to_module_def(file_id);

View file

@ -37,7 +37,7 @@ fn check_nth_fix(nth: usize, ra_fixture_before: &str, ra_fixture_after: &str) {
let after = trim_indent(ra_fixture_after);
let (db, file_position) = RootDatabase::with_position(ra_fixture_before);
let mut conf = DiagnosticsConfig::default();
let mut conf = DiagnosticsConfig::test_sample();
conf.expr_fill_default = ExprFillDefaultMode::Default;
let diagnostic =
super::diagnostics(&db, &conf, &AssistResolveStrategy::All, file_position.file_id)
@ -69,7 +69,7 @@ pub(crate) fn check_no_fix(ra_fixture: &str) {
let (db, file_position) = RootDatabase::with_position(ra_fixture);
let diagnostic = super::diagnostics(
&db,
&DiagnosticsConfig::default(),
&DiagnosticsConfig::test_sample(),
&AssistResolveStrategy::All,
file_position.file_id,
)
@ -82,7 +82,7 @@ pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
let (db, file_id) = RootDatabase::with_single_file(ra_fixture);
let diagnostics = super::diagnostics(
&db,
&DiagnosticsConfig::default(),
&DiagnosticsConfig::test_sample(),
&AssistResolveStrategy::All,
file_id,
);
@ -91,7 +91,7 @@ pub(crate) fn check_expect(ra_fixture: &str, expect: Expect) {
#[track_caller]
pub(crate) fn check_diagnostics(ra_fixture: &str) {
let mut config = DiagnosticsConfig::default();
let mut config = DiagnosticsConfig::test_sample();
config.disabled.insert("inactive-code".to_string());
check_diagnostics_with_config(config, ra_fixture)
}
@ -127,7 +127,7 @@ pub(crate) fn check_diagnostics_with_config(config: DiagnosticsConfig, ra_fixtur
#[test]
fn test_disabled_diagnostics() {
let mut config = DiagnosticsConfig::default();
let mut config = DiagnosticsConfig::test_sample();
config.disabled.insert("unresolved-module".into());
let (db, file_id) = RootDatabase::with_single_file(r#"mod foo;"#);
@ -137,7 +137,7 @@ fn test_disabled_diagnostics() {
let diagnostics = super::diagnostics(
&db,
&DiagnosticsConfig::default(),
&DiagnosticsConfig::test_sample(),
&AssistResolveStrategy::All,
file_id,
);

View file

@ -1,4 +1,4 @@
use std::{convert::TryInto, mem::discriminant};
use std::mem::discriminant;
use crate::{doc_links::token_as_doc_comment, FilePosition, NavigationTarget, RangeInfo, TryToNav};
use hir::{AsAssocItem, AssocItem, Semantics};

View file

@ -2225,4 +2225,190 @@ macro_rules! foo {
"#]],
);
}
#[test]
fn test_paths_with_raw_ident() {
check(
r#"
//- /lib.rs
$0
mod r#mod {
#[test]
fn r#fn() {}
/// ```
/// ```
fn r#for() {}
/// ```
/// ```
struct r#struct<r#type>(r#type);
/// ```
/// ```
impl<r#type> r#struct<r#type> {
/// ```
/// ```
fn r#fn() {}
}
enum r#enum {}
impl r#struct<r#enum> {
/// ```
/// ```
fn r#fn() {}
}
trait r#trait {}
/// ```
/// ```
impl<T> r#trait for r#struct<T> {}
}
"#,
&[TestMod, Test, DocTest, DocTest, DocTest, DocTest, DocTest, DocTest],
expect![[r#"
[
Runnable {
use_name_in_title: false,
nav: NavigationTarget {
file_id: FileId(
0,
),
full_range: 1..461,
focus_range: 5..10,
name: "r#mod",
kind: Module,
description: "mod r#mod",
},
kind: TestMod {
path: "r#mod",
},
cfg: None,
},
Runnable {
use_name_in_title: false,
nav: NavigationTarget {
file_id: FileId(
0,
),
full_range: 17..41,
focus_range: 32..36,
name: "r#fn",
kind: Function,
},
kind: Test {
test_id: Path(
"r#mod::r#fn",
),
attr: TestAttr {
ignore: false,
},
},
cfg: None,
},
Runnable {
use_name_in_title: false,
nav: NavigationTarget {
file_id: FileId(
0,
),
full_range: 47..84,
name: "r#for",
},
kind: DocTest {
test_id: Path(
"r#mod::r#for",
),
},
cfg: None,
},
Runnable {
use_name_in_title: false,
nav: NavigationTarget {
file_id: FileId(
0,
),
full_range: 90..146,
name: "r#struct",
},
kind: DocTest {
test_id: Path(
"r#mod::r#struct",
),
},
cfg: None,
},
Runnable {
use_name_in_title: false,
nav: NavigationTarget {
file_id: FileId(
0,
),
full_range: 152..266,
focus_range: 189..205,
name: "impl",
kind: Impl,
},
kind: DocTest {
test_id: Path(
"r#struct<r#type>",
),
},
cfg: None,
},
Runnable {
use_name_in_title: false,
nav: NavigationTarget {
file_id: FileId(
0,
),
full_range: 216..260,
name: "r#fn",
},
kind: DocTest {
test_id: Path(
"r#mod::r#struct<r#type>::r#fn",
),
},
cfg: None,
},
Runnable {
use_name_in_title: false,
nav: NavigationTarget {
file_id: FileId(
0,
),
full_range: 323..367,
name: "r#fn",
},
kind: DocTest {
test_id: Path(
"r#mod::r#struct<r#enum>::r#fn",
),
},
cfg: None,
},
Runnable {
use_name_in_title: false,
nav: NavigationTarget {
file_id: FileId(
0,
),
full_range: 401..459,
focus_range: 445..456,
name: "impl",
kind: Impl,
},
kind: DocTest {
test_id: Path(
"r#struct<T>",
),
},
cfg: None,
},
]
"#]],
)
}
}

View file

@ -1,4 +1,4 @@
use std::{fmt, iter::FromIterator, sync::Arc};
use std::{fmt, sync::Arc};
use hir::{ExpandResult, MacroFile};
use ide_db::base_db::{

View file

@ -228,16 +228,7 @@ fn convert_tokens<C: TokenConvertor>(conv: &mut C) -> tt::Subtree {
}
let spacing = match conv.peek().map(|next| next.kind(conv)) {
Some(kind)
if !kind.is_trivia()
&& kind.is_punct()
&& kind != T!['[']
&& kind != T!['{']
&& kind != T!['(']
&& kind != UNDERSCORE =>
{
tt::Spacing::Joint
}
Some(kind) if !kind.is_trivia() => tt::Spacing::Joint,
_ => tt::Spacing::Alone,
};
let char = match token.to_char(conv) {

View file

@ -564,8 +564,10 @@ fn path_expr(p: &mut Parser<'_>, r: Restrictions) -> (CompletedMarker, BlockLike
// test record_lit
// fn foo() {
// S {};
// S { x };
// S { x, y: 32, };
// S { x, y: 32, ..Default::default() };
// S { x: ::default() };
// TupleStruct { 0: 1 };
// }
pub(crate) fn record_expr_field_list(p: &mut Parser<'_>) {
@ -582,16 +584,26 @@ pub(crate) fn record_expr_field_list(p: &mut Parser<'_>) {
match p.current() {
IDENT | INT_NUMBER => {
// test_err record_literal_before_ellipsis_recovery
// test_err record_literal_missing_ellipsis_recovery
// fn main() {
// S { field ..S::default() }
// S { S::default() }
// }
if p.nth_at(1, T![:]) || p.nth_at(1, T![..]) {
name_ref_or_index(p);
p.expect(T![:]);
if p.nth_at(1, T![::]) {
m.abandon(p);
p.expect(T![..]);
expr(p);
} else {
// test_err record_literal_before_ellipsis_recovery
// fn main() {
// S { field ..S::default() }
// }
if p.nth_at(1, T![:]) || p.nth_at(1, T![..]) {
name_ref_or_index(p);
p.expect(T![:]);
}
expr(p);
m.complete(p, RECORD_EXPR_FIELD);
}
expr(p);
m.complete(p, RECORD_EXPR_FIELD);
}
T![.] if p.at(T![..]) => {
m.abandon(p);

View file

@ -75,6 +75,16 @@ fn pattern_single_r(p: &mut Parser<'_>, recovery_set: TokenSet) {
// Some(1..) => ()
// }
//
// match () {
// S { a: 0 } => (),
// S { a: 1.. } => (),
// }
//
// match () {
// [0] => (),
// [1..] => (),
// }
//
// match (10 as u8, 5 as u8) {
// (0, _) => (),
// (1.., _) => ()
@ -88,11 +98,27 @@ fn pattern_single_r(p: &mut Parser<'_>, recovery_set: TokenSet) {
let m = lhs.precede(p);
p.bump(range_op);
// `0 .. =>` or `let 0 .. =` or `Some(0 .. )`
// ^ ^ ^
if p.at(T![=]) | p.at(T![')']) | p.at(T![,]) {
// testing if we're at one of the following positions:
// `0 .. =>`
// ^
// `let 0 .. =`
// ^
// `let 0..: _ =`
// ^
// (1.., _)
// ^
// `Some(0 .. )`
// ^
// `S { t: 0.. }`
// ^
// `[0..]`
// ^
if matches!(p.current(), T![=] | T![,] | T![:] | T![')'] | T!['}'] | T![']']) {
// test half_open_range_pat
// fn f() { let 0 .. = 1u32; }
// fn f() {
// let 0 .. = 1u32;
// let 0..: _ = 1u32;
// }
} else {
atom_pat(p, recovery_set);
}

View file

@ -0,0 +1,43 @@
SOURCE_FILE
FN
FN_KW "fn"
WHITESPACE " "
NAME
IDENT "main"
PARAM_LIST
L_PAREN "("
R_PAREN ")"
WHITESPACE " "
BLOCK_EXPR
STMT_LIST
L_CURLY "{"
WHITESPACE "\n "
RECORD_EXPR
PATH
PATH_SEGMENT
NAME_REF
IDENT "S"
WHITESPACE " "
RECORD_EXPR_FIELD_LIST
L_CURLY "{"
WHITESPACE " "
CALL_EXPR
PATH_EXPR
PATH
PATH
PATH_SEGMENT
NAME_REF
IDENT "S"
COLON2 "::"
PATH_SEGMENT
NAME_REF
IDENT "default"
ARG_LIST
L_PAREN "("
R_PAREN ")"
WHITESPACE " "
R_CURLY "}"
WHITESPACE "\n"
R_CURLY "}"
WHITESPACE "\n"
error 19: expected DOT2

View file

@ -172,6 +172,122 @@ SOURCE_FILE
WHITESPACE "\n "
R_CURLY "}"
WHITESPACE "\n\n "
EXPR_STMT
MATCH_EXPR
MATCH_KW "match"
WHITESPACE " "
TUPLE_EXPR
L_PAREN "("
R_PAREN ")"
WHITESPACE " "
MATCH_ARM_LIST
L_CURLY "{"
WHITESPACE "\n "
MATCH_ARM
RECORD_PAT
PATH
PATH_SEGMENT
NAME_REF
IDENT "S"
WHITESPACE " "
RECORD_PAT_FIELD_LIST
L_CURLY "{"
WHITESPACE " "
RECORD_PAT_FIELD
NAME_REF
IDENT "a"
COLON ":"
WHITESPACE " "
LITERAL_PAT
LITERAL
INT_NUMBER "0"
WHITESPACE " "
R_CURLY "}"
WHITESPACE " "
FAT_ARROW "=>"
WHITESPACE " "
TUPLE_EXPR
L_PAREN "("
R_PAREN ")"
COMMA ","
WHITESPACE "\n "
MATCH_ARM
RECORD_PAT
PATH
PATH_SEGMENT
NAME_REF
IDENT "S"
WHITESPACE " "
RECORD_PAT_FIELD_LIST
L_CURLY "{"
WHITESPACE " "
RECORD_PAT_FIELD
NAME_REF
IDENT "a"
COLON ":"
WHITESPACE " "
RANGE_PAT
LITERAL_PAT
LITERAL
INT_NUMBER "1"
DOT2 ".."
WHITESPACE " "
R_CURLY "}"
WHITESPACE " "
FAT_ARROW "=>"
WHITESPACE " "
TUPLE_EXPR
L_PAREN "("
R_PAREN ")"
COMMA ","
WHITESPACE "\n "
R_CURLY "}"
WHITESPACE "\n\n "
EXPR_STMT
MATCH_EXPR
MATCH_KW "match"
WHITESPACE " "
TUPLE_EXPR
L_PAREN "("
R_PAREN ")"
WHITESPACE " "
MATCH_ARM_LIST
L_CURLY "{"
WHITESPACE "\n "
MATCH_ARM
SLICE_PAT
L_BRACK "["
LITERAL_PAT
LITERAL
INT_NUMBER "0"
R_BRACK "]"
WHITESPACE " "
FAT_ARROW "=>"
WHITESPACE " "
TUPLE_EXPR
L_PAREN "("
R_PAREN ")"
COMMA ","
WHITESPACE "\n "
MATCH_ARM
SLICE_PAT
L_BRACK "["
RANGE_PAT
LITERAL_PAT
LITERAL
INT_NUMBER "1"
DOT2 ".."
R_BRACK "]"
WHITESPACE " "
FAT_ARROW "=>"
WHITESPACE " "
TUPLE_EXPR
L_PAREN "("
R_PAREN ")"
COMMA ","
WHITESPACE "\n "
R_CURLY "}"
WHITESPACE "\n\n "
MATCH_EXPR
MATCH_KW "match"
WHITESPACE " "

View file

@ -11,6 +11,16 @@ fn main() {
Some(1..) => ()
}
match () {
S { a: 0 } => (),
S { a: 1.. } => (),
}
match () {
[0] => (),
[1..] => (),
}
match (10 as u8, 5 as u8) {
(0, _) => (),
(1.., _) => ()

View file

@ -24,6 +24,26 @@ SOURCE_FILE
R_CURLY "}"
SEMICOLON ";"
WHITESPACE "\n "
EXPR_STMT
RECORD_EXPR
PATH
PATH_SEGMENT
NAME_REF
IDENT "S"
WHITESPACE " "
RECORD_EXPR_FIELD_LIST
L_CURLY "{"
WHITESPACE " "
RECORD_EXPR_FIELD
PATH_EXPR
PATH
PATH_SEGMENT
NAME_REF
IDENT "x"
WHITESPACE " "
R_CURLY "}"
SEMICOLON ";"
WHITESPACE "\n "
EXPR_STMT
RECORD_EXPR
PATH
@ -100,6 +120,35 @@ SOURCE_FILE
R_CURLY "}"
SEMICOLON ";"
WHITESPACE "\n "
EXPR_STMT
RECORD_EXPR
PATH
PATH_SEGMENT
NAME_REF
IDENT "S"
WHITESPACE " "
RECORD_EXPR_FIELD_LIST
L_CURLY "{"
WHITESPACE " "
RECORD_EXPR_FIELD
NAME_REF
IDENT "x"
COLON ":"
WHITESPACE " "
CALL_EXPR
PATH_EXPR
PATH
PATH_SEGMENT
COLON2 "::"
NAME_REF
IDENT "default"
ARG_LIST
L_PAREN "("
R_PAREN ")"
WHITESPACE " "
R_CURLY "}"
SEMICOLON ";"
WHITESPACE "\n "
EXPR_STMT
RECORD_EXPR
PATH

View file

@ -1,6 +1,8 @@
fn foo() {
S {};
S { x };
S { x, y: 32, };
S { x, y: 32, ..Default::default() };
S { x: ::default() };
TupleStruct { 0: 1 };
}

View file

@ -11,7 +11,7 @@ SOURCE_FILE
BLOCK_EXPR
STMT_LIST
L_CURLY "{"
WHITESPACE " "
WHITESPACE "\n "
LET_STMT
LET_KW "let"
WHITESPACE " "
@ -27,6 +27,25 @@ SOURCE_FILE
LITERAL
INT_NUMBER "1u32"
SEMICOLON ";"
WHITESPACE " "
WHITESPACE "\n "
LET_STMT
LET_KW "let"
WHITESPACE " "
RANGE_PAT
LITERAL_PAT
LITERAL
INT_NUMBER "0"
DOT2 ".."
COLON ":"
WHITESPACE " "
INFER_TYPE
UNDERSCORE "_"
WHITESPACE " "
EQ "="
WHITESPACE " "
LITERAL
INT_NUMBER "1u32"
SEMICOLON ";"
WHITESPACE "\n"
R_CURLY "}"
WHITESPACE "\n"

View file

@ -1 +1,4 @@
fn f() { let 0 .. = 1u32; }
fn f() {
let 0 .. = 1u32;
let 0..: _ = 1u32;
}

View file

@ -35,10 +35,7 @@
//! as we don't have bincode in Cargo.toml yet, lets stick with serde_json for
//! the time being.
use std::{
collections::{HashMap, VecDeque},
convert::TryInto,
};
use std::collections::{HashMap, VecDeque};
use serde::{Deserialize, Serialize};
use tt::TokenId;

View file

@ -157,7 +157,7 @@ impl From<TokenTree> for TokenStream {
}
/// Collects a number of token trees into a single stream.
impl iter::FromIterator<TokenTree> for TokenStream {
impl FromIterator<TokenTree> for TokenStream {
fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
trees.into_iter().map(TokenStream::from).collect()
}
@ -165,7 +165,7 @@ impl iter::FromIterator<TokenTree> for TokenStream {
/// A "flattening" operation on token streams, collects token trees
/// from multiple token streams into a single stream.
impl iter::FromIterator<TokenStream> for TokenStream {
impl FromIterator<TokenStream> for TokenStream {
fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
let mut builder = bridge::client::TokenStreamBuilder::new();
streams.into_iter().for_each(|stream| builder.push(stream.0));

Some files were not shown because too many files have changed in this diff Show more