10440: Fix Clippy warnings and replace some `if let`s with `match` r=Veykril a=arzg

I decided to try fixing a bunch of Clippy warnings. I am aware of this project’s opinion of Clippy (I have read both [rust-lang/clippy#5537](https://github.com/rust-lang/rust-clippy/issues/5537) and [rust-analyzer/rowan#57 (comment)](https://github.com/rust-analyzer/rowan/pull/57#discussion_r415676159)), so I totally understand if part of or the entirety of this PR is rejected. In particular, I can see how the semicolons and `if let` vs `match` commits provide comparatively little benefit when compared to the ensuing churn.

I tried to separate each kind of change into its own commit to make it easier to discard certain changes. I also only applied Clippy suggestions where I thought they provided a definite improvement to the code (apart from semicolons, which is IMO more of a formatting/consistency question than a linting question). In the end I accumulated a list of 28 Clippy lints I ignored entirely.

Sidenote: I should really have asked about this on Zulip before going through all 1,555 `if let`s in the codebase to decide which ones definitely look better as `match` :P

Co-authored-by: Aramis Razzaghipour <aramisnoah@gmail.com>
This commit is contained in:
bors[bot] 2021-10-05 08:58:40 +00:00 committed by GitHub
commit 86c534f244
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
95 changed files with 399 additions and 478 deletions

View file

@ -179,7 +179,7 @@ impl FlycheckActor {
tracing::error!( tracing::error!(
"Flycheck failed to run the following command: {:?}", "Flycheck failed to run the following command: {:?}",
self.check_command() self.check_command()
) );
} }
self.progress(Progress::DidFinish(res)); self.progress(Progress::DidFinish(res));
} }
@ -253,14 +253,14 @@ impl FlycheckActor {
} }
fn send(&self, check_task: Message) { fn send(&self, check_task: Message) {
(self.sender)(check_task) (self.sender)(check_task);
} }
} }
struct CargoHandle { struct CargoHandle {
child: JodChild, child: JodChild,
#[allow(unused)] #[allow(unused)]
thread: jod_thread::JoinHandle<io::Result<bool>>, thread: jod_thread::JoinHandle<bool>,
receiver: Receiver<CargoMessage>, receiver: Receiver<CargoMessage>,
} }
@ -279,7 +279,7 @@ impl CargoHandle {
// It is okay to ignore the result, as it only errors if the process is already dead // It is okay to ignore the result, as it only errors if the process is already dead
let _ = self.child.kill(); let _ = self.child.kill();
let exit_status = self.child.wait()?; let exit_status = self.child.wait()?;
let read_at_least_one_message = self.thread.join()?; let read_at_least_one_message = self.thread.join();
if !exit_status.success() && !read_at_least_one_message { if !exit_status.success() && !read_at_least_one_message {
// FIXME: Read the stderr to display the reason, see `read2()` reference in PR comment: // FIXME: Read the stderr to display the reason, see `read2()` reference in PR comment:
// https://github.com/rust-analyzer/rust-analyzer/pull/3632#discussion_r395605298 // https://github.com/rust-analyzer/rust-analyzer/pull/3632#discussion_r395605298
@ -304,7 +304,7 @@ impl CargoActor {
fn new(child_stdout: process::ChildStdout, sender: Sender<CargoMessage>) -> CargoActor { fn new(child_stdout: process::ChildStdout, sender: Sender<CargoMessage>) -> CargoActor {
CargoActor { child_stdout, sender } CargoActor { child_stdout, sender }
} }
fn run(self) -> io::Result<bool> { fn run(self) -> bool {
// We manually read a line at a time, instead of using serde's // We manually read a line at a time, instead of using serde's
// stream deserializers, because the deserializer cannot recover // stream deserializers, because the deserializer cannot recover
// from an error, resulting in it getting stuck, because we try to // from an error, resulting in it getting stuck, because we try to
@ -334,20 +334,20 @@ impl CargoActor {
// Skip certain kinds of messages to only spend time on what's useful // Skip certain kinds of messages to only spend time on what's useful
JsonMessage::Cargo(message) => match message { JsonMessage::Cargo(message) => match message {
cargo_metadata::Message::CompilerArtifact(artifact) if !artifact.fresh => { cargo_metadata::Message::CompilerArtifact(artifact) if !artifact.fresh => {
self.sender.send(CargoMessage::CompilerArtifact(artifact)).unwrap() self.sender.send(CargoMessage::CompilerArtifact(artifact)).unwrap();
} }
cargo_metadata::Message::CompilerMessage(msg) => { cargo_metadata::Message::CompilerMessage(msg) => {
self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap() self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap();
} }
_ => (), _ => (),
}, },
JsonMessage::Rustc(message) => { JsonMessage::Rustc(message) => {
self.sender.send(CargoMessage::Diagnostic(message)).unwrap() self.sender.send(CargoMessage::Diagnostic(message)).unwrap();
} }
} }
} }
} }
Ok(read_at_least_one_message) read_at_least_one_message
} }
} }

View file

@ -1119,7 +1119,7 @@ impl DefWithBody {
if let ast::Expr::RecordExpr(record_expr) = if let ast::Expr::RecordExpr(record_expr) =
&source_ptr.value.to_node(&root) &source_ptr.value.to_node(&root)
{ {
if let Some(_) = record_expr.record_expr_field_list() { if record_expr.record_expr_field_list().is_some() {
acc.push( acc.push(
MissingFields { MissingFields {
file: source_ptr.file_id, file: source_ptr.file_id,
@ -1143,7 +1143,7 @@ impl DefWithBody {
if let Some(expr) = source_ptr.value.as_ref().left() { if let Some(expr) = source_ptr.value.as_ref().left() {
let root = source_ptr.file_syntax(db.upcast()); let root = source_ptr.file_syntax(db.upcast());
if let ast::Pat::RecordPat(record_pat) = expr.to_node(&root) { if let ast::Pat::RecordPat(record_pat) = expr.to_node(&root) {
if let Some(_) = record_pat.record_pat_field_list() { if record_pat.record_pat_field_list().is_some() {
acc.push( acc.push(
MissingFields { MissingFields {
file: source_ptr.file_id, file: source_ptr.file_id,
@ -2119,10 +2119,9 @@ impl Impl {
}; };
let fp = TyFingerprint::for_inherent_impl(&ty); let fp = TyFingerprint::for_inherent_impl(&ty);
let fp = if let Some(fp) = fp { let fp = match fp {
fp Some(fp) => fp,
} else { None => return Vec::new(),
return Vec::new();
}; };
let mut all = Vec::new(); let mut all = Vec::new();

View file

@ -474,10 +474,9 @@ impl ExprCollector<'_> {
} }
ast::Expr::PrefixExpr(e) => { ast::Expr::PrefixExpr(e) => {
let expr = self.collect_expr_opt(e.expr()); let expr = self.collect_expr_opt(e.expr());
if let Some(op) = e.op_kind() { match e.op_kind() {
self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr) Some(op) => self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr),
} else { None => self.alloc_expr(Expr::Missing, syntax_ptr),
self.alloc_expr(Expr::Missing, syntax_ptr)
} }
} }
ast::Expr::ClosureExpr(e) => { ast::Expr::ClosureExpr(e) => {
@ -624,10 +623,9 @@ impl ExprCollector<'_> {
} }
fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId { fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
if let Some(expr) = expr { match expr {
self.collect_expr(expr) Some(expr) => self.collect_expr(expr),
} else { None => self.missing_expr(),
self.missing_expr()
} }
} }
@ -724,10 +722,9 @@ impl ExprCollector<'_> {
} }
fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId { fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
if let Some(block) = expr { match expr {
self.collect_block(block) Some(block) => self.collect_block(block),
} else { None => self.missing_expr(),
self.missing_expr()
} }
} }
@ -890,10 +887,9 @@ impl ExprCollector<'_> {
} }
fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId { fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
if let Some(pat) = pat { match pat {
self.collect_pat(pat) Some(pat) => self.collect_pat(pat),
} else { None => self.missing_pat(),
self.missing_pat()
} }
} }

View file

@ -209,10 +209,9 @@ fn find_path_inner(
) { ) {
path.push_segment(name); path.push_segment(name);
let new_path = if let Some(best_path) = best_path { let new_path = match best_path {
select_best_path(best_path, path, prefer_no_std) Some(best_path) => select_best_path(best_path, path, prefer_no_std),
} else { None => path,
path
}; };
best_path_len = new_path.len(); best_path_len = new_path.len();
best_path = Some(new_path); best_path = Some(new_path);
@ -243,10 +242,9 @@ fn find_path_inner(
}); });
for path in extern_paths { for path in extern_paths {
let new_path = if let Some(best_path) = best_path { let new_path = match best_path {
select_best_path(best_path, path, prefer_no_std) Some(best_path) => select_best_path(best_path, path, prefer_no_std),
} else { None => path,
path
}; };
best_path = Some(new_path); best_path = Some(new_path);
} }
@ -261,12 +259,11 @@ fn find_path_inner(
} }
} }
if let Some(prefix) = prefixed.map(PrefixKind::prefix) { match prefixed.map(PrefixKind::prefix) {
best_path.or_else(|| { Some(prefix) => best_path.or_else(|| {
scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name])) scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
}) }),
} else { None => best_path,
best_path
} }
} }
@ -346,15 +343,13 @@ fn find_local_import_locations(
if let Some((name, vis)) = data.scope.name_of(item) { if let Some((name, vis)) = data.scope.name_of(item) {
if vis.is_visible_from(db, from) { if vis.is_visible_from(db, from) {
let is_private = if let Visibility::Module(private_to) = vis { let is_private = match vis {
private_to.local_id == module.local_id Visibility::Module(private_to) => private_to.local_id == module.local_id,
} else { Visibility::Public => false,
false
}; };
let is_original_def = if let Some(module_def_id) = item.as_module_def_id() { let is_original_def = match item.as_module_def_id() {
data.scope.declarations().any(|it| it == module_def_id) Some(module_def_id) => data.scope.declarations().any(|it| it == module_def_id),
} else { None => false,
false
}; };
// Ignore private imports. these could be used if we are // Ignore private imports. these could be used if we are

View file

@ -475,10 +475,9 @@ macro_rules! mod_items {
} }
fn id_from_mod_item(mod_item: ModItem) -> Option<FileItemTreeId<Self>> { fn id_from_mod_item(mod_item: ModItem) -> Option<FileItemTreeId<Self>> {
if let ModItem::$typ(id) = mod_item { match mod_item {
Some(id) ModItem::$typ(id) => Some(id),
} else { _ => None,
None
} }
} }

View file

@ -400,13 +400,10 @@ impl DefMap {
}; };
let from_scope_or_builtin = match shadow { let from_scope_or_builtin = match shadow {
BuiltinShadowMode::Module => from_scope.or(from_builtin), BuiltinShadowMode::Module => from_scope.or(from_builtin),
BuiltinShadowMode::Other => { BuiltinShadowMode::Other => match from_scope.take_types() {
if let Some(ModuleDefId::ModuleId(_)) = from_scope.take_types() { Some(ModuleDefId::ModuleId(_)) => from_builtin.or(from_scope),
from_builtin.or(from_scope) Some(_) | None => from_scope.or(from_builtin),
} else { },
from_scope.or(from_builtin)
}
}
}; };
let from_extern_prelude = self let from_extern_prelude = self
.extern_prelude .extern_prelude

View file

@ -18,10 +18,9 @@ pub(crate) fn convert_path(
path: ast::Path, path: ast::Path,
hygiene: &Hygiene, hygiene: &Hygiene,
) -> Option<ModPath> { ) -> Option<ModPath> {
let prefix = if let Some(qual) = path.qualifier() { let prefix = match path.qualifier() {
Some(convert_path(db, prefix, qual, hygiene)?) Some(qual) => Some(convert_path(db, prefix, qual, hygiene)?),
} else { None => prefix,
prefix
}; };
let segment = path.segment()?; let segment = path.segment()?;

View file

@ -214,10 +214,9 @@ impl TypeRef {
} }
pub(crate) fn from_ast_opt(ctx: &LowerCtx, node: Option<ast::Type>) -> Self { pub(crate) fn from_ast_opt(ctx: &LowerCtx, node: Option<ast::Type>) -> Self {
if let Some(node) = node { match node {
TypeRef::from_ast(ctx, node) Some(node) => TypeRef::from_ast(ctx, node),
} else { None => TypeRef::Error,
TypeRef::Error
} }
} }

View file

@ -48,10 +48,9 @@ impl Name {
/// Resolve a name from the text of token. /// Resolve a name from the text of token.
fn resolve(raw_text: &str) -> Name { fn resolve(raw_text: &str) -> Name {
if let Some(text) = raw_text.strip_prefix("r#") { match raw_text.strip_prefix("r#") {
Name::new_text(SmolStr::new(text)) Some(text) => Name::new_text(SmolStr::new(text)),
} else { None => Name::new_text(raw_text.into()),
Name::new_text(raw_text.into())
} }
} }

View file

@ -109,10 +109,9 @@ pub(crate) fn deref(
ty: InEnvironment<&Canonical<Ty>>, ty: InEnvironment<&Canonical<Ty>>,
) -> Option<Canonical<Ty>> { ) -> Option<Canonical<Ty>> {
let _p = profile::span("deref"); let _p = profile::span("deref");
if let Some(derefed) = builtin_deref(&ty.goal.value) { match builtin_deref(&ty.goal.value) {
Some(Canonical { value: derefed, binders: ty.goal.binders.clone() }) Some(derefed) => Some(Canonical { value: derefed, binders: ty.goal.binders.clone() }),
} else { None => deref_by_trait(db, krate, ty),
deref_by_trait(db, krate, ty)
} }
} }

View file

@ -104,10 +104,9 @@ impl TyExt for Ty {
} }
fn as_fn_def(&self, db: &dyn HirDatabase) -> Option<FunctionId> { fn as_fn_def(&self, db: &dyn HirDatabase) -> Option<FunctionId> {
if let Some(CallableDefId::FunctionId(func)) = self.callable_def(db) { match self.callable_def(db) {
Some(func) Some(CallableDefId::FunctionId(func)) => Some(func),
} else { Some(CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_)) | None => None,
None
} }
} }
fn as_reference(&self) -> Option<(&Ty, Lifetime, Mutability)> { fn as_reference(&self) -> Option<(&Ty, Lifetime, Mutability)> {

View file

@ -105,10 +105,9 @@ impl IntRange {
#[inline] #[inline]
fn from_range(lo: u128, hi: u128, scalar_ty: Scalar) -> IntRange { fn from_range(lo: u128, hi: u128, scalar_ty: Scalar) -> IntRange {
if let Scalar::Bool = scalar_ty { match scalar_ty {
IntRange { range: lo..=hi } Scalar::Bool => IntRange { range: lo..=hi },
} else { _ => unimplemented!(),
unimplemented!()
} }
} }

View file

@ -167,10 +167,9 @@ impl<'a> HirFormatter<'a> {
} }
pub fn should_truncate(&self) -> bool { pub fn should_truncate(&self) -> bool {
if let Some(max_size) = self.max_size { match self.max_size {
self.curr_size >= max_size Some(max_size) => self.curr_size >= max_size,
} else { None => false,
false
} }
} }

View file

@ -264,10 +264,9 @@ impl<'a> InferenceContext<'a> {
// collect explicitly written argument types // collect explicitly written argument types
for arg_type in arg_types.iter() { for arg_type in arg_types.iter() {
let arg_ty = if let Some(type_ref) = arg_type { let arg_ty = match arg_type {
self.make_ty(type_ref) Some(type_ref) => self.make_ty(type_ref),
} else { None => self.table.new_type_var(),
self.table.new_type_var()
}; };
sig_tys.push(arg_ty); sig_tys.push(arg_ty);
} }

View file

@ -204,10 +204,9 @@ impl<'a> InferenceContext<'a> {
} else { } else {
BindingMode::convert(*mode) BindingMode::convert(*mode)
}; };
let inner_ty = if let Some(subpat) = subpat { let inner_ty = match subpat {
self.infer_pat(*subpat, &expected, default_bm) Some(subpat) => self.infer_pat(*subpat, &expected, default_bm),
} else { None => expected,
expected
}; };
let inner_ty = self.insert_type_vars_shallow(inner_ty); let inner_ty = self.insert_type_vars_shallow(inner_ty);

View file

@ -324,10 +324,9 @@ impl<'a> InferenceTable<'a> {
/// Unify two types and register new trait goals that arise from that. /// Unify two types and register new trait goals that arise from that.
pub(crate) fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { pub(crate) fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
let result = if let Ok(r) = self.try_unify(ty1, ty2) { let result = match self.try_unify(ty1, ty2) {
r Ok(r) => r,
} else { Err(_) => return false,
return false;
}; };
self.register_infer_ok(result); self.register_infer_ok(result);
true true

View file

@ -369,10 +369,9 @@ impl<'a> TyLoweringContext<'a> {
Some((it, None)) => it, Some((it, None)) => it,
_ => return None, _ => return None,
}; };
if let TypeNs::GenericParam(param_id) = resolution { match resolution {
Some(param_id) TypeNs::GenericParam(param_id) => Some(param_id),
} else { _ => None,
None
} }
} }

View file

@ -82,10 +82,9 @@ impl TyFingerprint {
TyKind::Ref(_, _, ty) => return TyFingerprint::for_trait_impl(ty), TyKind::Ref(_, _, ty) => return TyFingerprint::for_trait_impl(ty),
TyKind::Tuple(_, subst) => { TyKind::Tuple(_, subst) => {
let first_ty = subst.interned().get(0).map(|arg| arg.assert_ty_ref(&Interner)); let first_ty = subst.interned().get(0).map(|arg| arg.assert_ty_ref(&Interner));
if let Some(ty) = first_ty { match first_ty {
return TyFingerprint::for_trait_impl(ty); Some(ty) => return TyFingerprint::for_trait_impl(ty),
} else { None => TyFingerprint::Unit,
TyFingerprint::Unit
} }
} }
TyKind::AssociatedType(_, _) TyKind::AssociatedType(_, _)

View file

@ -195,10 +195,9 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour
mismatch.expected.display_test(&db), mismatch.expected.display_test(&db),
mismatch.actual.display_test(&db) mismatch.actual.display_test(&db)
); );
if let Some(annotation) = mismatches.remove(&range) { match mismatches.remove(&range) {
assert_eq!(actual, annotation); Some(annotation) => assert_eq!(actual, annotation),
} else { None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual);
} }
} }
for (expr, mismatch) in inference_result.expr_type_mismatches() { for (expr, mismatch) in inference_result.expr_type_mismatches() {
@ -215,10 +214,9 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour
mismatch.expected.display_test(&db), mismatch.expected.display_test(&db),
mismatch.actual.display_test(&db) mismatch.actual.display_test(&db)
); );
if let Some(annotation) = mismatches.remove(&range) { match mismatches.remove(&range) {
assert_eq!(actual, annotation); Some(annotation) => assert_eq!(actual, annotation),
} else { None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual);
} }
} }
} }

View file

@ -292,10 +292,9 @@ impl TryToNav for hir::Impl {
fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> { fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
let src = self.source(db)?; let src = self.source(db)?;
let derive_attr = self.is_builtin_derive(db); let derive_attr = self.is_builtin_derive(db);
let frange = if let Some(item) = &derive_attr { let frange = match &derive_attr {
item.syntax().original_file_range(db) Some(item) => item.syntax().original_file_range(db),
} else { None => src.syntax().original_file_range(db),
src.syntax().original_file_range(db)
}; };
let focus_range = if derive_attr.is_some() { let focus_range = if derive_attr.is_some() {
None None

View file

@ -136,10 +136,9 @@ fn remove_newline(
} }
T!['}'] => { T!['}'] => {
// Removes: comma, newline (incl. surrounding whitespace) // Removes: comma, newline (incl. surrounding whitespace)
let space = if let Some(left) = prev.prev_sibling_or_token() { let space = match prev.prev_sibling_or_token() {
compute_ws(left.kind(), next.kind()) Some(left) => compute_ws(left.kind(), next.kind()),
} else { None => " ",
" "
}; };
edit.replace( edit.replace(
TextRange::new(prev.text_range().start(), token.text_range().end()), TextRange::new(prev.text_range().start(), token.text_range().end()),

View file

@ -156,7 +156,7 @@ fn rename_to_self(sema: &Semantics<RootDatabase>, local: hir::Local) -> RenameRe
_ => bail!("Cannot rename local to self outside of function"), _ => bail!("Cannot rename local to self outside of function"),
}; };
if let Some(_) = fn_def.self_param(sema.db) { if fn_def.self_param(sema.db).is_some() {
bail!("Method already has a self parameter"); bail!("Method already has a self parameter");
} }

View file

@ -103,10 +103,9 @@ impl StaticIndex<'_> {
for token in tokens { for token in tokens {
let range = token.text_range(); let range = token.text_range();
let node = token.parent().unwrap(); let node = token.parent().unwrap();
let def = if let Some(x) = get_definition(&sema, token.clone()) { let def = match get_definition(&sema, token.clone()) {
x Some(x) => x,
} else { None => continue,
continue;
}; };
let id = if let Some(x) = self.def_map.get(&def) { let id = if let Some(x) = self.def_map.get(&def) {
*x *x
@ -124,10 +123,9 @@ impl StaticIndex<'_> {
let token = self.tokens.get_mut(id).unwrap(); let token = self.tokens.get_mut(id).unwrap();
token.references.push(ReferenceData { token.references.push(ReferenceData {
range: FileRange { range, file_id }, range: FileRange { range, file_id },
is_definition: if let Some(x) = def.try_to_nav(self.db) { is_definition: match def.try_to_nav(self.db) {
x.file_id == file_id && x.focus_or_full_range() == range Some(x) => x.file_id == file_id && x.focus_or_full_range() == range,
} else { None => false,
false
}, },
}); });
result.tokens.push((range, id)); result.tokens.push((range, id));

View file

@ -330,7 +330,7 @@ fn traverse(
} }
} }
if let Some(_) = macro_highlighter.highlight(element_to_highlight.clone()) { if macro_highlighter.highlight(element_to_highlight.clone()).is_some() {
continue; continue;
} }

View file

@ -44,7 +44,7 @@ pub(crate) fn convert_while_to_loop(acc: &mut Assists, ctx: &AssistContext) -> O
let cond = while_expr.condition()?; let cond = while_expr.condition()?;
// Don't handle while let // Don't handle while let
if let Some(_) = cond.pat() { if cond.pat().is_some() {
return None; return None;
}; };

View file

@ -827,10 +827,9 @@ impl FunctionBody {
locals locals
.map(|local| (local, local.source(ctx.db()))) .map(|local| (local, local.source(ctx.db())))
.filter(|(_, src)| is_defined_outside_of_body(ctx, self, src)) .filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
.filter_map(|(local, src)| { .filter_map(|(local, src)| match src.value {
if let Either::Left(src) = src.value { Either::Left(src) => Some((local, src)),
Some((local, src)) Either::Right(_) => {
} else {
stdx::never!(false, "Local::is_self returned false, but source is SelfParam"); stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
None None
} }

View file

@ -76,10 +76,11 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option
None => to_extract.syntax().text_range(), None => to_extract.syntax().text_range(),
}; };
if let Anchor::WrapInBlock(_) = anchor { match anchor {
format_to!(buf, "{{ let {} = ", var_name); Anchor::Before(_) | Anchor::Replace(_) => {
} else { format_to!(buf, "let {} = ", var_name)
format_to!(buf, "let {} = ", var_name); }
Anchor::WrapInBlock(_) => format_to!(buf, "{{ let {} = ", var_name),
}; };
format_to!(buf, "{}", to_extract.syntax()); format_to!(buf, "{}", to_extract.syntax());

View file

@ -192,10 +192,9 @@ impl FunctionTemplate {
Some(cap) => { Some(cap) => {
let cursor = if self.should_focus_return_type { let cursor = if self.should_focus_return_type {
// Focus the return type if there is one // Focus the return type if there is one
if let Some(ref ret_type) = self.ret_type { match self.ret_type {
ret_type.syntax() Some(ref ret_type) => ret_type.syntax(),
} else { None => self.tail_expr.syntax(),
self.tail_expr.syntax()
} }
} else { } else {
self.tail_expr.syntax() self.tail_expr.syntax()
@ -428,10 +427,9 @@ fn fn_args(
arg_types.push(match fn_arg_type(ctx, target_module, &arg) { arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
Some(ty) => { Some(ty) => {
if !ty.is_empty() && ty.starts_with('&') { if !ty.is_empty() && ty.starts_with('&') {
if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) { match useless_type_special_case("", &ty[1..].to_owned()) {
new_ty Some((new_ty, _)) => new_ty,
} else { None => ty,
ty
} }
} else { } else {
ty ty
@ -523,11 +521,7 @@ fn fn_arg_type(
return None; return None;
} }
if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) { ty.display_source_code(ctx.db(), target_module.into()).ok()
Some(rendered)
} else {
None
}
} }
/// Returns the position inside the current mod or file /// Returns the position inside the current mod or file
@ -560,20 +554,14 @@ fn next_space_for_fn_in_module(
) -> Option<(FileId, GeneratedFunctionTarget)> { ) -> Option<(FileId, GeneratedFunctionTarget)> {
let file = module_source.file_id.original_file(db); let file = module_source.file_id.original_file(db);
let assist_item = match &module_source.value { let assist_item = match &module_source.value {
hir::ModuleSource::SourceFile(it) => { hir::ModuleSource::SourceFile(it) => match it.items().last() {
if let Some(last_item) = it.items().last() { Some(last_item) => GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()),
GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) None => GeneratedFunctionTarget::BehindItem(it.syntax().clone()),
} else { },
GeneratedFunctionTarget::BehindItem(it.syntax().clone()) hir::ModuleSource::Module(it) => match it.item_list().and_then(|it| it.items().last()) {
} Some(last_item) => GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()),
} None => GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone()),
hir::ModuleSource::Module(it) => { },
if let Some(last_item) = it.item_list().and_then(|it| it.items().last()) {
GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
} else {
GeneratedFunctionTarget::InEmptyItemList(it.item_list()?.syntax().clone())
}
}
hir::ModuleSource::BlockExpr(it) => { hir::ModuleSource::BlockExpr(it) => {
if let Some(last_item) = if let Some(last_item) =
it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last() it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()

View file

@ -141,10 +141,9 @@ pub(crate) fn inline_into_callers(acc: &mut Assists, ctx: &AssistContext) -> Opt
for (file_id, refs) in usages.into_iter() { for (file_id, refs) in usages.into_iter() {
inline_refs_for_file(file_id, refs); inline_refs_for_file(file_id, refs);
} }
if let Some(refs) = current_file_usage { match current_file_usage {
inline_refs_for_file(def_file, refs); Some(refs) => inline_refs_for_file(def_file, refs),
} else { None => builder.edit_file(def_file),
builder.edit_file(def_file);
} }
if remove_def { if remove_def {
builder.delete(ast_func.syntax().text_range()); builder.delete(ast_func.syntax().text_range());

View file

@ -127,12 +127,9 @@ impl<'a> AssignmentsCollector<'a> {
} }
} }
fn collect_block(&mut self, block: &ast::BlockExpr) -> Option<()> { fn collect_block(&mut self, block: &ast::BlockExpr) -> Option<()> {
let last_expr = block.tail_expr().or_else(|| { let last_expr = block.tail_expr().or_else(|| match block.statements().last()? {
if let ast::Stmt::ExprStmt(stmt) = block.statements().last()? { ast::Stmt::ExprStmt(stmt) => stmt.expr(),
stmt.expr() ast::Stmt::Item(_) | ast::Stmt::LetStmt(_) => None,
} else {
None
}
})?; })?;
if let ast::Expr::BinExpr(expr) = last_expr { if let ast::Expr::BinExpr(expr) = last_expr {

View file

@ -181,10 +181,9 @@ fn find_trait_method(
fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> { fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
let item_module_def = item.as_module_def()?; let item_module_def = item.as_module_def()?;
if let hir::ModuleDef::Trait(trait_) = item_module_def { match item_module_def {
Some(trait_) hir::ModuleDef::Trait(trait_) => Some(trait_),
} else { _ => item_module_def.as_assoc_item(db)?.containing_trait(db),
item_module_def.as_assoc_item(db)?.containing_trait(db)
} }
} }

View file

@ -250,13 +250,10 @@ fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
}; };
Some(make::expr_method_call(receiver, make::name_ref(method), arg_list)) Some(make::expr_method_call(receiver, make::name_ref(method), arg_list))
} }
ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => { ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => match pe.expr()? {
if let ast::Expr::ParenExpr(parexpr) = pe.expr()? { ast::Expr::ParenExpr(parexpr) => parexpr.expr(),
parexpr.expr() _ => pe.expr(),
} else { },
pe.expr()
}
}
ast::Expr::Literal(lit) => match lit.kind() { ast::Expr::Literal(lit) => match lit.kind() {
ast::LiteralKind::Bool(b) => match b { ast::LiteralKind::Bool(b) => match b {
true => Some(ast::Expr::Literal(make::expr_literal("false"))), true => Some(ast::Expr::Literal(make::expr_literal("false"))),
@ -276,13 +273,10 @@ pub(crate) fn does_pat_match_variant(pat: &ast::Pat, var: &ast::Pat) -> bool {
let first_node_text = |pat: &ast::Pat| pat.syntax().first_child().map(|node| node.text()); let first_node_text = |pat: &ast::Pat| pat.syntax().first_child().map(|node| node.text());
let pat_head = match pat { let pat_head = match pat {
ast::Pat::IdentPat(bind_pat) => { ast::Pat::IdentPat(bind_pat) => match bind_pat.pat() {
if let Some(p) = bind_pat.pat() { Some(p) => first_node_text(&p),
first_node_text(&p) None => return pat.syntax().text() == var.syntax().text(),
} else { },
return pat.syntax().text() == var.syntax().text();
}
}
pat => first_node_text(pat), pat => first_node_text(pat),
}; };

View file

@ -144,10 +144,9 @@ fn is_valid_name(name: &str) -> bool {
fn is_useless_method(method: &ast::MethodCallExpr) -> bool { fn is_useless_method(method: &ast::MethodCallExpr) -> bool {
let ident = method.name_ref().and_then(|it| it.ident_token()); let ident = method.name_ref().and_then(|it| it.ident_token());
if let Some(ident) = ident { match ident {
USELESS_METHODS.contains(&ident.text()) Some(ident) => USELESS_METHODS.contains(&ident.text()),
} else { None => false,
false
} }
} }

View file

@ -509,10 +509,9 @@ impl<'a> CompletionContext<'a> {
.and_then(|pat| self.sema.type_of_pat(&pat)) .and_then(|pat| self.sema.type_of_pat(&pat))
.or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it))) .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
.map(TypeInfo::original); .map(TypeInfo::original);
let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() { let name = match it.pat() {
ident.name().map(NameOrNameRef::Name) Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
} else { Some(_) | None => None,
None
}; };
(ty, name) (ty, name)

View file

@ -74,10 +74,9 @@ impl<'a> FunctionRender<'a> {
fn render(self, import_to_add: Option<ImportEdit>) -> CompletionItem { fn render(self, import_to_add: Option<ImportEdit>) -> CompletionItem {
let params = self.params(); let params = self.params();
let call = if let Some(receiver) = &self.receiver { let call = match &self.receiver {
format!("{}.{}", receiver, &self.name) Some(receiver) => format!("{}.{}", receiver, &self.name),
} else { None => self.name.clone(),
self.name.clone()
}; };
let mut item = let mut item =
CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), call.clone()); CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), call.clone());

View file

@ -63,10 +63,9 @@ fn build_completion(
.set_documentation(ctx.docs(def)) .set_documentation(ctx.docs(def))
.set_deprecated(ctx.is_deprecated(def)) .set_deprecated(ctx.is_deprecated(def))
.detail(&pat); .detail(&pat);
if let Some(snippet_cap) = ctx.snippet_cap() { match ctx.snippet_cap() {
item.insert_snippet(snippet_cap, pat); Some(snippet_cap) => item.insert_snippet(snippet_cap, pat),
} else { None => item.insert_text(pat),
item.insert_text(pat);
}; };
item.build() item.build()
} }

View file

@ -38,10 +38,9 @@ fn build_completion(
.set_documentation(ctx.docs(def)) .set_documentation(ctx.docs(def))
.set_deprecated(ctx.is_deprecated(def)) .set_deprecated(ctx.is_deprecated(def))
.detail(&literal); .detail(&literal);
if let Some(snippet_cap) = ctx.snippet_cap() { match ctx.snippet_cap() {
item.insert_snippet(snippet_cap, literal); Some(snippet_cap) => item.insert_snippet(snippet_cap, literal),
} else { None => item.insert_text(literal),
item.insert_text(literal);
}; };
item.build() item.build()
} }

View file

@ -318,7 +318,7 @@ pub fn source_edit_from_references(
} }
fn source_edit_from_name(edit: &mut TextEditBuilder, name: &ast::Name, new_name: &str) -> bool { fn source_edit_from_name(edit: &mut TextEditBuilder, name: &ast::Name, new_name: &str) -> bool {
if let Some(_) = ast::RecordPatField::for_field_name(name) { if ast::RecordPatField::for_field_name(name).is_some() {
if let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) { if let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
cov_mark::hit!(rename_record_pat_field_name_split); cov_mark::hit!(rename_record_pat_field_name_split);
// Foo { ref mut field } -> Foo { new_name: ref mut field } // Foo { ref mut field } -> Foo { new_name: ref mut field }

View file

@ -47,10 +47,9 @@ impl ResolvedRule {
) -> Result<ResolvedRule, SsrError> { ) -> Result<ResolvedRule, SsrError> {
let resolver = let resolver =
Resolver { resolution_scope, placeholders_by_stand_in: rule.placeholders_by_stand_in }; Resolver { resolution_scope, placeholders_by_stand_in: rule.placeholders_by_stand_in };
let resolved_template = if let Some(template) = rule.template { let resolved_template = match rule.template {
Some(resolver.resolve_pattern_tree(template)?) Some(template) => Some(resolver.resolve_pattern_tree(template)?),
} else { None => None,
None
}; };
Ok(ResolvedRule { Ok(ResolvedRule {
pattern: resolver.resolve_pattern_tree(rule.pattern)?, pattern: resolver.resolve_pattern_tree(rule.pattern)?,

View file

@ -67,11 +67,11 @@ pub(crate) mod entry_points {
} }
pub(crate) fn stmt(p: &mut Parser) { pub(crate) fn stmt(p: &mut Parser) {
expressions::stmt(p, expressions::StmtWithSemi::No, true) expressions::stmt(p, expressions::StmtWithSemi::No, true);
} }
pub(crate) fn stmt_optional_semi(p: &mut Parser) { pub(crate) fn stmt_optional_semi(p: &mut Parser) {
expressions::stmt(p, expressions::StmtWithSemi::Optional, false) expressions::stmt(p, expressions::StmtWithSemi::Optional, false);
} }
pub(crate) fn visibility(p: &mut Parser) { pub(crate) fn visibility(p: &mut Parser) {
@ -84,7 +84,7 @@ pub(crate) mod entry_points {
} }
pub(crate) fn item(p: &mut Parser) { pub(crate) fn item(p: &mut Parser) {
items::item_or_macro(p, true) items::item_or_macro(p, true);
} }
pub(crate) fn macro_items(p: &mut Parser) { pub(crate) fn macro_items(p: &mut Parser) {
@ -109,7 +109,7 @@ pub(crate) mod entry_points {
} }
pub(crate) fn attr(p: &mut Parser) { pub(crate) fn attr(p: &mut Parser) {
attributes::outer_attrs(p) attributes::outer_attrs(p);
} }
} }
@ -128,8 +128,7 @@ pub(crate) fn reparser(
EXTERN_ITEM_LIST => items::extern_item_list, EXTERN_ITEM_LIST => items::extern_item_list,
TOKEN_TREE if first_child? == T!['{'] => items::token_tree, TOKEN_TREE if first_child? == T!['{'] => items::token_tree,
ASSOC_ITEM_LIST => match parent? { ASSOC_ITEM_LIST => match parent? {
IMPL => items::assoc_item_list, IMPL | TRAIT => items::assoc_item_list,
TRAIT => items::assoc_item_list,
_ => return None, _ => return None,
}, },
ITEM_LIST => items::item_list, ITEM_LIST => items::item_list,
@ -246,7 +245,7 @@ fn name_r(p: &mut Parser, recovery: TokenSet) {
} }
fn name(p: &mut Parser) { fn name(p: &mut Parser) {
name_r(p, TokenSet::EMPTY) name_r(p, TokenSet::EMPTY);
} }
fn name_ref(p: &mut Parser) { fn name_ref(p: &mut Parser) {

View file

@ -2,13 +2,13 @@ use super::*;
pub(super) fn inner_attrs(p: &mut Parser) { pub(super) fn inner_attrs(p: &mut Parser) {
while p.at(T![#]) && p.nth(1) == T![!] { while p.at(T![#]) && p.nth(1) == T![!] {
attr(p, true) attr(p, true);
} }
} }
pub(super) fn outer_attrs(p: &mut Parser) { pub(super) fn outer_attrs(p: &mut Parser) {
while p.at(T![#]) { while p.at(T![#]) {
attr(p, false) attr(p, false);
} }
} }

View file

@ -139,7 +139,7 @@ pub(super) fn expr_block_contents(p: &mut Parser) {
continue; continue;
} }
stmt(p, StmtWithSemi::Yes, false) stmt(p, StmtWithSemi::Yes, false);
} }
} }
@ -311,7 +311,7 @@ fn lhs(p: &mut Parser, r: Restrictions) -> Option<(CompletedMarker, BlockLike)>
_ => { _ => {
// test full_range_expr // test full_range_expr
// fn foo() { xs[..]; } // fn foo() { xs[..]; }
for &op in [T![..=], T![..]].iter() { for op in [T![..=], T![..]] {
if p.at(op) { if p.at(op) {
m = p.start(); m = p.start();
p.bump(op); p.bump(op);
@ -468,12 +468,12 @@ fn field_expr(p: &mut Parser, lhs: CompletedMarker) -> CompletedMarker {
let m = lhs.precede(p); let m = lhs.precede(p);
p.bump(T![.]); p.bump(T![.]);
if p.at(IDENT) || p.at(INT_NUMBER) { if p.at(IDENT) || p.at(INT_NUMBER) {
name_ref_or_index(p) name_ref_or_index(p);
} else if p.at(FLOAT_NUMBER) { } else if p.at(FLOAT_NUMBER) {
// FIXME: How to recover and instead parse INT + T![.]? // FIXME: How to recover and instead parse INT + T![.]?
p.bump_any(); p.bump_any();
} else { } else {
p.error("expected field name or number") p.error("expected field name or number");
} }
m.complete(p, FIELD_EXPR) m.complete(p, FIELD_EXPR)
} }

View file

@ -374,7 +374,7 @@ fn match_expr(p: &mut Parser) -> CompletedMarker {
if p.at(T!['{']) { if p.at(T!['{']) {
match_arm_list(p); match_arm_list(p);
} else { } else {
p.error("expected `{`") p.error("expected `{`");
} }
m.complete(p, MATCH_EXPR) m.complete(p, MATCH_EXPR)
} }
@ -602,7 +602,7 @@ fn try_block_expr(p: &mut Parser, m: Option<Marker>) -> CompletedMarker {
if p.at(T!['{']) { if p.at(T!['{']) {
stmt_list(p); stmt_list(p);
} else { } else {
p.error("expected a block") p.error("expected a block");
} }
m.complete(p, BLOCK_EXPR) m.complete(p, BLOCK_EXPR)
} }
@ -639,7 +639,7 @@ fn meta_var_expr(p: &mut Parser) -> CompletedMarker {
} }
_ => { _ => {
while !p.at(R_DOLLAR) { while !p.at(R_DOLLAR) {
p.bump_any() p.bump_any();
} }
p.bump(R_DOLLAR); p.bump(R_DOLLAR);
m.complete(p, ERROR) m.complete(p, ERROR)

View file

@ -34,7 +34,7 @@ fn generic_param(p: &mut Parser) {
T![const] => const_param(p, m), T![const] => const_param(p, m),
_ => { _ => {
m.abandon(p); m.abandon(p);
p.err_and_bump("expected type parameter") p.err_and_bump("expected type parameter");
} }
} }
} }
@ -62,7 +62,7 @@ fn type_param(p: &mut Parser, m: Marker) {
// test type_param_default // test type_param_default
// struct S<T = i32>; // struct S<T = i32>;
p.bump(T![=]); p.bump(T![=]);
types::type_(p) types::type_(p);
} }
m.complete(p, TYPE_PARAM); m.complete(p, TYPE_PARAM);
} }

View file

@ -20,7 +20,7 @@ use super::*;
pub(super) fn mod_contents(p: &mut Parser, stop_on_r_curly: bool) { pub(super) fn mod_contents(p: &mut Parser, stop_on_r_curly: bool) {
attributes::inner_attrs(p); attributes::inner_attrs(p);
while !p.at(EOF) && !(p.at(T!['}']) && stop_on_r_curly) { while !p.at(EOF) && !(p.at(T!['}']) && stop_on_r_curly) {
item_or_macro(p, stop_on_r_curly) item_or_macro(p, stop_on_r_curly);
} }
} }
@ -165,7 +165,7 @@ pub(super) fn opt_item(p: &mut Parser, m: Marker) -> Result<(), Marker> {
p.bump_remap(T![default]); p.bump_remap(T![default]);
p.bump(T![async]); p.bump(T![async]);
if is_unsafe { if is_unsafe {
p.bump(T![unsafe]) p.bump(T![unsafe]);
} }
has_mods = true; has_mods = true;
} }
@ -404,7 +404,7 @@ fn fn_(p: &mut Parser, m: Marker) {
// trait T { fn foo(); } // trait T { fn foo(); }
p.bump(T![;]); p.bump(T![;]);
} else { } else {
expressions::block_expr(p) expressions::block_expr(p);
} }
m.complete(p, FN); m.complete(p, FN);
} }

View file

@ -58,7 +58,7 @@ pub(super) fn enum_(p: &mut Parser, m: Marker) {
if p.at(T!['{']) { if p.at(T!['{']) {
variant_list(p); variant_list(p);
} else { } else {
p.error("expected `{`") p.error("expected `{`");
} }
m.complete(p, ENUM); m.complete(p, ENUM);
} }

View file

@ -4,12 +4,12 @@ use super::*;
// const C: u32 = 92; // const C: u32 = 92;
pub(super) fn konst(p: &mut Parser, m: Marker) { pub(super) fn konst(p: &mut Parser, m: Marker) {
p.bump(T![const]); p.bump(T![const]);
const_or_static(p, m, true) const_or_static(p, m, true);
} }
pub(super) fn static_(p: &mut Parser, m: Marker) { pub(super) fn static_(p: &mut Parser, m: Marker) {
p.bump(T![static]); p.bump(T![static]);
const_or_static(p, m, false) const_or_static(p, m, false);
} }
fn const_or_static(p: &mut Parser, m: Marker, is_const: bool) { fn const_or_static(p: &mut Parser, m: Marker, is_const: bool) {
@ -27,7 +27,7 @@ fn const_or_static(p: &mut Parser, m: Marker, is_const: bool) {
if p.at(T![:]) { if p.at(T![:]) {
types::ascription(p); types::ascription(p);
} else { } else {
p.error("missing type for `const` or `static`") p.error("missing type for `const` or `static`");
} }
if p.eat(T![=]) { if p.eat(T![=]) {
expressions::expr(p); expressions::expr(p);

View file

@ -6,21 +6,21 @@ use super::*;
// fn c(x: i32, ) {} // fn c(x: i32, ) {}
// fn d(x: i32, y: ()) {} // fn d(x: i32, y: ()) {}
pub(super) fn param_list_fn_def(p: &mut Parser) { pub(super) fn param_list_fn_def(p: &mut Parser) {
list_(p, Flavor::FnDef) list_(p, Flavor::FnDef);
} }
// test param_list_opt_patterns // test param_list_opt_patterns
// fn foo<F: FnMut(&mut Foo<'a>)>(){} // fn foo<F: FnMut(&mut Foo<'a>)>(){}
pub(super) fn param_list_fn_trait(p: &mut Parser) { pub(super) fn param_list_fn_trait(p: &mut Parser) {
list_(p, Flavor::FnTrait) list_(p, Flavor::FnTrait);
} }
pub(super) fn param_list_fn_ptr(p: &mut Parser) { pub(super) fn param_list_fn_ptr(p: &mut Parser) {
list_(p, Flavor::FnPointer) list_(p, Flavor::FnPointer);
} }
pub(super) fn param_list_closure(p: &mut Parser) { pub(super) fn param_list_closure(p: &mut Parser) {
list_(p, Flavor::Closure) list_(p, Flavor::Closure);
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@ -104,13 +104,13 @@ fn param(p: &mut Parser, m: Marker, flavor: Flavor) -> Variadic {
Flavor::FnDef => { Flavor::FnDef => {
patterns::pattern(p); patterns::pattern(p);
if variadic_param(p) { if variadic_param(p) {
res = Variadic(true) res = Variadic(true);
} else if p.at(T![:]) { } else if p.at(T![:]) {
types::ascription(p) types::ascription(p);
} else { } else {
// test_err missing_fn_param_type // test_err missing_fn_param_type
// fn f(x y: i32, z, t: i32) {} // fn f(x y: i32, z, t: i32) {}
p.error("missing type for function parameter") p.error("missing type for function parameter");
} }
} }
// test value_parameters_no_patterns // test value_parameters_no_patterns
@ -128,11 +128,11 @@ fn param(p: &mut Parser, m: Marker, flavor: Flavor) -> Variadic {
if (p.at(IDENT) || p.at(UNDERSCORE)) && p.nth(1) == T![:] && !p.nth_at(1, T![::]) { if (p.at(IDENT) || p.at(UNDERSCORE)) && p.nth(1) == T![:] && !p.nth_at(1, T![::]) {
patterns::pattern_single(p); patterns::pattern_single(p);
if variadic_param(p) { if variadic_param(p) {
res = Variadic(true) res = Variadic(true);
} else if p.at(T![:]) { } else if p.at(T![:]) {
types::ascription(p) types::ascription(p);
} else { } else {
p.error("missing type for function parameter") p.error("missing type for function parameter");
} }
} else { } else {
types::type_(p); types::type_(p);

View file

@ -16,15 +16,15 @@ pub(super) fn is_use_path_start(p: &Parser) -> bool {
} }
pub(super) fn use_path(p: &mut Parser) { pub(super) fn use_path(p: &mut Parser) {
path(p, Mode::Use) path(p, Mode::Use);
} }
pub(crate) fn type_path(p: &mut Parser) { pub(crate) fn type_path(p: &mut Parser) {
path(p, Mode::Type) path(p, Mode::Type);
} }
pub(super) fn expr_path(p: &mut Parser) { pub(super) fn expr_path(p: &mut Parser) {
path(p, Mode::Expr) path(p, Mode::Expr);
} }
pub(crate) fn type_path_for_qualifier(p: &mut Parser, qual: CompletedMarker) -> CompletedMarker { pub(crate) fn type_path_for_qualifier(p: &mut Parser, qual: CompletedMarker) -> CompletedMarker {
@ -117,7 +117,7 @@ fn opt_path_type_args(p: &mut Parser, mode: Mode) {
params::param_list_fn_trait(p); params::param_list_fn_trait(p);
opt_ret_type(p); opt_ret_type(p);
} else { } else {
generic_args::opt_generic_arg_list(p, false) generic_args::opt_generic_arg_list(p, false);
} }
} }
Mode::Expr => generic_args::opt_generic_arg_list(p, true), Mode::Expr => generic_args::opt_generic_arg_list(p, true),

View file

@ -19,7 +19,7 @@ pub(crate) fn pattern(p: &mut Parser) {
/// Parses a pattern list separated by pipes `|`. /// Parses a pattern list separated by pipes `|`.
pub(super) fn pattern_top(p: &mut Parser) { pub(super) fn pattern_top(p: &mut Parser) {
pattern_top_r(p, PAT_RECOVERY_SET) pattern_top_r(p, PAT_RECOVERY_SET);
} }
pub(crate) fn pattern_single(p: &mut Parser) { pub(crate) fn pattern_single(p: &mut Parser) {
@ -78,7 +78,7 @@ fn pattern_single_r(p: &mut Parser, recovery_set: TokenSet) {
// FIXME: support half_open_range_patterns (`..=2`), // FIXME: support half_open_range_patterns (`..=2`),
// exclusive_range_pattern (`..5`) with missing lhs // exclusive_range_pattern (`..5`) with missing lhs
for &range_op in [T![...], T![..=], T![..]].iter() { for range_op in [T![...], T![..=], T![..]] {
if p.at(range_op) { if p.at(range_op) {
let m = lhs.precede(p); let m = lhs.precede(p);
p.bump(range_op); p.bump(range_op);

View file

@ -57,7 +57,7 @@ fn type_with_bounds_cond(p: &mut Parser, allow_bounds: bool) {
pub(super) fn ascription(p: &mut Parser) { pub(super) fn ascription(p: &mut Parser) {
assert!(p.at(T![:])); assert!(p.at(T![:]));
p.bump(T![:]); p.bump(T![:]);
type_(p) type_(p);
} }
fn paren_or_tuple_type(p: &mut Parser) { fn paren_or_tuple_type(p: &mut Parser) {
@ -204,7 +204,7 @@ fn fn_ptr_type(p: &mut Parser) {
if p.at(T!['(']) { if p.at(T!['(']) {
params::param_list_fn_ptr(p); params::param_list_fn_ptr(p);
} else { } else {
p.error("expected parameters") p.error("expected parameters");
} }
// test fn_pointer_type_with_ret // test fn_pointer_type_with_ret
// type F = fn() -> (); // type F = fn() -> ();
@ -274,7 +274,7 @@ fn dyn_trait_type(p: &mut Parser) {
// type C = self::Foo; // type C = self::Foo;
// type D = super::Foo; // type D = super::Foo;
pub(super) fn path_type(p: &mut Parser) { pub(super) fn path_type(p: &mut Parser) {
path_type_(p, true) path_type_(p, true);
} }
// test macro_call_type // test macro_call_type

View file

@ -177,7 +177,7 @@ impl<'t> Parser<'t> {
if kind == EOF { if kind == EOF {
return; return;
} }
self.do_bump(kind, 1) self.do_bump(kind, 1);
} }
/// Advances the parser by one token, remapping its kind. /// Advances the parser by one token, remapping its kind.
@ -200,7 +200,7 @@ impl<'t> Parser<'t> {
/// does. /// does.
pub(crate) fn error<T: Into<String>>(&mut self, message: T) { pub(crate) fn error<T: Into<String>>(&mut self, message: T) {
let msg = ParseError(Box::new(message.into())); let msg = ParseError(Box::new(message.into()));
self.push_event(Event::Error { msg }) self.push_event(Event::Error { msg });
} }
/// Consume the next token if it is `kind` or emit an error /// Consume the next token if it is `kind` or emit an error
@ -258,7 +258,7 @@ impl<'t> Parser<'t> {
} }
fn push_event(&mut self, event: Event) { fn push_event(&mut self, event: Event) {
self.events.push(event) self.events.push(event);
} }
} }

View file

@ -14,7 +14,7 @@ impl TokenSet {
let mut i = 0; let mut i = 0;
while i < kinds.len() { while i < kinds.len() {
res |= mask(kinds[i]); res |= mask(kinds[i]);
i += 1 i += 1;
} }
TokenSet(res) TokenSet(res)
} }

View file

@ -271,7 +271,7 @@ impl RelPath {
/// Taken from <https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85> /// Taken from <https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85>
fn normalize_path(path: &Path) -> PathBuf { fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable(); let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
components.next(); components.next();
PathBuf::from(c.as_os_str()) PathBuf::from(c.as_os_str())
} else { } else {

View file

@ -246,7 +246,7 @@ impl<'a> Writer<'a> {
fn enqueue(&mut self, subtree: &'a tt::Subtree) -> u32 { fn enqueue(&mut self, subtree: &'a tt::Subtree) -> u32 {
let idx = self.subtree.len(); let idx = self.subtree.len();
let delimiter_id = subtree.delimiter.map(|it| it.id).unwrap_or_else(TokenId::unspecified); let delimiter_id = subtree.delimiter.map_or(TokenId::unspecified(), |it| it.id);
let delimiter_kind = subtree.delimiter.map(|it| it.kind); let delimiter_kind = subtree.delimiter.map(|it| it.kind);
self.subtree.push(SubtreeRepr { id: delimiter_id, kind: delimiter_kind, tt: [!0, !0] }); self.subtree.push(SubtreeRepr { id: delimiter_id, kind: delimiter_kind, tt: [!0, !0] });
self.work.push_back((idx, subtree)); self.work.push_back((idx, subtree));
@ -320,7 +320,7 @@ impl Reader {
}) })
.collect(), .collect(),
}; };
res[i] = Some(s) res[i] = Some(s);
} }
res[0].take().unwrap() res[0].take().unwrap()

View file

@ -497,10 +497,9 @@ impl server::Literal for Rustc {
} }
fn integer(&mut self, n: &str) -> Self::Literal { fn integer(&mut self, n: &str) -> Self::Literal {
let n = if let Ok(n) = n.parse::<i128>() { let n = match n.parse::<i128>() {
n.to_string() Ok(n) => n.to_string(),
} else { Err(_) => n.parse::<u128>().unwrap().to_string(),
n.parse::<u128>().unwrap().to_string()
}; };
Literal { text: n.into(), id: tt::TokenId::unspecified() } Literal { text: n.into(), id: tt::TokenId::unspecified() }
} }

View file

@ -500,10 +500,9 @@ impl server::Literal for Rustc {
} }
fn integer(&mut self, n: &str) -> Self::Literal { fn integer(&mut self, n: &str) -> Self::Literal {
let n = if let Ok(n) = n.parse::<i128>() { let n = match n.parse::<i128>() {
n.to_string() Ok(n) => n.to_string(),
} else { Err(_) => n.parse::<u128>().unwrap().to_string(),
n.parse::<u128>().unwrap().to_string()
}; };
Literal { text: n.into(), id: tt::TokenId::unspecified() } Literal { text: n.into(), id: tt::TokenId::unspecified() }
} }

View file

@ -504,10 +504,9 @@ impl server::Literal for Rustc {
} }
fn integer(&mut self, n: &str) -> Self::Literal { fn integer(&mut self, n: &str) -> Self::Literal {
let n = if let Ok(n) = n.parse::<i128>() { let n = match n.parse::<i128>() {
n.to_string() Ok(n) => n.to_string(),
} else { Err(_) => n.parse::<u128>().unwrap().to_string(),
n.parse::<u128>().unwrap().to_string()
}; };
Literal { text: n.into(), id: tt::TokenId::unspecified() } Literal { text: n.into(), id: tt::TokenId::unspecified() }
} }

View file

@ -93,7 +93,7 @@ struct ProfilerImpl {
impl ProfileSpan { impl ProfileSpan {
pub fn detail(mut self, detail: impl FnOnce() -> String) -> ProfileSpan { pub fn detail(mut self, detail: impl FnOnce() -> String) -> ProfileSpan {
if let Some(profiler) = &mut self.0 { if let Some(profiler) = &mut self.0 {
profiler.detail = Some(detail()) profiler.detail = Some(detail());
} }
self self
} }
@ -114,7 +114,7 @@ impl HeartbeatSpan {
#[inline] #[inline]
pub fn new(enabled: bool) -> Self { pub fn new(enabled: bool) -> Self {
if enabled { if enabled {
with_profile_stack(|it| it.heartbeats(true)) with_profile_stack(|it| it.heartbeats(true));
} }
Self { enabled } Self { enabled }
} }
@ -123,7 +123,7 @@ impl HeartbeatSpan {
impl Drop for HeartbeatSpan { impl Drop for HeartbeatSpan {
fn drop(&mut self) { fn drop(&mut self) {
if self.enabled { if self.enabled {
with_profile_stack(|it| it.heartbeats(false)) with_profile_stack(|it| it.heartbeats(false));
} }
} }
} }
@ -238,7 +238,7 @@ impl ProfileStack {
self.heartbeat(frame.heartbeats); self.heartbeat(frame.heartbeats);
let avg_span = duration / (frame.heartbeats + 1); let avg_span = duration / (frame.heartbeats + 1);
if avg_span > self.filter.heartbeat_longer_than { if avg_span > self.filter.heartbeat_longer_than {
eprintln!("Too few heartbeats {} ({}/{:?})?", label, frame.heartbeats, duration) eprintln!("Too few heartbeats {} ({}/{:?})?", label, frame.heartbeats, duration);
} }
} }
@ -292,7 +292,7 @@ fn print(
accounted_for += tree[child].duration; accounted_for += tree[child].duration;
if tree[child].duration.as_millis() > longer_than.as_millis() { if tree[child].duration.as_millis() > longer_than.as_millis() {
print(tree, child, level + 1, longer_than, out) print(tree, child, level + 1, longer_than, out);
} else { } else {
let (total_duration, cnt) = let (total_duration, cnt) =
short_children.entry(tree[child].label).or_insert((Duration::default(), 0)); short_children.entry(tree[child].label).or_insert((Duration::default(), 0));
@ -301,7 +301,7 @@ fn print(
} }
} }
for (child_msg, (duration, count)) in short_children.iter() { for (child_msg, (duration, count)) in &short_children {
writeln!(out, " {}{} - {} ({} calls)", current_indent, ms(*duration), child_msg, count) writeln!(out, " {}{} - {} ({} calls)", current_indent, ms(*duration), child_msg, count)
.expect("printing profiling info"); .expect("printing profiling info");
} }

View file

@ -92,7 +92,7 @@ pub fn cpu_span() -> CpuSpan {
{ {
eprintln!( eprintln!(
r#"cpu profiling is disabled, uncomment `default = [ "cpu_profiler" ]` in Cargo.toml to enable."# r#"cpu profiling is disabled, uncomment `default = [ "cpu_profiler" ]` in Cargo.toml to enable."#
) );
} }
CpuSpan { _private: () } CpuSpan { _private: () }

View file

@ -70,15 +70,15 @@ impl fmt::Display for StopWatchSpan {
let mut prefix = ""; let mut prefix = "";
if instructions > 10000 { if instructions > 10000 {
instructions /= 1000; instructions /= 1000;
prefix = "k" prefix = "k";
} }
if instructions > 10000 { if instructions > 10000 {
instructions /= 1000; instructions /= 1000;
prefix = "m" prefix = "m";
} }
if instructions > 10000 { if instructions > 10000 {
instructions /= 1000; instructions /= 1000;
prefix = "g" prefix = "g";
} }
write!(f, ", {}{}instr", instructions, prefix)?; write!(f, ", {}{}instr", instructions, prefix)?;
} }

View file

@ -4,7 +4,7 @@ use std::{env, path::PathBuf, process::Command};
fn main() { fn main() {
set_rerun(); set_rerun();
println!("cargo:rustc-env=REV={}", rev()) println!("cargo:rustc-env=REV={}", rev());
} }
fn set_rerun() { fn set_rerun() {

View file

@ -427,10 +427,9 @@ pub(crate) fn handle_workspace_symbol(
// If no explicit marker was set, check request params. If that's also empty // If no explicit marker was set, check request params. If that's also empty
// use global config. // use global config.
if !all_symbols { if !all_symbols {
let search_kind = if let Some(ref search_kind) = params.search_kind { let search_kind = match params.search_kind {
search_kind Some(ref search_kind) => search_kind,
} else { None => &config.search_kind,
&config.search_kind
}; };
all_symbols = match search_kind { all_symbols = match search_kind {
lsp_ext::WorkspaceSymbolSearchKind::OnlyTypes => false, lsp_ext::WorkspaceSymbolSearchKind::OnlyTypes => false,
@ -439,10 +438,9 @@ pub(crate) fn handle_workspace_symbol(
} }
if !libs { if !libs {
let search_scope = if let Some(ref search_scope) = params.search_scope { let search_scope = match params.search_scope {
search_scope Some(ref search_scope) => search_scope,
} else { None => &config.search_scope,
&config.search_scope
}; };
libs = match search_scope { libs = match search_scope {
lsp_ext::WorkspaceSymbolSearchScope::Workspace => false, lsp_ext::WorkspaceSymbolSearchScope::Workspace => false,

View file

@ -33,9 +33,9 @@ pub fn list_files(dir: &Path) -> Vec<PathBuf> {
path.file_name().unwrap_or_default().to_str().unwrap_or_default().starts_with('.'); path.file_name().unwrap_or_default().to_str().unwrap_or_default().starts_with('.');
if !is_hidden { if !is_hidden {
if file_type.is_dir() { if file_type.is_dir() {
work.push(path) work.push(path);
} else if file_type.is_file() { } else if file_type.is_file() {
res.push(path) res.push(path);
} }
} }
} }
@ -66,7 +66,7 @@ impl CommentBlock {
panic!( panic!(
"Use plain (non-doc) comments with tags like {}:\n {}", "Use plain (non-doc) comments with tags like {}:\n {}",
tag, first tag, first
) );
} }
block.id = id.trim().to_string(); block.id = id.trim().to_string();
@ -106,7 +106,7 @@ impl CommentBlock {
} }
} }
if !block.contents.is_empty() { if !block.contents.is_empty() {
res.push(block) res.push(block);
} }
res res
} }
@ -139,7 +139,7 @@ fn ensure_rustfmt() {
panic!( panic!(
"Failed to run rustfmt from toolchain 'stable'. \ "Failed to run rustfmt from toolchain 'stable'. \
Please run `rustup component add rustfmt --toolchain stable` to install it.", Please run `rustup component add rustfmt --toolchain stable` to install it.",
) );
} }
} }
@ -185,7 +185,7 @@ pub fn ensure_file_contents(file: &Path, contents: &str) {
let _ = fs::create_dir_all(parent); let _ = fs::create_dir_all(parent);
} }
fs::write(file, contents).unwrap(); fs::write(file, contents).unwrap();
panic!("some file was not up to date and has been updated, simply re-run the tests") panic!("some file was not up to date and has been updated, simply re-run the tests");
} }
fn normalize_newlines(s: &str) -> String { fn normalize_newlines(s: &str) -> String {

View file

@ -45,7 +45,7 @@ fn to_snake_case<F: Fn(&char) -> char>(s: &str, change_case: F) -> String {
if c.is_ascii_uppercase() && prev { if c.is_ascii_uppercase() && prev {
// This check is required to not translate `Weird_Case` into `weird__case`. // This check is required to not translate `Weird_Case` into `weird__case`.
if !buf.ends_with('_') { if !buf.ends_with('_') {
buf.push('_') buf.push('_');
} }
} }
prev = true; prev = true;
@ -60,7 +60,7 @@ pub fn replace(buf: &mut String, from: char, to: &str) {
return; return;
} }
// FIXME: do this in place. // FIXME: do this in place.
*buf = buf.replace(from, to) *buf = buf.replace(from, to);
} }
pub fn trim_indent(mut text: &str) -> String { pub fn trim_indent(mut text: &str) -> String {
@ -101,7 +101,7 @@ pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
impl<F: FnOnce()> Drop for D<F> { impl<F: FnOnce()> Drop for D<F> {
fn drop(&mut self) { fn drop(&mut self) {
if let Some(f) = self.0.take() { if let Some(f) = self.0.take() {
f() f();
} }
} }
} }

View file

@ -25,19 +25,19 @@ impl PanicContext {
if !ctx.is_empty() { if !ctx.is_empty() {
eprintln!("Panic context:"); eprintln!("Panic context:");
for frame in ctx.iter() { for frame in ctx.iter() {
eprintln!("> {}\n", frame) eprintln!("> {}\n", frame);
} }
} }
default_hook(panic_info) default_hook(panic_info);
}) });
}; };
panic::set_hook(Box::new(hook)) panic::set_hook(Box::new(hook));
} }
} }
impl Drop for PanicContext { impl Drop for PanicContext {
fn drop(&mut self) { fn drop(&mut self) {
with_ctx(|ctx| assert!(ctx.pop().is_some())) with_ctx(|ctx| assert!(ctx.pop().is_some()));
} }
} }
@ -45,5 +45,5 @@ fn with_ctx(f: impl FnOnce(&mut Vec<String>)) {
thread_local! { thread_local! {
static CTX: RefCell<Vec<String>> = RefCell::new(Vec::new()); static CTX: RefCell<Vec<String>> = RefCell::new(Vec::new());
} }
CTX.with(|ctx| f(&mut *ctx.borrow_mut())) CTX.with(|ctx| f(&mut *ctx.borrow_mut()));
} }

View file

@ -42,9 +42,9 @@ pub fn streaming_output(
}; };
for line in String::from_utf8_lossy(new_lines).lines() { for line in String::from_utf8_lossy(new_lines).lines() {
if is_out { if is_out {
on_stdout_line(line) on_stdout_line(line);
} else { } else {
on_stderr_line(line) on_stderr_line(line);
} }
} }
} }

View file

@ -112,15 +112,15 @@ impl TreeDiff {
pub fn into_text_edit(&self, builder: &mut TextEditBuilder) { pub fn into_text_edit(&self, builder: &mut TextEditBuilder) {
let _p = profile::span("into_text_edit"); let _p = profile::span("into_text_edit");
for (anchor, to) in self.insertions.iter() { for (anchor, to) in &self.insertions {
let offset = match anchor { let offset = match anchor {
TreeDiffInsertPos::After(it) => it.text_range().end(), TreeDiffInsertPos::After(it) => it.text_range().end(),
TreeDiffInsertPos::AsFirstChild(it) => it.text_range().start(), TreeDiffInsertPos::AsFirstChild(it) => it.text_range().start(),
}; };
to.iter().for_each(|to| builder.insert(offset, to.to_string())); to.iter().for_each(|to| builder.insert(offset, to.to_string()));
} }
for (from, to) in self.replacements.iter() { for (from, to) in &self.replacements {
builder.replace(from.text_range(), to.to_string()) builder.replace(from.text_range(), to.to_string());
} }
for text_range in self.deletions.iter().map(SyntaxElement::text_range) { for text_range in self.deletions.iter().map(SyntaxElement::text_range) {
builder.delete(text_range); builder.delete(text_range);
@ -217,9 +217,8 @@ pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff {
cov_mark::hit!(diff_insertions); cov_mark::hit!(diff_insertions);
insert = true; insert = true;
break; break;
} else {
look_ahead_scratch.push(rhs_child);
} }
look_ahead_scratch.push(rhs_child);
} }
let drain = look_ahead_scratch.drain(..); let drain = look_ahead_scratch.drain(..);
if insert { if insert {
@ -233,7 +232,7 @@ pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff {
diff.insertions.entry(insert_pos).or_insert_with(Vec::new).extend(drain); diff.insertions.entry(insert_pos).or_insert_with(Vec::new).extend(drain);
rhs_children = rhs_children_clone; rhs_children = rhs_children_clone;
} else { } else {
go(diff, lhs_ele, rhs_ele) go(diff, lhs_ele, rhs_ele);
} }
} }
} }

View file

@ -126,7 +126,7 @@ impl IndentLevel {
if let Some(ws) = ast::Whitespace::cast(token) { if let Some(ws) = ast::Whitespace::cast(token) {
if ws.text().contains('\n') { if ws.text().contains('\n') {
let new_ws = make::tokens::whitespace(&format!("{}{}", ws.syntax(), self)); let new_ws = make::tokens::whitespace(&format!("{}{}", ws.syntax(), self));
ted::replace(ws.syntax(), &new_ws) ted::replace(ws.syntax(), &new_ws);
} }
} }
} }
@ -143,7 +143,7 @@ impl IndentLevel {
let new_ws = make::tokens::whitespace( let new_ws = make::tokens::whitespace(
&ws.syntax().text().replace(&format!("\n{}", self), "\n"), &ws.syntax().text().replace(&format!("\n{}", self), "\n"),
); );
ted::replace(ws.syntax(), &new_ws) ted::replace(ws.syntax(), &new_ws);
} }
} }
} }

View file

@ -49,7 +49,7 @@ impl GenericParamsOwnerEdit for ast::Fn {
} else { } else {
Position::last_child_of(self.syntax()) Position::last_child_of(self.syntax())
}; };
create_where_clause(position) create_where_clause(position);
} }
self.where_clause().unwrap() self.where_clause().unwrap()
} }
@ -60,10 +60,9 @@ impl GenericParamsOwnerEdit for ast::Impl {
match self.generic_param_list() { match self.generic_param_list() {
Some(it) => it, Some(it) => it,
None => { None => {
let position = if let Some(imp_token) = self.impl_token() { let position = match self.impl_token() {
Position::after(imp_token) Some(imp_token) => Position::after(imp_token),
} else { None => Position::last_child_of(self.syntax()),
Position::last_child_of(self.syntax())
}; };
create_generic_param_list(position) create_generic_param_list(position)
} }
@ -72,12 +71,11 @@ impl GenericParamsOwnerEdit for ast::Impl {
fn get_or_create_where_clause(&self) -> ast::WhereClause { fn get_or_create_where_clause(&self) -> ast::WhereClause {
if self.where_clause().is_none() { if self.where_clause().is_none() {
let position = if let Some(items) = self.assoc_item_list() { let position = match self.assoc_item_list() {
Position::before(items.syntax()) Some(items) => Position::before(items.syntax()),
} else { None => Position::last_child_of(self.syntax()),
Position::last_child_of(self.syntax())
}; };
create_where_clause(position) create_where_clause(position);
} }
self.where_clause().unwrap() self.where_clause().unwrap()
} }
@ -102,12 +100,11 @@ impl GenericParamsOwnerEdit for ast::Trait {
fn get_or_create_where_clause(&self) -> ast::WhereClause { fn get_or_create_where_clause(&self) -> ast::WhereClause {
if self.where_clause().is_none() { if self.where_clause().is_none() {
let position = if let Some(items) = self.assoc_item_list() { let position = match self.assoc_item_list() {
Position::before(items.syntax()) Some(items) => Position::before(items.syntax()),
} else { None => Position::last_child_of(self.syntax()),
Position::last_child_of(self.syntax())
}; };
create_where_clause(position) create_where_clause(position);
} }
self.where_clause().unwrap() self.where_clause().unwrap()
} }
@ -145,7 +142,7 @@ impl GenericParamsOwnerEdit for ast::Struct {
} else { } else {
Position::last_child_of(self.syntax()) Position::last_child_of(self.syntax())
}; };
create_where_clause(position) create_where_clause(position);
} }
self.where_clause().unwrap() self.where_clause().unwrap()
} }
@ -177,7 +174,7 @@ impl GenericParamsOwnerEdit for ast::Enum {
} else { } else {
Position::last_child_of(self.syntax()) Position::last_child_of(self.syntax())
}; };
create_where_clause(position) create_where_clause(position);
} }
self.where_clause().unwrap() self.where_clause().unwrap()
} }
@ -234,7 +231,7 @@ impl ast::GenericParamList {
} }
None => { None => {
let after_l_angle = Position::after(self.l_angle_token().unwrap()); let after_l_angle = Position::after(self.l_angle_token().unwrap());
ted::insert(after_l_angle, generic_param.syntax()) ted::insert(after_l_angle, generic_param.syntax());
} }
} }
} }
@ -247,18 +244,15 @@ impl ast::WhereClause {
ted::append_child_raw(self.syntax(), make::token(T![,])); ted::append_child_raw(self.syntax(), make::token(T![,]));
} }
} }
ted::append_child(self.syntax(), predicate.syntax()) ted::append_child(self.syntax(), predicate.syntax());
} }
} }
impl ast::TypeBoundList { impl ast::TypeBoundList {
pub fn remove(&self) { pub fn remove(&self) {
if let Some(colon) = match self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:]) {
self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:]) Some(colon) => ted::remove_all(colon..=self.syntax().clone().into()),
{ None => ted::remove(self.syntax()),
ted::remove_all(colon..=self.syntax().clone().into())
} else {
ted::remove(self.syntax())
} }
} }
} }
@ -267,7 +261,7 @@ impl ast::PathSegment {
pub fn get_or_create_generic_arg_list(&self) -> ast::GenericArgList { pub fn get_or_create_generic_arg_list(&self) -> ast::GenericArgList {
if self.generic_arg_list().is_none() { if self.generic_arg_list().is_none() {
let arg_list = make::generic_arg_list().clone_for_update(); let arg_list = make::generic_arg_list().clone_for_update();
ted::append_child(self.syntax(), arg_list.syntax()) ted::append_child(self.syntax(), arg_list.syntax());
} }
self.generic_arg_list().unwrap() self.generic_arg_list().unwrap()
} }
@ -275,7 +269,7 @@ impl ast::PathSegment {
impl ast::UseTree { impl ast::UseTree {
pub fn remove(&self) { pub fn remove(&self) {
for &dir in [Direction::Next, Direction::Prev].iter() { for dir in [Direction::Next, Direction::Prev] {
if let Some(next_use_tree) = neighbor(self, dir) { if let Some(next_use_tree) = neighbor(self, dir) {
let separators = self let separators = self
.syntax() .syntax()
@ -286,7 +280,7 @@ impl ast::UseTree {
break; break;
} }
} }
ted::remove(self.syntax()) ted::remove(self.syntax());
} }
} }
@ -301,13 +295,13 @@ impl ast::Use {
let ws_text = next_ws.syntax().text(); let ws_text = next_ws.syntax().text();
if let Some(rest) = ws_text.strip_prefix('\n') { if let Some(rest) = ws_text.strip_prefix('\n') {
if rest.is_empty() { if rest.is_empty() {
ted::remove(next_ws.syntax()) ted::remove(next_ws.syntax());
} else { } else {
ted::replace(next_ws.syntax(), make::tokens::whitespace(rest)) ted::replace(next_ws.syntax(), make::tokens::whitespace(rest));
} }
} }
} }
ted::remove(self.syntax()) ted::remove(self.syntax());
} }
} }
@ -455,7 +449,7 @@ impl ast::RecordExprField {
/// This will either replace the initializer, or in the case that this is a shorthand convert /// This will either replace the initializer, or in the case that this is a shorthand convert
/// the initializer into the name ref and insert the expr as the new initializer. /// the initializer into the name ref and insert the expr as the new initializer.
pub fn replace_expr(&self, expr: ast::Expr) { pub fn replace_expr(&self, expr: ast::Expr) {
if let Some(_) = self.name_ref() { if self.name_ref().is_some() {
match self.expr() { match self.expr() {
Some(prev) => ted::replace(prev.syntax(), expr.syntax()), Some(prev) => ted::replace(prev.syntax(), expr.syntax()),
None => ted::append_child(self.syntax(), expr.syntax()), None => ted::append_child(self.syntax(), expr.syntax()),
@ -525,7 +519,7 @@ pub trait Indent: AstNode + Clone + Sized {
fn reindent_to(&self, target_level: IndentLevel) { fn reindent_to(&self, target_level: IndentLevel) {
let current_level = IndentLevel::from_node(self.syntax()); let current_level = IndentLevel::from_node(self.syntax());
self.dedent(current_level); self.dedent(current_level);
self.indent(target_level) self.indent(target_level);
} }
} }

View file

@ -257,7 +257,7 @@ pub fn block_expr(
format_to!(buf, " {}\n", stmt); format_to!(buf, " {}\n", stmt);
} }
if let Some(tail_expr) = tail_expr { if let Some(tail_expr) = tail_expr {
format_to!(buf, " {}\n", tail_expr) format_to!(buf, " {}\n", tail_expr);
} }
buf += "}"; buf += "}";
ast_from_text(&format!("fn f() {}", buf)) ast_from_text(&format!("fn f() {}", buf))
@ -644,9 +644,14 @@ pub fn fn_(
ret_type: Option<ast::RetType>, ret_type: Option<ast::RetType>,
is_async: bool, is_async: bool,
) -> ast::Fn { ) -> ast::Fn {
let type_params = let type_params = match type_params {
if let Some(type_params) = type_params { format!("<{}>", type_params) } else { "".into() }; Some(type_params) => format!("<{}>", type_params),
let ret_type = if let Some(ret_type) = ret_type { format!("{} ", ret_type) } else { "".into() }; None => "".into(),
};
let ret_type = match ret_type {
Some(ret_type) => format!("{} ", ret_type),
None => "".into(),
};
let visibility = match visibility { let visibility = match visibility {
None => String::new(), None => String::new(),
Some(it) => format!("{} ", it), Some(it) => format!("{} ", it),

View file

@ -276,9 +276,9 @@ impl ast::Path {
impl ast::Use { impl ast::Use {
pub fn is_simple_glob(&self) -> bool { pub fn is_simple_glob(&self) -> bool {
self.use_tree() self.use_tree().map_or(false, |use_tree| {
.map(|use_tree| use_tree.use_tree_list().is_none() && use_tree.star_token().is_some()) use_tree.use_tree_list().is_none() && use_tree.star_token().is_some()
.unwrap_or(false) })
} }
} }
@ -549,10 +549,9 @@ impl ast::FieldExpr {
} }
pub fn field_access(&self) -> Option<FieldKind> { pub fn field_access(&self) -> Option<FieldKind> {
if let Some(nr) = self.name_ref() { match self.name_ref() {
Some(FieldKind::Name(nr)) Some(nr) => Some(FieldKind::Name(nr)),
} else { None => self.index_token().map(FieldKind::Index),
self.index_token().map(FieldKind::Index)
} }
} }
} }

View file

@ -283,10 +283,9 @@ pub trait HasFormatSpecifier: AstToken {
where where
F: FnMut(TextRange, FormatSpecifier), F: FnMut(TextRange, FormatSpecifier),
{ {
let char_ranges = if let Some(char_ranges) = self.char_ranges() { let char_ranges = match self.char_ranges() {
char_ranges Some(char_ranges) => char_ranges,
} else { None => return,
return;
}; };
let mut chars = char_ranges.iter().peekable(); let mut chars = char_ranges.iter().peekable();
@ -528,10 +527,11 @@ pub trait HasFormatSpecifier: AstToken {
} }
} }
if let Some((_, Ok('}'))) = chars.peek() { match chars.peek() {
Some((_, Ok('}'))) => {
skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback); skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback);
} else { }
continue; Some((_, _)) | None => continue,
} }
} }
_ => { _ => {
@ -609,7 +609,7 @@ impl HasFormatSpecifier for ast::String {
TextRange::new(range.start.try_into().unwrap(), range.end.try_into().unwrap()) TextRange::new(range.start.try_into().unwrap(), range.end.try_into().unwrap())
+ offset, + offset,
unescaped_char, unescaped_char,
)) ));
}); });
Some(res) Some(res)
@ -631,7 +631,7 @@ impl ast::IntNumber {
let mut text = token.text(); let mut text = token.text();
if let Some(suffix) = self.suffix() { if let Some(suffix) = self.suffix() {
text = &text[..text.len() - suffix.len()] text = &text[..text.len() - suffix.len()];
} }
let radix = self.radix(); let radix = self.radix();
@ -688,7 +688,7 @@ impl Radix {
pub const ALL: &'static [Radix] = pub const ALL: &'static [Radix] =
&[Radix::Binary, Radix::Octal, Radix::Decimal, Radix::Hexadecimal]; &[Radix::Binary, Radix::Octal, Radix::Decimal, Radix::Hexadecimal];
const fn prefix_len(&self) -> usize { const fn prefix_len(self) -> usize {
match self { match self {
Self::Decimal => 0, Self::Decimal => 0,
_ => 2, _ => 2,

View file

@ -28,7 +28,7 @@ pub fn function_declaration(node: &ast::Fn) -> String {
format_to!(buf, "{} ", abi); format_to!(buf, "{} ", abi);
} }
if let Some(name) = node.name() { if let Some(name) = node.name() {
format_to!(buf, "fn {}", name) format_to!(buf, "fn {}", name);
} }
if let Some(type_params) = node.generic_param_list() { if let Some(type_params) = node.generic_param_list() {
format_to!(buf, "{}", type_params); format_to!(buf, "{}", type_params);

View file

@ -44,8 +44,7 @@ impl<'t> TokenSource for TextTokenSource<'t> {
fn is_keyword(&self, kw: &str) -> bool { fn is_keyword(&self, kw: &str) -> bool {
self.token_offset_pairs self.token_offset_pairs
.get(self.curr.1) .get(self.curr.1)
.map(|(token, offset)| &self.text[TextRange::at(*offset, token.len)] == kw) .map_or(false, |(token, offset)| &self.text[TextRange::at(*offset, token.len)] == kw)
.unwrap_or(false)
} }
} }
@ -55,8 +54,7 @@ fn mk_token(pos: usize, token_offset_pairs: &[(Token, TextSize)]) -> parser::Tok
token.kind, token.kind,
token_offset_pairs token_offset_pairs
.get(pos + 1) .get(pos + 1)
.map(|(_, next_offset)| offset + token.len == *next_offset) .map_or(false, |(_, next_offset)| offset + token.len == *next_offset),
.unwrap_or(false),
), ),
None => (EOF, false), None => (EOF, false),
}; };

View file

@ -88,7 +88,7 @@ impl<'a> TreeSink for TextTreeSink<'a> {
} }
fn error(&mut self, error: ParseError) { fn error(&mut self, error: ParseError) {
self.inner.error(error, self.text_pos) self.inner.error(error, self.text_pos);
} }
} }
@ -108,7 +108,7 @@ impl<'a> TextTreeSink<'a> {
match mem::replace(&mut self.state, State::Normal) { match mem::replace(&mut self.state, State::Normal) {
State::PendingFinish => { State::PendingFinish => {
self.eat_trivias(); self.eat_trivias();
self.inner.finish_node() self.inner.finish_node();
} }
State::PendingStart | State::Normal => unreachable!(), State::PendingStart | State::Normal => unreachable!(),
} }

View file

@ -81,7 +81,7 @@ impl<N: AstNode> PartialEq for AstPtr<N> {
impl<N: AstNode> Hash for AstPtr<N> { impl<N: AstNode> Hash for AstPtr<N> {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.raw.hash(state) self.raw.hash(state);
} }
} }

View file

@ -56,19 +56,19 @@ impl SyntaxTreeBuilder {
pub fn token(&mut self, kind: SyntaxKind, text: &str) { pub fn token(&mut self, kind: SyntaxKind, text: &str) {
let kind = RustLanguage::kind_to_raw(kind); let kind = RustLanguage::kind_to_raw(kind);
self.inner.token(kind, text) self.inner.token(kind, text);
} }
pub fn start_node(&mut self, kind: SyntaxKind) { pub fn start_node(&mut self, kind: SyntaxKind) {
let kind = RustLanguage::kind_to_raw(kind); let kind = RustLanguage::kind_to_raw(kind);
self.inner.start_node(kind) self.inner.start_node(kind);
} }
pub fn finish_node(&mut self) { pub fn finish_node(&mut self) {
self.inner.finish_node() self.inner.finish_node();
} }
pub fn error(&mut self, error: parser::ParseError, text_pos: TextSize) { pub fn error(&mut self, error: parser::ParseError, text_pos: TextSize) {
self.errors.push(SyntaxError::new_at_offset(*error.0, text_pos)) self.errors.push(SyntaxError::new_at_offset(*error.0, text_pos));
} }
} }

View file

@ -77,23 +77,23 @@ impl Position {
} }
pub fn insert(position: Position, elem: impl Element) { pub fn insert(position: Position, elem: impl Element) {
insert_all(position, vec![elem.syntax_element()]) insert_all(position, vec![elem.syntax_element()]);
} }
pub fn insert_raw(position: Position, elem: impl Element) { pub fn insert_raw(position: Position, elem: impl Element) {
insert_all_raw(position, vec![elem.syntax_element()]) insert_all_raw(position, vec![elem.syntax_element()]);
} }
pub fn insert_all(position: Position, mut elements: Vec<SyntaxElement>) { pub fn insert_all(position: Position, mut elements: Vec<SyntaxElement>) {
if let Some(first) = elements.first() { if let Some(first) = elements.first() {
if let Some(ws) = ws_before(&position, first) { if let Some(ws) = ws_before(&position, first) {
elements.insert(0, ws.into()) elements.insert(0, ws.into());
} }
} }
if let Some(last) = elements.last() { if let Some(last) = elements.last() {
if let Some(ws) = ws_after(&position, last) { if let Some(ws) = ws_after(&position, last) {
elements.push(ws.into()) elements.push(ws.into());
} }
} }
insert_all_raw(position, elements) insert_all_raw(position, elements);
} }
pub fn insert_all_raw(position: Position, elements: Vec<SyntaxElement>) { pub fn insert_all_raw(position: Position, elements: Vec<SyntaxElement>) {
let (parent, index) = match position.repr { let (parent, index) = match position.repr {
@ -104,10 +104,10 @@ pub fn insert_all_raw(position: Position, elements: Vec<SyntaxElement>) {
} }
pub fn remove(elem: impl Element) { pub fn remove(elem: impl Element) {
elem.syntax_element().detach() elem.syntax_element().detach();
} }
pub fn remove_all(range: RangeInclusive<SyntaxElement>) { pub fn remove_all(range: RangeInclusive<SyntaxElement>) {
replace_all(range, Vec::new()) replace_all(range, Vec::new());
} }
pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) { pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) {
let mut it = range.into_iter(); let mut it = range.into_iter();
@ -115,9 +115,9 @@ pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) {
match it.last() { match it.last() {
Some(mut last) => { Some(mut last) => {
if first.index() > last.index() { if first.index() > last.index() {
mem::swap(&mut first, &mut last) mem::swap(&mut first, &mut last);
} }
remove_all(first..=last) remove_all(first..=last);
} }
None => remove(first), None => remove(first),
} }
@ -125,26 +125,26 @@ pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) {
} }
pub fn replace(old: impl Element, new: impl Element) { pub fn replace(old: impl Element, new: impl Element) {
replace_with_many(old, vec![new.syntax_element()]) replace_with_many(old, vec![new.syntax_element()]);
} }
pub fn replace_with_many(old: impl Element, new: Vec<SyntaxElement>) { pub fn replace_with_many(old: impl Element, new: Vec<SyntaxElement>) {
let old = old.syntax_element(); let old = old.syntax_element();
replace_all(old.clone()..=old, new) replace_all(old.clone()..=old, new);
} }
pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>) { pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>) {
let start = range.start().index(); let start = range.start().index();
let end = range.end().index(); let end = range.end().index();
let parent = range.start().parent().unwrap(); let parent = range.start().parent().unwrap();
parent.splice_children(start..end + 1, new) parent.splice_children(start..end + 1, new);
} }
pub fn append_child(node: &(impl Into<SyntaxNode> + Clone), child: impl Element) { pub fn append_child(node: &(impl Into<SyntaxNode> + Clone), child: impl Element) {
let position = Position::last_child_of(node); let position = Position::last_child_of(node);
insert(position, child) insert(position, child);
} }
pub fn append_child_raw(node: &(impl Into<SyntaxNode> + Clone), child: impl Element) { pub fn append_child_raw(node: &(impl Into<SyntaxNode> + Clone), child: impl Element) {
let position = Position::last_child_of(node); let position = Position::last_child_of(node);
insert_raw(position, child) insert_raw(position, child);
} }
fn ws_before(position: &Position, new: &SyntaxElement) -> Option<SyntaxToken> { fn ws_before(position: &Position, new: &SyntaxElement) -> Option<SyntaxToken> {

View file

@ -227,12 +227,9 @@ where
T: crate::AstNode, T: crate::AstNode,
F: Fn(&str) -> Result<T, ()>, F: Fn(&str) -> Result<T, ()>,
{ {
dir_tests(&test_data_dir(), ok_paths, "rast", |text, path| { dir_tests(&test_data_dir(), ok_paths, "rast", |text, path| match f(text) {
if let Ok(node) = f(text) { Ok(node) => format!("{:#?}", crate::ast::AstNode::syntax(&node)),
format!("{:#?}", crate::ast::AstNode::syntax(&node)) Err(_) => panic!("Failed to parse '{:?}'", path),
} else {
panic!("Failed to parse '{:?}'", path);
}
}); });
dir_tests(&test_data_dir(), err_paths, "rast", |text, path| { dir_tests(&test_data_dir(), err_paths, "rast", |text, path| {
if f(text).is_ok() { if f(text).is_ok() {

View file

@ -215,7 +215,7 @@ fn generate_nodes(kinds: KindsSrc<'_>, grammar: &AstSrc) -> String {
.flat_map(|node| node.traits.iter().map(move |t| (t, node))) .flat_map(|node| node.traits.iter().map(move |t| (t, node)))
.into_group_map() .into_group_map()
.into_iter() .into_iter()
.sorted_by_key(|(k, _)| k.clone()) .sorted_by_key(|(k, _)| *k)
.map(|(trait_name, nodes)| { .map(|(trait_name, nodes)| {
let name = format_ident!("Any{}", trait_name); let name = format_ident!("Any{}", trait_name);
let trait_name = format_ident!("{}", trait_name); let trait_name = format_ident!("{}", trait_name);
@ -558,12 +558,13 @@ impl Field {
} }
fn lower(grammar: &Grammar) -> AstSrc { fn lower(grammar: &Grammar) -> AstSrc {
let mut res = AstSrc::default(); let mut res = AstSrc {
tokens: "Whitespace Comment String ByteString IntNumber FloatNumber"
res.tokens = "Whitespace Comment String ByteString IntNumber FloatNumber"
.split_ascii_whitespace() .split_ascii_whitespace()
.map(|it| it.to_string()) .map(|it| it.to_string())
.collect::<Vec<_>>(); .collect::<Vec<_>>(),
..Default::default()
};
let nodes = grammar.iter().collect::<Vec<_>>(); let nodes = grammar.iter().collect::<Vec<_>>();

View file

@ -137,7 +137,7 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
if let Err(err) = char { if let Err(err) = char {
push_err(1, (range.start, err)); push_err(1, (range.start, err));
} }
}) });
} }
} }
} }
@ -148,7 +148,7 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
if let Err(err) = char { if let Err(err) = char {
push_err(2, (range.start, err)); push_err(2, (range.start, err));
} }
}) });
} }
} }
} }

View file

@ -19,6 +19,6 @@ pub(crate) fn validate_block_expr(block: ast::BlockExpr, errors: &mut Vec<Syntax
"A block in this position cannot accept inner attributes", "A block in this position cannot accept inner attributes",
attr.syntax().text_range(), attr.syntax().text_range(),
) )
})) }));
} }
} }

View file

@ -43,7 +43,7 @@ impl AssertLinear {
} }
pub fn sample(&mut self, x: f64, y: f64) { pub fn sample(&mut self, x: f64, y: f64) {
self.rounds.last_mut().unwrap().samples.push((x, y)) self.rounds.last_mut().unwrap().samples.push((x, y));
} }
} }
@ -54,7 +54,7 @@ impl Drop for AssertLinear {
for round in &self.rounds { for round in &self.rounds {
eprintln!("\n{}", round.plot); eprintln!("\n{}", round.plot);
} }
panic!("Doesn't look linear!") panic!("Doesn't look linear!");
} }
} }
} }

View file

@ -142,14 +142,14 @@ impl Fixture {
if line.starts_with("//-") { if line.starts_with("//-") {
let meta = Fixture::parse_meta_line(line); let meta = Fixture::parse_meta_line(line);
res.push(meta) res.push(meta);
} else { } else {
if line.starts_with("// ") if line.starts_with("// ")
&& line.contains(':') && line.contains(':')
&& !line.contains("::") && !line.contains("::")
&& line.chars().all(|it| !it.is_uppercase()) && line.chars().all(|it| !it.is_uppercase())
{ {
panic!("looks like invalid metadata line: {:?}", line) panic!("looks like invalid metadata line: {:?}", line);
} }
if let Some(entry) = res.last_mut() { if let Some(entry) = res.last_mut() {
@ -256,9 +256,9 @@ impl MiniCore {
let line = line.strip_prefix("//- minicore:").unwrap().trim(); let line = line.strip_prefix("//- minicore:").unwrap().trim();
for entry in line.split(", ") { for entry in line.split(", ") {
if res.has_flag(entry) { if res.has_flag(entry) {
panic!("duplicate minicore flag: {:?}", entry) panic!("duplicate minicore flag: {:?}", entry);
} }
res.activated_flags.push(entry.to_string()) res.activated_flags.push(entry.to_string());
} }
res res
@ -310,7 +310,7 @@ impl MiniCore {
// Fixed point loop to compute transitive closure of flags. // Fixed point loop to compute transitive closure of flags.
loop { loop {
let mut changed = false; let mut changed = false;
for &(u, v) in implications.iter() { for &(u, v) in &implications {
if self.has_flag(u) && !self.has_flag(v) { if self.has_flag(u) && !self.has_flag(v) {
self.activated_flags.push(v.to_string()); self.activated_flags.push(v.to_string());
changed = true; changed = true;
@ -354,7 +354,7 @@ impl MiniCore {
} }
if keep { if keep {
buf.push_str(line) buf.push_str(line);
} }
if line_region { if line_region {
active_regions.pop().unwrap(); active_regions.pop().unwrap();

View file

@ -244,7 +244,7 @@ pub fn extract_annotations(text: &str) -> Vec<(TextRange, String)> {
range + line_start.1 range + line_start.1
}; };
res.push((range, content)) res.push((range, content));
} }
LineAnnotation::Continuation { mut offset, content } => { LineAnnotation::Continuation { mut offset, content } => {
offset += annotation_offset; offset += annotation_offset;
@ -301,7 +301,7 @@ fn extract_line_annotations(mut line: &str) -> Vec<LineAnnotation> {
let mut file = false; let mut file = false;
if !continuation && content.starts_with("file") { if !continuation && content.starts_with("file") {
file = true; file = true;
content = &content["file".len()..] content = &content["file".len()..];
} }
let content = content.trim().to_string(); let content = content.trim().to_string();
@ -371,7 +371,7 @@ fn main() {
pub fn skip_slow_tests() -> bool { pub fn skip_slow_tests() -> bool {
let should_skip = std::env::var("CI").is_err() && std::env::var("RUN_SLOW_TESTS").is_err(); let should_skip = std::env::var("CI").is_err() && std::env::var("RUN_SLOW_TESTS").is_err();
if should_skip { if should_skip {
eprintln!("ignoring slow test") eprintln!("ignoring slow test");
} else { } else {
let path = project_root().join("./target/.slow_tests_cookie"); let path = project_root().join("./target/.slow_tests_cookie");
fs::write(&path, ".").unwrap(); fs::write(&path, ".").unwrap();
@ -432,7 +432,7 @@ pub fn bench(label: &'static str) -> impl Drop {
impl Drop for Bencher { impl Drop for Bencher {
fn drop(&mut self) { fn drop(&mut self) {
eprintln!("{}: {}", self.label, self.sw.elapsed()) eprintln!("{}: {}", self.label, self.sw.elapsed());
} }
} }

View file

@ -90,13 +90,13 @@ impl TextEdit {
} }
let mut total_len = TextSize::of(&*text); let mut total_len = TextSize::of(&*text);
for indel in self.indels.iter() { for indel in &self.indels {
total_len += TextSize::of(&indel.insert); total_len += TextSize::of(&indel.insert);
total_len -= indel.delete.end() - indel.delete.start(); total_len -= indel.delete.end() - indel.delete.start();
} }
let mut buf = String::with_capacity(total_len.into()); let mut buf = String::with_capacity(total_len.into());
let mut prev = 0; let mut prev = 0;
for indel in self.indels.iter() { for indel in &self.indels {
let start: usize = indel.delete.start().into(); let start: usize = indel.delete.start().into();
let end: usize = indel.delete.end().into(); let end: usize = indel.delete.end().into();
if start > prev { if start > prev {
@ -110,7 +110,7 @@ impl TextEdit {
// FIXME: figure out a way to mutate the text in-place or reuse the // FIXME: figure out a way to mutate the text in-place or reuse the
// memory in some other way // memory in some other way
*text = buf *text = buf;
} }
pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> { pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {
@ -126,7 +126,7 @@ impl TextEdit {
pub fn apply_to_offset(&self, offset: TextSize) -> Option<TextSize> { pub fn apply_to_offset(&self, offset: TextSize) -> Option<TextSize> {
let mut res = offset; let mut res = offset;
for indel in self.indels.iter() { for indel in &self.indels {
if indel.delete.start() >= offset { if indel.delete.start() >= offset {
break; break;
} }
@ -163,13 +163,13 @@ impl TextEditBuilder {
self.indels.is_empty() self.indels.is_empty()
} }
pub fn replace(&mut self, range: TextRange, replace_with: String) { pub fn replace(&mut self, range: TextRange, replace_with: String) {
self.indel(Indel::replace(range, replace_with)) self.indel(Indel::replace(range, replace_with));
} }
pub fn delete(&mut self, range: TextRange) { pub fn delete(&mut self, range: TextRange) {
self.indel(Indel::delete(range)) self.indel(Indel::delete(range));
} }
pub fn insert(&mut self, offset: TextSize, text: String) { pub fn insert(&mut self, offset: TextSize, text: String) {
self.indel(Indel::insert(offset, text)) self.indel(Indel::insert(offset, text));
} }
pub fn finish(self) -> TextEdit { pub fn finish(self) -> TextEdit {
let mut indels = self.indels; let mut indels = self.indels;

View file

@ -194,8 +194,7 @@ impl<'a> Cursor<'a> {
TokenTree::Subtree(subtree) => Some(TokenTreeRef::Subtree(subtree, Some(tt))), TokenTree::Subtree(subtree) => Some(TokenTreeRef::Subtree(subtree, Some(tt))),
}, },
Some(Entry::Subtree(tt, subtree, _)) => Some(TokenTreeRef::Subtree(subtree, *tt)), Some(Entry::Subtree(tt, subtree, _)) => Some(TokenTreeRef::Subtree(subtree, *tt)),
Some(Entry::End(_)) => None, Some(Entry::End(_)) | None => None,
None => None,
} }
} }
@ -206,10 +205,9 @@ impl<'a> Cursor<'a> {
/// Bump the cursor /// Bump the cursor
pub fn bump(self) -> Cursor<'a> { pub fn bump(self) -> Cursor<'a> {
if let Some(Entry::End(exit)) = self.buffer.entry(&self.ptr) { if let Some(Entry::End(exit)) = self.buffer.entry(&self.ptr) {
if let Some(exit) = exit { match exit {
Cursor::create(self.buffer, *exit) Some(exit) => Cursor::create(self.buffer, *exit),
} else { None => self,
self
} }
} else { } else {
Cursor::create(self.buffer, EntryPtr(self.ptr.0, self.ptr.1 + 1)) Cursor::create(self.buffer, EntryPtr(self.ptr.0, self.ptr.1 + 1))

View file

@ -161,7 +161,7 @@ impl fmt::Display for Subtree {
}; };
f.write_str(l)?; f.write_str(l)?;
let mut needs_space = false; let mut needs_space = false;
for tt in self.token_trees.iter() { for tt in &self.token_trees {
if needs_space { if needs_space {
f.write_str(" ")?; f.write_str(" ")?;
} }
@ -169,7 +169,7 @@ impl fmt::Display for Subtree {
match tt { match tt {
TokenTree::Leaf(Leaf::Punct(p)) => { TokenTree::Leaf(Leaf::Punct(p)) => {
needs_space = p.spacing == Spacing::Alone; needs_space = p.spacing == Spacing::Alone;
fmt::Display::fmt(p, f)? fmt::Display::fmt(p, f)?;
} }
tt => fmt::Display::fmt(tt, f)?, tt => fmt::Display::fmt(tt, f)?,
} }
@ -215,7 +215,7 @@ impl Subtree {
.iter() .iter()
.map(|c| match c { .map(|c| match c {
TokenTree::Subtree(c) => c.count(), TokenTree::Subtree(c) => c.count(),
_ => 0, TokenTree::Leaf(_) => 0,
}) })
.sum::<usize>(); .sum::<usize>();

View file

@ -38,7 +38,7 @@ impl loader::Handle for NotifyHandle {
NotifyHandle { sender, _thread: thread } NotifyHandle { sender, _thread: thread }
} }
fn set_config(&mut self, config: loader::Config) { fn set_config(&mut self, config: loader::Config) {
self.sender.send(Message::Config(config)).unwrap() self.sender.send(Message::Config(config)).unwrap();
} }
fn invalidate(&mut self, path: AbsPathBuf) { fn invalidate(&mut self, path: AbsPathBuf) {
self.sender.send(Message::Invalidate(path)).unwrap(); self.sender.send(Message::Invalidate(path)).unwrap();
@ -84,7 +84,7 @@ impl NotifyActor {
if !config.watch.is_empty() { if !config.watch.is_empty() {
let (watcher_sender, watcher_receiver) = unbounded(); let (watcher_sender, watcher_receiver) = unbounded();
let watcher = log_notify_error(RecommendedWatcher::new(move |event| { let watcher = log_notify_error(RecommendedWatcher::new(move |event| {
watcher_sender.send(event).unwrap() watcher_sender.send(event).unwrap();
})); }));
self.watcher = watcher.map(|it| (it, watcher_receiver)); self.watcher = watcher.map(|it| (it, watcher_receiver));
} }
@ -99,7 +99,7 @@ impl NotifyActor {
for (i, entry) in config.load.into_iter().enumerate() { for (i, entry) in config.load.into_iter().enumerate() {
let watch = config.watch.contains(&i); let watch = config.watch.contains(&i);
if watch { if watch {
self.watched_entries.push(entry.clone()) self.watched_entries.push(entry.clone());
} }
let files = self.load_entry(entry, watch); let files = self.load_entry(entry, watch);
self.send(loader::Message::Loaded { files }); self.send(loader::Message::Loaded { files });
@ -149,7 +149,7 @@ impl NotifyActor {
Some((path, contents)) Some((path, contents))
}) })
.collect(); .collect();
self.send(loader::Message::Loaded { files }) self.send(loader::Message::Loaded { files });
} }
} }
} }
@ -165,7 +165,7 @@ impl NotifyActor {
.into_iter() .into_iter()
.map(|file| { .map(|file| {
if watch { if watch {
self.watch(file.clone()) self.watch(file.clone());
} }
let contents = read(file.as_path()); let contents = read(file.as_path());
(file, contents) (file, contents)
@ -174,7 +174,7 @@ impl NotifyActor {
loader::Entry::Directories(dirs) => { loader::Entry::Directories(dirs) => {
let mut res = Vec::new(); let mut res = Vec::new();
for root in dirs.include.iter() { for root in &dirs.include {
let walkdir = let walkdir =
WalkDir::new(root).follow_links(true).into_iter().filter_entry(|entry| { WalkDir::new(root).follow_links(true).into_iter().filter_entry(|entry| {
if !entry.file_type().is_dir() { if !entry.file_type().is_dir() {
@ -218,7 +218,7 @@ impl NotifyActor {
} }
} }
fn send(&mut self, msg: loader::Message) { fn send(&mut self, msg: loader::Message) {
(self.sender)(msg) (self.sender)(msg);
} }
} }

View file

@ -112,7 +112,7 @@ impl FileSetConfig {
let mut res = vec![FileSet::default(); self.len()]; let mut res = vec![FileSet::default(); self.len()];
for (file_id, path) in vfs.iter() { for (file_id, path) in vfs.iter() {
let root = self.classify(path, &mut scratch_space); let root = self.classify(path, &mut scratch_space);
res[root].insert(file_id, path.clone()) res[root].insert(file_id, path.clone());
} }
res res
} }
@ -157,7 +157,7 @@ impl FileSetConfigBuilder {
/// Add a new set of paths prefixes. /// Add a new set of paths prefixes.
pub fn add_file_set(&mut self, roots: Vec<VfsPath>) { pub fn add_file_set(&mut self, roots: Vec<VfsPath>) {
self.roots.push(roots) self.roots.push(roots);
} }
/// Build the `FileSetConfig`. /// Build the `FileSetConfig`.

View file

@ -73,9 +73,8 @@ impl VfsPath {
pub fn starts_with(&self, other: &VfsPath) -> bool { pub fn starts_with(&self, other: &VfsPath) -> bool {
match (&self.0, &other.0) { match (&self.0, &other.0) {
(VfsPathRepr::PathBuf(lhs), VfsPathRepr::PathBuf(rhs)) => lhs.starts_with(rhs), (VfsPathRepr::PathBuf(lhs), VfsPathRepr::PathBuf(rhs)) => lhs.starts_with(rhs),
(VfsPathRepr::PathBuf(_), _) => false,
(VfsPathRepr::VirtualPath(lhs), VfsPathRepr::VirtualPath(rhs)) => lhs.starts_with(rhs), (VfsPathRepr::VirtualPath(lhs), VfsPathRepr::VirtualPath(rhs)) => lhs.starts_with(rhs),
(VfsPathRepr::VirtualPath(_), _) => false, (VfsPathRepr::PathBuf(_) | VfsPathRepr::VirtualPath(_), _) => false,
} }
} }
@ -357,7 +356,7 @@ impl VirtualPath {
if !res.pop() { if !res.pop() {
return None; return None;
} }
path = &path["../".len()..] path = &path["../".len()..];
} }
path = path.trim_start_matches("./"); path = path.trim_start_matches("./");
res.0 = format!("{}/{}", res.0, path); res.0 = format!("{}/{}", res.0, path);

View file

@ -63,7 +63,7 @@ impl<T> Eq for Idx<T> {}
impl<T> Hash for Idx<T> { impl<T> Hash for Idx<T> {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.raw.hash(state) self.raw.hash(state);
} }
} }
@ -71,7 +71,7 @@ impl<T> fmt::Debug for Idx<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut type_name = std::any::type_name::<T>(); let mut type_name = std::any::type_name::<T>();
if let Some(idx) = type_name.rfind(':') { if let Some(idx) = type_name.rfind(':') {
type_name = &type_name[idx + 1..] type_name = &type_name[idx + 1..];
} }
write!(f, "Idx::<{}>({})", type_name, self.raw) write!(f, "Idx::<{}>({})", type_name, self.raw)
} }

View file

@ -13,7 +13,7 @@ const REQUIRED_RUST_VERSION: u32 = 55;
impl flags::Install { impl flags::Install {
pub(crate) fn run(self) -> Result<()> { pub(crate) fn run(self) -> Result<()> {
if cfg!(target_os = "macos") { if cfg!(target_os = "macos") {
fix_path_for_mac().context("Fix path for mac")? fix_path_for_mac().context("Fix path for mac")?;
} }
if let Some(server) = self.server() { if let Some(server) = self.server() {
install_server(server).context("install server")?; install_server(server).context("install server")?;
@ -148,7 +148,7 @@ fn install_server(opts: ServerOpt) -> Result<()> {
eprintln!( eprintln!(
"\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n", "\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n",
REQUIRED_RUST_VERSION, REQUIRED_RUST_VERSION,
) );
} }
let features = match opts.malloc { let features = match opts.malloc {
Malloc::System => &[][..], Malloc::System => &[][..],

View file

@ -33,15 +33,13 @@ impl flags::Release {
let commit = cmd!("git rev-parse HEAD").read()?; let commit = cmd!("git rev-parse HEAD").read()?;
let changelog_n = read_dir(changelog_dir.as_path())?.len(); let changelog_n = read_dir(changelog_dir.as_path())?.len();
for &adoc in [ for adoc in [
"manual.adoc", "manual.adoc",
"generated_assists.adoc", "generated_assists.adoc",
"generated_config.adoc", "generated_config.adoc",
"generated_diagnostic.adoc", "generated_diagnostic.adoc",
"generated_features.adoc", "generated_features.adoc",
] ] {
.iter()
{
let src = project_root().join("./docs/user/").join(adoc); let src = project_root().join("./docs/user/").join(adoc);
let dst = website_root.join(adoc); let dst = website_root.join(adoc);