diff options
Diffstat (limited to 'crates')
-rw-r--r-- | crates/ra_ide/src/completion/complete_attribute.rs | 282 | ||||
-rw-r--r-- | crates/ra_prof/src/memory_usage.rs | 6 | ||||
-rw-r--r-- | crates/ra_ssr/src/lib.rs | 26 | ||||
-rw-r--r-- | crates/ra_ssr/src/resolving.rs | 67 | ||||
-rw-r--r-- | crates/ra_ssr/src/tests.rs | 37 | ||||
-rw-r--r-- | crates/rust-analyzer/src/cli.rs | 7 | ||||
-rw-r--r-- | crates/rust-analyzer/src/cli/analysis_stats.rs | 63 | ||||
-rw-r--r-- | crates/rust-analyzer/src/lib.rs | 2 | ||||
-rw-r--r-- | crates/vfs/src/file_set.rs | 71 |
9 files changed, 489 insertions, 72 deletions
diff --git a/crates/ra_ide/src/completion/complete_attribute.rs b/crates/ra_ide/src/completion/complete_attribute.rs index d268c92be..109c5e9a8 100644 --- a/crates/ra_ide/src/completion/complete_attribute.rs +++ b/crates/ra_ide/src/completion/complete_attribute.rs | |||
@@ -13,13 +13,19 @@ use crate::completion::{ | |||
13 | 13 | ||
14 | pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { | 14 | pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { |
15 | let attribute = ctx.attribute_under_caret.as_ref()?; | 15 | let attribute = ctx.attribute_under_caret.as_ref()?; |
16 | |||
17 | match (attribute.path(), attribute.input()) { | 16 | match (attribute.path(), attribute.input()) { |
18 | (Some(path), Some(ast::AttrInput::TokenTree(token_tree))) | 17 | (Some(path), Some(ast::AttrInput::TokenTree(token_tree))) |
19 | if path.to_string() == "derive" => | 18 | if path.to_string() == "derive" => |
20 | { | 19 | { |
21 | complete_derive(acc, ctx, token_tree) | 20 | complete_derive(acc, ctx, token_tree) |
22 | } | 21 | } |
22 | (Some(path), Some(ast::AttrInput::TokenTree(token_tree))) | ||
23 | if ["allow", "warn", "deny", "forbid"] | ||
24 | .iter() | ||
25 | .any(|lint_level| lint_level == &path.to_string()) => | ||
26 | { | ||
27 | complete_lint(acc, ctx, token_tree) | ||
28 | } | ||
23 | (_, Some(ast::AttrInput::TokenTree(_token_tree))) => {} | 29 | (_, Some(ast::AttrInput::TokenTree(_token_tree))) => {} |
24 | _ => complete_attribute_start(acc, ctx, attribute), | 30 | _ => complete_attribute_start(acc, ctx, attribute), |
25 | } | 31 | } |
@@ -125,7 +131,7 @@ const ATTRIBUTES: &[AttrCompletion] = &[ | |||
125 | ]; | 131 | ]; |
126 | 132 | ||
127 | fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input: ast::TokenTree) { | 133 | fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input: ast::TokenTree) { |
128 | if let Ok(existing_derives) = parse_derive_input(derive_input) { | 134 | if let Ok(existing_derives) = parse_comma_sep_input(derive_input) { |
129 | for derive_completion in DEFAULT_DERIVE_COMPLETIONS | 135 | for derive_completion in DEFAULT_DERIVE_COMPLETIONS |
130 | .into_iter() | 136 | .into_iter() |
131 | .filter(|completion| !existing_derives.contains(completion.label)) | 137 | .filter(|completion| !existing_derives.contains(completion.label)) |
@@ -158,7 +164,26 @@ fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input: | |||
158 | } | 164 | } |
159 | } | 165 | } |
160 | 166 | ||
161 | fn parse_derive_input(derive_input: ast::TokenTree) -> Result<FxHashSet<String>, ()> { | 167 | fn complete_lint(acc: &mut Completions, ctx: &CompletionContext, derive_input: ast::TokenTree) { |
168 | if let Ok(existing_lints) = parse_comma_sep_input(derive_input) { | ||
169 | for lint_completion in DEFAULT_LINT_COMPLETIONS | ||
170 | .into_iter() | ||
171 | .filter(|completion| !existing_lints.contains(completion.label)) | ||
172 | { | ||
173 | acc.add( | ||
174 | CompletionItem::new( | ||
175 | CompletionKind::Attribute, | ||
176 | ctx.source_range(), | ||
177 | lint_completion.label, | ||
178 | ) | ||
179 | .kind(CompletionItemKind::Attribute) | ||
180 | .detail(lint_completion.description), | ||
181 | ); | ||
182 | } | ||
183 | } | ||
184 | } | ||
185 | |||
186 | fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Result<FxHashSet<String>, ()> { | ||
162 | match (derive_input.left_delimiter_token(), derive_input.right_delimiter_token()) { | 187 | match (derive_input.left_delimiter_token(), derive_input.right_delimiter_token()) { |
163 | (Some(left_paren), Some(right_paren)) | 188 | (Some(left_paren), Some(right_paren)) |
164 | if left_paren.kind() == SyntaxKind::L_PAREN | 189 | if left_paren.kind() == SyntaxKind::L_PAREN |
@@ -212,6 +237,7 @@ struct DeriveCompletion { | |||
212 | 237 | ||
213 | /// Standard Rust derives and the information about their dependencies | 238 | /// Standard Rust derives and the information about their dependencies |
214 | /// (the dependencies are needed so that the main derive don't break the compilation when added) | 239 | /// (the dependencies are needed so that the main derive don't break the compilation when added) |
240 | #[rustfmt::skip] | ||
215 | const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[ | 241 | const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[ |
216 | DeriveCompletion { label: "Clone", dependencies: &[] }, | 242 | DeriveCompletion { label: "Clone", dependencies: &[] }, |
217 | DeriveCompletion { label: "Copy", dependencies: &["Clone"] }, | 243 | DeriveCompletion { label: "Copy", dependencies: &["Clone"] }, |
@@ -224,6 +250,130 @@ const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[ | |||
224 | DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] }, | 250 | DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] }, |
225 | ]; | 251 | ]; |
226 | 252 | ||
253 | struct LintCompletion { | ||
254 | label: &'static str, | ||
255 | description: &'static str, | ||
256 | } | ||
257 | |||
258 | #[rustfmt::skip] | ||
259 | const DEFAULT_LINT_COMPLETIONS: &[LintCompletion] = &[ | ||
260 | LintCompletion { label: "absolute_paths_not_starting_with_crate", description: r#"fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name"# }, | ||
261 | LintCompletion { label: "anonymous_parameters", description: r#"detects anonymous parameters"# }, | ||
262 | LintCompletion { label: "box_pointers", description: r#"use of owned (Box type) heap memory"# }, | ||
263 | LintCompletion { label: "deprecated_in_future", description: r#"detects use of items that will be deprecated in a future version"# }, | ||
264 | LintCompletion { label: "elided_lifetimes_in_paths", description: r#"hidden lifetime parameters in types are deprecated"# }, | ||
265 | LintCompletion { label: "explicit_outlives_requirements", description: r#"outlives requirements can be inferred"# }, | ||
266 | LintCompletion { label: "indirect_structural_match", description: r#"pattern with const indirectly referencing non-structural-match type"# }, | ||
267 | LintCompletion { label: "keyword_idents", description: r#"detects edition keywords being used as an identifier"# }, | ||
268 | LintCompletion { label: "macro_use_extern_crate", description: r#"the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system"# }, | ||
269 | LintCompletion { label: "meta_variable_misuse", description: r#"possible meta-variable misuse at macro definition"# }, | ||
270 | LintCompletion { label: "missing_copy_implementations", description: r#"detects potentially-forgotten implementations of `Copy`"# }, | ||
271 | LintCompletion { label: "missing_crate_level_docs", description: r#"detects crates with no crate-level documentation"# }, | ||
272 | LintCompletion { label: "missing_debug_implementations", description: r#"detects missing implementations of Debug"# }, | ||
273 | LintCompletion { label: "missing_docs", description: r#"detects missing documentation for public members"# }, | ||
274 | LintCompletion { label: "missing_doc_code_examples", description: r#"detects publicly-exported items without code samples in their documentation"# }, | ||
275 | LintCompletion { label: "non_ascii_idents", description: r#"detects non-ASCII identifiers"# }, | ||
276 | LintCompletion { label: "private_doc_tests", description: r#"detects code samples in docs of private items not documented by rustdoc"# }, | ||
277 | LintCompletion { label: "single_use_lifetimes", description: r#"detects lifetime parameters that are only used once"# }, | ||
278 | LintCompletion { label: "trivial_casts", description: r#"detects trivial casts which could be removed"# }, | ||
279 | LintCompletion { label: "trivial_numeric_casts", description: r#"detects trivial casts of numeric types which could be removed"# }, | ||
280 | LintCompletion { label: "unaligned_references", description: r#"detects unaligned references to fields of packed structs"# }, | ||
281 | LintCompletion { label: "unreachable_pub", description: r#"`pub` items not reachable from crate root"# }, | ||
282 | LintCompletion { label: "unsafe_code", description: r#"usage of `unsafe` code"# }, | ||
283 | LintCompletion { label: "unsafe_op_in_unsafe_fn", description: r#"unsafe operations in unsafe functions without an explicit unsafe block are deprecated"# }, | ||
284 | LintCompletion { label: "unstable_features", description: r#"enabling unstable features (deprecated. do not use)"# }, | ||
285 | LintCompletion { label: "unused_crate_dependencies", description: r#"crate dependencies that are never used"# }, | ||
286 | LintCompletion { label: "unused_extern_crates", description: r#"extern crates that are never used"# }, | ||
287 | LintCompletion { label: "unused_import_braces", description: r#"unnecessary braces around an imported item"# }, | ||
288 | LintCompletion { label: "unused_lifetimes", description: r#"detects lifetime parameters that are never used"# }, | ||
289 | LintCompletion { label: "unused_qualifications", description: r#"detects unnecessarily qualified names"# }, | ||
290 | LintCompletion { label: "unused_results", description: r#"unused result of an expression in a statement"# }, | ||
291 | LintCompletion { label: "variant_size_differences", description: r#"detects enums with widely varying variant sizes"# }, | ||
292 | LintCompletion { label: "array_into_iter", description: r#"detects calling `into_iter` on arrays"# }, | ||
293 | LintCompletion { label: "asm_sub_register", description: r#"using only a subset of a register for inline asm inputs"# }, | ||
294 | LintCompletion { label: "bare_trait_objects", description: r#"suggest using `dyn Trait` for trait objects"# }, | ||
295 | LintCompletion { label: "bindings_with_variant_name", description: r#"detects pattern bindings with the same name as one of the matched variants"# }, | ||
296 | LintCompletion { label: "cenum_impl_drop_cast", description: r#"a C-like enum implementing Drop is cast"# }, | ||
297 | LintCompletion { label: "clashing_extern_declarations", description: r#"detects when an extern fn has been declared with the same name but different types"# }, | ||
298 | LintCompletion { label: "coherence_leak_check", description: r#"distinct impls distinguished only by the leak-check code"# }, | ||
299 | LintCompletion { label: "confusable_idents", description: r#"detects visually confusable pairs between identifiers"# }, | ||
300 | LintCompletion { label: "dead_code", description: r#"detect unused, unexported items"# }, | ||
301 | LintCompletion { label: "deprecated", description: r#"detects use of deprecated items"# }, | ||
302 | LintCompletion { label: "ellipsis_inclusive_range_patterns", description: r#"`...` range patterns are deprecated"# }, | ||
303 | LintCompletion { label: "exported_private_dependencies", description: r#"public interface leaks type from a private dependency"# }, | ||
304 | LintCompletion { label: "illegal_floating_point_literal_pattern", description: r#"floating-point literals cannot be used in patterns"# }, | ||
305 | LintCompletion { label: "improper_ctypes", description: r#"proper use of libc types in foreign modules"# }, | ||
306 | LintCompletion { label: "improper_ctypes_definitions", description: r#"proper use of libc types in foreign item definitions"# }, | ||
307 | LintCompletion { label: "incomplete_features", description: r#"incomplete features that may function improperly in some or all cases"# }, | ||
308 | LintCompletion { label: "inline_no_sanitize", description: r#"detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]`"# }, | ||
309 | LintCompletion { label: "intra_doc_link_resolution_failure", description: r#"failures in resolving intra-doc link targets"# }, | ||
310 | LintCompletion { label: "invalid_codeblock_attributes", description: r#"codeblock attribute looks a lot like a known one"# }, | ||
311 | LintCompletion { label: "invalid_value", description: r#"an invalid value is being created (such as a NULL reference)"# }, | ||
312 | LintCompletion { label: "irrefutable_let_patterns", description: r#"detects irrefutable patterns in if-let and while-let statements"# }, | ||
313 | LintCompletion { label: "late_bound_lifetime_arguments", description: r#"detects generic lifetime arguments in path segments with late bound lifetime parameters"# }, | ||
314 | LintCompletion { label: "mixed_script_confusables", description: r#"detects Unicode scripts whose mixed script confusables codepoints are solely used"# }, | ||
315 | LintCompletion { label: "mutable_borrow_reservation_conflict", description: r#"reservation of a two-phased borrow conflicts with other shared borrows"# }, | ||
316 | LintCompletion { label: "non_camel_case_types", description: r#"types, variants, traits and type parameters should have camel case names"# }, | ||
317 | LintCompletion { label: "non_shorthand_field_patterns", description: r#"using `Struct { x: x }` instead of `Struct { x }` in a pattern"# }, | ||
318 | LintCompletion { label: "non_snake_case", description: r#"variables, methods, functions, lifetime parameters and modules should have snake case names"# }, | ||
319 | LintCompletion { label: "non_upper_case_globals", description: r#"static constants should have uppercase identifiers"# }, | ||
320 | LintCompletion { label: "no_mangle_generic_items", description: r#"generic items must be mangled"# }, | ||
321 | LintCompletion { label: "overlapping_patterns", description: r#"detects overlapping patterns"# }, | ||
322 | LintCompletion { label: "path_statements", description: r#"path statements with no effect"# }, | ||
323 | LintCompletion { label: "private_in_public", description: r#"detect private items in public interfaces not caught by the old implementation"# }, | ||
324 | LintCompletion { label: "proc_macro_derive_resolution_fallback", description: r#"detects proc macro derives using inaccessible names from parent modules"# }, | ||
325 | LintCompletion { label: "redundant_semicolons", description: r#"detects unnecessary trailing semicolons"# }, | ||
326 | LintCompletion { label: "renamed_and_removed_lints", description: r#"lints that have been renamed or removed"# }, | ||
327 | LintCompletion { label: "safe_packed_borrows", description: r#"safe borrows of fields of packed structs were erroneously allowed"# }, | ||
328 | LintCompletion { label: "stable_features", description: r#"stable features found in `#[feature]` directive"# }, | ||
329 | LintCompletion { label: "trivial_bounds", description: r#"these bounds don't depend on an type parameters"# }, | ||
330 | LintCompletion { label: "type_alias_bounds", description: r#"bounds in type aliases are not enforced"# }, | ||
331 | LintCompletion { label: "tyvar_behind_raw_pointer", description: r#"raw pointer to an inference variable"# }, | ||
332 | LintCompletion { label: "uncommon_codepoints", description: r#"detects uncommon Unicode codepoints in identifiers"# }, | ||
333 | LintCompletion { label: "unconditional_recursion", description: r#"functions that cannot return without calling themselves"# }, | ||
334 | LintCompletion { label: "unknown_lints", description: r#"unrecognized lint attribute"# }, | ||
335 | LintCompletion { label: "unnameable_test_items", description: r#"detects an item that cannot be named being marked as `#[test_case]`"# }, | ||
336 | LintCompletion { label: "unreachable_code", description: r#"detects unreachable code paths"# }, | ||
337 | LintCompletion { label: "unreachable_patterns", description: r#"detects unreachable patterns"# }, | ||
338 | LintCompletion { label: "unstable_name_collisions", description: r#"detects name collision with an existing but unstable method"# }, | ||
339 | LintCompletion { label: "unused_allocation", description: r#"detects unnecessary allocations that can be eliminated"# }, | ||
340 | LintCompletion { label: "unused_assignments", description: r#"detect assignments that will never be read"# }, | ||
341 | LintCompletion { label: "unused_attributes", description: r#"detects attributes that were not used by the compiler"# }, | ||
342 | LintCompletion { label: "unused_braces", description: r#"unnecessary braces around an expression"# }, | ||
343 | LintCompletion { label: "unused_comparisons", description: r#"comparisons made useless by limits of the types involved"# }, | ||
344 | LintCompletion { label: "unused_doc_comments", description: r#"detects doc comments that aren't used by rustdoc"# }, | ||
345 | LintCompletion { label: "unused_features", description: r#"unused features found in crate-level `#[feature]` directives"# }, | ||
346 | LintCompletion { label: "unused_imports", description: r#"imports that are never used"# }, | ||
347 | LintCompletion { label: "unused_labels", description: r#"detects labels that are never used"# }, | ||
348 | LintCompletion { label: "unused_macros", description: r#"detects macros that were not used"# }, | ||
349 | LintCompletion { label: "unused_must_use", description: r#"unused result of a type flagged as `#[must_use]`"# }, | ||
350 | LintCompletion { label: "unused_mut", description: r#"detect mut variables which don't need to be mutable"# }, | ||
351 | LintCompletion { label: "unused_parens", description: r#"`if`, `match`, `while` and `return` do not need parentheses"# }, | ||
352 | LintCompletion { label: "unused_unsafe", description: r#"unnecessary use of an `unsafe` block"# }, | ||
353 | LintCompletion { label: "unused_variables", description: r#"detect variables which are not used in any way"# }, | ||
354 | LintCompletion { label: "warnings", description: r#"mass-change the level for lints which produce warnings"# }, | ||
355 | LintCompletion { label: "where_clauses_object_safety", description: r#"checks the object safety of where clauses"# }, | ||
356 | LintCompletion { label: "while_true", description: r#"suggest using `loop { }` instead of `while true { }`"# }, | ||
357 | LintCompletion { label: "ambiguous_associated_items", description: r#"ambiguous associated items"# }, | ||
358 | LintCompletion { label: "arithmetic_overflow", description: r#"arithmetic operation overflows"# }, | ||
359 | LintCompletion { label: "conflicting_repr_hints", description: r#"conflicts between `#[repr(..)]` hints that were previously accepted and used in practice"# }, | ||
360 | LintCompletion { label: "const_err", description: r#"constant evaluation detected erroneous expression"# }, | ||
361 | LintCompletion { label: "ill_formed_attribute_input", description: r#"ill-formed attribute inputs that were previously accepted and used in practice"# }, | ||
362 | LintCompletion { label: "incomplete_include", description: r#"trailing content in included file"# }, | ||
363 | LintCompletion { label: "invalid_type_param_default", description: r#"type parameter default erroneously allowed in invalid location"# }, | ||
364 | LintCompletion { label: "macro_expanded_macro_exports_accessed_by_absolute_paths", description: r#"macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths"# }, | ||
365 | LintCompletion { label: "missing_fragment_specifier", description: r#"detects missing fragment specifiers in unused `macro_rules!` patterns"# }, | ||
366 | LintCompletion { label: "mutable_transmutes", description: r#"mutating transmuted &mut T from &T may cause undefined behavior"# }, | ||
367 | LintCompletion { label: "no_mangle_const_items", description: r#"const items will not have their symbols exported"# }, | ||
368 | LintCompletion { label: "order_dependent_trait_objects", description: r#"trait-object types were treated as different depending on marker-trait order"# }, | ||
369 | LintCompletion { label: "overflowing_literals", description: r#"literal out of range for its type"# }, | ||
370 | LintCompletion { label: "patterns_in_fns_without_body", description: r#"patterns in functions without body were erroneously allowed"# }, | ||
371 | LintCompletion { label: "pub_use_of_private_extern_crate", description: r#"detect public re-exports of private extern crates"# }, | ||
372 | LintCompletion { label: "soft_unstable", description: r#"a feature gate that doesn't break dependent crates"# }, | ||
373 | LintCompletion { label: "unconditional_panic", description: r#"operation will cause a panic at runtime"# }, | ||
374 | LintCompletion { label: "unknown_crate_types", description: r#"unknown crate type found in `#[crate_type]` directive"# }, | ||
375 | ]; | ||
376 | |||
227 | #[cfg(test)] | 377 | #[cfg(test)] |
228 | mod tests { | 378 | mod tests { |
229 | use expect::{expect, Expect}; | 379 | use expect::{expect, Expect}; |
@@ -257,6 +407,130 @@ struct Test {} | |||
257 | } | 407 | } |
258 | 408 | ||
259 | #[test] | 409 | #[test] |
410 | fn empty_lint_completion() { | ||
411 | check( | ||
412 | r#"#[allow(<|>)]"#, | ||
413 | expect![[r#" | ||
414 | at absolute_paths_not_starting_with_crate fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name | ||
415 | at ambiguous_associated_items ambiguous associated items | ||
416 | at anonymous_parameters detects anonymous parameters | ||
417 | at arithmetic_overflow arithmetic operation overflows | ||
418 | at array_into_iter detects calling `into_iter` on arrays | ||
419 | at asm_sub_register using only a subset of a register for inline asm inputs | ||
420 | at bare_trait_objects suggest using `dyn Trait` for trait objects | ||
421 | at bindings_with_variant_name detects pattern bindings with the same name as one of the matched variants | ||
422 | at box_pointers use of owned (Box type) heap memory | ||
423 | at cenum_impl_drop_cast a C-like enum implementing Drop is cast | ||
424 | at clashing_extern_declarations detects when an extern fn has been declared with the same name but different types | ||
425 | at coherence_leak_check distinct impls distinguished only by the leak-check code | ||
426 | at conflicting_repr_hints conflicts between `#[repr(..)]` hints that were previously accepted and used in practice | ||
427 | at confusable_idents detects visually confusable pairs between identifiers | ||
428 | at const_err constant evaluation detected erroneous expression | ||
429 | at dead_code detect unused, unexported items | ||
430 | at deprecated detects use of deprecated items | ||
431 | at deprecated_in_future detects use of items that will be deprecated in a future version | ||
432 | at elided_lifetimes_in_paths hidden lifetime parameters in types are deprecated | ||
433 | at ellipsis_inclusive_range_patterns `...` range patterns are deprecated | ||
434 | at explicit_outlives_requirements outlives requirements can be inferred | ||
435 | at exported_private_dependencies public interface leaks type from a private dependency | ||
436 | at ill_formed_attribute_input ill-formed attribute inputs that were previously accepted and used in practice | ||
437 | at illegal_floating_point_literal_pattern floating-point literals cannot be used in patterns | ||
438 | at improper_ctypes proper use of libc types in foreign modules | ||
439 | at improper_ctypes_definitions proper use of libc types in foreign item definitions | ||
440 | at incomplete_features incomplete features that may function improperly in some or all cases | ||
441 | at incomplete_include trailing content in included file | ||
442 | at indirect_structural_match pattern with const indirectly referencing non-structural-match type | ||
443 | at inline_no_sanitize detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]` | ||
444 | at intra_doc_link_resolution_failure failures in resolving intra-doc link targets | ||
445 | at invalid_codeblock_attributes codeblock attribute looks a lot like a known one | ||
446 | at invalid_type_param_default type parameter default erroneously allowed in invalid location | ||
447 | at invalid_value an invalid value is being created (such as a NULL reference) | ||
448 | at irrefutable_let_patterns detects irrefutable patterns in if-let and while-let statements | ||
449 | at keyword_idents detects edition keywords being used as an identifier | ||
450 | at late_bound_lifetime_arguments detects generic lifetime arguments in path segments with late bound lifetime parameters | ||
451 | at macro_expanded_macro_exports_accessed_by_absolute_paths macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths | ||
452 | at macro_use_extern_crate the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system | ||
453 | at meta_variable_misuse possible meta-variable misuse at macro definition | ||
454 | at missing_copy_implementations detects potentially-forgotten implementations of `Copy` | ||
455 | at missing_crate_level_docs detects crates with no crate-level documentation | ||
456 | at missing_debug_implementations detects missing implementations of Debug | ||
457 | at missing_doc_code_examples detects publicly-exported items without code samples in their documentation | ||
458 | at missing_docs detects missing documentation for public members | ||
459 | at missing_fragment_specifier detects missing fragment specifiers in unused `macro_rules!` patterns | ||
460 | at mixed_script_confusables detects Unicode scripts whose mixed script confusables codepoints are solely used | ||
461 | at mutable_borrow_reservation_conflict reservation of a two-phased borrow conflicts with other shared borrows | ||
462 | at mutable_transmutes mutating transmuted &mut T from &T may cause undefined behavior | ||
463 | at no_mangle_const_items const items will not have their symbols exported | ||
464 | at no_mangle_generic_items generic items must be mangled | ||
465 | at non_ascii_idents detects non-ASCII identifiers | ||
466 | at non_camel_case_types types, variants, traits and type parameters should have camel case names | ||
467 | at non_shorthand_field_patterns using `Struct { x: x }` instead of `Struct { x }` in a pattern | ||
468 | at non_snake_case variables, methods, functions, lifetime parameters and modules should have snake case names | ||
469 | at non_upper_case_globals static constants should have uppercase identifiers | ||
470 | at order_dependent_trait_objects trait-object types were treated as different depending on marker-trait order | ||
471 | at overflowing_literals literal out of range for its type | ||
472 | at overlapping_patterns detects overlapping patterns | ||
473 | at path_statements path statements with no effect | ||
474 | at patterns_in_fns_without_body patterns in functions without body were erroneously allowed | ||
475 | at private_doc_tests detects code samples in docs of private items not documented by rustdoc | ||
476 | at private_in_public detect private items in public interfaces not caught by the old implementation | ||
477 | at proc_macro_derive_resolution_fallback detects proc macro derives using inaccessible names from parent modules | ||
478 | at pub_use_of_private_extern_crate detect public re-exports of private extern crates | ||
479 | at redundant_semicolons detects unnecessary trailing semicolons | ||
480 | at renamed_and_removed_lints lints that have been renamed or removed | ||
481 | at safe_packed_borrows safe borrows of fields of packed structs were erroneously allowed | ||
482 | at single_use_lifetimes detects lifetime parameters that are only used once | ||
483 | at soft_unstable a feature gate that doesn't break dependent crates | ||
484 | at stable_features stable features found in `#[feature]` directive | ||
485 | at trivial_bounds these bounds don't depend on an type parameters | ||
486 | at trivial_casts detects trivial casts which could be removed | ||
487 | at trivial_numeric_casts detects trivial casts of numeric types which could be removed | ||
488 | at type_alias_bounds bounds in type aliases are not enforced | ||
489 | at tyvar_behind_raw_pointer raw pointer to an inference variable | ||
490 | at unaligned_references detects unaligned references to fields of packed structs | ||
491 | at uncommon_codepoints detects uncommon Unicode codepoints in identifiers | ||
492 | at unconditional_panic operation will cause a panic at runtime | ||
493 | at unconditional_recursion functions that cannot return without calling themselves | ||
494 | at unknown_crate_types unknown crate type found in `#[crate_type]` directive | ||
495 | at unknown_lints unrecognized lint attribute | ||
496 | at unnameable_test_items detects an item that cannot be named being marked as `#[test_case]` | ||
497 | at unreachable_code detects unreachable code paths | ||
498 | at unreachable_patterns detects unreachable patterns | ||
499 | at unreachable_pub `pub` items not reachable from crate root | ||
500 | at unsafe_code usage of `unsafe` code | ||
501 | at unsafe_op_in_unsafe_fn unsafe operations in unsafe functions without an explicit unsafe block are deprecated | ||
502 | at unstable_features enabling unstable features (deprecated. do not use) | ||
503 | at unstable_name_collisions detects name collision with an existing but unstable method | ||
504 | at unused_allocation detects unnecessary allocations that can be eliminated | ||
505 | at unused_assignments detect assignments that will never be read | ||
506 | at unused_attributes detects attributes that were not used by the compiler | ||
507 | at unused_braces unnecessary braces around an expression | ||
508 | at unused_comparisons comparisons made useless by limits of the types involved | ||
509 | at unused_crate_dependencies crate dependencies that are never used | ||
510 | at unused_doc_comments detects doc comments that aren't used by rustdoc | ||
511 | at unused_extern_crates extern crates that are never used | ||
512 | at unused_features unused features found in crate-level `#[feature]` directives | ||
513 | at unused_import_braces unnecessary braces around an imported item | ||
514 | at unused_imports imports that are never used | ||
515 | at unused_labels detects labels that are never used | ||
516 | at unused_lifetimes detects lifetime parameters that are never used | ||
517 | at unused_macros detects macros that were not used | ||
518 | at unused_must_use unused result of a type flagged as `#[must_use]` | ||
519 | at unused_mut detect mut variables which don't need to be mutable | ||
520 | at unused_parens `if`, `match`, `while` and `return` do not need parentheses | ||
521 | at unused_qualifications detects unnecessarily qualified names | ||
522 | at unused_results unused result of an expression in a statement | ||
523 | at unused_unsafe unnecessary use of an `unsafe` block | ||
524 | at unused_variables detect variables which are not used in any way | ||
525 | at variant_size_differences detects enums with widely varying variant sizes | ||
526 | at warnings mass-change the level for lints which produce warnings | ||
527 | at where_clauses_object_safety checks the object safety of where clauses | ||
528 | at while_true suggest using `loop { }` instead of `while true { }` | ||
529 | "#]], | ||
530 | ) | ||
531 | } | ||
532 | |||
533 | #[test] | ||
260 | fn no_completion_for_incorrect_derive() { | 534 | fn no_completion_for_incorrect_derive() { |
261 | check( | 535 | check( |
262 | r#" | 536 | r#" |
@@ -325,7 +599,7 @@ struct Test {} | |||
325 | 599 | ||
326 | #[test] | 600 | #[test] |
327 | fn test_attribute_completion_inside_nested_attr() { | 601 | fn test_attribute_completion_inside_nested_attr() { |
328 | check(r#"#[allow(<|>)]"#, expect![[]]) | 602 | check(r#"#[cfg(<|>)]"#, expect![[]]) |
329 | } | 603 | } |
330 | 604 | ||
331 | #[test] | 605 | #[test] |
diff --git a/crates/ra_prof/src/memory_usage.rs b/crates/ra_prof/src/memory_usage.rs index ee79ec3ee..745345fac 100644 --- a/crates/ra_prof/src/memory_usage.rs +++ b/crates/ra_prof/src/memory_usage.rs | |||
@@ -31,6 +31,12 @@ impl fmt::Display for MemoryUsage { | |||
31 | #[derive(Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] | 31 | #[derive(Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] |
32 | pub struct Bytes(usize); | 32 | pub struct Bytes(usize); |
33 | 33 | ||
34 | impl Bytes { | ||
35 | pub fn megabytes(self) -> usize { | ||
36 | self.0 / 1024 / 1024 | ||
37 | } | ||
38 | } | ||
39 | |||
34 | impl fmt::Display for Bytes { | 40 | impl fmt::Display for Bytes { |
35 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | 41 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
36 | let bytes = self.0; | 42 | let bytes = self.0; |
diff --git a/crates/ra_ssr/src/lib.rs b/crates/ra_ssr/src/lib.rs index 2fb326b45..7014a6ac6 100644 --- a/crates/ra_ssr/src/lib.rs +++ b/crates/ra_ssr/src/lib.rs | |||
@@ -51,8 +51,7 @@ pub struct MatchFinder<'db> { | |||
51 | /// Our source of information about the user's code. | 51 | /// Our source of information about the user's code. |
52 | sema: Semantics<'db, ra_ide_db::RootDatabase>, | 52 | sema: Semantics<'db, ra_ide_db::RootDatabase>, |
53 | rules: Vec<ResolvedRule>, | 53 | rules: Vec<ResolvedRule>, |
54 | scope: hir::SemanticsScope<'db>, | 54 | resolution_scope: resolving::ResolutionScope<'db>, |
55 | hygiene: hir::Hygiene, | ||
56 | } | 55 | } |
57 | 56 | ||
58 | impl<'db> MatchFinder<'db> { | 57 | impl<'db> MatchFinder<'db> { |
@@ -63,21 +62,8 @@ impl<'db> MatchFinder<'db> { | |||
63 | lookup_context: FilePosition, | 62 | lookup_context: FilePosition, |
64 | ) -> MatchFinder<'db> { | 63 | ) -> MatchFinder<'db> { |
65 | let sema = Semantics::new(db); | 64 | let sema = Semantics::new(db); |
66 | let file = sema.parse(lookup_context.file_id); | 65 | let resolution_scope = resolving::ResolutionScope::new(&sema, lookup_context); |
67 | // Find a node at the requested position, falling back to the whole file. | 66 | MatchFinder { sema: Semantics::new(db), rules: Vec::new(), resolution_scope } |
68 | let node = file | ||
69 | .syntax() | ||
70 | .token_at_offset(lookup_context.offset) | ||
71 | .left_biased() | ||
72 | .map(|token| token.parent()) | ||
73 | .unwrap_or_else(|| file.syntax().clone()); | ||
74 | let scope = sema.scope(&node); | ||
75 | MatchFinder { | ||
76 | sema: Semantics::new(db), | ||
77 | rules: Vec::new(), | ||
78 | scope, | ||
79 | hygiene: hir::Hygiene::new(db, lookup_context.file_id.into()), | ||
80 | } | ||
81 | } | 67 | } |
82 | 68 | ||
83 | /// Constructs an instance using the start of the first file in `db` as the lookup context. | 69 | /// Constructs an instance using the start of the first file in `db` as the lookup context. |
@@ -106,8 +92,7 @@ impl<'db> MatchFinder<'db> { | |||
106 | for parsed_rule in rule.parsed_rules { | 92 | for parsed_rule in rule.parsed_rules { |
107 | self.rules.push(ResolvedRule::new( | 93 | self.rules.push(ResolvedRule::new( |
108 | parsed_rule, | 94 | parsed_rule, |
109 | &self.scope, | 95 | &self.resolution_scope, |
110 | &self.hygiene, | ||
111 | self.rules.len(), | 96 | self.rules.len(), |
112 | )?); | 97 | )?); |
113 | } | 98 | } |
@@ -140,8 +125,7 @@ impl<'db> MatchFinder<'db> { | |||
140 | for parsed_rule in pattern.parsed_rules { | 125 | for parsed_rule in pattern.parsed_rules { |
141 | self.rules.push(ResolvedRule::new( | 126 | self.rules.push(ResolvedRule::new( |
142 | parsed_rule, | 127 | parsed_rule, |
143 | &self.scope, | 128 | &self.resolution_scope, |
144 | &self.hygiene, | ||
145 | self.rules.len(), | 129 | self.rules.len(), |
146 | )?); | 130 | )?); |
147 | } | 131 | } |
diff --git a/crates/ra_ssr/src/resolving.rs b/crates/ra_ssr/src/resolving.rs index 75f556785..123bd2bb2 100644 --- a/crates/ra_ssr/src/resolving.rs +++ b/crates/ra_ssr/src/resolving.rs | |||
@@ -3,10 +3,16 @@ | |||
3 | use crate::errors::error; | 3 | use crate::errors::error; |
4 | use crate::{parsing, SsrError}; | 4 | use crate::{parsing, SsrError}; |
5 | use parsing::Placeholder; | 5 | use parsing::Placeholder; |
6 | use ra_db::FilePosition; | ||
6 | use ra_syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken}; | 7 | use ra_syntax::{ast, SmolStr, SyntaxKind, SyntaxNode, SyntaxToken}; |
7 | use rustc_hash::{FxHashMap, FxHashSet}; | 8 | use rustc_hash::{FxHashMap, FxHashSet}; |
8 | use test_utils::mark; | 9 | use test_utils::mark; |
9 | 10 | ||
11 | pub(crate) struct ResolutionScope<'db> { | ||
12 | scope: hir::SemanticsScope<'db>, | ||
13 | hygiene: hir::Hygiene, | ||
14 | } | ||
15 | |||
10 | pub(crate) struct ResolvedRule { | 16 | pub(crate) struct ResolvedRule { |
11 | pub(crate) pattern: ResolvedPattern, | 17 | pub(crate) pattern: ResolvedPattern, |
12 | pub(crate) template: Option<ResolvedPattern>, | 18 | pub(crate) template: Option<ResolvedPattern>, |
@@ -30,12 +36,11 @@ pub(crate) struct ResolvedPath { | |||
30 | impl ResolvedRule { | 36 | impl ResolvedRule { |
31 | pub(crate) fn new( | 37 | pub(crate) fn new( |
32 | rule: parsing::ParsedRule, | 38 | rule: parsing::ParsedRule, |
33 | scope: &hir::SemanticsScope, | 39 | resolution_scope: &ResolutionScope, |
34 | hygiene: &hir::Hygiene, | ||
35 | index: usize, | 40 | index: usize, |
36 | ) -> Result<ResolvedRule, SsrError> { | 41 | ) -> Result<ResolvedRule, SsrError> { |
37 | let resolver = | 42 | let resolver = |
38 | Resolver { scope, hygiene, placeholders_by_stand_in: rule.placeholders_by_stand_in }; | 43 | Resolver { resolution_scope, placeholders_by_stand_in: rule.placeholders_by_stand_in }; |
39 | let resolved_template = if let Some(template) = rule.template { | 44 | let resolved_template = if let Some(template) = rule.template { |
40 | Some(resolver.resolve_pattern_tree(template)?) | 45 | Some(resolver.resolve_pattern_tree(template)?) |
41 | } else { | 46 | } else { |
@@ -57,8 +62,7 @@ impl ResolvedRule { | |||
57 | } | 62 | } |
58 | 63 | ||
59 | struct Resolver<'a, 'db> { | 64 | struct Resolver<'a, 'db> { |
60 | scope: &'a hir::SemanticsScope<'db>, | 65 | resolution_scope: &'a ResolutionScope<'db>, |
61 | hygiene: &'a hir::Hygiene, | ||
62 | placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>, | 66 | placeholders_by_stand_in: FxHashMap<SmolStr, parsing::Placeholder>, |
63 | } | 67 | } |
64 | 68 | ||
@@ -104,6 +108,7 @@ impl Resolver<'_, '_> { | |||
104 | && !self.path_contains_placeholder(&path) | 108 | && !self.path_contains_placeholder(&path) |
105 | { | 109 | { |
106 | let resolution = self | 110 | let resolution = self |
111 | .resolution_scope | ||
107 | .resolve_path(&path) | 112 | .resolve_path(&path) |
108 | .ok_or_else(|| error!("Failed to resolve path `{}`", node.text()))?; | 113 | .ok_or_else(|| error!("Failed to resolve path `{}`", node.text()))?; |
109 | resolved_paths.insert(node, ResolvedPath { resolution, depth }); | 114 | resolved_paths.insert(node, ResolvedPath { resolution, depth }); |
@@ -131,9 +136,32 @@ impl Resolver<'_, '_> { | |||
131 | } | 136 | } |
132 | false | 137 | false |
133 | } | 138 | } |
139 | } | ||
140 | |||
141 | impl<'db> ResolutionScope<'db> { | ||
142 | pub(crate) fn new( | ||
143 | sema: &hir::Semantics<'db, ra_ide_db::RootDatabase>, | ||
144 | lookup_context: FilePosition, | ||
145 | ) -> ResolutionScope<'db> { | ||
146 | use ra_syntax::ast::AstNode; | ||
147 | let file = sema.parse(lookup_context.file_id); | ||
148 | // Find a node at the requested position, falling back to the whole file. | ||
149 | let node = file | ||
150 | .syntax() | ||
151 | .token_at_offset(lookup_context.offset) | ||
152 | .left_biased() | ||
153 | .map(|token| token.parent()) | ||
154 | .unwrap_or_else(|| file.syntax().clone()); | ||
155 | let node = pick_node_for_resolution(node); | ||
156 | let scope = sema.scope(&node); | ||
157 | ResolutionScope { | ||
158 | scope, | ||
159 | hygiene: hir::Hygiene::new(sema.db, lookup_context.file_id.into()), | ||
160 | } | ||
161 | } | ||
134 | 162 | ||
135 | fn resolve_path(&self, path: &ast::Path) -> Option<hir::PathResolution> { | 163 | fn resolve_path(&self, path: &ast::Path) -> Option<hir::PathResolution> { |
136 | let hir_path = hir::Path::from_src(path.clone(), self.hygiene)?; | 164 | let hir_path = hir::Path::from_src(path.clone(), &self.hygiene)?; |
137 | // First try resolving the whole path. This will work for things like | 165 | // First try resolving the whole path. This will work for things like |
138 | // `std::collections::HashMap`, but will fail for things like | 166 | // `std::collections::HashMap`, but will fail for things like |
139 | // `std::collections::HashMap::new`. | 167 | // `std::collections::HashMap::new`. |
@@ -158,6 +186,33 @@ impl Resolver<'_, '_> { | |||
158 | } | 186 | } |
159 | } | 187 | } |
160 | 188 | ||
189 | /// Returns a suitable node for resolving paths in the current scope. If we create a scope based on | ||
190 | /// a statement node, then we can't resolve local variables that were defined in the current scope | ||
191 | /// (only in parent scopes). So we find another node, ideally a child of the statement where local | ||
192 | /// variable resolution is permitted. | ||
193 | fn pick_node_for_resolution(node: SyntaxNode) -> SyntaxNode { | ||
194 | match node.kind() { | ||
195 | SyntaxKind::EXPR_STMT => { | ||
196 | if let Some(n) = node.first_child() { | ||
197 | mark::hit!(cursor_after_semicolon); | ||
198 | return n; | ||
199 | } | ||
200 | } | ||
201 | SyntaxKind::LET_STMT | SyntaxKind::BIND_PAT => { | ||
202 | if let Some(next) = node.next_sibling() { | ||
203 | return pick_node_for_resolution(next); | ||
204 | } | ||
205 | } | ||
206 | SyntaxKind::NAME => { | ||
207 | if let Some(parent) = node.parent() { | ||
208 | return pick_node_for_resolution(parent); | ||
209 | } | ||
210 | } | ||
211 | _ => {} | ||
212 | } | ||
213 | node | ||
214 | } | ||
215 | |||
161 | /// Returns whether `path` or any of its qualifiers contains type arguments. | 216 | /// Returns whether `path` or any of its qualifiers contains type arguments. |
162 | fn path_contains_type_arguments(path: Option<ast::Path>) -> bool { | 217 | fn path_contains_type_arguments(path: Option<ast::Path>) -> bool { |
163 | if let Some(path) = path { | 218 | if let Some(path) = path { |
diff --git a/crates/ra_ssr/src/tests.rs b/crates/ra_ssr/src/tests.rs index b38807c0f..18ef2506a 100644 --- a/crates/ra_ssr/src/tests.rs +++ b/crates/ra_ssr/src/tests.rs | |||
@@ -885,3 +885,40 @@ fn ufcs_matches_method_call() { | |||
885 | "#]], | 885 | "#]], |
886 | ); | 886 | ); |
887 | } | 887 | } |
888 | |||
889 | #[test] | ||
890 | fn replace_local_variable_reference() { | ||
891 | // The pattern references a local variable `foo` in the block containing the cursor. We should | ||
892 | // only replace references to this variable `foo`, not other variables that just happen to have | ||
893 | // the same name. | ||
894 | mark::check!(cursor_after_semicolon); | ||
895 | assert_ssr_transform( | ||
896 | "foo + $a ==>> $a - foo", | ||
897 | r#" | ||
898 | fn bar1() -> i32 { | ||
899 | let mut res = 0; | ||
900 | let foo = 5; | ||
901 | res += foo + 1; | ||
902 | let foo = 10; | ||
903 | res += foo + 2;<|> | ||
904 | res += foo + 3; | ||
905 | let foo = 15; | ||
906 | res += foo + 4; | ||
907 | res | ||
908 | } | ||
909 | "#, | ||
910 | expect![[r#" | ||
911 | fn bar1() -> i32 { | ||
912 | let mut res = 0; | ||
913 | let foo = 5; | ||
914 | res += foo + 1; | ||
915 | let foo = 10; | ||
916 | res += 2 - foo; | ||
917 | res += 3 - foo; | ||
918 | let foo = 15; | ||
919 | res += foo + 4; | ||
920 | res | ||
921 | } | ||
922 | "#]], | ||
923 | ) | ||
924 | } | ||
diff --git a/crates/rust-analyzer/src/cli.rs b/crates/rust-analyzer/src/cli.rs index 753001949..a9b9c8923 100644 --- a/crates/rust-analyzer/src/cli.rs +++ b/crates/rust-analyzer/src/cli.rs | |||
@@ -74,3 +74,10 @@ fn read_stdin() -> Result<String> { | |||
74 | std::io::stdin().read_to_string(&mut buff)?; | 74 | std::io::stdin().read_to_string(&mut buff)?; |
75 | Ok(buff) | 75 | Ok(buff) |
76 | } | 76 | } |
77 | |||
78 | fn report_metric(metric: &str, value: u64, unit: &str) { | ||
79 | if std::env::var("RA_METRICS").is_err() { | ||
80 | return; | ||
81 | } | ||
82 | println!("METRIC:{}:{}:{}", metric, value, unit) | ||
83 | } | ||
diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index ddb3db6c3..ccc058682 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs | |||
@@ -3,26 +3,27 @@ | |||
3 | 3 | ||
4 | use std::{path::Path, time::Instant}; | 4 | use std::{path::Path, time::Instant}; |
5 | 5 | ||
6 | use itertools::Itertools; | ||
7 | use rand::{seq::SliceRandom, thread_rng}; | ||
8 | use rayon::prelude::*; | ||
9 | use rustc_hash::FxHashSet; | ||
10 | |||
11 | use hir::{ | 6 | use hir::{ |
12 | db::{AstDatabase, DefDatabase, HirDatabase}, | 7 | db::{AstDatabase, DefDatabase, HirDatabase}, |
13 | original_range, AssocItem, Crate, HasSource, HirDisplay, ModuleDef, | 8 | original_range, AssocItem, Crate, HasSource, HirDisplay, ModuleDef, |
14 | }; | 9 | }; |
15 | use hir_def::FunctionId; | 10 | use hir_def::FunctionId; |
16 | use hir_ty::{Ty, TypeWalk}; | 11 | use hir_ty::{Ty, TypeWalk}; |
12 | use itertools::Itertools; | ||
17 | use ra_db::{ | 13 | use ra_db::{ |
18 | salsa::{self, ParallelDatabase}, | 14 | salsa::{self, ParallelDatabase}, |
19 | SourceDatabaseExt, | 15 | SourceDatabaseExt, |
20 | }; | 16 | }; |
21 | use ra_syntax::AstNode; | 17 | use ra_syntax::AstNode; |
18 | use rand::{seq::SliceRandom, thread_rng}; | ||
19 | use rayon::prelude::*; | ||
20 | use rustc_hash::FxHashSet; | ||
22 | use stdx::format_to; | 21 | use stdx::format_to; |
23 | 22 | ||
24 | use crate::{ | 23 | use crate::{ |
25 | cli::{load_cargo::load_cargo, progress_report::ProgressReport, Result, Verbosity}, | 24 | cli::{ |
25 | load_cargo::load_cargo, progress_report::ProgressReport, report_metric, Result, Verbosity, | ||
26 | }, | ||
26 | print_memory_usage, | 27 | print_memory_usage, |
27 | }; | 28 | }; |
28 | 29 | ||
@@ -48,7 +49,7 @@ pub fn analysis_stats( | |||
48 | let db_load_time = Instant::now(); | 49 | let db_load_time = Instant::now(); |
49 | let (host, vfs) = load_cargo(path, load_output_dirs, with_proc_macro)?; | 50 | let (host, vfs) = load_cargo(path, load_output_dirs, with_proc_macro)?; |
50 | let db = host.raw_database(); | 51 | let db = host.raw_database(); |
51 | println!("Database loaded {:?}", db_load_time.elapsed()); | 52 | eprintln!("Database loaded {:?}", db_load_time.elapsed()); |
52 | let analysis_time = Instant::now(); | 53 | let analysis_time = Instant::now(); |
53 | let mut num_crates = 0; | 54 | let mut num_crates = 0; |
54 | let mut visited_modules = FxHashSet::default(); | 55 | let mut visited_modules = FxHashSet::default(); |
@@ -74,7 +75,7 @@ pub fn analysis_stats( | |||
74 | visit_queue.shuffle(&mut thread_rng()); | 75 | visit_queue.shuffle(&mut thread_rng()); |
75 | } | 76 | } |
76 | 77 | ||
77 | println!("Crates in this dir: {}", num_crates); | 78 | eprintln!("Crates in this dir: {}", num_crates); |
78 | let mut num_decls = 0; | 79 | let mut num_decls = 0; |
79 | let mut funcs = Vec::new(); | 80 | let mut funcs = Vec::new(); |
80 | while let Some(module) = visit_queue.pop() { | 81 | while let Some(module) = visit_queue.pop() { |
@@ -98,10 +99,15 @@ pub fn analysis_stats( | |||
98 | } | 99 | } |
99 | } | 100 | } |
100 | } | 101 | } |
101 | println!("Total modules found: {}", visited_modules.len()); | 102 | eprintln!("Total modules found: {}", visited_modules.len()); |
102 | println!("Total declarations: {}", num_decls); | 103 | eprintln!("Total declarations: {}", num_decls); |
103 | println!("Total functions: {}", funcs.len()); | 104 | eprintln!("Total functions: {}", funcs.len()); |
104 | println!("Item Collection: {:?}, {}", analysis_time.elapsed(), ra_prof::memory_usage()); | 105 | let item_collection_memory = ra_prof::memory_usage(); |
106 | eprintln!( | ||
107 | "Item Collection: {:?}, {}", | ||
108 | analysis_time.elapsed(), | ||
109 | item_collection_memory.allocated | ||
110 | ); | ||
105 | 111 | ||
106 | if randomize { | 112 | if randomize { |
107 | funcs.shuffle(&mut thread_rng()); | 113 | funcs.shuffle(&mut thread_rng()); |
@@ -123,7 +129,11 @@ pub fn analysis_stats( | |||
123 | snap.0.infer(f_id.into()); | 129 | snap.0.infer(f_id.into()); |
124 | }) | 130 | }) |
125 | .count(); | 131 | .count(); |
126 | println!("Parallel Inference: {:?}, {}", inference_time.elapsed(), ra_prof::memory_usage()); | 132 | eprintln!( |
133 | "Parallel Inference: {:?}, {}", | ||
134 | inference_time.elapsed(), | ||
135 | ra_prof::memory_usage().allocated | ||
136 | ); | ||
127 | } | 137 | } |
128 | 138 | ||
129 | let inference_time = Instant::now(); | 139 | let inference_time = Instant::now(); |
@@ -260,20 +270,35 @@ pub fn analysis_stats( | |||
260 | bar.inc(1); | 270 | bar.inc(1); |
261 | } | 271 | } |
262 | bar.finish_and_clear(); | 272 | bar.finish_and_clear(); |
263 | println!("Total expressions: {}", num_exprs); | 273 | eprintln!("Total expressions: {}", num_exprs); |
264 | println!( | 274 | eprintln!( |
265 | "Expressions of unknown type: {} ({}%)", | 275 | "Expressions of unknown type: {} ({}%)", |
266 | num_exprs_unknown, | 276 | num_exprs_unknown, |
267 | if num_exprs > 0 { num_exprs_unknown * 100 / num_exprs } else { 100 } | 277 | if num_exprs > 0 { num_exprs_unknown * 100 / num_exprs } else { 100 } |
268 | ); | 278 | ); |
269 | println!( | 279 | report_metric("unknown type", num_exprs_unknown, "#"); |
280 | |||
281 | eprintln!( | ||
270 | "Expressions of partially unknown type: {} ({}%)", | 282 | "Expressions of partially unknown type: {} ({}%)", |
271 | num_exprs_partially_unknown, | 283 | num_exprs_partially_unknown, |
272 | if num_exprs > 0 { num_exprs_partially_unknown * 100 / num_exprs } else { 100 } | 284 | if num_exprs > 0 { num_exprs_partially_unknown * 100 / num_exprs } else { 100 } |
273 | ); | 285 | ); |
274 | println!("Type mismatches: {}", num_type_mismatches); | 286 | |
275 | println!("Inference: {:?}, {}", inference_time.elapsed(), ra_prof::memory_usage()); | 287 | eprintln!("Type mismatches: {}", num_type_mismatches); |
276 | println!("Total: {:?}, {}", analysis_time.elapsed(), ra_prof::memory_usage()); | 288 | report_metric("type mismatches", num_type_mismatches, "#"); |
289 | |||
290 | let inference_time = inference_time.elapsed(); | ||
291 | let total_memory = ra_prof::memory_usage(); | ||
292 | eprintln!( | ||
293 | "Inference: {:?}, {}", | ||
294 | inference_time, | ||
295 | total_memory.allocated - item_collection_memory.allocated | ||
296 | ); | ||
297 | |||
298 | let analysis_time = analysis_time.elapsed(); | ||
299 | eprintln!("Total: {:?}, {}", analysis_time, total_memory); | ||
300 | report_metric("total time", analysis_time.as_millis() as u64, "ms"); | ||
301 | report_metric("total memory", total_memory.allocated.megabytes() as u64, "MB"); | ||
277 | 302 | ||
278 | if memory_usage { | 303 | if memory_usage { |
279 | print_memory_usage(host, vfs); | 304 | print_memory_usage(host, vfs); |
diff --git a/crates/rust-analyzer/src/lib.rs b/crates/rust-analyzer/src/lib.rs index c4284556e..ed37992cd 100644 --- a/crates/rust-analyzer/src/lib.rs +++ b/crates/rust-analyzer/src/lib.rs | |||
@@ -86,6 +86,6 @@ fn print_memory_usage(mut host: AnalysisHost, vfs: Vfs) { | |||
86 | mem.push(("Remaining".into(), ra_prof::memory_usage().allocated)); | 86 | mem.push(("Remaining".into(), ra_prof::memory_usage().allocated)); |
87 | 87 | ||
88 | for (name, bytes) in mem { | 88 | for (name, bytes) in mem { |
89 | println!("{:>8} {}", bytes, name); | 89 | eprintln!("{:>8} {}", bytes, name); |
90 | } | 90 | } |
91 | } | 91 | } |
diff --git a/crates/vfs/src/file_set.rs b/crates/vfs/src/file_set.rs index e5e2ef530..e9196fcd2 100644 --- a/crates/vfs/src/file_set.rs +++ b/crates/vfs/src/file_set.rs | |||
@@ -148,25 +148,54 @@ impl fst::Automaton for PrefixOf<'_> { | |||
148 | } | 148 | } |
149 | } | 149 | } |
150 | 150 | ||
151 | #[test] | 151 | #[cfg(test)] |
152 | fn test_partitioning() { | 152 | mod tests { |
153 | let mut file_set = FileSetConfig::builder(); | 153 | use super::*; |
154 | file_set.add_file_set(vec![VfsPath::new_virtual_path("/foo".into())]); | 154 | |
155 | file_set.add_file_set(vec![VfsPath::new_virtual_path("/foo/bar/baz".into())]); | 155 | #[test] |
156 | let file_set = file_set.build(); | 156 | fn path_prefix() { |
157 | 157 | let mut file_set = FileSetConfig::builder(); | |
158 | let mut vfs = Vfs::default(); | 158 | file_set.add_file_set(vec![VfsPath::new_virtual_path("/foo".into())]); |
159 | vfs.set_file_contents(VfsPath::new_virtual_path("/foo/src/lib.rs".into()), Some(Vec::new())); | 159 | file_set.add_file_set(vec![VfsPath::new_virtual_path("/foo/bar/baz".into())]); |
160 | vfs.set_file_contents( | 160 | let file_set = file_set.build(); |
161 | VfsPath::new_virtual_path("/foo/src/bar/baz/lib.rs".into()), | 161 | |
162 | Some(Vec::new()), | 162 | let mut vfs = Vfs::default(); |
163 | ); | 163 | vfs.set_file_contents( |
164 | vfs.set_file_contents( | 164 | VfsPath::new_virtual_path("/foo/src/lib.rs".into()), |
165 | VfsPath::new_virtual_path("/foo/bar/baz/lib.rs".into()), | 165 | Some(Vec::new()), |
166 | Some(Vec::new()), | 166 | ); |
167 | ); | 167 | vfs.set_file_contents( |
168 | vfs.set_file_contents(VfsPath::new_virtual_path("/quux/lib.rs".into()), Some(Vec::new())); | 168 | VfsPath::new_virtual_path("/foo/src/bar/baz/lib.rs".into()), |
169 | 169 | Some(Vec::new()), | |
170 | let partition = file_set.partition(&vfs).into_iter().map(|it| it.len()).collect::<Vec<_>>(); | 170 | ); |
171 | assert_eq!(partition, vec![2, 1, 1]); | 171 | vfs.set_file_contents( |
172 | VfsPath::new_virtual_path("/foo/bar/baz/lib.rs".into()), | ||
173 | Some(Vec::new()), | ||
174 | ); | ||
175 | vfs.set_file_contents(VfsPath::new_virtual_path("/quux/lib.rs".into()), Some(Vec::new())); | ||
176 | |||
177 | let partition = file_set.partition(&vfs).into_iter().map(|it| it.len()).collect::<Vec<_>>(); | ||
178 | assert_eq!(partition, vec![2, 1, 1]); | ||
179 | } | ||
180 | |||
181 | #[test] | ||
182 | fn name_prefix() { | ||
183 | let mut file_set = FileSetConfig::builder(); | ||
184 | file_set.add_file_set(vec![VfsPath::new_virtual_path("/foo".into())]); | ||
185 | file_set.add_file_set(vec![VfsPath::new_virtual_path("/foo-things".into())]); | ||
186 | let file_set = file_set.build(); | ||
187 | |||
188 | let mut vfs = Vfs::default(); | ||
189 | vfs.set_file_contents( | ||
190 | VfsPath::new_virtual_path("/foo/src/lib.rs".into()), | ||
191 | Some(Vec::new()), | ||
192 | ); | ||
193 | vfs.set_file_contents( | ||
194 | VfsPath::new_virtual_path("/foo-things/src/lib.rs".into()), | ||
195 | Some(Vec::new()), | ||
196 | ); | ||
197 | |||
198 | let partition = file_set.partition(&vfs).into_iter().map(|it| it.len()).collect::<Vec<_>>(); | ||
199 | assert_eq!(partition, vec![1, 1, 0]); | ||
200 | } | ||
172 | } | 201 | } |