Merge #10440
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:
commit
86c534f244
@ -179,7 +179,7 @@ fn run(mut self, inbox: Receiver<Restart>) {
|
||||
tracing::error!(
|
||||
"Flycheck failed to run the following command: {:?}",
|
||||
self.check_command()
|
||||
)
|
||||
);
|
||||
}
|
||||
self.progress(Progress::DidFinish(res));
|
||||
}
|
||||
@ -253,14 +253,14 @@ fn check_command(&self) -> Command {
|
||||
}
|
||||
|
||||
fn send(&self, check_task: Message) {
|
||||
(self.sender)(check_task)
|
||||
(self.sender)(check_task);
|
||||
}
|
||||
}
|
||||
|
||||
struct CargoHandle {
|
||||
child: JodChild,
|
||||
#[allow(unused)]
|
||||
thread: jod_thread::JoinHandle<io::Result<bool>>,
|
||||
thread: jod_thread::JoinHandle<bool>,
|
||||
receiver: Receiver<CargoMessage>,
|
||||
}
|
||||
|
||||
@ -279,7 +279,7 @@ fn join(mut self) -> io::Result<()> {
|
||||
// It is okay to ignore the result, as it only errors if the process is already dead
|
||||
let _ = self.child.kill();
|
||||
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 {
|
||||
// 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
|
||||
@ -304,7 +304,7 @@ impl CargoActor {
|
||||
fn new(child_stdout: process::ChildStdout, sender: Sender<CargoMessage>) -> CargoActor {
|
||||
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
|
||||
// stream deserializers, because the deserializer cannot recover
|
||||
// from an error, resulting in it getting stuck, because we try to
|
||||
@ -334,20 +334,20 @@ fn run(self) -> io::Result<bool> {
|
||||
// Skip certain kinds of messages to only spend time on what's useful
|
||||
JsonMessage::Cargo(message) => match message {
|
||||
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) => {
|
||||
self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap()
|
||||
self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap();
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1119,7 +1119,7 @@ pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
|
||||
if let ast::Expr::RecordExpr(record_expr) =
|
||||
&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(
|
||||
MissingFields {
|
||||
file: source_ptr.file_id,
|
||||
@ -1143,7 +1143,7 @@ pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
|
||||
if let Some(expr) = source_ptr.value.as_ref().left() {
|
||||
let root = source_ptr.file_syntax(db.upcast());
|
||||
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(
|
||||
MissingFields {
|
||||
file: source_ptr.file_id,
|
||||
@ -2119,10 +2119,9 @@ pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<I
|
||||
};
|
||||
|
||||
let fp = TyFingerprint::for_inherent_impl(&ty);
|
||||
let fp = if let Some(fp) = fp {
|
||||
fp
|
||||
} else {
|
||||
return Vec::new();
|
||||
let fp = match fp {
|
||||
Some(fp) => fp,
|
||||
None => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut all = Vec::new();
|
||||
|
@ -474,10 +474,9 @@ fn maybe_collect_expr(&mut self, expr: ast::Expr) -> Option<ExprId> {
|
||||
}
|
||||
ast::Expr::PrefixExpr(e) => {
|
||||
let expr = self.collect_expr_opt(e.expr());
|
||||
if let Some(op) = e.op_kind() {
|
||||
self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
|
||||
} else {
|
||||
self.alloc_expr(Expr::Missing, syntax_ptr)
|
||||
match e.op_kind() {
|
||||
Some(op) => self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr),
|
||||
None => self.alloc_expr(Expr::Missing, syntax_ptr),
|
||||
}
|
||||
}
|
||||
ast::Expr::ClosureExpr(e) => {
|
||||
@ -624,10 +623,9 @@ fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
|
||||
}
|
||||
|
||||
fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
|
||||
if let Some(expr) = expr {
|
||||
self.collect_expr(expr)
|
||||
} else {
|
||||
self.missing_expr()
|
||||
match expr {
|
||||
Some(expr) => self.collect_expr(expr),
|
||||
None => self.missing_expr(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -724,10 +722,9 @@ fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
|
||||
}
|
||||
|
||||
fn collect_block_opt(&mut self, expr: Option<ast::BlockExpr>) -> ExprId {
|
||||
if let Some(block) = expr {
|
||||
self.collect_block(block)
|
||||
} else {
|
||||
self.missing_expr()
|
||||
match expr {
|
||||
Some(block) => self.collect_block(block),
|
||||
None => self.missing_expr(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -890,10 +887,9 @@ fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
|
||||
}
|
||||
|
||||
fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
|
||||
if let Some(pat) = pat {
|
||||
self.collect_pat(pat)
|
||||
} else {
|
||||
self.missing_pat()
|
||||
match pat {
|
||||
Some(pat) => self.collect_pat(pat),
|
||||
None => self.missing_pat(),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -209,10 +209,9 @@ fn find_path_inner(
|
||||
) {
|
||||
path.push_segment(name);
|
||||
|
||||
let new_path = if let Some(best_path) = best_path {
|
||||
select_best_path(best_path, path, prefer_no_std)
|
||||
} else {
|
||||
path
|
||||
let new_path = match best_path {
|
||||
Some(best_path) => select_best_path(best_path, path, prefer_no_std),
|
||||
None => path,
|
||||
};
|
||||
best_path_len = new_path.len();
|
||||
best_path = Some(new_path);
|
||||
@ -243,10 +242,9 @@ fn find_path_inner(
|
||||
});
|
||||
|
||||
for path in extern_paths {
|
||||
let new_path = if let Some(best_path) = best_path {
|
||||
select_best_path(best_path, path, prefer_no_std)
|
||||
} else {
|
||||
path
|
||||
let new_path = match best_path {
|
||||
Some(best_path) => select_best_path(best_path, path, prefer_no_std),
|
||||
None => path,
|
||||
};
|
||||
best_path = Some(new_path);
|
||||
}
|
||||
@ -261,12 +259,11 @@ fn find_path_inner(
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(prefix) = prefixed.map(PrefixKind::prefix) {
|
||||
best_path.or_else(|| {
|
||||
match prefixed.map(PrefixKind::prefix) {
|
||||
Some(prefix) => best_path.or_else(|| {
|
||||
scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
|
||||
})
|
||||
} else {
|
||||
best_path
|
||||
}),
|
||||
None => best_path,
|
||||
}
|
||||
}
|
||||
|
||||
@ -346,15 +343,13 @@ fn find_local_import_locations(
|
||||
|
||||
if let Some((name, vis)) = data.scope.name_of(item) {
|
||||
if vis.is_visible_from(db, from) {
|
||||
let is_private = if let Visibility::Module(private_to) = vis {
|
||||
private_to.local_id == module.local_id
|
||||
} else {
|
||||
false
|
||||
let is_private = match vis {
|
||||
Visibility::Module(private_to) => private_to.local_id == module.local_id,
|
||||
Visibility::Public => false,
|
||||
};
|
||||
let is_original_def = if let Some(module_def_id) = item.as_module_def_id() {
|
||||
data.scope.declarations().any(|it| it == module_def_id)
|
||||
} else {
|
||||
false
|
||||
let is_original_def = match item.as_module_def_id() {
|
||||
Some(module_def_id) => data.scope.declarations().any(|it| it == module_def_id),
|
||||
None => false,
|
||||
};
|
||||
|
||||
// Ignore private imports. these could be used if we are
|
||||
|
@ -475,10 +475,9 @@ fn lookup(tree: &ItemTree, index: Idx<Self>) -> &Self {
|
||||
}
|
||||
|
||||
fn id_from_mod_item(mod_item: ModItem) -> Option<FileItemTreeId<Self>> {
|
||||
if let ModItem::$typ(id) = mod_item {
|
||||
Some(id)
|
||||
} else {
|
||||
None
|
||||
match mod_item {
|
||||
ModItem::$typ(id) => Some(id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -400,13 +400,10 @@ fn resolve_name_in_module(
|
||||
};
|
||||
let from_scope_or_builtin = match shadow {
|
||||
BuiltinShadowMode::Module => from_scope.or(from_builtin),
|
||||
BuiltinShadowMode::Other => {
|
||||
if let Some(ModuleDefId::ModuleId(_)) = from_scope.take_types() {
|
||||
from_builtin.or(from_scope)
|
||||
} else {
|
||||
from_scope.or(from_builtin)
|
||||
}
|
||||
}
|
||||
BuiltinShadowMode::Other => match from_scope.take_types() {
|
||||
Some(ModuleDefId::ModuleId(_)) => from_builtin.or(from_scope),
|
||||
Some(_) | None => from_scope.or(from_builtin),
|
||||
},
|
||||
};
|
||||
let from_extern_prelude = self
|
||||
.extern_prelude
|
||||
|
@ -18,10 +18,9 @@ pub(crate) fn convert_path(
|
||||
path: ast::Path,
|
||||
hygiene: &Hygiene,
|
||||
) -> Option<ModPath> {
|
||||
let prefix = if let Some(qual) = path.qualifier() {
|
||||
Some(convert_path(db, prefix, qual, hygiene)?)
|
||||
} else {
|
||||
prefix
|
||||
let prefix = match path.qualifier() {
|
||||
Some(qual) => Some(convert_path(db, prefix, qual, hygiene)?),
|
||||
None => prefix,
|
||||
};
|
||||
|
||||
let segment = path.segment()?;
|
||||
|
@ -214,10 +214,9 @@ pub fn from_ast(ctx: &LowerCtx, node: ast::Type) -> Self {
|
||||
}
|
||||
|
||||
pub(crate) fn from_ast_opt(ctx: &LowerCtx, node: Option<ast::Type>) -> Self {
|
||||
if let Some(node) = node {
|
||||
TypeRef::from_ast(ctx, node)
|
||||
} else {
|
||||
TypeRef::Error
|
||||
match node {
|
||||
Some(node) => TypeRef::from_ast(ctx, node),
|
||||
None => TypeRef::Error,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -48,10 +48,9 @@ const fn new_inline(text: &str) -> Name {
|
||||
|
||||
/// Resolve a name from the text of token.
|
||||
fn resolve(raw_text: &str) -> Name {
|
||||
if let Some(text) = raw_text.strip_prefix("r#") {
|
||||
Name::new_text(SmolStr::new(text))
|
||||
} else {
|
||||
Name::new_text(raw_text.into())
|
||||
match raw_text.strip_prefix("r#") {
|
||||
Some(text) => Name::new_text(SmolStr::new(text)),
|
||||
None => Name::new_text(raw_text.into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -109,10 +109,9 @@ pub(crate) fn deref(
|
||||
ty: InEnvironment<&Canonical<Ty>>,
|
||||
) -> Option<Canonical<Ty>> {
|
||||
let _p = profile::span("deref");
|
||||
if let Some(derefed) = builtin_deref(&ty.goal.value) {
|
||||
Some(Canonical { value: derefed, binders: ty.goal.binders.clone() })
|
||||
} else {
|
||||
deref_by_trait(db, krate, ty)
|
||||
match builtin_deref(&ty.goal.value) {
|
||||
Some(derefed) => Some(Canonical { value: derefed, binders: ty.goal.binders.clone() }),
|
||||
None => deref_by_trait(db, krate, ty),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -104,10 +104,9 @@ fn as_tuple(&self) -> Option<&Substitution> {
|
||||
}
|
||||
|
||||
fn as_fn_def(&self, db: &dyn HirDatabase) -> Option<FunctionId> {
|
||||
if let Some(CallableDefId::FunctionId(func)) = self.callable_def(db) {
|
||||
Some(func)
|
||||
} else {
|
||||
None
|
||||
match self.callable_def(db) {
|
||||
Some(CallableDefId::FunctionId(func)) => Some(func),
|
||||
Some(CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_)) | None => None,
|
||||
}
|
||||
}
|
||||
fn as_reference(&self) -> Option<(&Ty, Lifetime, Mutability)> {
|
||||
|
@ -105,10 +105,9 @@ fn from_bool(value: bool) -> IntRange {
|
||||
|
||||
#[inline]
|
||||
fn from_range(lo: u128, hi: u128, scalar_ty: Scalar) -> IntRange {
|
||||
if let Scalar::Bool = scalar_ty {
|
||||
IntRange { range: lo..=hi }
|
||||
} else {
|
||||
unimplemented!()
|
||||
match scalar_ty {
|
||||
Scalar::Bool => IntRange { range: lo..=hi },
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -167,10 +167,9 @@ pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError>
|
||||
}
|
||||
|
||||
pub fn should_truncate(&self) -> bool {
|
||||
if let Some(max_size) = self.max_size {
|
||||
self.curr_size >= max_size
|
||||
} else {
|
||||
false
|
||||
match self.max_size {
|
||||
Some(max_size) => self.curr_size >= max_size,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -264,10 +264,9 @@ fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
|
||||
|
||||
// collect explicitly written argument types
|
||||
for arg_type in arg_types.iter() {
|
||||
let arg_ty = if let Some(type_ref) = arg_type {
|
||||
self.make_ty(type_ref)
|
||||
} else {
|
||||
self.table.new_type_var()
|
||||
let arg_ty = match arg_type {
|
||||
Some(type_ref) => self.make_ty(type_ref),
|
||||
None => self.table.new_type_var(),
|
||||
};
|
||||
sig_tys.push(arg_ty);
|
||||
}
|
||||
|
@ -204,10 +204,9 @@ pub(super) fn infer_pat(
|
||||
} else {
|
||||
BindingMode::convert(*mode)
|
||||
};
|
||||
let inner_ty = if let Some(subpat) = subpat {
|
||||
self.infer_pat(*subpat, &expected, default_bm)
|
||||
} else {
|
||||
expected
|
||||
let inner_ty = match subpat {
|
||||
Some(subpat) => self.infer_pat(*subpat, &expected, default_bm),
|
||||
None => expected,
|
||||
};
|
||||
let inner_ty = self.insert_type_vars_shallow(inner_ty);
|
||||
|
||||
|
@ -324,10 +324,9 @@ pub(crate) fn resolve_completely<T>(&mut self, t: T) -> T::Result
|
||||
|
||||
/// Unify two types and register new trait goals that arise from that.
|
||||
pub(crate) fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
|
||||
let result = if let Ok(r) = self.try_unify(ty1, ty2) {
|
||||
r
|
||||
} else {
|
||||
return false;
|
||||
let result = match self.try_unify(ty1, ty2) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return false,
|
||||
};
|
||||
self.register_infer_ok(result);
|
||||
true
|
||||
|
@ -369,10 +369,9 @@ fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
|
||||
Some((it, None)) => it,
|
||||
_ => return None,
|
||||
};
|
||||
if let TypeNs::GenericParam(param_id) = resolution {
|
||||
Some(param_id)
|
||||
} else {
|
||||
None
|
||||
match resolution {
|
||||
TypeNs::GenericParam(param_id) => Some(param_id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -82,10 +82,9 @@ pub fn for_trait_impl(ty: &Ty) -> Option<TyFingerprint> {
|
||||
TyKind::Ref(_, _, ty) => return TyFingerprint::for_trait_impl(ty),
|
||||
TyKind::Tuple(_, subst) => {
|
||||
let first_ty = subst.interned().get(0).map(|arg| arg.assert_ty_ref(&Interner));
|
||||
if let Some(ty) = first_ty {
|
||||
return TyFingerprint::for_trait_impl(ty);
|
||||
} else {
|
||||
TyFingerprint::Unit
|
||||
match first_ty {
|
||||
Some(ty) => return TyFingerprint::for_trait_impl(ty),
|
||||
None => TyFingerprint::Unit,
|
||||
}
|
||||
}
|
||||
TyKind::AssociatedType(_, _)
|
||||
|
@ -195,10 +195,9 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour
|
||||
mismatch.expected.display_test(&db),
|
||||
mismatch.actual.display_test(&db)
|
||||
);
|
||||
if let Some(annotation) = mismatches.remove(&range) {
|
||||
assert_eq!(actual, annotation);
|
||||
} else {
|
||||
format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual);
|
||||
match mismatches.remove(&range) {
|
||||
Some(annotation) => assert_eq!(actual, annotation),
|
||||
None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
|
||||
}
|
||||
}
|
||||
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.actual.display_test(&db)
|
||||
);
|
||||
if let Some(annotation) = mismatches.remove(&range) {
|
||||
assert_eq!(actual, annotation);
|
||||
} else {
|
||||
format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual);
|
||||
match mismatches.remove(&range) {
|
||||
Some(annotation) => assert_eq!(actual, annotation),
|
||||
None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -292,10 +292,9 @@ impl TryToNav for hir::Impl {
|
||||
fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
|
||||
let src = self.source(db)?;
|
||||
let derive_attr = self.is_builtin_derive(db);
|
||||
let frange = if let Some(item) = &derive_attr {
|
||||
item.syntax().original_file_range(db)
|
||||
} else {
|
||||
src.syntax().original_file_range(db)
|
||||
let frange = match &derive_attr {
|
||||
Some(item) => item.syntax().original_file_range(db),
|
||||
None => src.syntax().original_file_range(db),
|
||||
};
|
||||
let focus_range = if derive_attr.is_some() {
|
||||
None
|
||||
|
@ -136,10 +136,9 @@ fn remove_newline(
|
||||
}
|
||||
T!['}'] => {
|
||||
// Removes: comma, newline (incl. surrounding whitespace)
|
||||
let space = if let Some(left) = prev.prev_sibling_or_token() {
|
||||
compute_ws(left.kind(), next.kind())
|
||||
} else {
|
||||
" "
|
||||
let space = match prev.prev_sibling_or_token() {
|
||||
Some(left) => compute_ws(left.kind(), next.kind()),
|
||||
None => " ",
|
||||
};
|
||||
edit.replace(
|
||||
TextRange::new(prev.text_range().start(), token.text_range().end()),
|
||||
|
@ -156,7 +156,7 @@ fn rename_to_self(sema: &Semantics<RootDatabase>, local: hir::Local) -> RenameRe
|
||||
_ => 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");
|
||||
}
|
||||
|
||||
|
@ -103,10 +103,9 @@ fn add_file(&mut self, file_id: FileId) {
|
||||
for token in tokens {
|
||||
let range = token.text_range();
|
||||
let node = token.parent().unwrap();
|
||||
let def = if let Some(x) = get_definition(&sema, token.clone()) {
|
||||
x
|
||||
} else {
|
||||
continue;
|
||||
let def = match get_definition(&sema, token.clone()) {
|
||||
Some(x) => x,
|
||||
None => continue,
|
||||
};
|
||||
let id = if let Some(x) = self.def_map.get(&def) {
|
||||
*x
|
||||
@ -124,10 +123,9 @@ fn add_file(&mut self, file_id: FileId) {
|
||||
let token = self.tokens.get_mut(id).unwrap();
|
||||
token.references.push(ReferenceData {
|
||||
range: FileRange { range, file_id },
|
||||
is_definition: if let Some(x) = def.try_to_nav(self.db) {
|
||||
x.file_id == file_id && x.focus_or_full_range() == range
|
||||
} else {
|
||||
false
|
||||
is_definition: match def.try_to_nav(self.db) {
|
||||
Some(x) => x.file_id == file_id && x.focus_or_full_range() == range,
|
||||
None => false,
|
||||
},
|
||||
});
|
||||
result.tokens.push((range, id));
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
|
@ -44,7 +44,7 @@ pub(crate) fn convert_while_to_loop(acc: &mut Assists, ctx: &AssistContext) -> O
|
||||
let cond = while_expr.condition()?;
|
||||
|
||||
// Don't handle while let
|
||||
if let Some(_) = cond.pat() {
|
||||
if cond.pat().is_some() {
|
||||
return None;
|
||||
};
|
||||
|
||||
|
@ -827,10 +827,9 @@ fn extracted_function_params(
|
||||
locals
|
||||
.map(|local| (local, local.source(ctx.db())))
|
||||
.filter(|(_, src)| is_defined_outside_of_body(ctx, self, src))
|
||||
.filter_map(|(local, src)| {
|
||||
if let Either::Left(src) = src.value {
|
||||
Some((local, src))
|
||||
} else {
|
||||
.filter_map(|(local, src)| match src.value {
|
||||
Either::Left(src) => Some((local, src)),
|
||||
Either::Right(_) => {
|
||||
stdx::never!(false, "Local::is_self returned false, but source is SelfParam");
|
||||
None
|
||||
}
|
||||
|
@ -76,10 +76,11 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option
|
||||
None => to_extract.syntax().text_range(),
|
||||
};
|
||||
|
||||
if let Anchor::WrapInBlock(_) = anchor {
|
||||
format_to!(buf, "{{ let {} = ", var_name);
|
||||
} else {
|
||||
format_to!(buf, "let {} = ", var_name);
|
||||
match anchor {
|
||||
Anchor::Before(_) | Anchor::Replace(_) => {
|
||||
format_to!(buf, "let {} = ", var_name)
|
||||
}
|
||||
Anchor::WrapInBlock(_) => format_to!(buf, "{{ let {} = ", var_name),
|
||||
};
|
||||
format_to!(buf, "{}", to_extract.syntax());
|
||||
|
||||
|
@ -192,10 +192,9 @@ fn to_string(&self, cap: Option<SnippetCap>) -> String {
|
||||
Some(cap) => {
|
||||
let cursor = if self.should_focus_return_type {
|
||||
// Focus the return type if there is one
|
||||
if let Some(ref ret_type) = self.ret_type {
|
||||
ret_type.syntax()
|
||||
} else {
|
||||
self.tail_expr.syntax()
|
||||
match self.ret_type {
|
||||
Some(ref ret_type) => ret_type.syntax(),
|
||||
None => self.tail_expr.syntax(),
|
||||
}
|
||||
} else {
|
||||
self.tail_expr.syntax()
|
||||
@ -428,10 +427,9 @@ fn fn_args(
|
||||
arg_types.push(match fn_arg_type(ctx, target_module, &arg) {
|
||||
Some(ty) => {
|
||||
if !ty.is_empty() && ty.starts_with('&') {
|
||||
if let Some((new_ty, _)) = useless_type_special_case("", &ty[1..].to_owned()) {
|
||||
new_ty
|
||||
} else {
|
||||
ty
|
||||
match useless_type_special_case("", &ty[1..].to_owned()) {
|
||||
Some((new_ty, _)) => new_ty,
|
||||
None => ty,
|
||||
}
|
||||
} else {
|
||||
ty
|
||||
@ -523,11 +521,7 @@ fn fn_arg_type(
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Ok(rendered) = ty.display_source_code(ctx.db(), target_module.into()) {
|
||||
Some(rendered)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
ty.display_source_code(ctx.db(), target_module.into()).ok()
|
||||
}
|
||||
|
||||
/// Returns the position inside the current mod or file
|
||||
@ -560,20 +554,14 @@ fn next_space_for_fn_in_module(
|
||||
) -> Option<(FileId, GeneratedFunctionTarget)> {
|
||||
let file = module_source.file_id.original_file(db);
|
||||
let assist_item = match &module_source.value {
|
||||
hir::ModuleSource::SourceFile(it) => {
|
||||
if let Some(last_item) = it.items().last() {
|
||||
GeneratedFunctionTarget::BehindItem(last_item.syntax().clone())
|
||||
} else {
|
||||
GeneratedFunctionTarget::BehindItem(it.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::SourceFile(it) => match it.items().last() {
|
||||
Some(last_item) => GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()),
|
||||
None => 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::BlockExpr(it) => {
|
||||
if let Some(last_item) =
|
||||
it.statements().take_while(|stmt| matches!(stmt, ast::Stmt::Item(_))).last()
|
||||
|
@ -141,10 +141,9 @@ pub(crate) fn inline_into_callers(acc: &mut Assists, ctx: &AssistContext) -> Opt
|
||||
for (file_id, refs) in usages.into_iter() {
|
||||
inline_refs_for_file(file_id, refs);
|
||||
}
|
||||
if let Some(refs) = current_file_usage {
|
||||
inline_refs_for_file(def_file, refs);
|
||||
} else {
|
||||
builder.edit_file(def_file);
|
||||
match current_file_usage {
|
||||
Some(refs) => inline_refs_for_file(def_file, refs),
|
||||
None => builder.edit_file(def_file),
|
||||
}
|
||||
if remove_def {
|
||||
builder.delete(ast_func.syntax().text_range());
|
||||
|
@ -127,12 +127,9 @@ fn collect_if(&mut self, if_expr: &ast::IfExpr) -> Option<()> {
|
||||
}
|
||||
}
|
||||
fn collect_block(&mut self, block: &ast::BlockExpr) -> Option<()> {
|
||||
let last_expr = block.tail_expr().or_else(|| {
|
||||
if let ast::Stmt::ExprStmt(stmt) = block.statements().last()? {
|
||||
stmt.expr()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let last_expr = block.tail_expr().or_else(|| match block.statements().last()? {
|
||||
ast::Stmt::ExprStmt(stmt) => stmt.expr(),
|
||||
ast::Stmt::Item(_) | ast::Stmt::LetStmt(_) => None,
|
||||
})?;
|
||||
|
||||
if let ast::Expr::BinExpr(expr) = last_expr {
|
||||
|
@ -181,10 +181,9 @@ fn find_trait_method(
|
||||
fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option<hir::Trait> {
|
||||
let item_module_def = item.as_module_def()?;
|
||||
|
||||
if let hir::ModuleDef::Trait(trait_) = item_module_def {
|
||||
Some(trait_)
|
||||
} else {
|
||||
item_module_def.as_assoc_item(db)?.containing_trait(db)
|
||||
match item_module_def {
|
||||
hir::ModuleDef::Trait(trait_) => Some(trait_),
|
||||
_ => item_module_def.as_assoc_item(db)?.containing_trait(db),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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))
|
||||
}
|
||||
ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => {
|
||||
if let ast::Expr::ParenExpr(parexpr) = pe.expr()? {
|
||||
parexpr.expr()
|
||||
} else {
|
||||
pe.expr()
|
||||
}
|
||||
}
|
||||
ast::Expr::PrefixExpr(pe) if pe.op_kind()? == ast::UnaryOp::Not => match pe.expr()? {
|
||||
ast::Expr::ParenExpr(parexpr) => parexpr.expr(),
|
||||
_ => pe.expr(),
|
||||
},
|
||||
ast::Expr::Literal(lit) => match lit.kind() {
|
||||
ast::LiteralKind::Bool(b) => match b {
|
||||
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 pat_head = match pat {
|
||||
ast::Pat::IdentPat(bind_pat) => {
|
||||
if let Some(p) = bind_pat.pat() {
|
||||
first_node_text(&p)
|
||||
} else {
|
||||
return pat.syntax().text() == var.syntax().text();
|
||||
}
|
||||
}
|
||||
ast::Pat::IdentPat(bind_pat) => match bind_pat.pat() {
|
||||
Some(p) => first_node_text(&p),
|
||||
None => return pat.syntax().text() == var.syntax().text(),
|
||||
},
|
||||
pat => first_node_text(pat),
|
||||
};
|
||||
|
||||
|
@ -144,10 +144,9 @@ fn is_valid_name(name: &str) -> bool {
|
||||
fn is_useless_method(method: &ast::MethodCallExpr) -> bool {
|
||||
let ident = method.name_ref().and_then(|it| it.ident_token());
|
||||
|
||||
if let Some(ident) = ident {
|
||||
USELESS_METHODS.contains(&ident.text())
|
||||
} else {
|
||||
false
|
||||
match ident {
|
||||
Some(ident) => USELESS_METHODS.contains(&ident.text()),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -509,10 +509,9 @@ fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
|
||||
.and_then(|pat| self.sema.type_of_pat(&pat))
|
||||
.or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)))
|
||||
.map(TypeInfo::original);
|
||||
let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
|
||||
ident.name().map(NameOrNameRef::Name)
|
||||
} else {
|
||||
None
|
||||
let name = match it.pat() {
|
||||
Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
|
||||
Some(_) | None => None,
|
||||
};
|
||||
|
||||
(ty, name)
|
||||
|
@ -74,10 +74,9 @@ fn new(
|
||||
|
||||
fn render(self, import_to_add: Option<ImportEdit>) -> CompletionItem {
|
||||
let params = self.params();
|
||||
let call = if let Some(receiver) = &self.receiver {
|
||||
format!("{}.{}", receiver, &self.name)
|
||||
} else {
|
||||
self.name.clone()
|
||||
let call = match &self.receiver {
|
||||
Some(receiver) => format!("{}.{}", receiver, &self.name),
|
||||
None => self.name.clone(),
|
||||
};
|
||||
let mut item =
|
||||
CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), call.clone());
|
||||
|
@ -63,10 +63,9 @@ fn build_completion(
|
||||
.set_documentation(ctx.docs(def))
|
||||
.set_deprecated(ctx.is_deprecated(def))
|
||||
.detail(&pat);
|
||||
if let Some(snippet_cap) = ctx.snippet_cap() {
|
||||
item.insert_snippet(snippet_cap, pat);
|
||||
} else {
|
||||
item.insert_text(pat);
|
||||
match ctx.snippet_cap() {
|
||||
Some(snippet_cap) => item.insert_snippet(snippet_cap, pat),
|
||||
None => item.insert_text(pat),
|
||||
};
|
||||
item.build()
|
||||
}
|
||||
|
@ -38,10 +38,9 @@ fn build_completion(
|
||||
.set_documentation(ctx.docs(def))
|
||||
.set_deprecated(ctx.is_deprecated(def))
|
||||
.detail(&literal);
|
||||
if let Some(snippet_cap) = ctx.snippet_cap() {
|
||||
item.insert_snippet(snippet_cap, literal);
|
||||
} else {
|
||||
item.insert_text(literal);
|
||||
match ctx.snippet_cap() {
|
||||
Some(snippet_cap) => item.insert_snippet(snippet_cap, literal),
|
||||
None => item.insert_text(literal),
|
||||
};
|
||||
item.build()
|
||||
}
|
||||
|
@ -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 {
|
||||
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) {
|
||||
cov_mark::hit!(rename_record_pat_field_name_split);
|
||||
// Foo { ref mut field } -> Foo { new_name: ref mut field }
|
||||
|
@ -47,10 +47,9 @@ pub(crate) fn new(
|
||||
) -> Result<ResolvedRule, SsrError> {
|
||||
let resolver =
|
||||
Resolver { resolution_scope, placeholders_by_stand_in: rule.placeholders_by_stand_in };
|
||||
let resolved_template = if let Some(template) = rule.template {
|
||||
Some(resolver.resolve_pattern_tree(template)?)
|
||||
} else {
|
||||
None
|
||||
let resolved_template = match rule.template {
|
||||
Some(template) => Some(resolver.resolve_pattern_tree(template)?),
|
||||
None => None,
|
||||
};
|
||||
Ok(ResolvedRule {
|
||||
pattern: resolver.resolve_pattern_tree(rule.pattern)?,
|
||||
|
@ -67,11 +67,11 @@ pub(crate) fn expr(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) {
|
||||
expressions::stmt(p, expressions::StmtWithSemi::Optional, false)
|
||||
expressions::stmt(p, expressions::StmtWithSemi::Optional, false);
|
||||
}
|
||||
|
||||
pub(crate) fn visibility(p: &mut Parser) {
|
||||
@ -84,7 +84,7 @@ pub(crate) fn meta_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) {
|
||||
@ -109,7 +109,7 @@ pub(crate) fn macro_stmts(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,
|
||||
TOKEN_TREE if first_child? == T!['{'] => items::token_tree,
|
||||
ASSOC_ITEM_LIST => match parent? {
|
||||
IMPL => items::assoc_item_list,
|
||||
TRAIT => items::assoc_item_list,
|
||||
IMPL | TRAIT => items::assoc_item_list,
|
||||
_ => return None,
|
||||
},
|
||||
ITEM_LIST => items::item_list,
|
||||
@ -246,7 +245,7 @@ fn name_r(p: &mut Parser, recovery: TokenSet) {
|
||||
}
|
||||
|
||||
fn name(p: &mut Parser) {
|
||||
name_r(p, TokenSet::EMPTY)
|
||||
name_r(p, TokenSet::EMPTY);
|
||||
}
|
||||
|
||||
fn name_ref(p: &mut Parser) {
|
||||
|
@ -2,13 +2,13 @@
|
||||
|
||||
pub(super) fn inner_attrs(p: &mut Parser) {
|
||||
while p.at(T![#]) && p.nth(1) == T![!] {
|
||||
attr(p, true)
|
||||
attr(p, true);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn outer_attrs(p: &mut Parser) {
|
||||
while p.at(T![#]) {
|
||||
attr(p, false)
|
||||
attr(p, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -139,7 +139,7 @@ pub(super) fn expr_block_contents(p: &mut Parser) {
|
||||
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
|
||||
// fn foo() { xs[..]; }
|
||||
for &op in [T![..=], T![..]].iter() {
|
||||
for op in [T![..=], T![..]] {
|
||||
if p.at(op) {
|
||||
m = p.start();
|
||||
p.bump(op);
|
||||
@ -468,12 +468,12 @@ fn field_expr(p: &mut Parser, lhs: CompletedMarker) -> CompletedMarker {
|
||||
let m = lhs.precede(p);
|
||||
p.bump(T![.]);
|
||||
if p.at(IDENT) || p.at(INT_NUMBER) {
|
||||
name_ref_or_index(p)
|
||||
name_ref_or_index(p);
|
||||
} else if p.at(FLOAT_NUMBER) {
|
||||
// FIXME: How to recover and instead parse INT + T![.]?
|
||||
p.bump_any();
|
||||
} else {
|
||||
p.error("expected field name or number")
|
||||
p.error("expected field name or number");
|
||||
}
|
||||
m.complete(p, FIELD_EXPR)
|
||||
}
|
||||
|
@ -374,7 +374,7 @@ fn match_expr(p: &mut Parser) -> CompletedMarker {
|
||||
if p.at(T!['{']) {
|
||||
match_arm_list(p);
|
||||
} else {
|
||||
p.error("expected `{`")
|
||||
p.error("expected `{`");
|
||||
}
|
||||
m.complete(p, MATCH_EXPR)
|
||||
}
|
||||
@ -602,7 +602,7 @@ fn try_block_expr(p: &mut Parser, m: Option<Marker>) -> CompletedMarker {
|
||||
if p.at(T!['{']) {
|
||||
stmt_list(p);
|
||||
} else {
|
||||
p.error("expected a block")
|
||||
p.error("expected a block");
|
||||
}
|
||||
m.complete(p, BLOCK_EXPR)
|
||||
}
|
||||
@ -639,7 +639,7 @@ fn meta_var_expr(p: &mut Parser) -> CompletedMarker {
|
||||
}
|
||||
_ => {
|
||||
while !p.at(R_DOLLAR) {
|
||||
p.bump_any()
|
||||
p.bump_any();
|
||||
}
|
||||
p.bump(R_DOLLAR);
|
||||
m.complete(p, ERROR)
|
||||
|
@ -34,7 +34,7 @@ fn generic_param(p: &mut Parser) {
|
||||
T![const] => const_param(p, m),
|
||||
_ => {
|
||||
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
|
||||
// struct S<T = i32>;
|
||||
p.bump(T![=]);
|
||||
types::type_(p)
|
||||
types::type_(p);
|
||||
}
|
||||
m.complete(p, TYPE_PARAM);
|
||||
}
|
||||
|
@ -20,7 +20,7 @@
|
||||
pub(super) fn mod_contents(p: &mut Parser, stop_on_r_curly: bool) {
|
||||
attributes::inner_attrs(p);
|
||||
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(T![async]);
|
||||
if is_unsafe {
|
||||
p.bump(T![unsafe])
|
||||
p.bump(T![unsafe]);
|
||||
}
|
||||
has_mods = true;
|
||||
}
|
||||
@ -404,7 +404,7 @@ fn fn_(p: &mut Parser, m: Marker) {
|
||||
// trait T { fn foo(); }
|
||||
p.bump(T![;]);
|
||||
} else {
|
||||
expressions::block_expr(p)
|
||||
expressions::block_expr(p);
|
||||
}
|
||||
m.complete(p, FN);
|
||||
}
|
||||
|
@ -58,7 +58,7 @@ pub(super) fn enum_(p: &mut Parser, m: Marker) {
|
||||
if p.at(T!['{']) {
|
||||
variant_list(p);
|
||||
} else {
|
||||
p.error("expected `{`")
|
||||
p.error("expected `{`");
|
||||
}
|
||||
m.complete(p, ENUM);
|
||||
}
|
||||
|
@ -4,12 +4,12 @@
|
||||
// const C: u32 = 92;
|
||||
pub(super) fn konst(p: &mut Parser, m: Marker) {
|
||||
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) {
|
||||
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) {
|
||||
@ -27,7 +27,7 @@ fn const_or_static(p: &mut Parser, m: Marker, is_const: bool) {
|
||||
if p.at(T![:]) {
|
||||
types::ascription(p);
|
||||
} else {
|
||||
p.error("missing type for `const` or `static`")
|
||||
p.error("missing type for `const` or `static`");
|
||||
}
|
||||
if p.eat(T![=]) {
|
||||
expressions::expr(p);
|
||||
|
@ -6,21 +6,21 @@
|
||||
// fn c(x: i32, ) {}
|
||||
// fn d(x: i32, y: ()) {}
|
||||
pub(super) fn param_list_fn_def(p: &mut Parser) {
|
||||
list_(p, Flavor::FnDef)
|
||||
list_(p, Flavor::FnDef);
|
||||
}
|
||||
|
||||
// test param_list_opt_patterns
|
||||
// fn foo<F: FnMut(&mut Foo<'a>)>(){}
|
||||
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) {
|
||||
list_(p, Flavor::FnPointer)
|
||||
list_(p, Flavor::FnPointer);
|
||||
}
|
||||
|
||||
pub(super) fn param_list_closure(p: &mut Parser) {
|
||||
list_(p, Flavor::Closure)
|
||||
list_(p, Flavor::Closure);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@ -104,13 +104,13 @@ fn param(p: &mut Parser, m: Marker, flavor: Flavor) -> Variadic {
|
||||
Flavor::FnDef => {
|
||||
patterns::pattern(p);
|
||||
if variadic_param(p) {
|
||||
res = Variadic(true)
|
||||
res = Variadic(true);
|
||||
} else if p.at(T![:]) {
|
||||
types::ascription(p)
|
||||
types::ascription(p);
|
||||
} else {
|
||||
// test_err missing_fn_param_type
|
||||
// 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
|
||||
@ -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![::]) {
|
||||
patterns::pattern_single(p);
|
||||
if variadic_param(p) {
|
||||
res = Variadic(true)
|
||||
res = Variadic(true);
|
||||
} else if p.at(T![:]) {
|
||||
types::ascription(p)
|
||||
types::ascription(p);
|
||||
} else {
|
||||
p.error("missing type for function parameter")
|
||||
p.error("missing type for function parameter");
|
||||
}
|
||||
} else {
|
||||
types::type_(p);
|
||||
|
@ -16,15 +16,15 @@ pub(super) fn is_use_path_start(p: &Parser) -> bool {
|
||||
}
|
||||
|
||||
pub(super) fn use_path(p: &mut Parser) {
|
||||
path(p, Mode::Use)
|
||||
path(p, Mode::Use);
|
||||
}
|
||||
|
||||
pub(crate) fn type_path(p: &mut Parser) {
|
||||
path(p, Mode::Type)
|
||||
path(p, Mode::Type);
|
||||
}
|
||||
|
||||
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 {
|
||||
@ -117,7 +117,7 @@ fn opt_path_type_args(p: &mut Parser, mode: Mode) {
|
||||
params::param_list_fn_trait(p);
|
||||
opt_ret_type(p);
|
||||
} 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),
|
||||
|
@ -19,7 +19,7 @@ pub(crate) fn pattern(p: &mut Parser) {
|
||||
|
||||
/// Parses a pattern list separated by pipes `|`.
|
||||
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) {
|
||||
@ -78,7 +78,7 @@ fn pattern_single_r(p: &mut Parser, recovery_set: TokenSet) {
|
||||
|
||||
// FIXME: support half_open_range_patterns (`..=2`),
|
||||
// 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) {
|
||||
let m = lhs.precede(p);
|
||||
p.bump(range_op);
|
||||
|
@ -57,7 +57,7 @@ fn type_with_bounds_cond(p: &mut Parser, allow_bounds: bool) {
|
||||
pub(super) fn ascription(p: &mut Parser) {
|
||||
assert!(p.at(T![:]));
|
||||
p.bump(T![:]);
|
||||
type_(p)
|
||||
type_(p);
|
||||
}
|
||||
|
||||
fn paren_or_tuple_type(p: &mut Parser) {
|
||||
@ -204,7 +204,7 @@ fn fn_ptr_type(p: &mut Parser) {
|
||||
if p.at(T!['(']) {
|
||||
params::param_list_fn_ptr(p);
|
||||
} else {
|
||||
p.error("expected parameters")
|
||||
p.error("expected parameters");
|
||||
}
|
||||
// test fn_pointer_type_with_ret
|
||||
// type F = fn() -> ();
|
||||
@ -274,7 +274,7 @@ fn dyn_trait_type(p: &mut Parser) {
|
||||
// type C = self::Foo;
|
||||
// type D = super::Foo;
|
||||
pub(super) fn path_type(p: &mut Parser) {
|
||||
path_type_(p, true)
|
||||
path_type_(p, true);
|
||||
}
|
||||
|
||||
// test macro_call_type
|
||||
|
@ -177,7 +177,7 @@ pub(crate) fn bump_any(&mut self) {
|
||||
if kind == EOF {
|
||||
return;
|
||||
}
|
||||
self.do_bump(kind, 1)
|
||||
self.do_bump(kind, 1);
|
||||
}
|
||||
|
||||
/// Advances the parser by one token, remapping its kind.
|
||||
@ -200,7 +200,7 @@ pub(crate) fn bump_remap(&mut self, kind: SyntaxKind) {
|
||||
/// does.
|
||||
pub(crate) fn error<T: Into<String>>(&mut self, message: T) {
|
||||
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
|
||||
@ -258,7 +258,7 @@ fn do_bump(&mut self, kind: SyntaxKind, n_raw_tokens: u8) {
|
||||
}
|
||||
|
||||
fn push_event(&mut self, event: Event) {
|
||||
self.events.push(event)
|
||||
self.events.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -14,7 +14,7 @@ pub(crate) const fn new(kinds: &[SyntaxKind]) -> TokenSet {
|
||||
let mut i = 0;
|
||||
while i < kinds.len() {
|
||||
res |= mask(kinds[i]);
|
||||
i += 1
|
||||
i += 1;
|
||||
}
|
||||
TokenSet(res)
|
||||
}
|
||||
|
@ -271,7 +271,7 @@ pub fn new_unchecked(path: &Path) -> &RelPath {
|
||||
/// Taken from <https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85>
|
||||
fn normalize_path(path: &Path) -> PathBuf {
|
||||
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();
|
||||
PathBuf::from(c.as_os_str())
|
||||
} else {
|
||||
|
@ -246,7 +246,7 @@ fn subtree(&mut self, idx: usize, subtree: &'a tt::Subtree) {
|
||||
|
||||
fn enqueue(&mut self, subtree: &'a tt::Subtree) -> u32 {
|
||||
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);
|
||||
self.subtree.push(SubtreeRepr { id: delimiter_id, kind: delimiter_kind, tt: [!0, !0] });
|
||||
self.work.push_back((idx, subtree));
|
||||
@ -320,7 +320,7 @@ pub(crate) fn read(self) -> tt::Subtree {
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
res[i] = Some(s)
|
||||
res[i] = Some(s);
|
||||
}
|
||||
|
||||
res[0].take().unwrap()
|
||||
|
@ -497,10 +497,9 @@ fn suffix(&mut self, _literal: &Self::Literal) -> Option<String> {
|
||||
}
|
||||
|
||||
fn integer(&mut self, n: &str) -> Self::Literal {
|
||||
let n = if let Ok(n) = n.parse::<i128>() {
|
||||
n.to_string()
|
||||
} else {
|
||||
n.parse::<u128>().unwrap().to_string()
|
||||
let n = match n.parse::<i128>() {
|
||||
Ok(n) => n.to_string(),
|
||||
Err(_) => n.parse::<u128>().unwrap().to_string(),
|
||||
};
|
||||
Literal { text: n.into(), id: tt::TokenId::unspecified() }
|
||||
}
|
||||
|
@ -500,10 +500,9 @@ fn suffix(&mut self, _literal: &Self::Literal) -> Option<String> {
|
||||
}
|
||||
|
||||
fn integer(&mut self, n: &str) -> Self::Literal {
|
||||
let n = if let Ok(n) = n.parse::<i128>() {
|
||||
n.to_string()
|
||||
} else {
|
||||
n.parse::<u128>().unwrap().to_string()
|
||||
let n = match n.parse::<i128>() {
|
||||
Ok(n) => n.to_string(),
|
||||
Err(_) => n.parse::<u128>().unwrap().to_string(),
|
||||
};
|
||||
Literal { text: n.into(), id: tt::TokenId::unspecified() }
|
||||
}
|
||||
|
@ -504,10 +504,9 @@ fn to_string(&mut self, literal: &Self::Literal) -> String {
|
||||
}
|
||||
|
||||
fn integer(&mut self, n: &str) -> Self::Literal {
|
||||
let n = if let Ok(n) = n.parse::<i128>() {
|
||||
n.to_string()
|
||||
} else {
|
||||
n.parse::<u128>().unwrap().to_string()
|
||||
let n = match n.parse::<i128>() {
|
||||
Ok(n) => n.to_string(),
|
||||
Err(_) => n.parse::<u128>().unwrap().to_string(),
|
||||
};
|
||||
Literal { text: n.into(), id: tt::TokenId::unspecified() }
|
||||
}
|
||||
|
@ -93,7 +93,7 @@ struct ProfilerImpl {
|
||||
impl ProfileSpan {
|
||||
pub fn detail(mut self, detail: impl FnOnce() -> String) -> ProfileSpan {
|
||||
if let Some(profiler) = &mut self.0 {
|
||||
profiler.detail = Some(detail())
|
||||
profiler.detail = Some(detail());
|
||||
}
|
||||
self
|
||||
}
|
||||
@ -114,7 +114,7 @@ impl HeartbeatSpan {
|
||||
#[inline]
|
||||
pub fn new(enabled: bool) -> Self {
|
||||
if enabled {
|
||||
with_profile_stack(|it| it.heartbeats(true))
|
||||
with_profile_stack(|it| it.heartbeats(true));
|
||||
}
|
||||
Self { enabled }
|
||||
}
|
||||
@ -123,7 +123,7 @@ pub fn new(enabled: bool) -> Self {
|
||||
impl Drop for HeartbeatSpan {
|
||||
fn drop(&mut self) {
|
||||
if self.enabled {
|
||||
with_profile_stack(|it| it.heartbeats(false))
|
||||
with_profile_stack(|it| it.heartbeats(false));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -238,7 +238,7 @@ fn pop(&mut self, label: Label, detail: Option<String>) {
|
||||
self.heartbeat(frame.heartbeats);
|
||||
let avg_span = duration / (frame.heartbeats + 1);
|
||||
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;
|
||||
|
||||
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 {
|
||||
let (total_duration, cnt) =
|
||||
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)
|
||||
.expect("printing profiling info");
|
||||
}
|
||||
|
@ -92,7 +92,7 @@ pub fn cpu_span() -> CpuSpan {
|
||||
{
|
||||
eprintln!(
|
||||
r#"cpu profiling is disabled, uncomment `default = [ "cpu_profiler" ]` in Cargo.toml to enable."#
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
CpuSpan { _private: () }
|
||||
|
@ -70,15 +70,15 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let mut prefix = "";
|
||||
if instructions > 10000 {
|
||||
instructions /= 1000;
|
||||
prefix = "k"
|
||||
prefix = "k";
|
||||
}
|
||||
if instructions > 10000 {
|
||||
instructions /= 1000;
|
||||
prefix = "m"
|
||||
prefix = "m";
|
||||
}
|
||||
if instructions > 10000 {
|
||||
instructions /= 1000;
|
||||
prefix = "g"
|
||||
prefix = "g";
|
||||
}
|
||||
write!(f, ", {}{}instr", instructions, prefix)?;
|
||||
}
|
||||
|
@ -4,7 +4,7 @@
|
||||
|
||||
fn main() {
|
||||
set_rerun();
|
||||
println!("cargo:rustc-env=REV={}", rev())
|
||||
println!("cargo:rustc-env=REV={}", rev());
|
||||
}
|
||||
|
||||
fn set_rerun() {
|
||||
|
@ -427,10 +427,9 @@ fn decide_search_scope_and_kind(
|
||||
// If no explicit marker was set, check request params. If that's also empty
|
||||
// use global config.
|
||||
if !all_symbols {
|
||||
let search_kind = if let Some(ref search_kind) = params.search_kind {
|
||||
search_kind
|
||||
} else {
|
||||
&config.search_kind
|
||||
let search_kind = match params.search_kind {
|
||||
Some(ref search_kind) => search_kind,
|
||||
None => &config.search_kind,
|
||||
};
|
||||
all_symbols = match search_kind {
|
||||
lsp_ext::WorkspaceSymbolSearchKind::OnlyTypes => false,
|
||||
@ -439,10 +438,9 @@ fn decide_search_scope_and_kind(
|
||||
}
|
||||
|
||||
if !libs {
|
||||
let search_scope = if let Some(ref search_scope) = params.search_scope {
|
||||
search_scope
|
||||
} else {
|
||||
&config.search_scope
|
||||
let search_scope = match params.search_scope {
|
||||
Some(ref search_scope) => search_scope,
|
||||
None => &config.search_scope,
|
||||
};
|
||||
libs = match search_scope {
|
||||
lsp_ext::WorkspaceSymbolSearchScope::Workspace => false,
|
||||
|
@ -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('.');
|
||||
if !is_hidden {
|
||||
if file_type.is_dir() {
|
||||
work.push(path)
|
||||
work.push(path);
|
||||
} else if file_type.is_file() {
|
||||
res.push(path)
|
||||
res.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -66,7 +66,7 @@ pub fn extract(tag: &str, text: &str) -> Vec<CommentBlock> {
|
||||
panic!(
|
||||
"Use plain (non-doc) comments with tags like {}:\n {}",
|
||||
tag, first
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
block.id = id.trim().to_string();
|
||||
@ -106,7 +106,7 @@ pub fn extract_untagged(text: &str) -> Vec<CommentBlock> {
|
||||
}
|
||||
}
|
||||
if !block.contents.is_empty() {
|
||||
res.push(block)
|
||||
res.push(block);
|
||||
}
|
||||
res
|
||||
}
|
||||
@ -139,7 +139,7 @@ fn ensure_rustfmt() {
|
||||
panic!(
|
||||
"Failed to run rustfmt from toolchain 'stable'. \
|
||||
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);
|
||||
}
|
||||
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 {
|
||||
|
@ -45,7 +45,7 @@ fn to_snake_case<F: Fn(&char) -> char>(s: &str, change_case: F) -> String {
|
||||
if c.is_ascii_uppercase() && prev {
|
||||
// This check is required to not translate `Weird_Case` into `weird__case`.
|
||||
if !buf.ends_with('_') {
|
||||
buf.push('_')
|
||||
buf.push('_');
|
||||
}
|
||||
}
|
||||
prev = true;
|
||||
@ -60,7 +60,7 @@ pub fn replace(buf: &mut String, from: char, to: &str) {
|
||||
return;
|
||||
}
|
||||
// FIXME: do this in place.
|
||||
*buf = buf.replace(from, to)
|
||||
*buf = buf.replace(from, to);
|
||||
}
|
||||
|
||||
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> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(f) = self.0.take() {
|
||||
f()
|
||||
f();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -25,19 +25,19 @@ fn init() {
|
||||
if !ctx.is_empty() {
|
||||
eprintln!("Panic context:");
|
||||
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 {
|
||||
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! {
|
||||
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()));
|
||||
}
|
||||
|
@ -42,9 +42,9 @@ pub fn streaming_output(
|
||||
};
|
||||
for line in String::from_utf8_lossy(new_lines).lines() {
|
||||
if is_out {
|
||||
on_stdout_line(line)
|
||||
on_stdout_line(line);
|
||||
} else {
|
||||
on_stderr_line(line)
|
||||
on_stderr_line(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -112,15 +112,15 @@ impl TreeDiff {
|
||||
pub fn into_text_edit(&self, builder: &mut TextEditBuilder) {
|
||||
let _p = profile::span("into_text_edit");
|
||||
|
||||
for (anchor, to) in self.insertions.iter() {
|
||||
for (anchor, to) in &self.insertions {
|
||||
let offset = match anchor {
|
||||
TreeDiffInsertPos::After(it) => it.text_range().end(),
|
||||
TreeDiffInsertPos::AsFirstChild(it) => it.text_range().start(),
|
||||
};
|
||||
to.iter().for_each(|to| builder.insert(offset, to.to_string()));
|
||||
}
|
||||
for (from, to) in self.replacements.iter() {
|
||||
builder.replace(from.text_range(), to.to_string())
|
||||
for (from, to) in &self.replacements {
|
||||
builder.replace(from.text_range(), to.to_string());
|
||||
}
|
||||
for text_range in self.deletions.iter().map(SyntaxElement::text_range) {
|
||||
builder.delete(text_range);
|
||||
@ -217,9 +217,8 @@ fn go(diff: &mut TreeDiff, lhs: SyntaxElement, rhs: SyntaxElement) {
|
||||
cov_mark::hit!(diff_insertions);
|
||||
insert = true;
|
||||
break;
|
||||
} else {
|
||||
look_ahead_scratch.push(rhs_child);
|
||||
}
|
||||
look_ahead_scratch.push(rhs_child);
|
||||
}
|
||||
let drain = look_ahead_scratch.drain(..);
|
||||
if insert {
|
||||
@ -233,7 +232,7 @@ fn go(diff: &mut TreeDiff, lhs: SyntaxElement, rhs: SyntaxElement) {
|
||||
diff.insertions.entry(insert_pos).or_insert_with(Vec::new).extend(drain);
|
||||
rhs_children = rhs_children_clone;
|
||||
} else {
|
||||
go(diff, lhs_ele, rhs_ele)
|
||||
go(diff, lhs_ele, rhs_ele);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -126,7 +126,7 @@ pub(super) fn increase_indent(self, node: &SyntaxNode) {
|
||||
if let Some(ws) = ast::Whitespace::cast(token) {
|
||||
if ws.text().contains('\n') {
|
||||
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 @@ pub(super) fn decrease_indent(self, node: &SyntaxNode) {
|
||||
let new_ws = make::tokens::whitespace(
|
||||
&ws.syntax().text().replace(&format!("\n{}", self), "\n"),
|
||||
);
|
||||
ted::replace(ws.syntax(), &new_ws)
|
||||
ted::replace(ws.syntax(), &new_ws);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -49,7 +49,7 @@ fn get_or_create_where_clause(&self) -> ast::WhereClause {
|
||||
} else {
|
||||
Position::last_child_of(self.syntax())
|
||||
};
|
||||
create_where_clause(position)
|
||||
create_where_clause(position);
|
||||
}
|
||||
self.where_clause().unwrap()
|
||||
}
|
||||
@ -60,10 +60,9 @@ fn get_or_create_generic_param_list(&self) -> ast::GenericParamList {
|
||||
match self.generic_param_list() {
|
||||
Some(it) => it,
|
||||
None => {
|
||||
let position = if let Some(imp_token) = self.impl_token() {
|
||||
Position::after(imp_token)
|
||||
} else {
|
||||
Position::last_child_of(self.syntax())
|
||||
let position = match self.impl_token() {
|
||||
Some(imp_token) => Position::after(imp_token),
|
||||
None => Position::last_child_of(self.syntax()),
|
||||
};
|
||||
create_generic_param_list(position)
|
||||
}
|
||||
@ -72,12 +71,11 @@ fn get_or_create_generic_param_list(&self) -> ast::GenericParamList {
|
||||
|
||||
fn get_or_create_where_clause(&self) -> ast::WhereClause {
|
||||
if self.where_clause().is_none() {
|
||||
let position = if let Some(items) = self.assoc_item_list() {
|
||||
Position::before(items.syntax())
|
||||
} else {
|
||||
Position::last_child_of(self.syntax())
|
||||
let position = match self.assoc_item_list() {
|
||||
Some(items) => Position::before(items.syntax()),
|
||||
None => Position::last_child_of(self.syntax()),
|
||||
};
|
||||
create_where_clause(position)
|
||||
create_where_clause(position);
|
||||
}
|
||||
self.where_clause().unwrap()
|
||||
}
|
||||
@ -102,12 +100,11 @@ fn get_or_create_generic_param_list(&self) -> ast::GenericParamList {
|
||||
|
||||
fn get_or_create_where_clause(&self) -> ast::WhereClause {
|
||||
if self.where_clause().is_none() {
|
||||
let position = if let Some(items) = self.assoc_item_list() {
|
||||
Position::before(items.syntax())
|
||||
} else {
|
||||
Position::last_child_of(self.syntax())
|
||||
let position = match self.assoc_item_list() {
|
||||
Some(items) => Position::before(items.syntax()),
|
||||
None => Position::last_child_of(self.syntax()),
|
||||
};
|
||||
create_where_clause(position)
|
||||
create_where_clause(position);
|
||||
}
|
||||
self.where_clause().unwrap()
|
||||
}
|
||||
@ -145,7 +142,7 @@ fn get_or_create_where_clause(&self) -> ast::WhereClause {
|
||||
} else {
|
||||
Position::last_child_of(self.syntax())
|
||||
};
|
||||
create_where_clause(position)
|
||||
create_where_clause(position);
|
||||
}
|
||||
self.where_clause().unwrap()
|
||||
}
|
||||
@ -177,7 +174,7 @@ fn get_or_create_where_clause(&self) -> ast::WhereClause {
|
||||
} else {
|
||||
Position::last_child_of(self.syntax())
|
||||
};
|
||||
create_where_clause(position)
|
||||
create_where_clause(position);
|
||||
}
|
||||
self.where_clause().unwrap()
|
||||
}
|
||||
@ -234,7 +231,7 @@ pub fn add_generic_param(&self, generic_param: ast::GenericParam) {
|
||||
}
|
||||
None => {
|
||||
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 @@ pub fn add_predicate(&self, predicate: ast::WherePred) {
|
||||
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 {
|
||||
pub fn remove(&self) {
|
||||
if let Some(colon) =
|
||||
self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:])
|
||||
{
|
||||
ted::remove_all(colon..=self.syntax().clone().into())
|
||||
} else {
|
||||
ted::remove(self.syntax())
|
||||
match 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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -267,7 +261,7 @@ impl ast::PathSegment {
|
||||
pub fn get_or_create_generic_arg_list(&self) -> ast::GenericArgList {
|
||||
if self.generic_arg_list().is_none() {
|
||||
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()
|
||||
}
|
||||
@ -275,7 +269,7 @@ pub fn get_or_create_generic_arg_list(&self) -> ast::GenericArgList {
|
||||
|
||||
impl ast::UseTree {
|
||||
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) {
|
||||
let separators = self
|
||||
.syntax()
|
||||
@ -286,7 +280,7 @@ pub fn remove(&self) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
ted::remove(self.syntax())
|
||||
ted::remove(self.syntax());
|
||||
}
|
||||
}
|
||||
|
||||
@ -301,13 +295,13 @@ pub fn remove(&self) {
|
||||
let ws_text = next_ws.syntax().text();
|
||||
if let Some(rest) = ws_text.strip_prefix('\n') {
|
||||
if rest.is_empty() {
|
||||
ted::remove(next_ws.syntax())
|
||||
ted::remove(next_ws.syntax());
|
||||
} 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
|
||||
/// the initializer into the name ref and insert the expr as the new initializer.
|
||||
pub fn replace_expr(&self, expr: ast::Expr) {
|
||||
if let Some(_) = self.name_ref() {
|
||||
if self.name_ref().is_some() {
|
||||
match self.expr() {
|
||||
Some(prev) => ted::replace(prev.syntax(), expr.syntax()),
|
||||
None => ted::append_child(self.syntax(), expr.syntax()),
|
||||
@ -525,7 +519,7 @@ fn dedent(&self, by: IndentLevel) {
|
||||
fn reindent_to(&self, target_level: IndentLevel) {
|
||||
let current_level = IndentLevel::from_node(self.syntax());
|
||||
self.dedent(current_level);
|
||||
self.indent(target_level)
|
||||
self.indent(target_level);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -257,7 +257,7 @@ pub fn block_expr(
|
||||
format_to!(buf, " {}\n", stmt);
|
||||
}
|
||||
if let Some(tail_expr) = tail_expr {
|
||||
format_to!(buf, " {}\n", tail_expr)
|
||||
format_to!(buf, " {}\n", tail_expr);
|
||||
}
|
||||
buf += "}";
|
||||
ast_from_text(&format!("fn f() {}", buf))
|
||||
@ -644,9 +644,14 @@ pub fn fn_(
|
||||
ret_type: Option<ast::RetType>,
|
||||
is_async: bool,
|
||||
) -> ast::Fn {
|
||||
let type_params =
|
||||
if let Some(type_params) = type_params { format!("<{}>", type_params) } else { "".into() };
|
||||
let ret_type = if let Some(ret_type) = ret_type { format!("{} ", ret_type) } else { "".into() };
|
||||
let type_params = match type_params {
|
||||
Some(type_params) => format!("<{}>", type_params),
|
||||
None => "".into(),
|
||||
};
|
||||
let ret_type = match ret_type {
|
||||
Some(ret_type) => format!("{} ", ret_type),
|
||||
None => "".into(),
|
||||
};
|
||||
let visibility = match visibility {
|
||||
None => String::new(),
|
||||
Some(it) => format!("{} ", it),
|
||||
|
@ -276,9 +276,9 @@ pub fn top_path(&self) -> ast::Path {
|
||||
|
||||
impl ast::Use {
|
||||
pub fn is_simple_glob(&self) -> bool {
|
||||
self.use_tree()
|
||||
.map(|use_tree| use_tree.use_tree_list().is_none() && use_tree.star_token().is_some())
|
||||
.unwrap_or(false)
|
||||
self.use_tree().map_or(false, |use_tree| {
|
||||
use_tree.use_tree_list().is_none() && use_tree.star_token().is_some()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -549,10 +549,9 @@ pub fn index_token(&self) -> Option<SyntaxToken> {
|
||||
}
|
||||
|
||||
pub fn field_access(&self) -> Option<FieldKind> {
|
||||
if let Some(nr) = self.name_ref() {
|
||||
Some(FieldKind::Name(nr))
|
||||
} else {
|
||||
self.index_token().map(FieldKind::Index)
|
||||
match self.name_ref() {
|
||||
Some(nr) => Some(FieldKind::Name(nr)),
|
||||
None => self.index_token().map(FieldKind::Index),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -283,10 +283,9 @@ fn lex_format_specifier<F>(&self, mut callback: F)
|
||||
where
|
||||
F: FnMut(TextRange, FormatSpecifier),
|
||||
{
|
||||
let char_ranges = if let Some(char_ranges) = self.char_ranges() {
|
||||
char_ranges
|
||||
} else {
|
||||
return;
|
||||
let char_ranges = match self.char_ranges() {
|
||||
Some(char_ranges) => char_ranges,
|
||||
None => return,
|
||||
};
|
||||
let mut chars = char_ranges.iter().peekable();
|
||||
|
||||
@ -528,10 +527,11 @@ fn lex_format_specifier<F>(&self, mut callback: F)
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((_, Ok('}'))) = chars.peek() {
|
||||
skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback);
|
||||
} else {
|
||||
continue;
|
||||
match chars.peek() {
|
||||
Some((_, Ok('}'))) => {
|
||||
skip_char_and_emit(&mut chars, FormatSpecifier::Close, &mut callback);
|
||||
}
|
||||
Some((_, _)) | None => continue,
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
@ -609,7 +609,7 @@ fn char_ranges(
|
||||
TextRange::new(range.start.try_into().unwrap(), range.end.try_into().unwrap())
|
||||
+ offset,
|
||||
unescaped_char,
|
||||
))
|
||||
));
|
||||
});
|
||||
|
||||
Some(res)
|
||||
@ -631,7 +631,7 @@ pub fn value(&self) -> Option<u128> {
|
||||
|
||||
let mut text = token.text();
|
||||
if let Some(suffix) = self.suffix() {
|
||||
text = &text[..text.len() - suffix.len()]
|
||||
text = &text[..text.len() - suffix.len()];
|
||||
}
|
||||
|
||||
let radix = self.radix();
|
||||
@ -688,7 +688,7 @@ impl Radix {
|
||||
pub const ALL: &'static [Radix] =
|
||||
&[Radix::Binary, Radix::Octal, Radix::Decimal, Radix::Hexadecimal];
|
||||
|
||||
const fn prefix_len(&self) -> usize {
|
||||
const fn prefix_len(self) -> usize {
|
||||
match self {
|
||||
Self::Decimal => 0,
|
||||
_ => 2,
|
||||
|
@ -28,7 +28,7 @@ pub fn function_declaration(node: &ast::Fn) -> String {
|
||||
format_to!(buf, "{} ", abi);
|
||||
}
|
||||
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() {
|
||||
format_to!(buf, "{}", type_params);
|
||||
|
@ -44,8 +44,7 @@ fn bump(&mut self) {
|
||||
fn is_keyword(&self, kw: &str) -> bool {
|
||||
self.token_offset_pairs
|
||||
.get(self.curr.1)
|
||||
.map(|(token, offset)| &self.text[TextRange::at(*offset, token.len)] == kw)
|
||||
.unwrap_or(false)
|
||||
.map_or(false, |(token, offset)| &self.text[TextRange::at(*offset, token.len)] == kw)
|
||||
}
|
||||
}
|
||||
|
||||
@ -55,8 +54,7 @@ fn mk_token(pos: usize, token_offset_pairs: &[(Token, TextSize)]) -> parser::Tok
|
||||
token.kind,
|
||||
token_offset_pairs
|
||||
.get(pos + 1)
|
||||
.map(|(_, next_offset)| offset + token.len == *next_offset)
|
||||
.unwrap_or(false),
|
||||
.map_or(false, |(_, next_offset)| offset + token.len == *next_offset),
|
||||
),
|
||||
None => (EOF, false),
|
||||
};
|
||||
|
@ -88,7 +88,7 @@ fn finish_node(&mut self) {
|
||||
}
|
||||
|
||||
fn error(&mut self, error: ParseError) {
|
||||
self.inner.error(error, self.text_pos)
|
||||
self.inner.error(error, self.text_pos);
|
||||
}
|
||||
}
|
||||
|
||||
@ -108,7 +108,7 @@ pub(super) fn finish(mut self) -> (GreenNode, Vec<SyntaxError>) {
|
||||
match mem::replace(&mut self.state, State::Normal) {
|
||||
State::PendingFinish => {
|
||||
self.eat_trivias();
|
||||
self.inner.finish_node()
|
||||
self.inner.finish_node();
|
||||
}
|
||||
State::PendingStart | State::Normal => unreachable!(),
|
||||
}
|
||||
|
@ -81,7 +81,7 @@ fn eq(&self, other: &AstPtr<N>) -> bool {
|
||||
|
||||
impl<N: AstNode> Hash for AstPtr<N> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.raw.hash(state)
|
||||
self.raw.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -56,19 +56,19 @@ pub fn finish(self) -> Parse<SyntaxNode> {
|
||||
|
||||
pub fn token(&mut self, kind: SyntaxKind, text: &str) {
|
||||
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) {
|
||||
let kind = RustLanguage::kind_to_raw(kind);
|
||||
self.inner.start_node(kind)
|
||||
self.inner.start_node(kind);
|
||||
}
|
||||
|
||||
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) {
|
||||
self.errors.push(SyntaxError::new_at_offset(*error.0, text_pos))
|
||||
self.errors.push(SyntaxError::new_at_offset(*error.0, text_pos));
|
||||
}
|
||||
}
|
||||
|
@ -77,23 +77,23 @@ pub fn last_child_of(node: &(impl Into<SyntaxNode> + Clone)) -> Position {
|
||||
}
|
||||
|
||||
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) {
|
||||
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>) {
|
||||
if let Some(first) = elements.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(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>) {
|
||||
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) {
|
||||
elem.syntax_element().detach()
|
||||
elem.syntax_element().detach();
|
||||
}
|
||||
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>) {
|
||||
let mut it = range.into_iter();
|
||||
@ -115,9 +115,9 @@ pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) {
|
||||
match it.last() {
|
||||
Some(mut last) => {
|
||||
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),
|
||||
}
|
||||
@ -125,26 +125,26 @@ pub fn remove_all_iter(range: impl IntoIterator<Item = SyntaxElement>) {
|
||||
}
|
||||
|
||||
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>) {
|
||||
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>) {
|
||||
let start = range.start().index();
|
||||
let end = range.end().index();
|
||||
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) {
|
||||
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) {
|
||||
let position = Position::last_child_of(node);
|
||||
insert_raw(position, child)
|
||||
insert_raw(position, child);
|
||||
}
|
||||
|
||||
fn ws_before(position: &Position, new: &SyntaxElement) -> Option<SyntaxToken> {
|
||||
|
@ -227,12 +227,9 @@ fn fragment_parser_dir_test<T, F>(ok_paths: &[&str], err_paths: &[&str], f: F)
|
||||
T: crate::AstNode,
|
||||
F: Fn(&str) -> Result<T, ()>,
|
||||
{
|
||||
dir_tests(&test_data_dir(), ok_paths, "rast", |text, path| {
|
||||
if let Ok(node) = f(text) {
|
||||
format!("{:#?}", crate::ast::AstNode::syntax(&node))
|
||||
} else {
|
||||
panic!("Failed to parse '{:?}'", path);
|
||||
}
|
||||
dir_tests(&test_data_dir(), ok_paths, "rast", |text, path| match f(text) {
|
||||
Ok(node) => format!("{:#?}", crate::ast::AstNode::syntax(&node)),
|
||||
Err(_) => panic!("Failed to parse '{:?}'", path),
|
||||
});
|
||||
dir_tests(&test_data_dir(), err_paths, "rast", |text, path| {
|
||||
if f(text).is_ok() {
|
||||
|
@ -215,7 +215,7 @@ fn from(node: #variants) -> #name {
|
||||
.flat_map(|node| node.traits.iter().map(move |t| (t, node)))
|
||||
.into_group_map()
|
||||
.into_iter()
|
||||
.sorted_by_key(|(k, _)| k.clone())
|
||||
.sorted_by_key(|(k, _)| *k)
|
||||
.map(|(trait_name, nodes)| {
|
||||
let name = format_ident!("Any{}", trait_name);
|
||||
let trait_name = format_ident!("{}", trait_name);
|
||||
@ -558,12 +558,13 @@ fn ty(&self) -> proc_macro2::Ident {
|
||||
}
|
||||
|
||||
fn lower(grammar: &Grammar) -> AstSrc {
|
||||
let mut res = AstSrc::default();
|
||||
|
||||
res.tokens = "Whitespace Comment String ByteString IntNumber FloatNumber"
|
||||
.split_ascii_whitespace()
|
||||
.map(|it| it.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
let mut res = AstSrc {
|
||||
tokens: "Whitespace Comment String ByteString IntNumber FloatNumber"
|
||||
.split_ascii_whitespace()
|
||||
.map(|it| it.to_string())
|
||||
.collect::<Vec<_>>(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let nodes = grammar.iter().collect::<Vec<_>>();
|
||||
|
||||
|
@ -137,7 +137,7 @@ fn unquote(text: &str, prefix_len: usize, end_delimiter: char) -> Option<&str> {
|
||||
if let Err(err) = char {
|
||||
push_err(1, (range.start, err));
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -148,7 +148,7 @@ fn unquote(text: &str, prefix_len: usize, end_delimiter: char) -> Option<&str> {
|
||||
if let Err(err) = char {
|
||||
push_err(2, (range.start, err));
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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",
|
||||
attr.syntax().text_range(),
|
||||
)
|
||||
}))
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
@ -43,7 +43,7 @@ pub fn next_round(&mut self) -> bool {
|
||||
}
|
||||
|
||||
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 @@ fn drop(&mut self) {
|
||||
for round in &self.rounds {
|
||||
eprintln!("\n{}", round.plot);
|
||||
}
|
||||
panic!("Doesn't look linear!")
|
||||
panic!("Doesn't look linear!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -142,14 +142,14 @@ pub fn parse(ra_fixture: &str) -> (Option<MiniCore>, Vec<String>, Vec<Fixture>)
|
||||
|
||||
if line.starts_with("//-") {
|
||||
let meta = Fixture::parse_meta_line(line);
|
||||
res.push(meta)
|
||||
res.push(meta);
|
||||
} else {
|
||||
if line.starts_with("// ")
|
||||
&& line.contains(':')
|
||||
&& !line.contains("::")
|
||||
&& 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() {
|
||||
@ -256,9 +256,9 @@ fn parse(line: &str) -> MiniCore {
|
||||
let line = line.strip_prefix("//- minicore:").unwrap().trim();
|
||||
for entry in line.split(", ") {
|
||||
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
|
||||
@ -310,7 +310,7 @@ pub fn source_code(mut self) -> String {
|
||||
// Fixed point loop to compute transitive closure of flags.
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for &(u, v) in implications.iter() {
|
||||
for &(u, v) in &implications {
|
||||
if self.has_flag(u) && !self.has_flag(v) {
|
||||
self.activated_flags.push(v.to_string());
|
||||
changed = true;
|
||||
@ -354,7 +354,7 @@ pub fn source_code(mut self) -> String {
|
||||
}
|
||||
|
||||
if keep {
|
||||
buf.push_str(line)
|
||||
buf.push_str(line);
|
||||
}
|
||||
if line_region {
|
||||
active_regions.pop().unwrap();
|
||||
|
@ -244,7 +244,7 @@ pub fn extract_annotations(text: &str) -> Vec<(TextRange, String)> {
|
||||
|
||||
range + line_start.1
|
||||
};
|
||||
res.push((range, content))
|
||||
res.push((range, content));
|
||||
}
|
||||
LineAnnotation::Continuation { mut offset, content } => {
|
||||
offset += annotation_offset;
|
||||
@ -301,7 +301,7 @@ fn extract_line_annotations(mut line: &str) -> Vec<LineAnnotation> {
|
||||
let mut file = false;
|
||||
if !continuation && content.starts_with("file") {
|
||||
file = true;
|
||||
content = &content["file".len()..]
|
||||
content = &content["file".len()..];
|
||||
}
|
||||
|
||||
let content = content.trim().to_string();
|
||||
@ -371,7 +371,7 @@ fn main() {
|
||||
pub fn skip_slow_tests() -> bool {
|
||||
let should_skip = std::env::var("CI").is_err() && std::env::var("RUN_SLOW_TESTS").is_err();
|
||||
if should_skip {
|
||||
eprintln!("ignoring slow test")
|
||||
eprintln!("ignoring slow test");
|
||||
} else {
|
||||
let path = project_root().join("./target/.slow_tests_cookie");
|
||||
fs::write(&path, ".").unwrap();
|
||||
@ -432,7 +432,7 @@ struct Bencher {
|
||||
|
||||
impl Drop for Bencher {
|
||||
fn drop(&mut self) {
|
||||
eprintln!("{}: {}", self.label, self.sw.elapsed())
|
||||
eprintln!("{}: {}", self.label, self.sw.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -90,13 +90,13 @@ pub fn apply(&self, text: &mut String) {
|
||||
}
|
||||
|
||||
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 -= indel.delete.end() - indel.delete.start();
|
||||
}
|
||||
let mut buf = String::with_capacity(total_len.into());
|
||||
let mut prev = 0;
|
||||
for indel in self.indels.iter() {
|
||||
for indel in &self.indels {
|
||||
let start: usize = indel.delete.start().into();
|
||||
let end: usize = indel.delete.end().into();
|
||||
if start > prev {
|
||||
@ -110,7 +110,7 @@ pub fn apply(&self, text: &mut String) {
|
||||
|
||||
// FIXME: figure out a way to mutate the text in-place or reuse the
|
||||
// memory in some other way
|
||||
*text = buf
|
||||
*text = buf;
|
||||
}
|
||||
|
||||
pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {
|
||||
@ -126,7 +126,7 @@ pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {
|
||||
|
||||
pub fn apply_to_offset(&self, offset: TextSize) -> Option<TextSize> {
|
||||
let mut res = offset;
|
||||
for indel in self.indels.iter() {
|
||||
for indel in &self.indels {
|
||||
if indel.delete.start() >= offset {
|
||||
break;
|
||||
}
|
||||
@ -163,13 +163,13 @@ pub fn is_empty(&self) -> bool {
|
||||
self.indels.is_empty()
|
||||
}
|
||||
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) {
|
||||
self.indel(Indel::delete(range))
|
||||
self.indel(Indel::delete(range));
|
||||
}
|
||||
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 {
|
||||
let mut indels = self.indels;
|
||||
|
@ -194,8 +194,7 @@ pub fn token_tree(self) -> Option<TokenTreeRef<'a>> {
|
||||
TokenTree::Subtree(subtree) => Some(TokenTreeRef::Subtree(subtree, Some(tt))),
|
||||
},
|
||||
Some(Entry::Subtree(tt, subtree, _)) => Some(TokenTreeRef::Subtree(subtree, *tt)),
|
||||
Some(Entry::End(_)) => None,
|
||||
None => None,
|
||||
Some(Entry::End(_)) | None => None,
|
||||
}
|
||||
}
|
||||
|
||||
@ -206,10 +205,9 @@ fn create(buffer: &'a TokenBuffer, ptr: EntryPtr) -> Cursor<'a> {
|
||||
/// Bump the cursor
|
||||
pub fn bump(self) -> Cursor<'a> {
|
||||
if let Some(Entry::End(exit)) = self.buffer.entry(&self.ptr) {
|
||||
if let Some(exit) = exit {
|
||||
Cursor::create(self.buffer, *exit)
|
||||
} else {
|
||||
self
|
||||
match exit {
|
||||
Some(exit) => Cursor::create(self.buffer, *exit),
|
||||
None => self,
|
||||
}
|
||||
} else {
|
||||
Cursor::create(self.buffer, EntryPtr(self.ptr.0, self.ptr.1 + 1))
|
||||
|
@ -161,7 +161,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
};
|
||||
f.write_str(l)?;
|
||||
let mut needs_space = false;
|
||||
for tt in self.token_trees.iter() {
|
||||
for tt in &self.token_trees {
|
||||
if needs_space {
|
||||
f.write_str(" ")?;
|
||||
}
|
||||
@ -169,7 +169,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match tt {
|
||||
TokenTree::Leaf(Leaf::Punct(p)) => {
|
||||
needs_space = p.spacing == Spacing::Alone;
|
||||
fmt::Display::fmt(p, f)?
|
||||
fmt::Display::fmt(p, f)?;
|
||||
}
|
||||
tt => fmt::Display::fmt(tt, f)?,
|
||||
}
|
||||
@ -215,7 +215,7 @@ pub fn count(&self) -> usize {
|
||||
.iter()
|
||||
.map(|c| match c {
|
||||
TokenTree::Subtree(c) => c.count(),
|
||||
_ => 0,
|
||||
TokenTree::Leaf(_) => 0,
|
||||
})
|
||||
.sum::<usize>();
|
||||
|
||||
|
@ -38,7 +38,7 @@ fn spawn(sender: loader::Sender) -> NotifyHandle {
|
||||
NotifyHandle { sender, _thread: thread }
|
||||
}
|
||||
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) {
|
||||
self.sender.send(Message::Invalidate(path)).unwrap();
|
||||
@ -84,7 +84,7 @@ fn run(mut self, inbox: Receiver<Message>) {
|
||||
if !config.watch.is_empty() {
|
||||
let (watcher_sender, watcher_receiver) = unbounded();
|
||||
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));
|
||||
}
|
||||
@ -99,7 +99,7 @@ fn run(mut self, inbox: Receiver<Message>) {
|
||||
for (i, entry) in config.load.into_iter().enumerate() {
|
||||
let watch = config.watch.contains(&i);
|
||||
if watch {
|
||||
self.watched_entries.push(entry.clone())
|
||||
self.watched_entries.push(entry.clone());
|
||||
}
|
||||
let files = self.load_entry(entry, watch);
|
||||
self.send(loader::Message::Loaded { files });
|
||||
@ -149,7 +149,7 @@ fn run(mut self, inbox: Receiver<Message>) {
|
||||
Some((path, contents))
|
||||
})
|
||||
.collect();
|
||||
self.send(loader::Message::Loaded { files })
|
||||
self.send(loader::Message::Loaded { files });
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -165,7 +165,7 @@ fn load_entry(
|
||||
.into_iter()
|
||||
.map(|file| {
|
||||
if watch {
|
||||
self.watch(file.clone())
|
||||
self.watch(file.clone());
|
||||
}
|
||||
let contents = read(file.as_path());
|
||||
(file, contents)
|
||||
@ -174,7 +174,7 @@ fn load_entry(
|
||||
loader::Entry::Directories(dirs) => {
|
||||
let mut res = Vec::new();
|
||||
|
||||
for root in dirs.include.iter() {
|
||||
for root in &dirs.include {
|
||||
let walkdir =
|
||||
WalkDir::new(root).follow_links(true).into_iter().filter_entry(|entry| {
|
||||
if !entry.file_type().is_dir() {
|
||||
@ -218,7 +218,7 @@ fn watch(&mut self, path: AbsPathBuf) {
|
||||
}
|
||||
}
|
||||
fn send(&mut self, msg: loader::Message) {
|
||||
(self.sender)(msg)
|
||||
(self.sender)(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -112,7 +112,7 @@ pub fn partition(&self, vfs: &Vfs) -> Vec<FileSet> {
|
||||
let mut res = vec![FileSet::default(); self.len()];
|
||||
for (file_id, path) in vfs.iter() {
|
||||
let root = self.classify(path, &mut scratch_space);
|
||||
res[root].insert(file_id, path.clone())
|
||||
res[root].insert(file_id, path.clone());
|
||||
}
|
||||
res
|
||||
}
|
||||
@ -157,7 +157,7 @@ pub fn len(&self) -> usize {
|
||||
|
||||
/// Add a new set of paths prefixes.
|
||||
pub fn add_file_set(&mut self, roots: Vec<VfsPath>) {
|
||||
self.roots.push(roots)
|
||||
self.roots.push(roots);
|
||||
}
|
||||
|
||||
/// Build the `FileSetConfig`.
|
||||
|
@ -73,9 +73,8 @@ pub fn pop(&mut self) -> bool {
|
||||
pub fn starts_with(&self, other: &VfsPath) -> bool {
|
||||
match (&self.0, &other.0) {
|
||||
(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(_), _) => false,
|
||||
(VfsPathRepr::PathBuf(_) | VfsPathRepr::VirtualPath(_), _) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@ -357,7 +356,7 @@ fn join(&self, mut path: &str) -> Option<VirtualPath> {
|
||||
if !res.pop() {
|
||||
return None;
|
||||
}
|
||||
path = &path["../".len()..]
|
||||
path = &path["../".len()..];
|
||||
}
|
||||
path = path.trim_start_matches("./");
|
||||
res.0 = format!("{}/{}", res.0, path);
|
||||
|
@ -63,7 +63,7 @@ impl<T> Eq for Idx<T> {}
|
||||
|
||||
impl<T> Hash for Idx<T> {
|
||||
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 {
|
||||
let mut type_name = std::any::type_name::<T>();
|
||||
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)
|
||||
}
|
||||
|
@ -13,7 +13,7 @@
|
||||
impl flags::Install {
|
||||
pub(crate) fn run(self) -> Result<()> {
|
||||
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() {
|
||||
install_server(server).context("install server")?;
|
||||
@ -148,7 +148,7 @@ fn install_server(opts: ServerOpt) -> Result<()> {
|
||||
eprintln!(
|
||||
"\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n",
|
||||
REQUIRED_RUST_VERSION,
|
||||
)
|
||||
);
|
||||
}
|
||||
let features = match opts.malloc {
|
||||
Malloc::System => &[][..],
|
||||
|
@ -33,15 +33,13 @@ pub(crate) fn run(self) -> Result<()> {
|
||||
let commit = cmd!("git rev-parse HEAD").read()?;
|
||||
let changelog_n = read_dir(changelog_dir.as_path())?.len();
|
||||
|
||||
for &adoc in [
|
||||
for adoc in [
|
||||
"manual.adoc",
|
||||
"generated_assists.adoc",
|
||||
"generated_config.adoc",
|
||||
"generated_diagnostic.adoc",
|
||||
"generated_features.adoc",
|
||||
]
|
||||
.iter()
|
||||
{
|
||||
] {
|
||||
let src = project_root().join("./docs/user/").join(adoc);
|
||||
let dst = website_root.join(adoc);
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user