aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/assists/src/handlers/extract_struct_from_enum_variant.rs22
-rw-r--r--crates/assists/src/handlers/move_guard.rs87
-rw-r--r--crates/assists/src/handlers/qualify_path.rs182
-rw-r--r--crates/assists/src/lib.rs5
-rw-r--r--crates/assists/src/utils/import_assets.rs6
-rw-r--r--crates/assists/src/utils/insert_use.rs4
-rw-r--r--crates/base_db/src/input.rs4
-rw-r--r--crates/base_db/src/lib.rs4
-rw-r--r--crates/completion/src/completions.rs (renamed from crates/completion/src/presentation.rs)102
-rw-r--r--crates/completion/src/completions/attribute.rs (renamed from crates/completion/src/complete_attribute.rs)50
-rw-r--r--crates/completion/src/completions/dot.rs (renamed from crates/completion/src/complete_dot.rs)10
-rw-r--r--crates/completion/src/completions/fn_param.rs (renamed from crates/completion/src/complete_fn_param.rs)2
-rw-r--r--crates/completion/src/completions/keyword.rs (renamed from crates/completion/src/complete_keyword.rs)4
-rw-r--r--crates/completion/src/completions/macro_in_item_position.rs (renamed from crates/completion/src/complete_macro_in_item_position.rs)2
-rw-r--r--crates/completion/src/completions/mod_.rs (renamed from crates/completion/src/complete_mod.rs)14
-rw-r--r--crates/completion/src/completions/pattern.rs (renamed from crates/completion/src/complete_pattern.rs)2
-rw-r--r--crates/completion/src/completions/postfix.rs (renamed from crates/completion/src/complete_postfix.rs)10
-rw-r--r--crates/completion/src/completions/postfix/format_like.rs (renamed from crates/completion/src/complete_postfix/format_like.rs)14
-rw-r--r--crates/completion/src/completions/qualified_path.rs (renamed from crates/completion/src/complete_qualified_path.rs)14
-rw-r--r--crates/completion/src/completions/record.rs (renamed from crates/completion/src/complete_record.rs)2
-rw-r--r--crates/completion/src/completions/snippet.rs (renamed from crates/completion/src/complete_snippet.rs)8
-rw-r--r--crates/completion/src/completions/trait_impl.rs (renamed from crates/completion/src/complete_trait_impl.rs)0
-rw-r--r--crates/completion/src/completions/unqualified_path.rs (renamed from crates/completion/src/complete_unqualified_path.rs)2
-rw-r--r--crates/completion/src/config.rs (renamed from crates/completion/src/completion_config.rs)0
-rw-r--r--crates/completion/src/context.rs (renamed from crates/completion/src/completion_context.rs)0
-rw-r--r--crates/completion/src/generated_lint_completions.rs6
-rw-r--r--crates/completion/src/item.rs (renamed from crates/completion/src/completion_item.rs)31
-rw-r--r--crates/completion/src/lib.rs62
-rw-r--r--crates/completion/src/test_utils.rs19
-rw-r--r--crates/hir/src/code_model.rs16
-rw-r--r--crates/hir/src/from_id.rs8
-rw-r--r--crates/hir/src/has_source.rs3
-rw-r--r--crates/hir/src/lib.rs3
-rw-r--r--crates/hir_def/src/body/diagnostics.rs4
-rw-r--r--crates/hir_def/src/body/lower.rs6
-rw-r--r--crates/hir_def/src/lib.rs6
-rw-r--r--crates/hir_def/src/nameres/collector.rs21
-rw-r--r--crates/hir_def/src/nameres/tests.rs17
-rw-r--r--crates/hir_def/src/test_db.rs14
-rw-r--r--crates/hir_expand/src/test_db.rs2
-rw-r--r--crates/hir_ty/Cargo.toml6
-rw-r--r--crates/hir_ty/src/diagnostics/decl_check/case_conv.rs6
-rw-r--r--crates/hir_ty/src/diagnostics/expr.rs15
-rw-r--r--crates/hir_ty/src/diagnostics/unsafe_check.rs8
-rw-r--r--crates/hir_ty/src/display.rs149
-rw-r--r--crates/hir_ty/src/infer.rs8
-rw-r--r--crates/hir_ty/src/infer/expr.rs2
-rw-r--r--crates/hir_ty/src/infer/unify.rs37
-rw-r--r--crates/hir_ty/src/lib.rs3
-rw-r--r--crates/hir_ty/src/method_resolution.rs13
-rw-r--r--crates/hir_ty/src/test_db.rs6
-rw-r--r--crates/hir_ty/src/tests.rs8
-rw-r--r--crates/hir_ty/src/traits/chalk.rs23
-rw-r--r--crates/hir_ty/src/traits/chalk/interner.rs37
-rw-r--r--crates/hir_ty/src/traits/chalk/mapping.rs362
-rw-r--r--crates/hir_ty/src/traits/chalk/tls.rs162
-rw-r--r--crates/ide/src/diagnostics/fixes.rs2
-rw-r--r--crates/ide/src/doc_links.rs9
-rw-r--r--crates/ide/src/file_structure.rs2
-rw-r--r--crates/ide/src/inlay_hints.rs129
-rw-r--r--crates/ide/src/join_lines.rs2
-rw-r--r--crates/ide/src/lib.rs14
-rw-r--r--crates/ide/src/markdown_remove.rs3
-rw-r--r--crates/ide/src/matching_brace.rs2
-rw-r--r--crates/ide/src/references.rs8
-rw-r--r--crates/ide/src/runnables.rs70
-rw-r--r--crates/ide/src/syntax_highlighting.rs12
-rw-r--r--crates/ide/src/syntax_highlighting/test_data/highlighting.html12
-rw-r--r--crates/ide/src/syntax_highlighting/tests.rs12
-rw-r--r--crates/mbe/src/mbe_expander/matcher.rs10
-rw-r--r--crates/mbe/src/subtree_source.rs10
-rw-r--r--crates/parser/src/grammar.rs6
-rw-r--r--crates/proc_macro_api/src/process.rs8
-rw-r--r--crates/proc_macro_api/src/rpc.rs34
-rw-r--r--crates/proc_macro_srv/src/lib.rs1
-rw-r--r--crates/profile/src/hprof.rs4
-rw-r--r--crates/profile/src/tree.rs16
-rw-r--r--crates/project_model/src/cargo_workspace.rs4
-rw-r--r--crates/project_model/src/sysroot.rs9
-rw-r--r--crates/rust-analyzer/Cargo.toml2
-rw-r--r--crates/rust-analyzer/src/bin/main.rs2
-rw-r--r--crates/rust-analyzer/src/caps.rs3
-rw-r--r--crates/rust-analyzer/src/cli/progress_report.rs16
-rw-r--r--crates/rust-analyzer/src/config.rs10
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt4
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt2
-rw-r--r--crates/rust-analyzer/src/diagnostics/to_proto.rs4
-rw-r--r--crates/rust-analyzer/src/dispatch.rs40
-rw-r--r--crates/rust-analyzer/src/document.rs4
-rw-r--r--crates/rust-analyzer/src/global_state.rs2
-rw-r--r--crates/rust-analyzer/src/handlers.rs2
-rw-r--r--crates/rust-analyzer/src/lib.rs10
-rw-r--r--crates/rust-analyzer/src/main_loop.rs117
-rw-r--r--crates/rust-analyzer/src/semantic_tokens.rs10
-rw-r--r--crates/rust-analyzer/src/to_proto.rs11
-rw-r--r--crates/rust-analyzer/tests/rust-analyzer/support.rs28
-rw-r--r--crates/rust-analyzer/tests/rust-analyzer/testdir.rs8
-rw-r--r--crates/ssr/src/parsing.rs2
-rw-r--r--crates/syntax/Cargo.toml4
-rw-r--r--crates/syntax/src/ast.rs2
-rw-r--r--crates/syntax/src/ast/generated.rs6
-rw-r--r--crates/syntax/src/lib.rs11
-rw-r--r--crates/syntax/src/parsing.rs4
-rw-r--r--crates/syntax/src/parsing/text_token_source.rs2
-rw-r--r--crates/syntax/src/syntax_node.rs6
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rast54
-rw-r--r--crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rs2
-rw-r--r--crates/vfs/src/vfs_path.rs6
116 files changed, 1446 insertions, 936 deletions
diff --git a/crates/assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/assists/src/handlers/extract_struct_from_enum_variant.rs
index 48433feb9..178718c5e 100644
--- a/crates/assists/src/handlers/extract_struct_from_enum_variant.rs
+++ b/crates/assists/src/handlers/extract_struct_from_enum_variant.rs
@@ -37,6 +37,12 @@ pub(crate) fn extract_struct_from_enum_variant(
37 ast::StructKind::Tuple(field_list) => field_list, 37 ast::StructKind::Tuple(field_list) => field_list,
38 _ => return None, 38 _ => return None,
39 }; 39 };
40
41 // skip 1-tuple variants
42 if field_list.fields().count() == 1 {
43 return None;
44 }
45
40 let variant_name = variant.name()?.to_string(); 46 let variant_name = variant.name()?.to_string();
41 let variant_hir = ctx.sema.to_def(&variant)?; 47 let variant_hir = ctx.sema.to_def(&variant)?;
42 if existing_struct_def(ctx.db(), &variant_name, &variant_hir) { 48 if existing_struct_def(ctx.db(), &variant_name, &variant_hir) {
@@ -233,17 +239,6 @@ enum A { One(One) }"#,
233 } 239 }
234 240
235 #[test] 241 #[test]
236 fn test_extract_struct_one_field() {
237 check_assist(
238 extract_struct_from_enum_variant,
239 "enum A { <|>One(u32) }",
240 r#"struct One(pub u32);
241
242enum A { One(One) }"#,
243 );
244 }
245
246 #[test]
247 fn test_extract_struct_pub_visibility() { 242 fn test_extract_struct_pub_visibility() {
248 check_assist( 243 check_assist(
249 extract_struct_from_enum_variant, 244 extract_struct_from_enum_variant,
@@ -324,4 +319,9 @@ fn another_fn() {
324 enum A { <|>One(u8) }"#, 319 enum A { <|>One(u8) }"#,
325 ); 320 );
326 } 321 }
322
323 #[test]
324 fn test_extract_not_applicable_one_field() {
325 check_not_applicable(r"enum A { <|>One(u32) }");
326 }
327} 327}
diff --git a/crates/assists/src/handlers/move_guard.rs b/crates/assists/src/handlers/move_guard.rs
index 452115fe6..e1855b63d 100644
--- a/crates/assists/src/handlers/move_guard.rs
+++ b/crates/assists/src/handlers/move_guard.rs
@@ -1,5 +1,5 @@
1use syntax::{ 1use syntax::{
2 ast::{edit::AstNodeEdit, make, AstNode, IfExpr, MatchArm}, 2 ast::{edit::AstNodeEdit, make, AstNode, BlockExpr, Expr, IfExpr, MatchArm},
3 SyntaxKind::WHITESPACE, 3 SyntaxKind::WHITESPACE,
4}; 4};
5 5
@@ -92,9 +92,20 @@ pub(crate) fn move_guard_to_arm_body(acc: &mut Assists, ctx: &AssistContext) ->
92pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 92pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
93 let match_arm: MatchArm = ctx.find_node_at_offset::<MatchArm>()?; 93 let match_arm: MatchArm = ctx.find_node_at_offset::<MatchArm>()?;
94 let match_pat = match_arm.pat()?; 94 let match_pat = match_arm.pat()?;
95
96 let arm_body = match_arm.expr()?; 95 let arm_body = match_arm.expr()?;
97 let if_expr: IfExpr = IfExpr::cast(arm_body.syntax().clone())?; 96
97 let mut replace_node = None;
98 let if_expr: IfExpr = IfExpr::cast(arm_body.syntax().clone()).or_else(|| {
99 let block_expr = BlockExpr::cast(arm_body.syntax().clone())?;
100 if let Expr::IfExpr(e) = block_expr.expr()? {
101 replace_node = Some(block_expr.syntax().clone());
102 Some(e)
103 } else {
104 None
105 }
106 })?;
107 let replace_node = replace_node.unwrap_or_else(|| if_expr.syntax().clone());
108
98 let cond = if_expr.condition()?; 109 let cond = if_expr.condition()?;
99 let then_block = if_expr.then_branch()?; 110 let then_block = if_expr.then_branch()?;
100 111
@@ -109,19 +120,23 @@ pub(crate) fn move_arm_cond_to_match_guard(acc: &mut Assists, ctx: &AssistContex
109 120
110 let buf = format!(" if {}", cond.syntax().text()); 121 let buf = format!(" if {}", cond.syntax().text());
111 122
112 let target = if_expr.syntax().text_range();
113 acc.add( 123 acc.add(
114 AssistId("move_arm_cond_to_match_guard", AssistKind::RefactorRewrite), 124 AssistId("move_arm_cond_to_match_guard", AssistKind::RefactorRewrite),
115 "Move condition to match guard", 125 "Move condition to match guard",
116 target, 126 replace_node.text_range(),
117 |edit| { 127 |edit| {
118 let then_only_expr = then_block.statements().next().is_none(); 128 let then_only_expr = then_block.statements().next().is_none();
119 129
120 match &then_block.expr() { 130 match &then_block.expr() {
121 Some(then_expr) if then_only_expr => { 131 Some(then_expr) if then_only_expr => {
122 edit.replace(if_expr.syntax().text_range(), then_expr.syntax().text()) 132 edit.replace(replace_node.text_range(), then_expr.syntax().text())
123 } 133 }
124 _ => edit.replace(if_expr.syntax().text_range(), then_block.syntax().text()), 134 _ if replace_node != *if_expr.syntax() => {
135 // Dedent because if_expr is in a BlockExpr
136 let replace_with = then_block.dedent(1.into()).syntax().text();
137 edit.replace(replace_node.text_range(), replace_with)
138 }
139 _ => edit.replace(replace_node.text_range(), then_block.syntax().text()),
125 } 140 }
126 141
127 edit.insert(match_pat.syntax().text_range().end(), buf); 142 edit.insert(match_pat.syntax().text_range().end(), buf);
@@ -225,6 +240,33 @@ fn main() {
225 } 240 }
226 241
227 #[test] 242 #[test]
243 fn move_arm_cond_in_block_to_match_guard_works() {
244 check_assist(
245 move_arm_cond_to_match_guard,
246 r#"
247fn main() {
248 match 92 {
249 x => {
250 <|>if x > 10 {
251 false
252 }
253 },
254 _ => true
255 }
256}
257"#,
258 r#"
259fn main() {
260 match 92 {
261 x if x > 10 => false,
262 _ => true
263 }
264}
265"#,
266 );
267 }
268
269 #[test]
228 fn move_arm_cond_to_match_guard_if_let_not_works() { 270 fn move_arm_cond_to_match_guard_if_let_not_works() {
229 check_assist_not_applicable( 271 check_assist_not_applicable(
230 move_arm_cond_to_match_guard, 272 move_arm_cond_to_match_guard,
@@ -290,4 +332,35 @@ fn main() {
290"#, 332"#,
291 ); 333 );
292 } 334 }
335
336 #[test]
337 fn move_arm_cond_in_block_to_match_guard_if_multiline_body_works() {
338 check_assist(
339 move_arm_cond_to_match_guard,
340 r#"
341fn main() {
342 match 92 {
343 x => {
344 if x > 10 {
345 92;<|>
346 false
347 }
348 }
349 _ => true
350 }
351}
352"#,
353 r#"
354fn main() {
355 match 92 {
356 x if x > 10 => {
357 92;
358 false
359 }
360 _ => true
361 }
362}
363"#,
364 )
365 }
293} 366}
diff --git a/crates/assists/src/handlers/qualify_path.rs b/crates/assists/src/handlers/qualify_path.rs
index f436bdbbf..d5bc4e574 100644
--- a/crates/assists/src/handlers/qualify_path.rs
+++ b/crates/assists/src/handlers/qualify_path.rs
@@ -56,12 +56,14 @@ pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext) -> Option<()>
56 ImportCandidate::QualifierStart(_) => { 56 ImportCandidate::QualifierStart(_) => {
57 mark::hit!(qualify_path_qualifier_start); 57 mark::hit!(qualify_path_qualifier_start);
58 let path = ast::Path::cast(import_assets.syntax_under_caret().clone())?; 58 let path = ast::Path::cast(import_assets.syntax_under_caret().clone())?;
59 let segment = path.segment()?; 59 let (prev_segment, segment) = (path.qualifier()?.segment()?, path.segment()?);
60 QualifyCandidate::QualifierStart(segment) 60 QualifyCandidate::QualifierStart(segment, prev_segment.generic_arg_list())
61 } 61 }
62 ImportCandidate::UnqualifiedName(_) => { 62 ImportCandidate::UnqualifiedName(_) => {
63 mark::hit!(qualify_path_unqualified_name); 63 mark::hit!(qualify_path_unqualified_name);
64 QualifyCandidate::UnqualifiedName 64 let path = ast::Path::cast(import_assets.syntax_under_caret().clone())?;
65 let generics = path.segment()?.generic_arg_list();
66 QualifyCandidate::UnqualifiedName(generics)
65 } 67 }
66 ImportCandidate::TraitAssocItem(_) => { 68 ImportCandidate::TraitAssocItem(_) => {
67 mark::hit!(qualify_path_trait_assoc_item); 69 mark::hit!(qualify_path_trait_assoc_item);
@@ -96,22 +98,25 @@ pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext) -> Option<()>
96} 98}
97 99
98enum QualifyCandidate<'db> { 100enum QualifyCandidate<'db> {
99 QualifierStart(ast::PathSegment), 101 QualifierStart(ast::PathSegment, Option<ast::GenericArgList>),
100 UnqualifiedName, 102 UnqualifiedName(Option<ast::GenericArgList>),
101 TraitAssocItem(ast::Path, ast::PathSegment), 103 TraitAssocItem(ast::Path, ast::PathSegment),
102 TraitMethod(&'db RootDatabase, ast::MethodCallExpr), 104 TraitMethod(&'db RootDatabase, ast::MethodCallExpr),
103} 105}
104 106
105impl QualifyCandidate<'_> { 107impl QualifyCandidate<'_> {
106 fn qualify(&self, mut replacer: impl FnMut(String), import: hir::ModPath, item: hir::ItemInNs) { 108 fn qualify(&self, mut replacer: impl FnMut(String), import: hir::ModPath, item: hir::ItemInNs) {
109 let import = mod_path_to_ast(&import);
107 match self { 110 match self {
108 QualifyCandidate::QualifierStart(segment) => { 111 QualifyCandidate::QualifierStart(segment, generics) => {
109 let import = mod_path_to_ast(&import); 112 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
110 replacer(format!("{}::{}", import, segment)); 113 replacer(format!("{}{}::{}", import, generics, segment));
114 }
115 QualifyCandidate::UnqualifiedName(generics) => {
116 let generics = generics.as_ref().map_or_else(String::new, ToString::to_string);
117 replacer(format!("{}{}", import.to_string(), generics));
111 } 118 }
112 QualifyCandidate::UnqualifiedName => replacer(mod_path_to_ast(&import).to_string()),
113 QualifyCandidate::TraitAssocItem(qualifier, segment) => { 119 QualifyCandidate::TraitAssocItem(qualifier, segment) => {
114 let import = mod_path_to_ast(&import);
115 replacer(format!("<{} as {}>::{}", qualifier, import, segment)); 120 replacer(format!("<{} as {}>::{}", qualifier, import, segment));
116 } 121 }
117 &QualifyCandidate::TraitMethod(db, ref mcall_expr) => { 122 &QualifyCandidate::TraitMethod(db, ref mcall_expr) => {
@@ -124,25 +129,27 @@ impl QualifyCandidate<'_> {
124 db: &RootDatabase, 129 db: &RootDatabase,
125 mcall_expr: &ast::MethodCallExpr, 130 mcall_expr: &ast::MethodCallExpr,
126 mut replacer: impl FnMut(String), 131 mut replacer: impl FnMut(String),
127 import: hir::ModPath, 132 import: ast::Path,
128 item: hir::ItemInNs, 133 item: hir::ItemInNs,
129 ) -> Option<()> { 134 ) -> Option<()> {
130 let receiver = mcall_expr.receiver()?; 135 let receiver = mcall_expr.receiver()?;
131 let trait_method_name = mcall_expr.name_ref()?; 136 let trait_method_name = mcall_expr.name_ref()?;
137 let generics =
138 mcall_expr.generic_arg_list().as_ref().map_or_else(String::new, ToString::to_string);
132 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args()); 139 let arg_list = mcall_expr.arg_list().map(|arg_list| arg_list.args());
133 let trait_ = item_as_trait(item)?; 140 let trait_ = item_as_trait(item)?;
134 let method = find_trait_method(db, trait_, &trait_method_name)?; 141 let method = find_trait_method(db, trait_, &trait_method_name)?;
135 if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) { 142 if let Some(self_access) = method.self_param(db).map(|sp| sp.access(db)) {
136 let import = mod_path_to_ast(&import);
137 let receiver = match self_access { 143 let receiver = match self_access {
138 hir::Access::Shared => make::expr_ref(receiver, false), 144 hir::Access::Shared => make::expr_ref(receiver, false),
139 hir::Access::Exclusive => make::expr_ref(receiver, true), 145 hir::Access::Exclusive => make::expr_ref(receiver, true),
140 hir::Access::Owned => receiver, 146 hir::Access::Owned => receiver,
141 }; 147 };
142 replacer(format!( 148 replacer(format!(
143 "{}::{}{}", 149 "{}::{}{}{}",
144 import, 150 import,
145 trait_method_name, 151 trait_method_name,
152 generics,
146 match arg_list.clone() { 153 match arg_list.clone() {
147 Some(args) => make::arg_list(iter::once(receiver).chain(args)), 154 Some(args) => make::arg_list(iter::once(receiver).chain(args)),
148 None => make::arg_list(iter::once(receiver)), 155 None => make::arg_list(iter::once(receiver)),
@@ -1045,4 +1052,153 @@ fn main() {
1045", 1052",
1046 ); 1053 );
1047 } 1054 }
1055
1056 #[test]
1057 fn keep_generic_annotations() {
1058 check_assist(
1059 qualify_path,
1060 r"
1061//- /lib.rs crate:dep
1062pub mod generic { pub struct Thing<'a, T>(&'a T); }
1063
1064//- /main.rs crate:main deps:dep
1065fn foo() -> Thin<|>g<'static, ()> {}
1066
1067fn main() {}
1068",
1069 r"
1070fn foo() -> dep::generic::Thing<'static, ()> {}
1071
1072fn main() {}
1073",
1074 );
1075 }
1076
1077 #[test]
1078 fn keep_generic_annotations_leading_colon() {
1079 check_assist(
1080 qualify_path,
1081 r"
1082//- /lib.rs crate:dep
1083pub mod generic { pub struct Thing<'a, T>(&'a T); }
1084
1085//- /main.rs crate:main deps:dep
1086fn foo() -> Thin<|>g::<'static, ()> {}
1087
1088fn main() {}
1089",
1090 r"
1091fn foo() -> dep::generic::Thing::<'static, ()> {}
1092
1093fn main() {}
1094",
1095 );
1096 }
1097
1098 #[test]
1099 fn associated_struct_const_generic() {
1100 check_assist(
1101 qualify_path,
1102 r"
1103 mod test_mod {
1104 pub struct TestStruct<T> {}
1105 impl<T> TestStruct<T> {
1106 const TEST_CONST: u8 = 42;
1107 }
1108 }
1109
1110 fn main() {
1111 TestStruct::<()>::TEST_CONST<|>
1112 }
1113 ",
1114 r"
1115 mod test_mod {
1116 pub struct TestStruct<T> {}
1117 impl<T> TestStruct<T> {
1118 const TEST_CONST: u8 = 42;
1119 }
1120 }
1121
1122 fn main() {
1123 test_mod::TestStruct::<()>::TEST_CONST
1124 }
1125 ",
1126 );
1127 }
1128
1129 #[test]
1130 fn associated_trait_const_generic() {
1131 check_assist(
1132 qualify_path,
1133 r"
1134 mod test_mod {
1135 pub trait TestTrait {
1136 const TEST_CONST: u8;
1137 }
1138 pub struct TestStruct<T> {}
1139 impl<T> TestTrait for TestStruct<T> {
1140 const TEST_CONST: u8 = 42;
1141 }
1142 }
1143
1144 fn main() {
1145 test_mod::TestStruct::<()>::TEST_CONST<|>
1146 }
1147 ",
1148 r"
1149 mod test_mod {
1150 pub trait TestTrait {
1151 const TEST_CONST: u8;
1152 }
1153 pub struct TestStruct<T> {}
1154 impl<T> TestTrait for TestStruct<T> {
1155 const TEST_CONST: u8 = 42;
1156 }
1157 }
1158
1159 fn main() {
1160 <test_mod::TestStruct::<()> as test_mod::TestTrait>::TEST_CONST
1161 }
1162 ",
1163 );
1164 }
1165
1166 #[test]
1167 fn trait_method_generic() {
1168 check_assist(
1169 qualify_path,
1170 r"
1171 mod test_mod {
1172 pub trait TestTrait {
1173 fn test_method<T>(&self);
1174 }
1175 pub struct TestStruct {}
1176 impl TestTrait for TestStruct {
1177 fn test_method<T>(&self) {}
1178 }
1179 }
1180
1181 fn main() {
1182 let test_struct = test_mod::TestStruct {};
1183 test_struct.test_meth<|>od::<()>()
1184 }
1185 ",
1186 r"
1187 mod test_mod {
1188 pub trait TestTrait {
1189 fn test_method<T>(&self);
1190 }
1191 pub struct TestStruct {}
1192 impl TestTrait for TestStruct {
1193 fn test_method<T>(&self) {}
1194 }
1195 }
1196
1197 fn main() {
1198 let test_struct = test_mod::TestStruct {};
1199 test_mod::TestTrait::test_method::<()>(&test_struct)
1200 }
1201 ",
1202 );
1203 }
1048} 1204}
diff --git a/crates/assists/src/lib.rs b/crates/assists/src/lib.rs
index 70a651e10..b804e495d 100644
--- a/crates/assists/src/lib.rs
+++ b/crates/assists/src/lib.rs
@@ -200,7 +200,6 @@ mod handlers {
200 move_guard::move_guard_to_arm_body, 200 move_guard::move_guard_to_arm_body,
201 qualify_path::qualify_path, 201 qualify_path::qualify_path,
202 raw_string::add_hash, 202 raw_string::add_hash,
203 raw_string::make_raw_string,
204 raw_string::make_usual_string, 203 raw_string::make_usual_string,
205 raw_string::remove_hash, 204 raw_string::remove_hash,
206 remove_dbg::remove_dbg, 205 remove_dbg::remove_dbg,
@@ -211,13 +210,15 @@ mod handlers {
211 replace_impl_trait_with_generic::replace_impl_trait_with_generic, 210 replace_impl_trait_with_generic::replace_impl_trait_with_generic,
212 replace_let_with_if_let::replace_let_with_if_let, 211 replace_let_with_if_let::replace_let_with_if_let,
213 replace_qualified_name_with_use::replace_qualified_name_with_use, 212 replace_qualified_name_with_use::replace_qualified_name_with_use,
214 replace_string_with_char::replace_string_with_char,
215 replace_unwrap_with_match::replace_unwrap_with_match, 213 replace_unwrap_with_match::replace_unwrap_with_match,
216 split_import::split_import, 214 split_import::split_import,
217 unwrap_block::unwrap_block, 215 unwrap_block::unwrap_block,
218 // These are manually sorted for better priorities 216 // These are manually sorted for better priorities
219 add_missing_impl_members::add_missing_impl_members, 217 add_missing_impl_members::add_missing_impl_members,
220 add_missing_impl_members::add_missing_default_members, 218 add_missing_impl_members::add_missing_default_members,
219 //
220 replace_string_with_char::replace_string_with_char,
221 raw_string::make_raw_string,
221 // Are you sure you want to add new assist here, and not to the 222 // Are you sure you want to add new assist here, and not to the
222 // sorted list above? 223 // sorted list above?
223 ] 224 ]
diff --git a/crates/assists/src/utils/import_assets.rs b/crates/assists/src/utils/import_assets.rs
index 23db3a74b..f47edbb76 100644
--- a/crates/assists/src/utils/import_assets.rs
+++ b/crates/assists/src/utils/import_assets.rs
@@ -26,13 +26,13 @@ pub(crate) enum ImportCandidate {
26 26
27#[derive(Debug)] 27#[derive(Debug)]
28pub(crate) struct TraitImportCandidate { 28pub(crate) struct TraitImportCandidate {
29 pub ty: hir::Type, 29 pub(crate) ty: hir::Type,
30 pub name: ast::NameRef, 30 pub(crate) name: ast::NameRef,
31} 31}
32 32
33#[derive(Debug)] 33#[derive(Debug)]
34pub(crate) struct PathImportCandidate { 34pub(crate) struct PathImportCandidate {
35 pub name: ast::NameRef, 35 pub(crate) name: ast::NameRef,
36} 36}
37 37
38#[derive(Debug)] 38#[derive(Debug)]
diff --git a/crates/assists/src/utils/insert_use.rs b/crates/assists/src/utils/insert_use.rs
index 033fbcedc..a76bd5ebf 100644
--- a/crates/assists/src/utils/insert_use.rs
+++ b/crates/assists/src/utils/insert_use.rs
@@ -17,13 +17,13 @@ use syntax::{
17use test_utils::mark; 17use test_utils::mark;
18 18
19#[derive(Debug)] 19#[derive(Debug)]
20pub enum ImportScope { 20pub(crate) enum ImportScope {
21 File(ast::SourceFile), 21 File(ast::SourceFile),
22 Module(ast::ItemList), 22 Module(ast::ItemList),
23} 23}
24 24
25impl ImportScope { 25impl ImportScope {
26 pub fn from(syntax: SyntaxNode) -> Option<Self> { 26 pub(crate) fn from(syntax: SyntaxNode) -> Option<Self> {
27 if let Some(module) = ast::Module::cast(syntax.clone()) { 27 if let Some(module) = ast::Module::cast(syntax.clone()) {
28 module.item_list().map(ImportScope::Module) 28 module.item_list().map(ImportScope::Module)
29 } else if let this @ Some(_) = ast::SourceFile::cast(syntax.clone()) { 29 } else if let this @ Some(_) = ast::SourceFile::cast(syntax.clone()) {
diff --git a/crates/base_db/src/input.rs b/crates/base_db/src/input.rs
index 87f0a0ce5..31907ed98 100644
--- a/crates/base_db/src/input.rs
+++ b/crates/base_db/src/input.rs
@@ -12,9 +12,7 @@ use cfg::CfgOptions;
12use rustc_hash::{FxHashMap, FxHashSet}; 12use rustc_hash::{FxHashMap, FxHashSet};
13use syntax::SmolStr; 13use syntax::SmolStr;
14use tt::TokenExpander; 14use tt::TokenExpander;
15use vfs::{file_set::FileSet, VfsPath}; 15use vfs::{file_set::FileSet, FileId, VfsPath};
16
17pub use vfs::FileId;
18 16
19/// Files are grouped into source roots. A source root is a directory on the 17/// Files are grouped into source roots. A source root is a directory on the
20/// file systems which is watched for changes. Typically it corresponds to a 18/// file systems which is watched for changes. Typically it corresponds to a
diff --git a/crates/base_db/src/lib.rs b/crates/base_db/src/lib.rs
index 0804202d6..ce75a5337 100644
--- a/crates/base_db/src/lib.rs
+++ b/crates/base_db/src/lib.rs
@@ -14,11 +14,11 @@ pub use crate::{
14 change::Change, 14 change::Change,
15 input::{ 15 input::{
16 CrateData, CrateDisplayName, CrateGraph, CrateId, CrateName, Dependency, Edition, Env, 16 CrateData, CrateDisplayName, CrateGraph, CrateId, CrateName, Dependency, Edition, Env,
17 FileId, ProcMacroId, SourceRoot, SourceRootId, 17 ProcMacroId, SourceRoot, SourceRootId,
18 }, 18 },
19}; 19};
20pub use salsa; 20pub use salsa;
21pub use vfs::{file_set::FileSet, VfsPath}; 21pub use vfs::{file_set::FileSet, FileId, VfsPath};
22 22
23#[macro_export] 23#[macro_export]
24macro_rules! impl_intern_key { 24macro_rules! impl_intern_key {
diff --git a/crates/completion/src/presentation.rs b/crates/completion/src/completions.rs
index 0a6f5a1ea..d5fb85b79 100644
--- a/crates/completion/src/presentation.rs
+++ b/crates/completion/src/completions.rs
@@ -1,5 +1,18 @@
1//! This modules takes care of rendering various definitions as completion items. 1//! This module defines an accumulator for completions which are going to be presented to user.
2//! It also handles scoring (sorting) completions. 2
3pub(crate) mod attribute;
4pub(crate) mod dot;
5pub(crate) mod record;
6pub(crate) mod pattern;
7pub(crate) mod fn_param;
8pub(crate) mod keyword;
9pub(crate) mod snippet;
10pub(crate) mod qualified_path;
11pub(crate) mod unqualified_path;
12pub(crate) mod postfix;
13pub(crate) mod macro_in_item_position;
14pub(crate) mod trait_impl;
15pub(crate) mod mod_;
3 16
4use hir::{HasAttrs, HasSource, HirDisplay, ModPath, Mutability, ScopeDef, StructKind, Type}; 17use hir::{HasAttrs, HasSource, HirDisplay, ModPath, Mutability, ScopeDef, StructKind, Type};
5use itertools::Itertools; 18use itertools::Itertools;
@@ -7,20 +20,47 @@ use syntax::{ast::NameOwner, display::*};
7use test_utils::mark; 20use test_utils::mark;
8 21
9use crate::{ 22use crate::{
10 // display::{const_label, function_declaration, macro_label, type_label}, 23 item::Builder, CompletionContext, CompletionItem, CompletionItemKind, CompletionKind,
11 CompletionScore, 24 CompletionScore, RootDatabase,
12 RootDatabase,
13 {
14 completion_item::Builder, CompletionContext, CompletionItem, CompletionItemKind,
15 CompletionKind, Completions,
16 },
17}; 25};
18 26
27/// Represents an in-progress set of completions being built.
28#[derive(Debug, Default)]
29pub struct Completions {
30 buf: Vec<CompletionItem>,
31}
32
33impl Into<Vec<CompletionItem>> for Completions {
34 fn into(self) -> Vec<CompletionItem> {
35 self.buf
36 }
37}
38
39impl Builder {
40 /// Convenience method, which allows to add a freshly created completion into accumulator
41 /// without binding it to the variable.
42 pub(crate) fn add_to(self, acc: &mut Completions) {
43 acc.add(self.build())
44 }
45}
46
19impl Completions { 47impl Completions {
48 pub(crate) fn add(&mut self, item: CompletionItem) {
49 self.buf.push(item.into())
50 }
51
52 pub(crate) fn add_all<I>(&mut self, items: I)
53 where
54 I: IntoIterator,
55 I::Item: Into<CompletionItem>,
56 {
57 items.into_iter().for_each(|item| self.add(item.into()))
58 }
59
20 pub(crate) fn add_field(&mut self, ctx: &CompletionContext, field: hir::Field, ty: &Type) { 60 pub(crate) fn add_field(&mut self, ctx: &CompletionContext, field: hir::Field, ty: &Type) {
21 let is_deprecated = is_deprecated(field, ctx.db); 61 let is_deprecated = is_deprecated(field, ctx.db);
22 let name = field.name(ctx.db); 62 let name = field.name(ctx.db);
23 let mut completion_item = 63 let mut item =
24 CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.to_string()) 64 CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.to_string())
25 .kind(CompletionItemKind::Field) 65 .kind(CompletionItemKind::Field)
26 .detail(ty.display(ctx.db).to_string()) 66 .detail(ty.display(ctx.db).to_string())
@@ -28,10 +68,10 @@ impl Completions {
28 .set_deprecated(is_deprecated); 68 .set_deprecated(is_deprecated);
29 69
30 if let Some(score) = compute_score(ctx, &ty, &name.to_string()) { 70 if let Some(score) = compute_score(ctx, &ty, &name.to_string()) {
31 completion_item = completion_item.set_score(score); 71 item = item.set_score(score);
32 } 72 }
33 73
34 completion_item.add_to(self); 74 item.add_to(self);
35 } 75 }
36 76
37 pub(crate) fn add_tuple_field(&mut self, ctx: &CompletionContext, field: usize, ty: &Type) { 77 pub(crate) fn add_tuple_field(&mut self, ctx: &CompletionContext, field: usize, ty: &Type) {
@@ -57,7 +97,8 @@ impl Completions {
57 let kind = match resolution { 97 let kind = match resolution {
58 ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::Module, 98 ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::Module,
59 ScopeDef::ModuleDef(Function(func)) => { 99 ScopeDef::ModuleDef(Function(func)) => {
60 return self.add_function(ctx, *func, Some(local_name)); 100 self.add_function(ctx, *func, Some(local_name));
101 return;
61 } 102 }
62 ScopeDef::ModuleDef(Adt(hir::Adt::Struct(_))) => CompletionItemKind::Struct, 103 ScopeDef::ModuleDef(Adt(hir::Adt::Struct(_))) => CompletionItemKind::Struct,
63 // FIXME: add CompletionItemKind::Union 104 // FIXME: add CompletionItemKind::Union
@@ -65,7 +106,8 @@ impl Completions {
65 ScopeDef::ModuleDef(Adt(hir::Adt::Enum(_))) => CompletionItemKind::Enum, 106 ScopeDef::ModuleDef(Adt(hir::Adt::Enum(_))) => CompletionItemKind::Enum,
66 107
67 ScopeDef::ModuleDef(EnumVariant(var)) => { 108 ScopeDef::ModuleDef(EnumVariant(var)) => {
68 return self.add_enum_variant(ctx, *var, Some(local_name)); 109 self.add_enum_variant(ctx, *var, Some(local_name));
110 return;
69 } 111 }
70 ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::Const, 112 ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::Const,
71 ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::Static, 113 ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::Static,
@@ -77,13 +119,14 @@ impl Completions {
77 // (does this need its own kind?) 119 // (does this need its own kind?)
78 ScopeDef::AdtSelfType(..) | ScopeDef::ImplSelfType(..) => CompletionItemKind::TypeParam, 120 ScopeDef::AdtSelfType(..) | ScopeDef::ImplSelfType(..) => CompletionItemKind::TypeParam,
79 ScopeDef::MacroDef(mac) => { 121 ScopeDef::MacroDef(mac) => {
80 return self.add_macro(ctx, Some(local_name), *mac); 122 self.add_macro(ctx, Some(local_name), *mac);
123 return;
81 } 124 }
82 ScopeDef::Unknown => { 125 ScopeDef::Unknown => {
83 return self.add( 126 CompletionItem::new(CompletionKind::Reference, ctx.source_range(), local_name)
84 CompletionItem::new(CompletionKind::Reference, ctx.source_range(), local_name) 127 .kind(CompletionItemKind::UnresolvedReference)
85 .kind(CompletionItemKind::UnresolvedReference), 128 .add_to(self);
86 ); 129 return;
87 } 130 }
88 }; 131 };
89 132
@@ -98,12 +141,11 @@ impl Completions {
98 _ => None, 141 _ => None,
99 }; 142 };
100 143
101 let mut completion_item = 144 let mut item = CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone());
102 CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone());
103 if let ScopeDef::Local(local) = resolution { 145 if let ScopeDef::Local(local) = resolution {
104 let ty = local.ty(ctx.db); 146 let ty = local.ty(ctx.db);
105 if !ty.is_unknown() { 147 if !ty.is_unknown() {
106 completion_item = completion_item.detail(ty.display(ctx.db).to_string()); 148 item = item.detail(ty.display(ctx.db).to_string());
107 } 149 }
108 }; 150 };
109 151
@@ -114,7 +156,7 @@ impl Completions {
114 if let Some(score) = 156 if let Some(score) =
115 compute_score_from_active(&active_type, &active_name, &ty, &local_name) 157 compute_score_from_active(&active_type, &active_name, &ty, &local_name)
116 { 158 {
117 completion_item = completion_item.set_score(score); 159 item = item.set_score(score);
118 } 160 }
119 ref_match = refed_type_matches(&active_type, &active_name, &ty, &local_name); 161 ref_match = refed_type_matches(&active_type, &active_name, &ty, &local_name);
120 } 162 }
@@ -130,7 +172,7 @@ impl Completions {
130 }; 172 };
131 if has_non_default_type_params { 173 if has_non_default_type_params {
132 mark::hit!(inserts_angle_brackets_for_generics); 174 mark::hit!(inserts_angle_brackets_for_generics);
133 completion_item = completion_item 175 item = item
134 .lookup_by(local_name.clone()) 176 .lookup_by(local_name.clone())
135 .label(format!("{}<…>", local_name)) 177 .label(format!("{}<…>", local_name))
136 .insert_snippet(cap, format!("{}<$0>", local_name)); 178 .insert_snippet(cap, format!("{}<$0>", local_name));
@@ -138,7 +180,7 @@ impl Completions {
138 } 180 }
139 } 181 }
140 182
141 completion_item.kind(kind).set_documentation(docs).set_ref_match(ref_match).add_to(self) 183 item.kind(kind).set_documentation(docs).set_ref_match(ref_match).add_to(self)
142 } 184 }
143 185
144 pub(crate) fn add_macro( 186 pub(crate) fn add_macro(
@@ -190,7 +232,7 @@ impl Completions {
190 } 232 }
191 }; 233 };
192 234
193 self.add(builder); 235 self.add(builder.build());
194 } 236 }
195 237
196 pub(crate) fn add_function( 238 pub(crate) fn add_function(
@@ -242,7 +284,7 @@ impl Completions {
242 284
243 builder = builder.add_call_parens(ctx, name, Params::Named(params)); 285 builder = builder.add_call_parens(ctx, name, Params::Named(params));
244 286
245 self.add(builder) 287 self.add(builder.build())
246 } 288 }
247 289
248 pub(crate) fn add_const(&mut self, ctx: &CompletionContext, constant: hir::Const) { 290 pub(crate) fn add_const(&mut self, ctx: &CompletionContext, constant: hir::Const) {
@@ -506,7 +548,7 @@ mod tests {
506 use test_utils::mark; 548 use test_utils::mark;
507 549
508 use crate::{ 550 use crate::{
509 test_utils::{check_edit, check_edit_with_config, do_completion, get_all_completion_items}, 551 test_utils::{check_edit, check_edit_with_config, do_completion, get_all_items},
510 CompletionConfig, CompletionKind, CompletionScore, 552 CompletionConfig, CompletionKind, CompletionScore,
511 }; 553 };
512 554
@@ -524,7 +566,7 @@ mod tests {
524 } 566 }
525 } 567 }
526 568
527 let mut completions = get_all_completion_items(CompletionConfig::default(), ra_fixture); 569 let mut completions = get_all_items(CompletionConfig::default(), ra_fixture);
528 completions.sort_by_key(|it| (Reverse(it.score()), it.label().to_string())); 570 completions.sort_by_key(|it| (Reverse(it.score()), it.label().to_string()));
529 let actual = completions 571 let actual = completions
530 .into_iter() 572 .into_iter()
@@ -661,7 +703,7 @@ fn main() { let _: m::Spam = S<|> }
661 } 703 }
662 704
663 #[test] 705 #[test]
664 fn sets_deprecated_flag_in_completion_items() { 706 fn sets_deprecated_flag_in_items() {
665 check( 707 check(
666 r#" 708 r#"
667#[deprecated] 709#[deprecated]
diff --git a/crates/completion/src/complete_attribute.rs b/crates/completion/src/completions/attribute.rs
index f97ab7dd0..f3d669458 100644
--- a/crates/completion/src/complete_attribute.rs
+++ b/crates/completion/src/completions/attribute.rs
@@ -7,12 +7,13 @@ use rustc_hash::FxHashSet;
7use syntax::{ast, AstNode, SyntaxKind}; 7use syntax::{ast, AstNode, SyntaxKind};
8 8
9use crate::{ 9use crate::{
10 completion_context::CompletionContext, 10 context::CompletionContext,
11 completion_item::{CompletionItem, CompletionItemKind, CompletionKind, Completions},
12 generated_lint_completions::{CLIPPY_LINTS, FEATURES}, 11 generated_lint_completions::{CLIPPY_LINTS, FEATURES},
12 item::{CompletionItem, CompletionItemKind, CompletionKind},
13 Completions,
13}; 14};
14 15
15pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { 16pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
16 if ctx.mod_declaration_under_caret.is_some() { 17 if ctx.mod_declaration_under_caret.is_some() {
17 return None; 18 return None;
18 } 19 }
@@ -60,7 +61,7 @@ fn complete_attribute_start(acc: &mut Completions, ctx: &CompletionContext, attr
60 } 61 }
61 62
62 if attribute.kind() == ast::AttrKind::Inner || !attr_completion.prefer_inner { 63 if attribute.kind() == ast::AttrKind::Inner || !attr_completion.prefer_inner {
63 acc.add(item); 64 acc.add(item.build());
64 } 65 }
65 } 66 }
66} 67}
@@ -152,21 +153,15 @@ fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input:
152 label.push_str(", "); 153 label.push_str(", ");
153 label.push_str(dependency); 154 label.push_str(dependency);
154 } 155 }
155 acc.add( 156 CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label)
156 CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label) 157 .kind(CompletionItemKind::Attribute)
157 .kind(CompletionItemKind::Attribute), 158 .add_to(acc)
158 );
159 } 159 }
160 160
161 for custom_derive_name in get_derive_names_in_scope(ctx).difference(&existing_derives) { 161 for custom_derive_name in get_derive_names_in_scope(ctx).difference(&existing_derives) {
162 acc.add( 162 CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), custom_derive_name)
163 CompletionItem::new( 163 .kind(CompletionItemKind::Attribute)
164 CompletionKind::Attribute, 164 .add_to(acc)
165 ctx.source_range(),
166 custom_derive_name,
167 )
168 .kind(CompletionItemKind::Attribute),
169 );
170 } 165 }
171 } 166 }
172} 167}
@@ -182,15 +177,14 @@ fn complete_lint(
182 .into_iter() 177 .into_iter()
183 .filter(|completion| !existing_lints.contains(completion.label)) 178 .filter(|completion| !existing_lints.contains(completion.label))
184 { 179 {
185 acc.add( 180 CompletionItem::new(
186 CompletionItem::new( 181 CompletionKind::Attribute,
187 CompletionKind::Attribute, 182 ctx.source_range(),
188 ctx.source_range(), 183 lint_completion.label,
189 lint_completion.label, 184 )
190 ) 185 .kind(CompletionItemKind::Attribute)
191 .kind(CompletionItemKind::Attribute) 186 .detail(lint_completion.description)
192 .detail(lint_completion.description), 187 .add_to(acc)
193 );
194 } 188 }
195 } 189 }
196} 190}
@@ -262,9 +256,9 @@ const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[
262 DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] }, 256 DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] },
263]; 257];
264 258
265pub(super) struct LintCompletion { 259pub(crate) struct LintCompletion {
266 pub(super) label: &'static str, 260 pub(crate) label: &'static str,
267 pub(super) description: &'static str, 261 pub(crate) description: &'static str,
268} 262}
269 263
270#[rustfmt::skip] 264#[rustfmt::skip]
diff --git a/crates/completion/src/complete_dot.rs b/crates/completion/src/completions/dot.rs
index 0eabb48ae..c9875045a 100644
--- a/crates/completion/src/complete_dot.rs
+++ b/crates/completion/src/completions/dot.rs
@@ -4,10 +4,10 @@ use hir::{HasVisibility, Type};
4use rustc_hash::FxHashSet; 4use rustc_hash::FxHashSet;
5use test_utils::mark; 5use test_utils::mark;
6 6
7use crate::{completion_context::CompletionContext, completion_item::Completions}; 7use crate::{context::CompletionContext, Completions};
8 8
9/// Complete dot accesses, i.e. fields or methods. 9/// Complete dot accesses, i.e. fields or methods.
10pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) { 10pub(crate) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
11 let dot_receiver = match &ctx.dot_receiver { 11 let dot_receiver = match &ctx.dot_receiver {
12 Some(expr) => expr, 12 Some(expr) => expr,
13 _ => return, 13 _ => return,
@@ -141,7 +141,7 @@ mod inner {
141 private_field: u32, 141 private_field: u32,
142 pub pub_field: u32, 142 pub pub_field: u32,
143 pub(crate) crate_field: u32, 143 pub(crate) crate_field: u32,
144 pub(super) super_field: u32, 144 pub(crate) super_field: u32,
145 } 145 }
146} 146}
147fn foo(a: inner::A) { a.<|> } 147fn foo(a: inner::A) { a.<|> }
@@ -159,13 +159,13 @@ struct A {}
159mod m { 159mod m {
160 impl super::A { 160 impl super::A {
161 fn private_method(&self) {} 161 fn private_method(&self) {}
162 pub(super) fn the_method(&self) {} 162 pub(crate) fn the_method(&self) {}
163 } 163 }
164} 164}
165fn foo(a: A) { a.<|> } 165fn foo(a: A) { a.<|> }
166"#, 166"#,
167 expect![[r#" 167 expect![[r#"
168 me the_method() pub(super) fn the_method(&self) 168 me the_method() pub(crate) fn the_method(&self)
169 "#]], 169 "#]],
170 ); 170 );
171 } 171 }
diff --git a/crates/completion/src/complete_fn_param.rs b/crates/completion/src/completions/fn_param.rs
index 918996727..e777a53c1 100644
--- a/crates/completion/src/complete_fn_param.rs
+++ b/crates/completion/src/completions/fn_param.rs
@@ -12,7 +12,7 @@ use crate::{CompletionContext, CompletionItem, CompletionKind, Completions};
12/// functions in a file have a `spam: &mut Spam` parameter, a completion with 12/// functions in a file have a `spam: &mut Spam` parameter, a completion with
13/// `spam: &mut Spam` insert text/label and `spam` lookup string will be 13/// `spam: &mut Spam` insert text/label and `spam` lookup string will be
14/// suggested. 14/// suggested.
15pub(super) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) { 15pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) {
16 if !ctx.is_param { 16 if !ctx.is_param {
17 return; 17 return;
18 } 18 }
diff --git a/crates/completion/src/complete_keyword.rs b/crates/completion/src/completions/keyword.rs
index ace914f3f..c7df15900 100644
--- a/crates/completion/src/complete_keyword.rs
+++ b/crates/completion/src/completions/keyword.rs
@@ -5,7 +5,7 @@ use test_utils::mark;
5 5
6use crate::{CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions}; 6use crate::{CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions};
7 7
8pub(super) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionContext) { 8pub(crate) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionContext) {
9 // complete keyword "crate" in use stmt 9 // complete keyword "crate" in use stmt
10 let source_range = ctx.source_range(); 10 let source_range = ctx.source_range();
11 11
@@ -39,7 +39,7 @@ pub(super) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionC
39 } 39 }
40} 40}
41 41
42pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) { 42pub(crate) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) {
43 if ctx.token.kind() == SyntaxKind::COMMENT { 43 if ctx.token.kind() == SyntaxKind::COMMENT {
44 mark::hit!(no_keyword_completion_in_comments); 44 mark::hit!(no_keyword_completion_in_comments);
45 return; 45 return;
diff --git a/crates/completion/src/complete_macro_in_item_position.rs b/crates/completion/src/completions/macro_in_item_position.rs
index d1d8c23d2..82884a181 100644
--- a/crates/completion/src/complete_macro_in_item_position.rs
+++ b/crates/completion/src/completions/macro_in_item_position.rs
@@ -2,7 +2,7 @@
2 2
3use crate::{CompletionContext, Completions}; 3use crate::{CompletionContext, Completions};
4 4
5pub(super) fn complete_macro_in_item_position(acc: &mut Completions, ctx: &CompletionContext) { 5pub(crate) fn complete_macro_in_item_position(acc: &mut Completions, ctx: &CompletionContext) {
6 // Show only macros in top level. 6 // Show only macros in top level.
7 if ctx.is_new_item { 7 if ctx.is_new_item {
8 ctx.scope.process_all_names(&mut |name, res| { 8 ctx.scope.process_all_names(&mut |name, res| {
diff --git a/crates/completion/src/complete_mod.rs b/crates/completion/src/completions/mod_.rs
index 385911afa..c96f84171 100644
--- a/crates/completion/src/complete_mod.rs
+++ b/crates/completion/src/completions/mod_.rs
@@ -7,13 +7,10 @@ use rustc_hash::FxHashSet;
7 7
8use crate::{CompletionItem, CompletionItemKind}; 8use crate::{CompletionItem, CompletionItemKind};
9 9
10use super::{ 10use crate::{context::CompletionContext, item::CompletionKind, Completions};
11 completion_context::CompletionContext, completion_item::CompletionKind,
12 completion_item::Completions,
13};
14 11
15/// Complete mod declaration, i.e. `mod <|> ;` 12/// Complete mod declaration, i.e. `mod <|> ;`
16pub(super) fn complete_mod(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { 13pub(crate) fn complete_mod(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
17 let mod_under_caret = match &ctx.mod_declaration_under_caret { 14 let mod_under_caret = match &ctx.mod_declaration_under_caret {
18 Some(mod_under_caret) if mod_under_caret.item_list().is_some() => return None, 15 Some(mod_under_caret) if mod_under_caret.item_list().is_some() => return None,
19 Some(mod_under_caret) => mod_under_caret, 16 Some(mod_under_caret) => mod_under_caret,
@@ -78,10 +75,9 @@ pub(super) fn complete_mod(acc: &mut Completions, ctx: &CompletionContext) -> Op
78 if mod_under_caret.semicolon_token().is_none() { 75 if mod_under_caret.semicolon_token().is_none() {
79 label.push(';') 76 label.push(';')
80 } 77 }
81 acc.add( 78 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), &label)
82 CompletionItem::new(CompletionKind::Magic, ctx.source_range(), &label) 79 .kind(CompletionItemKind::Module)
83 .kind(CompletionItemKind::Module), 80 .add_to(acc)
84 )
85 }); 81 });
86 82
87 Some(()) 83 Some(())
diff --git a/crates/completion/src/complete_pattern.rs b/crates/completion/src/completions/pattern.rs
index 5606dcdd9..7ab7f09fe 100644
--- a/crates/completion/src/complete_pattern.rs
+++ b/crates/completion/src/completions/pattern.rs
@@ -3,7 +3,7 @@
3use crate::{CompletionContext, Completions}; 3use crate::{CompletionContext, Completions};
4 4
5/// Completes constats and paths in patterns. 5/// Completes constats and paths in patterns.
6pub(super) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) { 6pub(crate) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) {
7 if !ctx.is_pat_binding_or_const { 7 if !ctx.is_pat_binding_or_const {
8 return; 8 return;
9 } 9 }
diff --git a/crates/completion/src/complete_postfix.rs b/crates/completion/src/completions/postfix.rs
index 2622f12ab..348f017bd 100644
--- a/crates/completion/src/complete_postfix.rs
+++ b/crates/completion/src/completions/postfix.rs
@@ -11,13 +11,13 @@ use text_edit::TextEdit;
11 11
12use self::format_like::add_format_like_completions; 12use self::format_like::add_format_like_completions;
13use crate::{ 13use crate::{
14 completion_config::SnippetCap, 14 config::SnippetCap,
15 completion_context::CompletionContext, 15 context::CompletionContext,
16 completion_item::{Builder, CompletionKind, Completions}, 16 item::{Builder, CompletionKind},
17 CompletionItem, CompletionItemKind, 17 CompletionItem, CompletionItemKind, Completions,
18}; 18};
19 19
20pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { 20pub(crate) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
21 if !ctx.config.enable_postfix_completions { 21 if !ctx.config.enable_postfix_completions {
22 return; 22 return;
23 } 23 }
diff --git a/crates/completion/src/complete_postfix/format_like.rs b/crates/completion/src/completions/postfix/format_like.rs
index 205c384e2..88ba86acb 100644
--- a/crates/completion/src/complete_postfix/format_like.rs
+++ b/crates/completion/src/completions/postfix/format_like.rs
@@ -15,8 +15,8 @@
15// + `loge` -> `log::error!(...)` 15// + `loge` -> `log::error!(...)`
16 16
17use crate::{ 17use crate::{
18 complete_postfix::postfix_snippet, completion_config::SnippetCap, 18 completions::postfix::postfix_snippet, config::SnippetCap, context::CompletionContext,
19 completion_context::CompletionContext, completion_item::Completions, 19 Completions,
20}; 20};
21use syntax::ast::{self, AstToken}; 21use syntax::ast::{self, AstToken};
22 22
@@ -33,7 +33,7 @@ static KINDS: &[(&str, &str)] = &[
33 ("loge", "log::error!"), 33 ("loge", "log::error!"),
34]; 34];
35 35
36pub(super) fn add_format_like_completions( 36pub(crate) fn add_format_like_completions(
37 acc: &mut Completions, 37 acc: &mut Completions,
38 ctx: &CompletionContext, 38 ctx: &CompletionContext,
39 dot_receiver: &ast::Expr, 39 dot_receiver: &ast::Expr,
@@ -70,7 +70,7 @@ fn string_literal_contents(item: &ast::String) -> Option<String> {
70/// Parser for a format-like string. It is more allowing in terms of string contents, 70/// Parser for a format-like string. It is more allowing in terms of string contents,
71/// as we expect variable placeholders to be filled with expressions. 71/// as we expect variable placeholders to be filled with expressions.
72#[derive(Debug)] 72#[derive(Debug)]
73pub struct FormatStrParser { 73pub(crate) struct FormatStrParser {
74 input: String, 74 input: String,
75 output: String, 75 output: String,
76 extracted_expressions: Vec<String>, 76 extracted_expressions: Vec<String>,
@@ -88,7 +88,7 @@ enum State {
88} 88}
89 89
90impl FormatStrParser { 90impl FormatStrParser {
91 pub fn new(input: String) -> Self { 91 pub(crate) fn new(input: String) -> Self {
92 Self { 92 Self {
93 input: input.into(), 93 input: input.into(),
94 output: String::new(), 94 output: String::new(),
@@ -98,7 +98,7 @@ impl FormatStrParser {
98 } 98 }
99 } 99 }
100 100
101 pub fn parse(&mut self) -> Result<(), ()> { 101 pub(crate) fn parse(&mut self) -> Result<(), ()> {
102 let mut current_expr = String::new(); 102 let mut current_expr = String::new();
103 103
104 let mut placeholder_id = 1; 104 let mut placeholder_id = 1;
@@ -194,7 +194,7 @@ impl FormatStrParser {
194 Ok(()) 194 Ok(())
195 } 195 }
196 196
197 pub fn into_suggestion(&self, macro_name: &str) -> String { 197 pub(crate) fn into_suggestion(&self, macro_name: &str) -> String {
198 assert!(self.parsed, "Attempt to get a suggestion from not parsed expression"); 198 assert!(self.parsed, "Attempt to get a suggestion from not parsed expression");
199 199
200 let expressions_as_string = self.extracted_expressions.join(", "); 200 let expressions_as_string = self.extracted_expressions.join(", ");
diff --git a/crates/completion/src/complete_qualified_path.rs b/crates/completion/src/completions/qualified_path.rs
index 80b271fdf..d9387054d 100644
--- a/crates/completion/src/complete_qualified_path.rs
+++ b/crates/completion/src/completions/qualified_path.rs
@@ -7,7 +7,7 @@ use test_utils::mark;
7 7
8use crate::{CompletionContext, Completions}; 8use crate::{CompletionContext, Completions};
9 9
10pub(super) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionContext) { 10pub(crate) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionContext) {
11 let path = match &ctx.path_qual { 11 let path = match &ctx.path_qual {
12 Some(path) => path.clone(), 12 Some(path) => path.clone(),
13 None => return, 13 None => return,
@@ -369,11 +369,11 @@ struct S;
369 369
370mod m { 370mod m {
371 impl super::S { 371 impl super::S {
372 pub(super) fn public_method() { } 372 pub(crate) fn public_method() { }
373 fn private_method() { } 373 fn private_method() { }
374 pub(super) type PublicType = u32; 374 pub(crate) type PublicType = u32;
375 type PrivateType = u32; 375 type PrivateType = u32;
376 pub(super) const PUBLIC_CONST: u32 = 1; 376 pub(crate) const PUBLIC_CONST: u32 = 1;
377 const PRIVATE_CONST: u32 = 1; 377 const PRIVATE_CONST: u32 = 1;
378 } 378 }
379} 379}
@@ -381,9 +381,9 @@ mod m {
381fn foo() { let _ = S::<|> } 381fn foo() { let _ = S::<|> }
382"#, 382"#,
383 expect![[r#" 383 expect![[r#"
384 ct PUBLIC_CONST pub(super) const PUBLIC_CONST: u32 = 1; 384 ct PUBLIC_CONST pub(crate) const PUBLIC_CONST: u32 = 1;
385 ta PublicType pub(super) type PublicType = u32; 385 ta PublicType pub(crate) type PublicType = u32;
386 fn public_method() pub(super) fn public_method() 386 fn public_method() pub(crate) fn public_method()
387 "#]], 387 "#]],
388 ); 388 );
389 } 389 }
diff --git a/crates/completion/src/complete_record.rs b/crates/completion/src/completions/record.rs
index 129ddc055..0f611084b 100644
--- a/crates/completion/src/complete_record.rs
+++ b/crates/completion/src/completions/record.rs
@@ -1,7 +1,7 @@
1//! Complete fields in record literals and patterns. 1//! Complete fields in record literals and patterns.
2use crate::{CompletionContext, Completions}; 2use crate::{CompletionContext, Completions};
3 3
4pub(super) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { 4pub(crate) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
5 let missing_fields = match (ctx.record_pat_syntax.as_ref(), ctx.record_lit_syntax.as_ref()) { 5 let missing_fields = match (ctx.record_pat_syntax.as_ref(), ctx.record_lit_syntax.as_ref()) {
6 (None, None) => return None, 6 (None, None) => return None,
7 (Some(_), Some(_)) => unreachable!("A record cannot be both a literal and a pattern"), 7 (Some(_), Some(_)) => unreachable!("A record cannot be both a literal and a pattern"),
diff --git a/crates/completion/src/complete_snippet.rs b/crates/completion/src/completions/snippet.rs
index 06096722b..6f0c00078 100644
--- a/crates/completion/src/complete_snippet.rs
+++ b/crates/completion/src/completions/snippet.rs
@@ -1,8 +1,8 @@
1//! This file provides snippet completions, like `pd` => `eprintln!(...)`. 1//! This file provides snippet completions, like `pd` => `eprintln!(...)`.
2 2
3use crate::{ 3use crate::{
4 completion_config::SnippetCap, completion_item::Builder, CompletionContext, CompletionItem, 4 config::SnippetCap, item::Builder, CompletionContext, CompletionItem, CompletionItemKind,
5 CompletionItemKind, CompletionKind, Completions, 5 CompletionKind, Completions,
6}; 6};
7 7
8fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder { 8fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder {
@@ -11,7 +11,7 @@ fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str)
11 .kind(CompletionItemKind::Snippet) 11 .kind(CompletionItemKind::Snippet)
12} 12}
13 13
14pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) { 14pub(crate) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) {
15 if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) { 15 if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) {
16 return; 16 return;
17 } 17 }
@@ -24,7 +24,7 @@ pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionConte
24 snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc); 24 snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc);
25} 25}
26 26
27pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) { 27pub(crate) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) {
28 if !ctx.is_new_item { 28 if !ctx.is_new_item {
29 return; 29 return;
30 } 30 }
diff --git a/crates/completion/src/complete_trait_impl.rs b/crates/completion/src/completions/trait_impl.rs
index a14be9c73..a14be9c73 100644
--- a/crates/completion/src/complete_trait_impl.rs
+++ b/crates/completion/src/completions/trait_impl.rs
diff --git a/crates/completion/src/complete_unqualified_path.rs b/crates/completion/src/completions/unqualified_path.rs
index 5464a160d..7df58e1da 100644
--- a/crates/completion/src/complete_unqualified_path.rs
+++ b/crates/completion/src/completions/unqualified_path.rs
@@ -6,7 +6,7 @@ use test_utils::mark;
6 6
7use crate::{CompletionContext, Completions}; 7use crate::{CompletionContext, Completions};
8 8
9pub(super) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) { 9pub(crate) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) {
10 if !(ctx.is_trivial_path || ctx.is_pat_binding_or_const) { 10 if !(ctx.is_trivial_path || ctx.is_pat_binding_or_const) {
11 return; 11 return;
12 } 12 }
diff --git a/crates/completion/src/completion_config.rs b/crates/completion/src/config.rs
index 71b49ace8..71b49ace8 100644
--- a/crates/completion/src/completion_config.rs
+++ b/crates/completion/src/config.rs
diff --git a/crates/completion/src/completion_context.rs b/crates/completion/src/context.rs
index dca304a8f..dca304a8f 100644
--- a/crates/completion/src/completion_context.rs
+++ b/crates/completion/src/context.rs
diff --git a/crates/completion/src/generated_lint_completions.rs b/crates/completion/src/generated_lint_completions.rs
index 5a7dba1f5..87df7f1c9 100644
--- a/crates/completion/src/generated_lint_completions.rs
+++ b/crates/completion/src/generated_lint_completions.rs
@@ -1,5 +1,5 @@
1//! Generated file, do not edit by hand, see `xtask/src/codegen` 1//! Generated file, do not edit by hand, see `xtask/src/codegen`
2 2
3use crate::complete_attribute::LintCompletion; 3use crate::completions::attribute::LintCompletion;
4pub (super) const FEATURES : & [LintCompletion] = & [LintCompletion { label : "link_args" , description : "# `link_args`\n\nThe tracking issue for this feature is: [#29596]\n\n[#29596]: https://github.com/rust-lang/rust/issues/29596\n\n------------------------\n\nYou can tell `rustc` how to customize linking, and that is via the `link_args`\nattribute. This attribute is applied to `extern` blocks and specifies raw flags\nwhich need to get passed to the linker when producing an artifact. An example\nusage would be:\n\n```rust,no_run\n#![feature(link_args)]\n\n#[link_args = \"-foo -bar -baz\"]\nextern {}\n# fn main() {}\n```\n\nNote that this feature is currently hidden behind the `feature(link_args)` gate\nbecause this is not a sanctioned way of performing linking. Right now `rustc`\nshells out to the system linker (`gcc` on most systems, `link.exe` on MSVC), so\nit makes sense to provide extra command line arguments, but this will not\nalways be the case. In the future `rustc` may use LLVM directly to link native\nlibraries, in which case `link_args` will have no meaning. You can achieve the\nsame effect as the `link_args` attribute with the `-C link-args` argument to\n`rustc`.\n\nIt is highly recommended to *not* use this attribute, and rather use the more\nformal `#[link(...)]` attribute on `extern` blocks instead.\n" } , LintCompletion { label : "repr128" , description : "# `repr128`\n\nThe tracking issue for this feature is: [#56071]\n\n[#56071]: https://github.com/rust-lang/rust/issues/56071\n\n------------------------\n\nThe `repr128` feature adds support for `#[repr(u128)]` on `enum`s.\n\n```rust\n#![feature(repr128)]\n\n#[repr(u128)]\nenum Foo {\n Bar(u64),\n}\n```\n" } , LintCompletion { label : "crate_visibility_modifier" , description : "# `crate_visibility_modifier`\n\nThe tracking issue for this feature is: [#53120]\n\n[#53120]: https://github.com/rust-lang/rust/issues/53120\n\n-----\n\nThe `crate_visibility_modifier` feature allows the `crate` keyword to be used\nas a visibility modifier synonymous to `pub(crate)`, indicating that a type\n(function, _&c._) is to be visible to the entire enclosing crate, but not to\nother crates.\n\n```rust\n#![feature(crate_visibility_modifier)]\n\ncrate struct Foo {\n bar: usize,\n}\n```\n" } , LintCompletion { label : "doc_masked" , description : "# `doc_masked`\n\nThe tracking issue for this feature is: [#44027]\n\n-----\n\nThe `doc_masked` feature allows a crate to exclude types from a given crate from appearing in lists\nof trait implementations. The specifics of the feature are as follows:\n\n1. When rustdoc encounters an `extern crate` statement annotated with a `#[doc(masked)]` attribute,\n it marks the crate as being masked.\n\n2. When listing traits a given type implements, rustdoc ensures that traits from masked crates are\n not emitted into the documentation.\n\n3. When listing types that implement a given trait, rustdoc ensures that types from masked crates\n are not emitted into the documentation.\n\nThis feature was introduced in PR [#44026] to ensure that compiler-internal and\nimplementation-specific types and traits were not included in the standard library's documentation.\nSuch types would introduce broken links into the documentation.\n\n[#44026]: https://github.com/rust-lang/rust/pull/44026\n[#44027]: https://github.com/rust-lang/rust/pull/44027\n" } , LintCompletion { label : "cfg_sanitize" , description : "# `cfg_sanitize`\n\nThe tracking issue for this feature is: [#39699]\n\n[#39699]: https://github.com/rust-lang/rust/issues/39699\n\n------------------------\n\nThe `cfg_sanitize` feature makes it possible to execute different code\ndepending on whether a particular sanitizer is enabled or not.\n\n## Examples\n\n```rust\n#![feature(cfg_sanitize)]\n\n#[cfg(sanitize = \"thread\")]\nfn a() {\n // ...\n}\n\n#[cfg(not(sanitize = \"thread\"))]\nfn a() {\n // ...\n}\n\nfn b() {\n if cfg!(sanitize = \"leak\") {\n // ...\n } else {\n // ...\n }\n}\n```\n" } , LintCompletion { label : "generators" , description : "# `generators`\n\nThe tracking issue for this feature is: [#43122]\n\n[#43122]: https://github.com/rust-lang/rust/issues/43122\n\n------------------------\n\nThe `generators` feature gate in Rust allows you to define generator or\ncoroutine literals. A generator is a \"resumable function\" that syntactically\nresembles a closure but compiles to much different semantics in the compiler\nitself. The primary feature of a generator is that it can be suspended during\nexecution to be resumed at a later date. Generators use the `yield` keyword to\n\"return\", and then the caller can `resume` a generator to resume execution just\nafter the `yield` keyword.\n\nGenerators are an extra-unstable feature in the compiler right now. Added in\n[RFC 2033] they're mostly intended right now as a information/constraint\ngathering phase. The intent is that experimentation can happen on the nightly\ncompiler before actual stabilization. A further RFC will be required to\nstabilize generators/coroutines and will likely contain at least a few small\ntweaks to the overall design.\n\n[RFC 2033]: https://github.com/rust-lang/rfcs/pull/2033\n\nA syntactical example of a generator is:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::{Generator, GeneratorState};\nuse std::pin::Pin;\n\nfn main() {\n let mut generator = || {\n yield 1;\n return \"foo\"\n };\n\n match Pin::new(&mut generator).resume(()) {\n GeneratorState::Yielded(1) => {}\n _ => panic!(\"unexpected value from resume\"),\n }\n match Pin::new(&mut generator).resume(()) {\n GeneratorState::Complete(\"foo\") => {}\n _ => panic!(\"unexpected value from resume\"),\n }\n}\n```\n\nGenerators are closure-like literals which can contain a `yield` statement. The\n`yield` statement takes an optional expression of a value to yield out of the\ngenerator. All generator literals implement the `Generator` trait in the\n`std::ops` module. The `Generator` trait has one main method, `resume`, which\nresumes execution of the generator at the previous suspension point.\n\nAn example of the control flow of generators is that the following example\nprints all numbers in order:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::Generator;\nuse std::pin::Pin;\n\nfn main() {\n let mut generator = || {\n println!(\"2\");\n yield;\n println!(\"4\");\n };\n\n println!(\"1\");\n Pin::new(&mut generator).resume(());\n println!(\"3\");\n Pin::new(&mut generator).resume(());\n println!(\"5\");\n}\n```\n\nAt this time the main intended use case of generators is an implementation\nprimitive for async/await syntax, but generators will likely be extended to\nergonomic implementations of iterators and other primitives in the future.\nFeedback on the design and usage is always appreciated!\n\n### The `Generator` trait\n\nThe `Generator` trait in `std::ops` currently looks like:\n\n```rust\n# #![feature(arbitrary_self_types, generator_trait)]\n# use std::ops::GeneratorState;\n# use std::pin::Pin;\n\npub trait Generator<R = ()> {\n type Yield;\n type Return;\n fn resume(self: Pin<&mut Self>, resume: R) -> GeneratorState<Self::Yield, Self::Return>;\n}\n```\n\nThe `Generator::Yield` type is the type of values that can be yielded with the\n`yield` statement. The `Generator::Return` type is the returned type of the\ngenerator. This is typically the last expression in a generator's definition or\nany value passed to `return` in a generator. The `resume` function is the entry\npoint for executing the `Generator` itself.\n\nThe return value of `resume`, `GeneratorState`, looks like:\n\n```rust\npub enum GeneratorState<Y, R> {\n Yielded(Y),\n Complete(R),\n}\n```\n\nThe `Yielded` variant indicates that the generator can later be resumed. This\ncorresponds to a `yield` point in a generator. The `Complete` variant indicates\nthat the generator is complete and cannot be resumed again. Calling `resume`\nafter a generator has returned `Complete` will likely result in a panic of the\nprogram.\n\n### Closure-like semantics\n\nThe closure-like syntax for generators alludes to the fact that they also have\nclosure-like semantics. Namely:\n\n* When created, a generator executes no code. A closure literal does not\n actually execute any of the closure's code on construction, and similarly a\n generator literal does not execute any code inside the generator when\n constructed.\n\n* Generators can capture outer variables by reference or by move, and this can\n be tweaked with the `move` keyword at the beginning of the closure. Like\n closures all generators will have an implicit environment which is inferred by\n the compiler. Outer variables can be moved into a generator for use as the\n generator progresses.\n\n* Generator literals produce a value with a unique type which implements the\n `std::ops::Generator` trait. This allows actual execution of the generator\n through the `Generator::resume` method as well as also naming it in return\n types and such.\n\n* Traits like `Send` and `Sync` are automatically implemented for a `Generator`\n depending on the captured variables of the environment. Unlike closures,\n generators also depend on variables live across suspension points. This means\n that although the ambient environment may be `Send` or `Sync`, the generator\n itself may not be due to internal variables live across `yield` points being\n not-`Send` or not-`Sync`. Note that generators do\n not implement traits like `Copy` or `Clone` automatically.\n\n* Whenever a generator is dropped it will drop all captured environment\n variables.\n\n### Generators as state machines\n\nIn the compiler, generators are currently compiled as state machines. Each\n`yield` expression will correspond to a different state that stores all live\nvariables over that suspension point. Resumption of a generator will dispatch on\nthe current state and then execute internally until a `yield` is reached, at\nwhich point all state is saved off in the generator and a value is returned.\n\nLet's take a look at an example to see what's going on here:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::Generator;\nuse std::pin::Pin;\n\nfn main() {\n let ret = \"foo\";\n let mut generator = move || {\n yield 1;\n return ret\n };\n\n Pin::new(&mut generator).resume(());\n Pin::new(&mut generator).resume(());\n}\n```\n\nThis generator literal will compile down to something similar to:\n\n```rust\n#![feature(arbitrary_self_types, generators, generator_trait)]\n\nuse std::ops::{Generator, GeneratorState};\nuse std::pin::Pin;\n\nfn main() {\n let ret = \"foo\";\n let mut generator = {\n enum __Generator {\n Start(&'static str),\n Yield1(&'static str),\n Done,\n }\n\n impl Generator for __Generator {\n type Yield = i32;\n type Return = &'static str;\n\n fn resume(mut self: Pin<&mut Self>, resume: ()) -> GeneratorState<i32, &'static str> {\n use std::mem;\n match mem::replace(&mut *self, __Generator::Done) {\n __Generator::Start(s) => {\n *self = __Generator::Yield1(s);\n GeneratorState::Yielded(1)\n }\n\n __Generator::Yield1(s) => {\n *self = __Generator::Done;\n GeneratorState::Complete(s)\n }\n\n __Generator::Done => {\n panic!(\"generator resumed after completion\")\n }\n }\n }\n }\n\n __Generator::Start(ret)\n };\n\n Pin::new(&mut generator).resume(());\n Pin::new(&mut generator).resume(());\n}\n```\n\nNotably here we can see that the compiler is generating a fresh type,\n`__Generator` in this case. This type has a number of states (represented here\nas an `enum`) corresponding to each of the conceptual states of the generator.\nAt the beginning we're closing over our outer variable `foo` and then that\nvariable is also live over the `yield` point, so it's stored in both states.\n\nWhen the generator starts it'll immediately yield 1, but it saves off its state\njust before it does so indicating that it has reached the yield point. Upon\nresuming again we'll execute the `return ret` which returns the `Complete`\nstate.\n\nHere we can also note that the `Done` state, if resumed, panics immediately as\nit's invalid to resume a completed generator. It's also worth noting that this\nis just a rough desugaring, not a normative specification for what the compiler\ndoes.\n" } , LintCompletion { label : "abi_ptx" , description : "# `abi_ptx`\n\nThe tracking issue for this feature is: [#38788]\n\n[#38788]: https://github.com/rust-lang/rust/issues/38788\n\n------------------------\n\nWhen emitting PTX code, all vanilla Rust functions (`fn`) get translated to\n\"device\" functions. These functions are *not* callable from the host via the\nCUDA API so a crate with only device functions is not too useful!\n\nOTOH, \"global\" functions *can* be called by the host; you can think of them\nas the real public API of your crate. To produce a global function use the\n`\"ptx-kernel\"` ABI.\n\n<!-- NOTE(ignore) this example is specific to the nvptx targets -->\n\n``` rust,ignore\n#![feature(abi_ptx)]\n#![no_std]\n\npub unsafe extern \"ptx-kernel\" fn global_function() {\n device_function();\n}\n\npub fn device_function() {\n // ..\n}\n```\n\n``` text\n$ xargo rustc --target nvptx64-nvidia-cuda --release -- --emit=asm\n\n$ cat $(find -name '*.s')\n//\n// Generated by LLVM NVPTX Back-End\n//\n\n.version 3.2\n.target sm_20\n.address_size 64\n\n // .globl _ZN6kernel15global_function17h46111ebe6516b382E\n\n.visible .entry _ZN6kernel15global_function17h46111ebe6516b382E()\n{\n\n\n ret;\n}\n\n // .globl _ZN6kernel15device_function17hd6a0e4993bbf3f78E\n.visible .func _ZN6kernel15device_function17hd6a0e4993bbf3f78E()\n{\n\n\n ret;\n}\n```\n" } , LintCompletion { label : "unsized_tuple_coercion" , description : "# `unsized_tuple_coercion`\n\nThe tracking issue for this feature is: [#42877]\n\n[#42877]: https://github.com/rust-lang/rust/issues/42877\n\n------------------------\n\nThis is a part of [RFC0401]. According to the RFC, there should be an implementation like this:\n\n```rust,ignore\nimpl<..., T, U: ?Sized> Unsized<(..., U)> for (..., T) where T: Unsized<U> {}\n```\n\nThis implementation is currently gated behind `#[feature(unsized_tuple_coercion)]` to avoid insta-stability. Therefore you can use it like this:\n\n```rust\n#![feature(unsized_tuple_coercion)]\n\nfn main() {\n let x : ([i32; 3], [i32; 3]) = ([1, 2, 3], [4, 5, 6]);\n let y : &([i32; 3], [i32]) = &x;\n assert_eq!(y.1[0], 4);\n}\n```\n\n[RFC0401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md\n" } , LintCompletion { label : "const_in_array_repeat_expressions" , description : "# `const_in_array_repeat_expressions`\n\nThe tracking issue for this feature is: [#49147]\n\n[#49147]: https://github.com/rust-lang/rust/issues/49147\n\n------------------------\n\nRelaxes the rules for repeat expressions, `[x; N]` such that `x` may also be `const` (strictly\nspeaking rvalue promotable), in addition to `typeof(x): Copy`. The result of `[x; N]` where `x` is\n`const` is itself also `const`.\n" } , LintCompletion { label : "impl_trait_in_bindings" , description : "# `impl_trait_in_bindings`\n\nThe tracking issue for this feature is: [#63065]\n\n[#63065]: https://github.com/rust-lang/rust/issues/63065\n\n------------------------\n\nThe `impl_trait_in_bindings` feature gate lets you use `impl Trait` syntax in\n`let`, `static`, and `const` bindings.\n\nA simple example is:\n\n```rust\n#![feature(impl_trait_in_bindings)]\n\nuse std::fmt::Debug;\n\nfn main() {\n let a: impl Debug + Clone = 42;\n let b = a.clone();\n println!(\"{:?}\", b); // prints `42`\n}\n```\n\nNote however that because the types of `a` and `b` are opaque in the above\nexample, calling inherent methods or methods outside of the specified traits\n(e.g., `a.abs()` or `b.abs()`) is not allowed, and yields an error.\n" } , LintCompletion { label : "trait_alias" , description : "# `trait_alias`\n\nThe tracking issue for this feature is: [#41517]\n\n[#41517]: https://github.com/rust-lang/rust/issues/41517\n\n------------------------\n\nThe `trait_alias` feature adds support for trait aliases. These allow aliases\nto be created for one or more traits (currently just a single regular trait plus\nany number of auto-traits), and used wherever traits would normally be used as\neither bounds or trait objects.\n\n```rust\n#![feature(trait_alias)]\n\ntrait Foo = std::fmt::Debug + Send;\ntrait Bar = Foo + Sync;\n\n// Use trait alias as bound on type parameter.\nfn foo<T: Foo>(v: &T) {\n println!(\"{:?}\", v);\n}\n\npub fn main() {\n foo(&1);\n\n // Use trait alias for trait objects.\n let a: &Bar = &123;\n println!(\"{:?}\", a);\n let b = Box::new(456) as Box<dyn Foo>;\n println!(\"{:?}\", b);\n}\n```\n" } , LintCompletion { label : "doc_cfg" , description : "# `doc_cfg`\n\nThe tracking issue for this feature is: [#43781]\n\n------\n\nThe `doc_cfg` feature allows an API be documented as only available in some specific platforms.\nThis attribute has two effects:\n\n1. In the annotated item's documentation, there will be a message saying \"This is supported on\n (platform) only\".\n\n2. The item's doc-tests will only run on the specific platform.\n\nIn addition to allowing the use of the `#[doc(cfg)]` attribute, this feature enables the use of a\nspecial conditional compilation flag, `#[cfg(doc)]`, set whenever building documentation on your\ncrate.\n\nThis feature was introduced as part of PR [#43348] to allow the platform-specific parts of the\nstandard library be documented.\n\n```rust\n#![feature(doc_cfg)]\n\n#[cfg(any(windows, doc))]\n#[doc(cfg(windows))]\n/// The application's icon in the notification area (a.k.a. system tray).\n///\n/// # Examples\n///\n/// ```no_run\n/// extern crate my_awesome_ui_library;\n/// use my_awesome_ui_library::current_app;\n/// use my_awesome_ui_library::windows::notification;\n///\n/// let icon = current_app().get::<notification::Icon>();\n/// icon.show();\n/// icon.show_message(\"Hello\");\n/// ```\npub struct Icon {\n // ...\n}\n```\n\n[#43781]: https://github.com/rust-lang/rust/issues/43781\n[#43348]: https://github.com/rust-lang/rust/issues/43348\n" } , LintCompletion { label : "lang_items" , description : "# `lang_items`\n\nThe tracking issue for this feature is: None.\n\n------------------------\n\nThe `rustc` compiler has certain pluggable operations, that is,\nfunctionality that isn't hard-coded into the language, but is\nimplemented in libraries, with a special marker to tell the compiler\nit exists. The marker is the attribute `#[lang = \"...\"]` and there are\nvarious different values of `...`, i.e. various different 'lang\nitems'.\n\nFor example, `Box` pointers require two lang items, one for allocation\nand one for deallocation. A freestanding program that uses the `Box`\nsugar for dynamic allocations via `malloc` and `free`:\n\n```rust,ignore\n#![feature(lang_items, box_syntax, start, libc, core_intrinsics)]\n#![no_std]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\nextern crate libc;\n\n#[lang = \"owned_box\"]\npub struct Box<T>(*mut T);\n\n#[lang = \"exchange_malloc\"]\nunsafe fn allocate(size: usize, _align: usize) -> *mut u8 {\n let p = libc::malloc(size as libc::size_t) as *mut u8;\n\n // Check if `malloc` failed:\n if p as usize == 0 {\n intrinsics::abort();\n }\n\n p\n}\n\n#[lang = \"box_free\"]\nunsafe fn box_free<T: ?Sized>(ptr: *mut T) {\n libc::free(ptr as *mut libc::c_void)\n}\n\n#[start]\nfn main(_argc: isize, _argv: *const *const u8) -> isize {\n let _x = box 1;\n\n 0\n}\n\n#[lang = \"eh_personality\"] extern fn rust_eh_personality() {}\n#[lang = \"panic_impl\"] extern fn rust_begin_panic(info: &PanicInfo) -> ! { unsafe { intrinsics::abort() } }\n#[no_mangle] pub extern fn rust_eh_register_frames () {}\n#[no_mangle] pub extern fn rust_eh_unregister_frames () {}\n```\n\nNote the use of `abort`: the `exchange_malloc` lang item is assumed to\nreturn a valid pointer, and so needs to do the check internally.\n\nOther features provided by lang items include:\n\n- overloadable operators via traits: the traits corresponding to the\n `==`, `<`, dereferencing (`*`) and `+` (etc.) operators are all\n marked with lang items; those specific four are `eq`, `ord`,\n `deref`, and `add` respectively.\n- stack unwinding and general failure; the `eh_personality`,\n `panic` and `panic_bounds_checks` lang items.\n- the traits in `std::marker` used to indicate types of\n various kinds; lang items `send`, `sync` and `copy`.\n- the marker types and variance indicators found in\n `std::marker`; lang items `covariant_type`,\n `contravariant_lifetime`, etc.\n\nLang items are loaded lazily by the compiler; e.g. if one never uses\n`Box` then there is no need to define functions for `exchange_malloc`\nand `box_free`. `rustc` will emit an error when an item is needed\nbut not found in the current crate or any that it depends on.\n\nMost lang items are defined by `libcore`, but if you're trying to build\nan executable without the standard library, you'll run into the need\nfor lang items. The rest of this page focuses on this use-case, even though\nlang items are a bit broader than that.\n\n### Using libc\n\nIn order to build a `#[no_std]` executable we will need libc as a dependency.\nWe can specify this using our `Cargo.toml` file:\n\n```toml\n[dependencies]\nlibc = { version = \"0.2.14\", default-features = false }\n```\n\nNote that the default features have been disabled. This is a critical step -\n**the default features of libc include the standard library and so must be\ndisabled.**\n\n### Writing an executable without stdlib\n\nControlling the entry point is possible in two ways: the `#[start]` attribute,\nor overriding the default shim for the C `main` function with your own.\n\nThe function marked `#[start]` is passed the command line parameters\nin the same format as C:\n\n```rust,ignore\n#![feature(lang_items, core_intrinsics)]\n#![feature(start)]\n#![no_std]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\n// Pull in the system libc library for what crt0.o likely requires.\nextern crate libc;\n\n// Entry point for this program.\n#[start]\nfn start(_argc: isize, _argv: *const *const u8) -> isize {\n 0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn rust_eh_personality() {\n}\n\n#[lang = \"panic_impl\"]\n#[no_mangle]\npub extern fn rust_begin_panic(info: &PanicInfo) -> ! {\n unsafe { intrinsics::abort() }\n}\n```\n\nTo override the compiler-inserted `main` shim, one has to disable it\nwith `#![no_main]` and then create the appropriate symbol with the\ncorrect ABI and the correct name, which requires overriding the\ncompiler's name mangling too:\n\n```rust,ignore\n#![feature(lang_items, core_intrinsics)]\n#![feature(start)]\n#![no_std]\n#![no_main]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\n// Pull in the system libc library for what crt0.o likely requires.\nextern crate libc;\n\n// Entry point for this program.\n#[no_mangle] // ensure that this symbol is called `main` in the output\npub extern fn main(_argc: i32, _argv: *const *const u8) -> i32 {\n 0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn rust_eh_personality() {\n}\n\n#[lang = \"panic_impl\"]\n#[no_mangle]\npub extern fn rust_begin_panic(info: &PanicInfo) -> ! {\n unsafe { intrinsics::abort() }\n}\n```\n\nIn many cases, you may need to manually link to the `compiler_builtins` crate\nwhen building a `no_std` binary. You may observe this via linker error messages\nsuch as \"```undefined reference to `__rust_probestack'```\".\n\n## More about the language items\n\nThe compiler currently makes a few assumptions about symbols which are\navailable in the executable to call. Normally these functions are provided by\nthe standard library, but without it you must define your own. These symbols\nare called \"language items\", and they each have an internal name, and then a\nsignature that an implementation must conform to.\n\nThe first of these functions, `rust_eh_personality`, is used by the failure\nmechanisms of the compiler. This is often mapped to GCC's personality function\n(see the [libstd implementation][unwind] for more information), but crates\nwhich do not trigger a panic can be assured that this function is never\ncalled. The language item's name is `eh_personality`.\n\n[unwind]: https://github.com/rust-lang/rust/blob/master/src/libpanic_unwind/gcc.rs\n\nThe second function, `rust_begin_panic`, is also used by the failure mechanisms of the\ncompiler. When a panic happens, this controls the message that's displayed on\nthe screen. While the language item's name is `panic_impl`, the symbol name is\n`rust_begin_panic`.\n\nFinally, a `eh_catch_typeinfo` static is needed for certain targets which\nimplement Rust panics on top of C++ exceptions.\n\n## List of all language items\n\nThis is a list of all language items in Rust along with where they are located in\nthe source code.\n\n- Primitives\n - `i8`: `libcore/num/mod.rs`\n - `i16`: `libcore/num/mod.rs`\n - `i32`: `libcore/num/mod.rs`\n - `i64`: `libcore/num/mod.rs`\n - `i128`: `libcore/num/mod.rs`\n - `isize`: `libcore/num/mod.rs`\n - `u8`: `libcore/num/mod.rs`\n - `u16`: `libcore/num/mod.rs`\n - `u32`: `libcore/num/mod.rs`\n - `u64`: `libcore/num/mod.rs`\n - `u128`: `libcore/num/mod.rs`\n - `usize`: `libcore/num/mod.rs`\n - `f32`: `libstd/f32.rs`\n - `f64`: `libstd/f64.rs`\n - `char`: `libcore/char.rs`\n - `slice`: `liballoc/slice.rs`\n - `str`: `liballoc/str.rs`\n - `const_ptr`: `libcore/ptr.rs`\n - `mut_ptr`: `libcore/ptr.rs`\n - `unsafe_cell`: `libcore/cell.rs`\n- Runtime\n - `start`: `libstd/rt.rs`\n - `eh_personality`: `libpanic_unwind/emcc.rs` (EMCC)\n - `eh_personality`: `libpanic_unwind/gcc.rs` (GNU)\n - `eh_personality`: `libpanic_unwind/seh.rs` (SEH)\n - `eh_catch_typeinfo`: `libpanic_unwind/emcc.rs` (EMCC)\n - `panic`: `libcore/panicking.rs`\n - `panic_bounds_check`: `libcore/panicking.rs`\n - `panic_impl`: `libcore/panicking.rs`\n - `panic_impl`: `libstd/panicking.rs`\n- Allocations\n - `owned_box`: `liballoc/boxed.rs`\n - `exchange_malloc`: `liballoc/heap.rs`\n - `box_free`: `liballoc/heap.rs`\n- Operands\n - `not`: `libcore/ops/bit.rs`\n - `bitand`: `libcore/ops/bit.rs`\n - `bitor`: `libcore/ops/bit.rs`\n - `bitxor`: `libcore/ops/bit.rs`\n - `shl`: `libcore/ops/bit.rs`\n - `shr`: `libcore/ops/bit.rs`\n - `bitand_assign`: `libcore/ops/bit.rs`\n - `bitor_assign`: `libcore/ops/bit.rs`\n - `bitxor_assign`: `libcore/ops/bit.rs`\n - `shl_assign`: `libcore/ops/bit.rs`\n - `shr_assign`: `libcore/ops/bit.rs`\n - `deref`: `libcore/ops/deref.rs`\n - `deref_mut`: `libcore/ops/deref.rs`\n - `index`: `libcore/ops/index.rs`\n - `index_mut`: `libcore/ops/index.rs`\n - `add`: `libcore/ops/arith.rs`\n - `sub`: `libcore/ops/arith.rs`\n - `mul`: `libcore/ops/arith.rs`\n - `div`: `libcore/ops/arith.rs`\n - `rem`: `libcore/ops/arith.rs`\n - `neg`: `libcore/ops/arith.rs`\n - `add_assign`: `libcore/ops/arith.rs`\n - `sub_assign`: `libcore/ops/arith.rs`\n - `mul_assign`: `libcore/ops/arith.rs`\n - `div_assign`: `libcore/ops/arith.rs`\n - `rem_assign`: `libcore/ops/arith.rs`\n - `eq`: `libcore/cmp.rs`\n - `ord`: `libcore/cmp.rs`\n- Functions\n - `fn`: `libcore/ops/function.rs`\n - `fn_mut`: `libcore/ops/function.rs`\n - `fn_once`: `libcore/ops/function.rs`\n - `generator_state`: `libcore/ops/generator.rs`\n - `generator`: `libcore/ops/generator.rs`\n- Other\n - `coerce_unsized`: `libcore/ops/unsize.rs`\n - `drop`: `libcore/ops/drop.rs`\n - `drop_in_place`: `libcore/ptr.rs`\n - `clone`: `libcore/clone.rs`\n - `copy`: `libcore/marker.rs`\n - `send`: `libcore/marker.rs`\n - `sized`: `libcore/marker.rs`\n - `unsize`: `libcore/marker.rs`\n - `sync`: `libcore/marker.rs`\n - `phantom_data`: `libcore/marker.rs`\n - `discriminant_kind`: `libcore/marker.rs`\n - `freeze`: `libcore/marker.rs`\n - `debug_trait`: `libcore/fmt/mod.rs`\n - `non_zero`: `libcore/nonzero.rs`\n - `arc`: `liballoc/sync.rs`\n - `rc`: `liballoc/rc.rs`\n" } , LintCompletion { label : "transparent_unions" , description : "# `transparent_unions`\n\nThe tracking issue for this feature is [#60405]\n\n[#60405]: https://github.com/rust-lang/rust/issues/60405\n\n----\n\nThe `transparent_unions` feature allows you mark `union`s as\n`#[repr(transparent)]`. A `union` may be `#[repr(transparent)]` in exactly the\nsame conditions in which a `struct` may be `#[repr(transparent)]` (generally,\nthis means the `union` must have exactly one non-zero-sized field). Some\nconcrete illustrations follow.\n\n```rust\n#![feature(transparent_unions)]\n\n// This union has the same representation as `f32`.\n#[repr(transparent)]\nunion SingleFieldUnion {\n field: f32,\n}\n\n// This union has the same representation as `usize`.\n#[repr(transparent)]\nunion MultiFieldUnion {\n field: usize,\n nothing: (),\n}\n```\n\nFor consistency with transparent `struct`s, `union`s must have exactly one\nnon-zero-sized field. If all fields are zero-sized, the `union` must not be\n`#[repr(transparent)]`:\n\n```rust\n#![feature(transparent_unions)]\n\n// This (non-transparent) union is already valid in stable Rust:\npub union GoodUnion {\n pub nothing: (),\n}\n\n// Error: transparent union needs exactly one non-zero-sized field, but has 0\n// #[repr(transparent)]\n// pub union BadUnion {\n// pub nothing: (),\n// }\n```\n\nThe one exception is if the `union` is generic over `T` and has a field of type\n`T`, it may be `#[repr(transparent)]` even if `T` is a zero-sized type:\n\n```rust\n#![feature(transparent_unions)]\n\n// This union has the same representation as `T`.\n#[repr(transparent)]\npub union GenericUnion<T: Copy> { // Unions with non-`Copy` fields are unstable.\n pub field: T,\n pub nothing: (),\n}\n\n// This is okay even though `()` is a zero-sized type.\npub const THIS_IS_OKAY: GenericUnion<()> = GenericUnion { field: () };\n```\n\nLike transarent `struct`s, a transparent `union` of type `U` has the same\nlayout, size, and ABI as its single non-ZST field. If it is generic over a type\n`T`, and all its fields are ZSTs except for exactly one field of type `T`, then\nit has the same layout and ABI as `T` (even if `T` is a ZST when monomorphized).\n\nLike transparent `struct`s, transparent `union`s are FFI-safe if and only if\ntheir underlying representation type is also FFI-safe.\n\nA `union` may not be eligible for the same nonnull-style optimizations that a\n`struct` or `enum` (with the same fields) are eligible for. Adding\n`#[repr(transparent)]` to `union` does not change this. To give a more concrete\nexample, it is unspecified whether `size_of::<T>()` is equal to\n`size_of::<Option<T>>()`, where `T` is a `union` (regardless of whether or not\nit is transparent). The Rust compiler is free to perform this optimization if\npossible, but is not required to, and different compiler versions may differ in\ntheir application of these optimizations.\n" } , LintCompletion { label : "abi_msp430_interrupt" , description : "# `abi_msp430_interrupt`\n\nThe tracking issue for this feature is: [#38487]\n\n[#38487]: https://github.com/rust-lang/rust/issues/38487\n\n------------------------\n\nIn the MSP430 architecture, interrupt handlers have a special calling\nconvention. You can use the `\"msp430-interrupt\"` ABI to make the compiler apply\nthe right calling convention to the interrupt handlers you define.\n\n<!-- NOTE(ignore) this example is specific to the msp430 target -->\n\n``` rust,ignore\n#![feature(abi_msp430_interrupt)]\n#![no_std]\n\n// Place the interrupt handler at the appropriate memory address\n// (Alternatively, you can use `#[used]` and remove `pub` and `#[no_mangle]`)\n#[link_section = \"__interrupt_vector_10\"]\n#[no_mangle]\npub static TIM0_VECTOR: extern \"msp430-interrupt\" fn() = tim0;\n\n// The interrupt handler\nextern \"msp430-interrupt\" fn tim0() {\n // ..\n}\n```\n\n``` text\n$ msp430-elf-objdump -CD ./target/msp430/release/app\nDisassembly of section __interrupt_vector_10:\n\n0000fff2 <TIM0_VECTOR>:\n fff2: 00 c0 interrupt service routine at 0xc000\n\nDisassembly of section .text:\n\n0000c000 <int::tim0>:\n c000: 00 13 reti\n```\n" } , LintCompletion { label : "plugin" , description : "# `plugin`\n\nThe tracking issue for this feature is: [#29597]\n\n[#29597]: https://github.com/rust-lang/rust/issues/29597\n\n\nThis feature is part of \"compiler plugins.\" It will often be used with the\n[`plugin_registrar`] and `rustc_private` features.\n\n[`plugin_registrar`]: plugin-registrar.md\n\n------------------------\n\n`rustc` can load compiler plugins, which are user-provided libraries that\nextend the compiler's behavior with new lint checks, etc.\n\nA plugin is a dynamic library crate with a designated *registrar* function that\nregisters extensions with `rustc`. Other crates can load these extensions using\nthe crate attribute `#![plugin(...)]`. See the\n`rustc_driver::plugin` documentation for more about the\nmechanics of defining and loading a plugin.\n\nIn the vast majority of cases, a plugin should *only* be used through\n`#![plugin]` and not through an `extern crate` item. Linking a plugin would\npull in all of librustc_ast and librustc as dependencies of your crate. This is\ngenerally unwanted unless you are building another plugin.\n\nThe usual practice is to put compiler plugins in their own crate, separate from\nany `macro_rules!` macros or ordinary Rust code meant to be used by consumers\nof a library.\n\n# Lint plugins\n\nPlugins can extend [Rust's lint\ninfrastructure](../../reference/attributes/diagnostics.md#lint-check-attributes) with\nadditional checks for code style, safety, etc. Now let's write a plugin\n[`lint-plugin-test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui-fulldeps/auxiliary/lint-plugin-test.rs)\nthat warns about any item named `lintme`.\n\n```rust,ignore\n#![feature(plugin_registrar)]\n#![feature(box_syntax, rustc_private)]\n\nextern crate rustc_ast;\n\n// Load rustc as a plugin to get macros\nextern crate rustc_driver;\n#[macro_use]\nextern crate rustc_lint;\n#[macro_use]\nextern crate rustc_session;\n\nuse rustc_driver::plugin::Registry;\nuse rustc_lint::{EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};\nuse rustc_ast::ast;\ndeclare_lint!(TEST_LINT, Warn, \"Warn about items named 'lintme'\");\n\ndeclare_lint_pass!(Pass => [TEST_LINT]);\n\nimpl EarlyLintPass for Pass {\n fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {\n if it.ident.name.as_str() == \"lintme\" {\n cx.lint(TEST_LINT, |lint| {\n lint.build(\"item is named 'lintme'\").set_span(it.span).emit()\n });\n }\n }\n}\n\n#[plugin_registrar]\npub fn plugin_registrar(reg: &mut Registry) {\n reg.lint_store.register_lints(&[&TEST_LINT]);\n reg.lint_store.register_early_pass(|| box Pass);\n}\n```\n\nThen code like\n\n```rust,ignore\n#![feature(plugin)]\n#![plugin(lint_plugin_test)]\n\nfn lintme() { }\n```\n\nwill produce a compiler warning:\n\n```txt\nfoo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default\nfoo.rs:4 fn lintme() { }\n ^~~~~~~~~~~~~~~\n```\n\nThe components of a lint plugin are:\n\n* one or more `declare_lint!` invocations, which define static `Lint` structs;\n\n* a struct holding any state needed by the lint pass (here, none);\n\n* a `LintPass`\n implementation defining how to check each syntax element. A single\n `LintPass` may call `span_lint` for several different `Lint`s, but should\n register them all through the `get_lints` method.\n\nLint passes are syntax traversals, but they run at a late stage of compilation\nwhere type information is available. `rustc`'s [built-in\nlints](https://github.com/rust-lang/rust/blob/master/src/librustc_session/lint/builtin.rs)\nmostly use the same infrastructure as lint plugins, and provide examples of how\nto access type information.\n\nLints defined by plugins are controlled by the usual [attributes and compiler\nflags](../../reference/attributes/diagnostics.md#lint-check-attributes), e.g.\n`#[allow(test_lint)]` or `-A test-lint`. These identifiers are derived from the\nfirst argument to `declare_lint!`, with appropriate case and punctuation\nconversion.\n\nYou can run `rustc -W help foo.rs` to see a list of lints known to `rustc`,\nincluding those provided by plugins loaded by `foo.rs`.\n" } , LintCompletion { label : "optin_builtin_traits" , description : "# `optin_builtin_traits`\n\nThe tracking issue for this feature is [#13231] \n\n[#13231]: https://github.com/rust-lang/rust/issues/13231\n\n----\n\nThe `optin_builtin_traits` feature gate allows you to define auto traits.\n\nAuto traits, like [`Send`] or [`Sync`] in the standard library, are marker traits\nthat are automatically implemented for every type, unless the type, or a type it contains, \nhas explicitly opted out via a negative impl. (Negative impls are separately controlled\nby the `negative_impls` feature.)\n\n[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html\n[`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html\n\n```rust,ignore\nimpl !Trait for Type\n```\n\nExample:\n\n```rust\n#![feature(negative_impls)]\n#![feature(optin_builtin_traits)]\n\nauto trait Valid {}\n\nstruct True;\nstruct False;\n\nimpl !Valid for False {}\n\nstruct MaybeValid<T>(T);\n\nfn must_be_valid<T: Valid>(_t: T) { }\n\nfn main() {\n // works\n must_be_valid( MaybeValid(True) );\n \n // compiler error - trait bound not satisfied\n // must_be_valid( MaybeValid(False) );\n}\n```\n\n## Automatic trait implementations\n\nWhen a type is declared as an `auto trait`, we will automatically\ncreate impls for every struct/enum/union, unless an explicit impl is\nprovided. These automatic impls contain a where clause for each field\nof the form `T: AutoTrait`, where `T` is the type of the field and\n`AutoTrait` is the auto trait in question. As an example, consider the\nstruct `List` and the auto trait `Send`:\n\n```rust\nstruct List<T> {\n data: T,\n next: Option<Box<List<T>>>,\n}\n```\n\nPresuming that there is no explicit impl of `Send` for `List`, the\ncompiler will supply an automatic impl of the form:\n\n```rust\nstruct List<T> {\n data: T,\n next: Option<Box<List<T>>>,\n}\n\nunsafe impl<T> Send for List<T>\nwhere\n T: Send, // from the field `data`\n Option<Box<List<T>>>: Send, // from the field `next`\n{ }\n```\n\nExplicit impls may be either positive or negative. They take the form:\n\n```rust,ignore\nimpl<...> AutoTrait for StructName<..> { }\nimpl<...> !AutoTrait for StructName<..> { }\n```\n\n## Coinduction: Auto traits permit cyclic matching\n\nUnlike ordinary trait matching, auto traits are **coinductive**. This\nmeans, in short, that cycles which occur in trait matching are\nconsidered ok. As an example, consider the recursive struct `List`\nintroduced in the previous section. In attempting to determine whether\n`List: Send`, we would wind up in a cycle: to apply the impl, we must\nshow that `Option<Box<List>>: Send`, which will in turn require\n`Box<List>: Send` and then finally `List: Send` again. Under ordinary\ntrait matching, this cycle would be an error, but for an auto trait it\nis considered a successful match.\n\n## Items\n\nAuto traits cannot have any trait items, such as methods or associated types. This ensures that we can generate default implementations.\n\n## Supertraits\n\nAuto traits cannot have supertraits. This is for soundness reasons, as the interaction of coinduction with implied bounds is difficult to reconcile.\n\n" } , LintCompletion { label : "unboxed_closures" , description : "# `unboxed_closures`\n\nThe tracking issue for this feature is [#29625]\n\nSee Also: [`fn_traits`](../library-features/fn-traits.md)\n\n[#29625]: https://github.com/rust-lang/rust/issues/29625\n\n----\n\nThe `unboxed_closures` feature allows you to write functions using the `\"rust-call\"` ABI,\nrequired for implementing the [`Fn*`] family of traits. `\"rust-call\"` functions must have \nexactly one (non self) argument, a tuple representing the argument list.\n\n[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html\n\n```rust\n#![feature(unboxed_closures)]\n\nextern \"rust-call\" fn add_args(args: (u32, u32)) -> u32 {\n args.0 + args.1\n}\n\nfn main() {}\n```\n" } , LintCompletion { label : "intrinsics" , description : "# `intrinsics`\n\nThe tracking issue for this feature is: None.\n\nIntrinsics are never intended to be stable directly, but intrinsics are often\nexported in some sort of stable manner. Prefer using the stable interfaces to\nthe intrinsic directly when you can.\n\n------------------------\n\n\nThese are imported as if they were FFI functions, with the special\n`rust-intrinsic` ABI. For example, if one was in a freestanding\ncontext, but wished to be able to `transmute` between types, and\nperform efficient pointer arithmetic, one would import those functions\nvia a declaration like\n\n```rust\n#![feature(intrinsics)]\n# fn main() {}\n\nextern \"rust-intrinsic\" {\n fn transmute<T, U>(x: T) -> U;\n\n fn offset<T>(dst: *const T, offset: isize) -> *const T;\n}\n```\n\nAs with any other FFI functions, these are always `unsafe` to call.\n\n" } , LintCompletion { label : "no_sanitize" , description : "# `no_sanitize`\n\nThe tracking issue for this feature is: [#39699]\n\n[#39699]: https://github.com/rust-lang/rust/issues/39699\n\n------------------------\n\nThe `no_sanitize` attribute can be used to selectively disable sanitizer\ninstrumentation in an annotated function. This might be useful to: avoid\ninstrumentation overhead in a performance critical function, or avoid\ninstrumenting code that contains constructs unsupported by given sanitizer.\n\nThe precise effect of this annotation depends on particular sanitizer in use.\nFor example, with `no_sanitize(thread)`, the thread sanitizer will no longer\ninstrument non-atomic store / load operations, but it will instrument atomic\noperations to avoid reporting false positives and provide meaning full stack\ntraces.\n\n## Examples\n\n``` rust\n#![feature(no_sanitize)]\n\n#[no_sanitize(address)]\nfn foo() {\n // ...\n}\n```\n" } , LintCompletion { label : "ffi_const" , description : "# `ffi_const`\n\nThe tracking issue for this feature is: [#58328]\n\n------\n\nThe `#[ffi_const]` attribute applies clang's `const` attribute to foreign\nfunctions declarations.\n\nThat is, `#[ffi_const]` functions shall have no effects except for its return\nvalue, which can only depend on the values of the function parameters, and is\nnot affected by changes to the observable state of the program.\n\nApplying the `#[ffi_const]` attribute to a function that violates these\nrequirements is undefined behaviour.\n\nThis attribute enables Rust to perform common optimizations, like sub-expression\nelimination, and it can avoid emitting some calls in repeated invocations of the\nfunction with the same argument values regardless of other operations being\nperformed in between these functions calls (as opposed to `#[ffi_pure]`\nfunctions).\n\n## Pitfalls\n\nA `#[ffi_const]` function can only read global memory that would not affect\nits return value for the whole execution of the program (e.g. immutable global\nmemory). `#[ffi_const]` functions are referentially-transparent and therefore\nmore strict than `#[ffi_pure]` functions.\n\nA common pitfall involves applying the `#[ffi_const]` attribute to a\nfunction that reads memory through pointer arguments which do not necessarily\npoint to immutable global memory.\n\nA `#[ffi_const]` function that returns unit has no effect on the abstract\nmachine's state, and a `#[ffi_const]` function cannot be `#[ffi_pure]`.\n\nA `#[ffi_const]` function must not diverge, neither via a side effect (e.g. a\ncall to `abort`) nor by infinite loops.\n\nWhen translating C headers to Rust FFI, it is worth verifying for which targets\nthe `const` attribute is enabled in those headers, and using the appropriate\n`cfg` macros in the Rust side to match those definitions. While the semantics of\n`const` are implemented identically by many C and C++ compilers, e.g., clang,\n[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily\nimplemented in this way on all of them. It is therefore also worth verifying\nthat the semantics of the C toolchain used to compile the binary being linked\nagainst are compatible with those of the `#[ffi_const]`.\n\n[#58328]: https://github.com/rust-lang/rust/issues/58328\n[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacgigch.html\n[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-const-function-attribute\n[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_const.htm\n" } , LintCompletion { label : "unsized_locals" , description : "# `unsized_locals`\n\nThe tracking issue for this feature is: [#48055]\n\n[#48055]: https://github.com/rust-lang/rust/issues/48055\n\n------------------------\n\nThis implements [RFC1909]. When turned on, you can have unsized arguments and locals:\n\n[RFC1909]: https://github.com/rust-lang/rfcs/blob/master/text/1909-unsized-rvalues.md\n\n```rust\n#![feature(unsized_locals)]\n\nuse std::any::Any;\n\nfn main() {\n let x: Box<dyn Any> = Box::new(42);\n let x: dyn Any = *x;\n // ^ unsized local variable\n // ^^ unsized temporary\n foo(x);\n}\n\nfn foo(_: dyn Any) {}\n// ^^^^^^ unsized argument\n```\n\nThe RFC still forbids the following unsized expressions:\n\n```rust,ignore\n#![feature(unsized_locals)]\n\nuse std::any::Any;\n\nstruct MyStruct<T: ?Sized> {\n content: T,\n}\n\nstruct MyTupleStruct<T: ?Sized>(T);\n\nfn answer() -> Box<dyn Any> {\n Box::new(42)\n}\n\nfn main() {\n // You CANNOT have unsized statics.\n static X: dyn Any = *answer(); // ERROR\n const Y: dyn Any = *answer(); // ERROR\n\n // You CANNOT have struct initialized unsized.\n MyStruct { content: *answer() }; // ERROR\n MyTupleStruct(*answer()); // ERROR\n (42, *answer()); // ERROR\n\n // You CANNOT have unsized return types.\n fn my_function() -> dyn Any { *answer() } // ERROR\n\n // You CAN have unsized local variables...\n let mut x: dyn Any = *answer(); // OK\n // ...but you CANNOT reassign to them.\n x = *answer(); // ERROR\n\n // You CANNOT even initialize them separately.\n let y: dyn Any; // OK\n y = *answer(); // ERROR\n\n // Not mentioned in the RFC, but by-move captured variables are also Sized.\n let x: dyn Any = *answer();\n (move || { // ERROR\n let y = x;\n })();\n\n // You CAN create a closure with unsized arguments,\n // but you CANNOT call it.\n // This is an implementation detail and may be changed in the future.\n let f = |x: dyn Any| {};\n f(*answer()); // ERROR\n}\n```\n\n## By-value trait objects\n\nWith this feature, you can have by-value `self` arguments without `Self: Sized` bounds.\n\n```rust\n#![feature(unsized_locals)]\n\ntrait Foo {\n fn foo(self) {}\n}\n\nimpl<T: ?Sized> Foo for T {}\n\nfn main() {\n let slice: Box<[i32]> = Box::new([1, 2, 3]);\n <[i32] as Foo>::foo(*slice);\n}\n```\n\nAnd `Foo` will also be object-safe.\n\n```rust\n#![feature(unsized_locals)]\n\ntrait Foo {\n fn foo(self) {}\n}\n\nimpl<T: ?Sized> Foo for T {}\n\nfn main () {\n let slice: Box<dyn Foo> = Box::new([1, 2, 3]);\n // doesn't compile yet\n <dyn Foo as Foo>::foo(*slice);\n}\n```\n\nOne of the objectives of this feature is to allow `Box<dyn FnOnce>`.\n\n## Variable length arrays\n\nThe RFC also describes an extension to the array literal syntax: `[e; dyn n]`. In the syntax, `n` isn't necessarily a constant expression. The array is dynamically allocated on the stack and has the type of `[T]`, instead of `[T; n]`.\n\n```rust,ignore\n#![feature(unsized_locals)]\n\nfn mergesort<T: Ord>(a: &mut [T]) {\n let mut tmp = [T; dyn a.len()];\n // ...\n}\n\nfn main() {\n let mut a = [3, 1, 5, 6];\n mergesort(&mut a);\n assert_eq!(a, [1, 3, 5, 6]);\n}\n```\n\nVLAs are not implemented yet. The syntax isn't final, either. We may need an alternative syntax for Rust 2015 because, in Rust 2015, expressions like `[e; dyn(1)]` would be ambiguous. One possible alternative proposed in the RFC is `[e; n]`: if `n` captures one or more local variables, then it is considered as `[e; dyn n]`.\n\n## Advisory on stack usage\n\nIt's advised not to casually use the `#![feature(unsized_locals)]` feature. Typical use-cases are:\n\n- When you need a by-value trait objects.\n- When you really need a fast allocation of small temporary arrays.\n\nAnother pitfall is repetitive allocation and temporaries. Currently the compiler simply extends the stack frame every time it encounters an unsized assignment. So for example, the code\n\n```rust\n#![feature(unsized_locals)]\n\nfn main() {\n let x: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);\n let _x = {{{{{{{{{{*x}}}}}}}}}};\n}\n```\n\nand the code\n\n```rust\n#![feature(unsized_locals)]\n\nfn main() {\n for _ in 0..10 {\n let x: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);\n let _x = *x;\n }\n}\n```\n\nwill unnecessarily extend the stack frame.\n" } , LintCompletion { label : "infer_static_outlives_requirements" , description : "# `infer_static_outlives_requirements`\n\nThe tracking issue for this feature is: [#54185]\n\n[#54185]: https://github.com/rust-lang/rust/issues/54185\n\n------------------------\nThe `infer_static_outlives_requirements` feature indicates that certain\n`'static` outlives requirements can be inferred by the compiler rather than\nstating them explicitly.\n\nNote: It is an accompanying feature to `infer_outlives_requirements`,\nwhich must be enabled to infer outlives requirements.\n\nFor example, currently generic struct definitions that contain\nreferences, require where-clauses of the form T: 'static. By using\nthis feature the outlives predicates will be inferred, although\nthey may still be written explicitly.\n\n```rust,ignore (pseudo-Rust)\nstruct Foo<U> where U: 'static { // <-- currently required\n bar: Bar<U>\n}\nstruct Bar<T: 'static> {\n x: T,\n}\n```\n\n\n## Examples:\n\n```rust,ignore (pseudo-Rust)\n#![feature(infer_outlives_requirements)]\n#![feature(infer_static_outlives_requirements)]\n\n#[rustc_outlives]\n// Implicitly infer U: 'static\nstruct Foo<U> {\n bar: Bar<U>\n}\nstruct Bar<T: 'static> {\n x: T,\n}\n```\n\n" } , LintCompletion { label : "const_fn" , description : "# `const_fn`\n\nThe tracking issue for this feature is: [#57563]\n\n[#57563]: https://github.com/rust-lang/rust/issues/57563\n\n------------------------\n\nThe `const_fn` feature allows marking free functions and inherent methods as\n`const`, enabling them to be called in constants contexts, with constant\narguments.\n\n## Examples\n\n```rust\n#![feature(const_fn)]\n\nconst fn double(x: i32) -> i32 {\n x * 2\n}\n\nconst FIVE: i32 = 5;\nconst TEN: i32 = double(FIVE);\n\nfn main() {\n assert_eq!(5, FIVE);\n assert_eq!(10, TEN);\n}\n```\n" } , LintCompletion { label : "custom_test_frameworks" , description : "# `custom_test_frameworks`\n\nThe tracking issue for this feature is: [#50297]\n\n[#50297]: https://github.com/rust-lang/rust/issues/50297\n\n------------------------\n\nThe `custom_test_frameworks` feature allows the use of `#[test_case]` and `#![test_runner]`.\nAny function, const, or static can be annotated with `#[test_case]` causing it to be aggregated (like `#[test]`)\nand be passed to the test runner determined by the `#![test_runner]` crate attribute.\n\n```rust\n#![feature(custom_test_frameworks)]\n#![test_runner(my_runner)]\n\nfn my_runner(tests: &[&i32]) {\n for t in tests {\n if **t == 0 {\n println!(\"PASSED\");\n } else {\n println!(\"FAILED\");\n }\n }\n}\n\n#[test_case]\nconst WILL_PASS: i32 = 0;\n\n#[test_case]\nconst WILL_FAIL: i32 = 4;\n```\n\n" } , LintCompletion { label : "or_patterns" , description : "# `or_patterns`\n\nThe tracking issue for this feature is: [#54883]\n\n[#54883]: https://github.com/rust-lang/rust/issues/54883\n\n------------------------\n\nThe `or_pattern` language feature allows `|` to be arbitrarily nested within\na pattern, for example, `Some(A(0) | B(1 | 2))` becomes a valid pattern.\n\n## Examples\n\n```rust,ignore\n#![feature(or_patterns)]\n\npub enum Foo {\n Bar,\n Baz,\n Quux,\n}\n\npub fn example(maybe_foo: Option<Foo>) {\n match maybe_foo {\n Some(Foo::Bar | Foo::Baz) => {\n println!(\"The value contained `Bar` or `Baz`\");\n }\n Some(_) => {\n println!(\"The value did not contain `Bar` or `Baz`\");\n }\n None => {\n println!(\"The value was `None`\");\n }\n }\n}\n```\n" } , LintCompletion { label : "marker_trait_attr" , description : "# `marker_trait_attr`\n\nThe tracking issue for this feature is: [#29864]\n\n[#29864]: https://github.com/rust-lang/rust/issues/29864\n\n------------------------\n\nNormally, Rust keeps you from adding trait implementations that could\noverlap with each other, as it would be ambiguous which to use. This\nfeature, however, carves out an exception to that rule: a trait can\nopt-in to having overlapping implementations, at the cost that those\nimplementations are not allowed to override anything (and thus the\ntrait itself cannot have any associated items, as they're pointless\nwhen they'd need to do the same thing for every type anyway).\n\n```rust\n#![feature(marker_trait_attr)]\n\n#[marker] trait CheapToClone: Clone {}\n\nimpl<T: Copy> CheapToClone for T {}\n\n// These could potentially overlap with the blanket implementation above,\n// so are only allowed because CheapToClone is a marker trait.\nimpl<T: CheapToClone, U: CheapToClone> CheapToClone for (T, U) {}\nimpl<T: CheapToClone> CheapToClone for std::ops::Range<T> {}\n\nfn cheap_clone<T: CheapToClone>(t: T) -> T {\n t.clone()\n}\n```\n\nThis is expected to replace the unstable `overlapping_marker_traits`\nfeature, which applied to all empty traits (without needing an opt-in).\n" } , LintCompletion { label : "compiler_builtins" , description : "# `compiler_builtins`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "member_constraints" , description : "# `member_constraints`\n\nThe tracking issue for this feature is: [#61997]\n\n[#61997]: https://github.com/rust-lang/rust/issues/61997\n\n------------------------\n\nThe `member_constraints` feature gate lets you use `impl Trait` syntax with\nmultiple unrelated lifetime parameters.\n\nA simple example is:\n\n```rust\n#![feature(member_constraints)]\n\ntrait Trait<'a, 'b> { }\nimpl<T> Trait<'_, '_> for T {}\n\nfn foo<'a, 'b>(x: &'a u32, y: &'b u32) -> impl Trait<'a, 'b> {\n (x, y)\n}\n\nfn main() { }\n```\n\nWithout the `member_constraints` feature gate, the above example is an\nerror because both `'a` and `'b` appear in the impl Trait bounds, but\nneither outlives the other.\n" } , LintCompletion { label : "link_cfg" , description : "# `link_cfg`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "plugin_registrar" , description : "# `plugin_registrar`\n\nThe tracking issue for this feature is: [#29597]\n\n[#29597]: https://github.com/rust-lang/rust/issues/29597\n\nThis feature is part of \"compiler plugins.\" It will often be used with the\n[`plugin`] and `rustc_private` features as well. For more details, see\ntheir docs.\n\n[`plugin`]: plugin.md\n\n------------------------\n" } , LintCompletion { label : "abi_thiscall" , description : "# `abi_thiscall`\n\nThe tracking issue for this feature is: [#42202]\n\n[#42202]: https://github.com/rust-lang/rust/issues/42202\n\n------------------------\n\nThe MSVC ABI on x86 Windows uses the `thiscall` calling convention for C++\ninstance methods by default; it is identical to the usual (C) calling\nconvention on x86 Windows except that the first parameter of the method,\nthe `this` pointer, is passed in the ECX register.\n" } , LintCompletion { label : "c_variadic" , description : "# `c_variadic`\n\nThe tracking issue for this feature is: [#44930]\n\n[#44930]: https://github.com/rust-lang/rust/issues/44930\n\n------------------------\n\nThe `c_variadic` language feature enables C-variadic functions to be\ndefined in Rust. The may be called both from within Rust and via FFI.\n\n## Examples\n\n```rust\n#![feature(c_variadic)]\n\npub unsafe extern \"C\" fn add(n: usize, mut args: ...) -> usize {\n let mut sum = 0;\n for _ in 0..n {\n sum += args.arg::<usize>();\n }\n sum\n}\n```\n" } , LintCompletion { label : "ffi_pure" , description : "# `ffi_pure`\n\nThe tracking issue for this feature is: [#58329]\n\n------\n\nThe `#[ffi_pure]` attribute applies clang's `pure` attribute to foreign\nfunctions declarations.\n\nThat is, `#[ffi_pure]` functions shall have no effects except for its return\nvalue, which shall not change across two consecutive function calls with\nthe same parameters.\n\nApplying the `#[ffi_pure]` attribute to a function that violates these\nrequirements is undefined behavior.\n\nThis attribute enables Rust to perform common optimizations, like sub-expression\nelimination and loop optimizations. Some common examples of pure functions are\n`strlen` or `memcmp`.\n\nThese optimizations are only applicable when the compiler can prove that no\nprogram state observable by the `#[ffi_pure]` function has changed between calls\nof the function, which could alter the result. See also the `#[ffi_const]`\nattribute, which provides stronger guarantees regarding the allowable behavior\nof a function, enabling further optimization.\n\n## Pitfalls\n\nA `#[ffi_pure]` function can read global memory through the function\nparameters (e.g. pointers), globals, etc. `#[ffi_pure]` functions are not\nreferentially-transparent, and are therefore more relaxed than `#[ffi_const]`\nfunctions.\n\nHowever, accesing global memory through volatile or atomic reads can violate the\nrequirement that two consecutive function calls shall return the same value.\n\nA `pure` function that returns unit has no effect on the abstract machine's\nstate.\n\nA `#[ffi_pure]` function must not diverge, neither via a side effect (e.g. a\ncall to `abort`) nor by infinite loops.\n\nWhen translating C headers to Rust FFI, it is worth verifying for which targets\nthe `pure` attribute is enabled in those headers, and using the appropriate\n`cfg` macros in the Rust side to match those definitions. While the semantics of\n`pure` are implemented identically by many C and C++ compilers, e.g., clang,\n[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily\nimplemented in this way on all of them. It is therefore also worth verifying\nthat the semantics of the C toolchain used to compile the binary being linked\nagainst are compatible with those of the `#[ffi_pure]`.\n\n\n[#58329]: https://github.com/rust-lang/rust/issues/58329\n[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacigdac.html\n[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-pure-function-attribute\n[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_pure.htm\n" } , LintCompletion { label : "cfg_version" , description : "# `cfg_version`\n\nThe tracking issue for this feature is: [#64796]\n\n[#64796]: https://github.com/rust-lang/rust/issues/64796\n\n------------------------\n\nThe `cfg_version` feature makes it possible to execute different code\ndepending on the compiler version.\n\n## Examples\n\n```rust\n#![feature(cfg_version)]\n\n#[cfg(version(\"1.42\"))]\nfn a() {\n // ...\n}\n\n#[cfg(not(version(\"1.42\")))]\nfn a() {\n // ...\n}\n\nfn b() {\n if cfg!(version(\"1.42\")) {\n // ...\n } else {\n // ...\n }\n}\n```\n" } , LintCompletion { label : "doc_spotlight" , description : "# `doc_spotlight`\n\nThe tracking issue for this feature is: [#45040]\n\nThe `doc_spotlight` feature allows the use of the `spotlight` parameter to the `#[doc]` attribute,\nto \"spotlight\" a specific trait on the return values of functions. Adding a `#[doc(spotlight)]`\nattribute to a trait definition will make rustdoc print extra information for functions which return\na type that implements that trait. This attribute is applied to the `Iterator`, `io::Read`, and\n`io::Write` traits in the standard library.\n\nYou can do this on your own traits, like this:\n\n```\n#![feature(doc_spotlight)]\n\n#[doc(spotlight)]\npub trait MyTrait {}\n\npub struct MyStruct;\nimpl MyTrait for MyStruct {}\n\n/// The docs for this function will have an extra line about `MyStruct` implementing `MyTrait`,\n/// without having to write that yourself!\npub fn my_fn() -> MyStruct { MyStruct }\n```\n\nThis feature was originally implemented in PR [#45039].\n\n[#45040]: https://github.com/rust-lang/rust/issues/45040\n[#45039]: https://github.com/rust-lang/rust/pull/45039\n" } , LintCompletion { label : "arbitrary_enum_discriminant" , description : "# `arbitrary_enum_discriminant`\n\nThe tracking issue for this feature is: [#60553]\n\n[#60553]: https://github.com/rust-lang/rust/issues/60553\n\n------------------------\n\nThe `arbitrary_enum_discriminant` feature permits tuple-like and\nstruct-like enum variants with `#[repr(<int-type>)]` to have explicit discriminants.\n\n## Examples\n\n```rust\n#![feature(arbitrary_enum_discriminant)]\n\n#[allow(dead_code)]\n#[repr(u8)]\nenum Enum {\n Unit = 3,\n Tuple(u16) = 2,\n Struct {\n a: u8,\n b: u16,\n } = 1,\n}\n\nimpl Enum {\n fn tag(&self) -> u8 {\n unsafe { *(self as *const Self as *const u8) }\n }\n}\n\nassert_eq!(3, Enum::Unit.tag());\nassert_eq!(2, Enum::Tuple(5).tag());\nassert_eq!(1, Enum::Struct{a: 7, b: 11}.tag());\n```\n" } , LintCompletion { label : "cmse_nonsecure_entry" , description : "# `cmse_nonsecure_entry`\n\nThe tracking issue for this feature is: [#75835]\n\n[#75835]: https://github.com/rust-lang/rust/issues/75835\n\n------------------------\n\nThe [TrustZone-M\nfeature](https://developer.arm.com/documentation/100690/latest/) is available\nfor targets with the Armv8-M architecture profile (`thumbv8m` in their target\nname).\nLLVM, the Rust compiler and the linker are providing\n[support](https://developer.arm.com/documentation/ecm0359818/latest/) for the\nTrustZone-M feature.\n\nOne of the things provided, with this unstable feature, is the\n`cmse_nonsecure_entry` attribute. This attribute marks a Secure function as an\nentry function (see [section\n5.4](https://developer.arm.com/documentation/ecm0359818/latest/) for details).\nWith this attribute, the compiler will do the following:\n* add a special symbol on the function which is the `__acle_se_` prefix and the\n standard function name\n* constrain the number of parameters to avoid using the Non-Secure stack\n* before returning from the function, clear registers that might contain Secure\n information\n* use the `BXNS` instruction to return\n\nBecause the stack can not be used to pass parameters, there will be compilation\nerrors if:\n* the total size of all parameters is too big (for example more than four 32\n bits integers)\n* the entry function is not using a C ABI\n\nThe special symbol `__acle_se_` will be used by the linker to generate a secure\ngateway veneer.\n\n<!-- NOTE(ignore) this example is specific to thumbv8m targets -->\n\n``` rust,ignore\n#![feature(cmse_nonsecure_entry)]\n\n#[no_mangle]\n#[cmse_nonsecure_entry]\npub extern \"C\" fn entry_function(input: u32) -> u32 {\n input + 6\n}\n```\n\n``` text\n$ rustc --emit obj --crate-type lib --target thumbv8m.main-none-eabi function.rs\n$ arm-none-eabi-objdump -D function.o\n\n00000000 <entry_function>:\n 0: b580 push {r7, lr}\n 2: 466f mov r7, sp\n 4: b082 sub sp, #8\n 6: 9001 str r0, [sp, #4]\n 8: 1d81 adds r1, r0, #6\n a: 460a mov r2, r1\n c: 4281 cmp r1, r0\n e: 9200 str r2, [sp, #0]\n 10: d30b bcc.n 2a <entry_function+0x2a>\n 12: e7ff b.n 14 <entry_function+0x14>\n 14: 9800 ldr r0, [sp, #0]\n 16: b002 add sp, #8\n 18: e8bd 4080 ldmia.w sp!, {r7, lr}\n 1c: 4671 mov r1, lr\n 1e: 4672 mov r2, lr\n 20: 4673 mov r3, lr\n 22: 46f4 mov ip, lr\n 24: f38e 8800 msr CPSR_f, lr\n 28: 4774 bxns lr\n 2a: f240 0000 movw r0, #0\n 2e: f2c0 0000 movt r0, #0\n 32: f240 0200 movw r2, #0\n 36: f2c0 0200 movt r2, #0\n 3a: 211c movs r1, #28\n 3c: f7ff fffe bl 0 <_ZN4core9panicking5panic17h5c028258ca2fb3f5E>\n 40: defe udf #254 ; 0xfe\n```\n" } , LintCompletion { label : "const_eval_limit" , description : "# `const_eval_limit`\n\nThe tracking issue for this feature is: [#67217]\n\n[#67217]: https://github.com/rust-lang/rust/issues/67217\n\nThe `const_eval_limit` allows someone to limit the evaluation steps the CTFE undertakes to evaluate a `const fn`.\n" } , LintCompletion { label : "external_doc" , description : "# `external_doc`\n\nThe tracking issue for this feature is: [#44732]\n\nThe `external_doc` feature allows the use of the `include` parameter to the `#[doc]` attribute, to\ninclude external files in documentation. Use the attribute in place of, or in addition to, regular\ndoc comments and `#[doc]` attributes, and `rustdoc` will load the given file when it renders\ndocumentation for your crate.\n\nWith the following files in the same directory:\n\n`external-doc.md`:\n\n```markdown\n# My Awesome Type\n\nThis is the documentation for this spectacular type.\n```\n\n`lib.rs`:\n\n```no_run (needs-external-files)\n#![feature(external_doc)]\n\n#[doc(include = \"external-doc.md\")]\npub struct MyAwesomeType;\n```\n\n`rustdoc` will load the file `external-doc.md` and use it as the documentation for the `MyAwesomeType`\nstruct.\n\nWhen locating files, `rustdoc` will base paths in the `src/` directory, as if they were alongside the\n`lib.rs` for your crate. So if you want a `docs/` folder to live alongside the `src/` directory,\nstart your paths with `../docs/` for `rustdoc` to properly find the file.\n\nThis feature was proposed in [RFC #1990] and initially implemented in PR [#44781].\n\n[#44732]: https://github.com/rust-lang/rust/issues/44732\n[RFC #1990]: https://github.com/rust-lang/rfcs/pull/1990\n[#44781]: https://github.com/rust-lang/rust/pull/44781\n" } , LintCompletion { label : "rustc_attrs" , description : "# `rustc_attrs`\n\nThis feature has no tracking issue, and is therefore internal to\nthe compiler, not being intended for general use.\n\nNote: `rustc_attrs` enables many rustc-internal attributes and this page\nonly discuss a few of them.\n\n------------------------\n\nThe `rustc_attrs` feature allows debugging rustc type layouts by using\n`#[rustc_layout(...)]` to debug layout at compile time (it even works\nwith `cargo check`) as an alternative to `rustc -Z print-type-sizes`\nthat is way more verbose.\n\nOptions provided by `#[rustc_layout(...)]` are `debug`, `size`, `align`,\n`abi`. Note that it only works on sized types without generics.\n\n## Examples\n\n```rust,ignore\n#![feature(rustc_attrs)]\n\n#[rustc_layout(abi, size)]\npub enum X {\n Y(u8, u8, u8),\n Z(isize),\n}\n```\n\nWhen that is compiled, the compiler will error with something like\n\n```text\nerror: abi: Aggregate { sized: true }\n --> src/lib.rs:4:1\n |\n4 | / pub enum T {\n5 | | Y(u8, u8, u8),\n6 | | Z(isize),\n7 | | }\n | |_^\n\nerror: size: Size { raw: 16 }\n --> src/lib.rs:4:1\n |\n4 | / pub enum T {\n5 | | Y(u8, u8, u8),\n6 | | Z(isize),\n7 | | }\n | |_^\n\nerror: aborting due to 2 previous errors\n```\n" } , LintCompletion { label : "allocator_internals" , description : "# `allocator_internals`\n\nThis feature does not have a tracking issue, it is an unstable implementation\ndetail of the `global_allocator` feature not intended for use outside the\ncompiler.\n\n------------------------\n" } , LintCompletion { label : "non_ascii_idents" , description : "# `non_ascii_idents`\n\nThe tracking issue for this feature is: [#55467]\n\n[#55467]: https://github.com/rust-lang/rust/issues/55467\n\n------------------------\n\nThe `non_ascii_idents` feature adds support for non-ASCII identifiers.\n\n## Examples\n\n```rust\n#![feature(non_ascii_idents)]\n\nconst ε: f64 = 0.00001f64;\nconst Π: f64 = 3.14f64;\n```\n\n## Changes to the language reference\n\n> **<sup>Lexer:<sup>** \n> IDENTIFIER : \n> &nbsp;&nbsp; &nbsp;&nbsp; XID_start XID_continue<sup>\\*</sup> \n> &nbsp;&nbsp; | `_` XID_continue<sup>+</sup> \n\nAn identifier is any nonempty Unicode string of the following form:\n\nEither\n\n * The first character has property [`XID_start`]\n * The remaining characters have property [`XID_continue`]\n\nOr\n\n * The first character is `_`\n * The identifier is more than one character, `_` alone is not an identifier\n * The remaining characters have property [`XID_continue`]\n\nthat does _not_ occur in the set of [strict keywords].\n\n> **Note**: [`XID_start`] and [`XID_continue`] as character properties cover the\n> character ranges used to form the more familiar C and Java language-family\n> identifiers.\n\n[`XID_start`]: http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&abb=on&g=&i=\n[`XID_continue`]: http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&abb=on&g=&i=\n[strict keywords]: ../../reference/keywords.md#strict-keywords\n" } , LintCompletion { label : "try_blocks" , description : "# `try_blocks`\n\nThe tracking issue for this feature is: [#31436]\n\n[#31436]: https://github.com/rust-lang/rust/issues/31436\n\n------------------------\n\nThe `try_blocks` feature adds support for `try` blocks. A `try`\nblock creates a new scope one can use the `?` operator in.\n\n```rust,edition2018\n#![feature(try_blocks)]\n\nuse std::num::ParseIntError;\n\nlet result: Result<i32, ParseIntError> = try {\n \"1\".parse::<i32>()?\n + \"2\".parse::<i32>()?\n + \"3\".parse::<i32>()?\n};\nassert_eq!(result, Ok(6));\n\nlet result: Result<i32, ParseIntError> = try {\n \"1\".parse::<i32>()?\n + \"foo\".parse::<i32>()?\n + \"3\".parse::<i32>()?\n};\nassert!(result.is_err());\n```\n" } , LintCompletion { label : "box_patterns" , description : "# `box_patterns`\n\nThe tracking issue for this feature is: [#29641]\n\n[#29641]: https://github.com/rust-lang/rust/issues/29641\n\nSee also [`box_syntax`](box-syntax.md)\n\n------------------------\n\nBox patterns let you match on `Box<T>`s:\n\n\n```rust\n#![feature(box_patterns)]\n\nfn main() {\n let b = Some(Box::new(5));\n match b {\n Some(box n) if n < 0 => {\n println!(\"Box contains negative number {}\", n);\n },\n Some(box n) if n >= 0 => {\n println!(\"Box contains non-negative number {}\", n);\n },\n None => {\n println!(\"No box\");\n },\n _ => unreachable!()\n }\n}\n```\n" } , LintCompletion { label : "profiler_runtime" , description : "# `profiler_runtime`\n\nThe tracking issue for this feature is: [#42524](https://github.com/rust-lang/rust/issues/42524).\n\n------------------------\n" } , LintCompletion { label : "negative_impls" , description : "# `negative_impls`\n\nThe tracking issue for this feature is [#68318].\n\n[#68318]: https://github.com/rust-lang/rust/issues/68318\n\n----\n\nWith the feature gate `negative_impls`, you can write negative impls as well as positive ones:\n\n```rust\n#![feature(negative_impls)]\ntrait DerefMut { }\nimpl<T: ?Sized> !DerefMut for &T { }\n```\n\nNegative impls indicate a semver guarantee that the given trait will not be implemented for the given types. Negative impls play an additional purpose for auto traits, described below.\n\nNegative impls have the following characteristics:\n\n* They do not have any items.\n* They must obey the orphan rules as if they were a positive impl.\n* They cannot \"overlap\" with any positive impls.\n\n## Semver interaction\n\nIt is a breaking change to remove a negative impl. Negative impls are a commitment not to implement the given trait for the named types.\n\n## Orphan and overlap rules\n\nNegative impls must obey the same orphan rules as a positive impl. This implies you cannot add a negative impl for types defined in upstream crates and so forth.\n\nSimilarly, negative impls cannot overlap with positive impls, again using the same \"overlap\" check that we ordinarily use to determine if two impls overlap. (Note that positive impls typically cannot overlap with one another either, except as permitted by specialization.)\n\n## Interaction with auto traits\n\nDeclaring a negative impl `impl !SomeAutoTrait for SomeType` for an\nauto-trait serves two purposes:\n\n* as with any trait, it declares that `SomeType` will never implement `SomeAutoTrait`;\n* it disables the automatic `SomeType: SomeAutoTrait` impl that would otherwise have been generated.\n\nNote that, at present, there is no way to indicate that a given type\ndoes not implement an auto trait *but that it may do so in the\nfuture*. For ordinary types, this is done by simply not declaring any\nimpl at all, but that is not an option for auto traits. A workaround\nis that one could embed a marker type as one of the fields, where the\nmarker type is `!AutoTrait`.\n\n## Immediate uses\n\nNegative impls are used to declare that `&T: !DerefMut` and `&mut T: !Clone`, as required to fix the soundness of `Pin` described in [#66544](https://github.com/rust-lang/rust/issues/66544).\n\nThis serves two purposes:\n\n* For proving the correctness of unsafe code, we can use that impl as evidence that no `DerefMut` or `Clone` impl exists.\n* It prevents downstream crates from creating such impls.\n" } , LintCompletion { label : "box_syntax" , description : "# `box_syntax`\n\nThe tracking issue for this feature is: [#49733]\n\n[#49733]: https://github.com/rust-lang/rust/issues/49733\n\nSee also [`box_patterns`](box-patterns.md)\n\n------------------------\n\nCurrently the only stable way to create a `Box` is via the `Box::new` method.\nAlso it is not possible in stable Rust to destructure a `Box` in a match\npattern. The unstable `box` keyword can be used to create a `Box`. An example\nusage would be:\n\n```rust\n#![feature(box_syntax)]\n\nfn main() {\n let b = box 5;\n}\n```\n" } , LintCompletion { label : "derive_clone_copy" , description : "# `derive_clone_copy`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "llvm_asm" , description : "# `llvm_asm`\n\nThe tracking issue for this feature is: [#70173]\n\n[#70173]: https://github.com/rust-lang/rust/issues/70173\n\n------------------------\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `llvm_asm!` macro.\n\n```rust,ignore\nllvm_asm!(assembly template\n : output operands\n : input operands\n : clobbers\n : options\n );\n```\n\nAny use of `llvm_asm` is feature gated (requires `#![feature(llvm_asm)]` on the\ncrate to allow) and of course requires an `unsafe` block.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but\n> all platforms are supported.\n\n## Assembly template\n\nThe `assembly template` is the only required parameter and must be a\nliteral string (i.e. `\"\"`)\n\n```rust\n#![feature(llvm_asm)]\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn foo() {\n unsafe {\n llvm_asm!(\"NOP\");\n }\n}\n\n// Other platforms:\n#[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\nfn foo() { /* ... */ }\n\nfn main() {\n // ...\n foo();\n // ...\n}\n```\n\n(The `feature(llvm_asm)` and `#[cfg]`s are omitted from now on.)\n\nOutput operands, input operands, clobbers and options are all optional\nbut you must add the right number of `:` if you skip them:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nllvm_asm!(\"xor %eax, %eax\"\n :\n :\n : \"eax\"\n );\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nWhitespace also doesn't matter:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nllvm_asm!(\"xor %eax, %eax\" ::: \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## Operands\n\nInput and output operands follow the same format: `:\n\"constraints1\"(expr1), \"constraints2\"(expr2), ...\"`. Output operand\nexpressions must be mutable place, or not yet assigned:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn add(a: i32, b: i32) -> i32 {\n let c: i32;\n unsafe {\n llvm_asm!(\"add $2, $0\"\n : \"=r\"(c)\n : \"0\"(a), \"r\"(b)\n );\n }\n c\n}\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn add(a: i32, b: i32) -> i32 { a + b }\n\nfn main() {\n assert_eq!(add(3, 14159), 14162)\n}\n```\n\nIf you would like to use real operands in this position, however,\nyou are required to put curly braces `{}` around the register that\nyou want, and you are required to put the specific size of the\noperand. This is useful for very low level programming, where\nwhich register you use is important:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# unsafe fn read_byte_in(port: u16) -> u8 {\nlet result: u8;\nllvm_asm!(\"in %dx, %al\" : \"={al}\"(result) : \"{dx}\"(port));\nresult\n# }\n```\n\n## Clobbers\n\nSome instructions modify registers which might otherwise have held\ndifferent values so we use the clobbers list to indicate to the\ncompiler not to assume any values loaded into those registers will\nstay valid.\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\n// Put the value 0x200 in eax:\nllvm_asm!(\"mov $$0x200, %eax\" : /* no outputs */ : /* no inputs */ : \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nInput and output registers need not be listed since that information\nis already communicated by the given constraints. Otherwise, any other\nregisters used either implicitly or explicitly should be listed.\n\nIf the assembly changes the condition code register `cc` should be\nspecified as one of the clobbers. Similarly, if the assembly modifies\nmemory, `memory` should also be specified.\n\n## Options\n\nThe last section, `options` is specific to Rust. The format is comma\nseparated literal strings (i.e. `:\"foo\", \"bar\", \"baz\"`). It's used to\nspecify some extra info about the inline assembly:\n\nCurrent valid options are:\n\n1. `volatile` - specifying this is analogous to\n `__asm__ __volatile__ (...)` in gcc/clang.\n2. `alignstack` - certain instructions expect the stack to be\n aligned a certain way (i.e. SSE) and specifying this indicates to\n the compiler to insert its usual stack alignment code\n3. `intel` - use intel syntax instead of the default AT&T.\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() {\nlet result: i32;\nunsafe {\n llvm_asm!(\"mov eax, 2\" : \"={eax}\"(result) : : : \"intel\")\n}\nprintln!(\"eax is currently {}\", result);\n# }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## More Information\n\nThe current implementation of the `llvm_asm!` macro is a direct binding to [LLVM's\ninline assembler expressions][llvm-docs], so be sure to check out [their\ndocumentation as well][llvm-docs] for more information about clobbers,\nconstraints, etc.\n\n[llvm-docs]: http://llvm.org/docs/LangRef.html#inline-assembler-expressions\n\nIf you need more power and don't mind losing some of the niceties of\n`llvm_asm!`, check out [global_asm](global-asm.md).\n" } , LintCompletion { label : "windows_c" , description : "# `windows_c`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fmt_internals" , description : "# `fmt_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "trace_macros" , description : "# `trace_macros`\n\nThe tracking issue for this feature is [#29598].\n\n[#29598]: https://github.com/rust-lang/rust/issues/29598\n\n------------------------\n\nWith `trace_macros` you can trace the expansion of macros in your code.\n\n## Examples\n\n```rust\n#![feature(trace_macros)]\n\nfn main() {\n trace_macros!(true);\n println!(\"Hello, Rust!\");\n trace_macros!(false);\n}\n```\n\nThe `cargo build` output:\n\n```txt\nnote: trace_macro\n --> src/main.rs:5:5\n |\n5 | println!(\"Hello, Rust!\");\n | ^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: expanding `println! { \"Hello, Rust!\" }`\n = note: to `print ! ( concat ! ( \"Hello, Rust!\" , \"\\n\" ) )`\n = note: expanding `print! { concat ! ( \"Hello, Rust!\" , \"\\n\" ) }`\n = note: to `$crate :: io :: _print ( format_args ! ( concat ! ( \"Hello, Rust!\" , \"\\n\" ) )\n )`\n\n Finished dev [unoptimized + debuginfo] target(s) in 0.60 secs\n```\n" } , LintCompletion { label : "str_internals" , description : "# `str_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "c_void_variant" , description : "# `c_void_variant`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "update_panic_count" , description : "# `update_panic_count`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_net" , description : "# `windows_net`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_sys_internals" , description : "# `libstd_sys_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "rt" , description : "# `rt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "asm" , description : "# `asm`\n\nThe tracking issue for this feature is: [#72016]\n\n[#72016]: https://github.com/rust-lang/rust/issues/72016\n\n------------------------\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `asm!` macro.\n\n# Guide-level explanation\n[guide-level-explanation]: #guide-level-explanation\n\nRust provides support for inline assembly via the `asm!` macro.\nIt can be used to embed handwritten assembly in the assembly output generated by the compiler.\nGenerally this should not be necessary, but might be where the required performance or timing\ncannot be otherwise achieved. Accessing low level hardware primitives, e.g. in kernel code, may also demand this functionality.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but other architectures are also supported.\n\nInline assembly is currently supported on the following architectures:\n- x86 and x86-64\n- ARM\n- AArch64\n- RISC-V\n- NVPTX\n- Hexagon\n- MIPS32r2 and MIPS64r2\n\n## Basic usage\n\nLet us start with the simplest possible example:\n\n```rust,allow_fail\n# #![feature(asm)]\nunsafe {\n asm!(\"nop\");\n}\n```\n\nThis will insert a NOP (no operation) instruction into the assembly generated by the compiler.\nNote that all `asm!` invocations have to be inside an `unsafe` block, as they could insert\narbitrary instructions and break various invariants. The instructions to be inserted are listed\nin the first argument of the `asm!` macro as a string literal.\n\n## Inputs and outputs\n\nNow inserting an instruction that does nothing is rather boring. Let us do something that\nactually acts on data:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet x: u64;\nunsafe {\n asm!(\"mov {}, 5\", out(reg) x);\n}\nassert_eq!(x, 5);\n```\n\nThis will write the value `5` into the `u64` variable `x`.\nYou can see that the string literal we use to specify instructions is actually a template string.\nIt is governed by the same rules as Rust [format strings][format-syntax].\nThe arguments that are inserted into the template however look a bit different then you may\nbe familiar with. First we need to specify if the variable is an input or an output of the\ninline assembly. In this case it is an output. We declared this by writing `out`.\nWe also need to specify in what kind of register the assembly expects the variable.\nIn this case we put it in an arbitrary general purpose register by specifying `reg`.\nThe compiler will choose an appropriate register to insert into\nthe template and will read the variable from there after the inline assembly finishes executing.\n\nLet us see another example that also uses an input:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet i: u64 = 3;\nlet o: u64;\nunsafe {\n asm!(\n \"mov {0}, {1}\",\n \"add {0}, {number}\",\n out(reg) o,\n in(reg) i,\n number = const 5,\n );\n}\nassert_eq!(o, 8);\n```\n\nThis will add `5` to the input in variable `i` and write the result to variable `o`.\nThe particular way this assembly does this is first copying the value from `i` to the output,\nand then adding `5` to it.\n\nThe example shows a few things:\n\nFirst, we can see that `asm!` allows multiple template string arguments; each\none is treated as a separate line of assembly code, as if they were all joined\ntogether with newlines between them. This makes it easy to format assembly\ncode.\n\nSecond, we can see that inputs are declared by writing `in` instead of `out`.\n\nThird, one of our operands has a type we haven't seen yet, `const`.\nThis tells the compiler to expand this argument to value directly inside the assembly template.\nThis is only possible for constants and literals.\n\nFourth, we can see that we can specify an argument number, or name as in any format string.\nFor inline assembly templates this is particularly useful as arguments are often used more than once.\nFor more complex inline assembly using this facility is generally recommended, as it improves\nreadability, and allows reordering instructions without changing the argument order.\n\nWe can further refine the above example to avoid the `mov` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut x: u64 = 3;\nunsafe {\n asm!(\"add {0}, {number}\", inout(reg) x, number = const 5);\n}\nassert_eq!(x, 8);\n```\n\nWe can see that `inout` is used to specify an argument that is both input and output.\nThis is different from specifying an input and output separately in that it is guaranteed to assign both to the same register.\n\nIt is also possible to specify different variables for the input and output parts of an `inout` operand:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet x: u64 = 3;\nlet y: u64;\nunsafe {\n asm!(\"add {0}, {number}\", inout(reg) x => y, number = const 5);\n}\nassert_eq!(y, 8);\n```\n\n## Late output operands\n\nThe Rust compiler is conservative with its allocation of operands. It is assumed that an `out`\ncan be written at any time, and can therefore not share its location with any other argument.\nHowever, to guarantee optimal performance it is important to use as few registers as possible,\nso they won't have to be saved and reloaded around the inline assembly block.\nTo achieve this Rust provides a `lateout` specifier. This can be used on any output that is\nwritten only after all inputs have been consumed.\nThere is also a `inlateout` variant of this specifier.\n\nHere is an example where `inlateout` *cannot* be used:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nlet c: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n \"add {0}, {2}\",\n inout(reg) a,\n in(reg) b,\n in(reg) c,\n );\n}\nassert_eq!(a, 12);\n```\n\nHere the compiler is free to allocate the same register for inputs `b` and `c` since it knows they have the same value. However it must allocate a separate register for `a` since it uses `inout` and not `inlateout`. If `inlateout` was used, then `a` and `c` could be allocated to the same register, in which case the first instruction to overwrite the value of `c` and cause the assembly code to produce the wrong result.\n\nHowever the following example can use `inlateout` since the output is only modified after all input registers have been read:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\"add {0}, {1}\", inlateout(reg) a, in(reg) b);\n}\nassert_eq!(a, 8);\n```\n\nAs you can see, this assembly fragment will still work correctly if `a` and `b` are assigned to the same register.\n\n## Explicit register operands\n\nSome instructions require that the operands be in a specific register.\nTherefore, Rust inline assembly provides some more specific constraint specifiers.\nWhile `reg` is generally available on any architecture, these are highly architecture specific. E.g. for x86 the general purpose registers `eax`, `ebx`, `ecx`, `edx`, `ebp`, `esi`, and `edi`\namong others can be addressed by their name.\n\n```rust,allow_fail,no_run\n# #![feature(asm)]\nlet cmd = 0xd1;\nunsafe {\n asm!(\"out 0x64, eax\", in(\"eax\") cmd);\n}\n```\n\nIn this example we call the `out` instruction to output the content of the `cmd` variable\nto port `0x64`. Since the `out` instruction only accepts `eax` (and its sub registers) as operand\nwe had to use the `eax` constraint specifier.\n\nNote that unlike other operand types, explicit register operands cannot be used in the template string: you can't use `{}` and should write the register name directly instead. Also, they must appear at the end of the operand list after all other operand types.\n\nConsider this example which uses the x86 `mul` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nfn mul(a: u64, b: u64) -> u128 {\n let lo: u64;\n let hi: u64;\n\n unsafe {\n asm!(\n // The x86 mul instruction takes rax as an implicit input and writes\n // the 128-bit result of the multiplication to rax:rdx.\n \"mul {}\",\n in(reg) a,\n inlateout(\"rax\") b => lo,\n lateout(\"rdx\") hi\n );\n }\n\n ((hi as u128) << 64) + lo as u128\n}\n```\n\nThis uses the `mul` instruction to multiply two 64-bit inputs with a 128-bit result.\nThe only explicit operand is a register, that we fill from the variable `a`.\nThe second operand is implicit, and must be the `rax` register, which we fill from the variable `b`.\nThe lower 64 bits of the result are stored in `rax` from which we fill the variable `lo`.\nThe higher 64 bits are stored in `rdx` from which we fill the variable `hi`.\n\n## Clobbered registers\n\nIn many cases inline assembly will modify state that is not needed as an output.\nUsually this is either because we have to use a scratch register in the assembly,\nor instructions modify state that we don't need to further examine.\nThis state is generally referred to as being \"clobbered\".\nWe need to tell the compiler about this since it may need to save and restore this state\naround the inline assembly block.\n\n```rust,allow_fail\n# #![feature(asm)]\nlet ebx: u32;\nlet ecx: u32;\n\nunsafe {\n asm!(\n \"cpuid\",\n // EAX 4 selects the \"Deterministic Cache Parameters\" CPUID leaf\n inout(\"eax\") 4 => _,\n // ECX 0 selects the L0 cache information.\n inout(\"ecx\") 0 => ecx,\n lateout(\"ebx\") ebx,\n lateout(\"edx\") _,\n );\n}\n\nprintln!(\n \"L1 Cache: {}\",\n ((ebx >> 22) + 1) * (((ebx >> 12) & 0x3ff) + 1) * ((ebx & 0xfff) + 1) * (ecx + 1)\n);\n```\n\nIn the example above we use the `cpuid` instruction to get the L1 cache size.\nThis instruction writes to `eax`, `ebx`, `ecx`, and `edx`, but for the cache size we only care about the contents of `ebx` and `ecx`.\n\nHowever we still need to tell the compiler that `eax` and `edx` have been modified so that it can save any values that were in these registers before the asm. This is done by declaring these as outputs but with `_` instead of a variable name, which indicates that the output value is to be discarded.\n\nThis can also be used with a general register class (e.g. `reg`) to obtain a scratch register for use inside the asm code:\n\n```rust,allow_fail\n# #![feature(asm)]\n// Multiply x by 6 using shifts and adds\nlet mut x: u64 = 4;\nunsafe {\n asm!(\n \"mov {tmp}, {x}\",\n \"shl {tmp}, 1\",\n \"shl {x}, 2\",\n \"add {x}, {tmp}\",\n x = inout(reg) x,\n tmp = out(reg) _,\n );\n}\nassert_eq!(x, 4 * 6);\n```\n\n## Symbol operands\n\nA special operand type, `sym`, allows you to use the symbol name of a `fn` or `static` in inline assembly code.\nThis allows you to call a function or access a global variable without needing to keep its address in a register.\n\n```rust,allow_fail\n# #![feature(asm)]\nextern \"C\" fn foo(arg: i32) {\n println!(\"arg = {}\", arg);\n}\n\nfn call_foo(arg: i32) {\n unsafe {\n asm!(\n \"call {}\",\n sym foo,\n // 1st argument in rdi, which is caller-saved\n inout(\"rdi\") arg => _,\n // All caller-saved registers must be marked as clobberred\n out(\"rax\") _, out(\"rcx\") _, out(\"rdx\") _, out(\"rsi\") _,\n out(\"r8\") _, out(\"r9\") _, out(\"r10\") _, out(\"r11\") _,\n out(\"xmm0\") _, out(\"xmm1\") _, out(\"xmm2\") _, out(\"xmm3\") _,\n out(\"xmm4\") _, out(\"xmm5\") _, out(\"xmm6\") _, out(\"xmm7\") _,\n out(\"xmm8\") _, out(\"xmm9\") _, out(\"xmm10\") _, out(\"xmm11\") _,\n out(\"xmm12\") _, out(\"xmm13\") _, out(\"xmm14\") _, out(\"xmm15\") _,\n )\n }\n}\n```\n\nNote that the `fn` or `static` item does not need to be public or `#[no_mangle]`:\nthe compiler will automatically insert the appropriate mangled symbol name into the assembly code.\n\n## Register template modifiers\n\nIn some cases, fine control is needed over the way a register name is formatted when inserted into the template string. This is needed when an architecture's assembly language has several names for the same register, each typically being a \"view\" over a subset of the register (e.g. the low 32 bits of a 64-bit register).\n\nBy default the compiler will always choose the name that refers to the full register size (e.g. `rax` on x86-64, `eax` on x86, etc).\n\nThis default can be overriden by using modifiers on the template string operands, just like you would with format strings:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut x: u16 = 0xab;\n\nunsafe {\n asm!(\"mov {0:h}, {0:l}\", inout(reg_abcd) x);\n}\n\nassert_eq!(x, 0xabab);\n```\n\nIn this example, we use the `reg_abcd` register class to restrict the register allocator to the 4 legacy x86 register (`ax`, `bx`, `cx`, `dx`) of which the first two bytes can be addressed independently.\n\nLet us assume that the register allocator has chosen to allocate `x` in the `ax` register.\nThe `h` modifier will emit the register name for the high byte of that register and the `l` modifier will emit the register name for the low byte. The asm code will therefore be expanded as `mov ah, al` which copies the low byte of the value into the high byte.\n\nIf you use a smaller data type (e.g. `u16`) with an operand and forget the use template modifiers, the compiler will emit a warning and suggest the correct modifier to use.\n\n## Memory address operands\n\nSometimes assembly instructions require operands passed via memory addresses/memory locations.\nYou have to manually use the memory address syntax specified by the respectively architectures.\nFor example, in x86/x86_64 and intel assembly syntax, you should wrap inputs/outputs in `[]`\nto indicate they are memory operands:\n\n```rust,allow_fail\n# #![feature(asm, llvm_asm)]\n# fn load_fpu_control_word(control: u16) {\nunsafe {\n asm!(\"fldcw [{}]\", in(reg) &control, options(nostack));\n\n // Previously this would have been written with the deprecated `llvm_asm!` like this\n llvm_asm!(\"fldcw $0\" :: \"m\" (control) :: \"volatile\");\n}\n# }\n```\n\n## Options\n\nBy default, an inline assembly block is treated the same way as an external FFI function call with a custom calling convention: it may read/write memory, have observable side effects, etc. However in many cases, it is desirable to give the compiler more information about what the assembly code is actually doing so that it can optimize better.\n\nLet's take our previous example of an `add` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n inlateout(reg) a, in(reg) b,\n options(pure, nomem, nostack),\n );\n}\nassert_eq!(a, 8);\n```\n\nOptions can be provided as an optional final argument to the `asm!` macro. We specified three options here:\n- `pure` means that the asm code has no observable side effects and that its output depends only on its inputs. This allows the compiler optimizer to call the inline asm fewer times or even eliminate it entirely.\n- `nomem` means that the asm code does not read or write to memory. By default the compiler will assume that inline assembly can read or write any memory address that is accessible to it (e.g. through a pointer passed as an operand, or a global).\n- `nostack` means that the asm code does not push any data onto the stack. This allows the compiler to use optimizations such as the stack red zone on x86-64 to avoid stack pointer adjustments.\n\nThese allow the compiler to better optimize code using `asm!`, for example by eliminating pure `asm!` blocks whose outputs are not needed.\n\nSee the reference for the full list of available options and their effects.\n\n# Reference-level explanation\n[reference-level-explanation]: #reference-level-explanation\n\nInline assembler is implemented as an unsafe macro `asm!()`.\nThe first argument to this macro is a template string literal used to build the final assembly.\nThe following arguments specify input and output operands.\nWhen required, options are specified as the final argument.\n\nThe following ABNF specifies the general syntax:\n\n```ignore\ndir_spec := \"in\" / \"out\" / \"lateout\" / \"inout\" / \"inlateout\"\nreg_spec := <register class> / \"<explicit register>\"\noperand_expr := expr / \"_\" / expr \"=>\" expr / expr \"=>\" \"_\"\nreg_operand := dir_spec \"(\" reg_spec \")\" operand_expr\noperand := reg_operand / \"const\" const_expr / \"sym\" path\noption := \"pure\" / \"nomem\" / \"readonly\" / \"preserves_flags\" / \"noreturn\" / \"nostack\" / \"att_syntax\"\noptions := \"options(\" option *[\",\" option] [\",\"] \")\"\nasm := \"asm!(\" format_string *(\",\" format_string) *(\",\" [ident \"=\"] operand) [\",\" options] [\",\"] \")\"\n```\n\nThe macro will initially be supported only on ARM, AArch64, Hexagon, x86, x86-64 and RISC-V targets. Support for more targets may be added in the future. The compiler will emit an error if `asm!` is used on an unsupported target.\n\n[format-syntax]: https://doc.rust-lang.org/std/fmt/#syntax\n\n## Template string arguments\n\nThe assembler template uses the same syntax as [format strings][format-syntax] (i.e. placeholders are specified by curly braces). The corresponding arguments are accessed in order, by index, or by name. However, implicit named arguments (introduced by [RFC #2795][rfc-2795]) are not supported.\n\nAn `asm!` invocation may have one or more template string arguments; an `asm!` with multiple template string arguments is treated as if all the strings were concatenated with a `\\n` between them. The expected usage is for each template string argument to correspond to a line of assembly code. All template string arguments must appear before any other arguments.\n\nAs with format strings, named arguments must appear after positional arguments. Explicit register operands must appear at the end of the operand list, after named arguments if any.\n\nExplicit register operands cannot be used by placeholders in the template string. All other named and positional operands must appear at least once in the template string, otherwise a compiler error is generated.\n\nThe exact assembly code syntax is target-specific and opaque to the compiler except for the way operands are substituted into the template string to form the code passed to the assembler.\n\nThe 5 targets specified in this RFC (x86, ARM, AArch64, RISC-V, Hexagon) all use the assembly code syntax of the GNU assembler (GAS). On x86, the `.intel_syntax noprefix` mode of GAS is used by default. On ARM, the `.syntax unified` mode is used. These targets impose an additional restriction on the assembly code: any assembler state (e.g. the current section which can be changed with `.section`) must be restored to its original value at the end of the asm string. Assembly code that does not conform to the GAS syntax will result in assembler-specific behavior.\n\n[rfc-2795]: https://github.com/rust-lang/rfcs/pull/2795\n\n## Operand type\n\nSeveral types of operands are supported:\n\n* `in(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `<expr>` at the start of the asm code.\n - The allocated register must contain the same value at the end of the asm code (except if a `lateout` is allocated to the same register).\n* `out(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain an undefined value at the start of the asm code.\n - `<expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register is written to at the end of the asm code.\n - An underscore (`_`) may be specified instead of an expression, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).\n* `lateout(<reg>) <expr>`\n - Identical to `out` except that the register allocator can reuse a register allocated to an `in`.\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n* `inout(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `<expr>` at the start of the asm code.\n - `<expr>` must be a mutable initialized place expression, to which the contents of the allocated register is written to at the end of the asm code.\n* `inout(<reg>) <in expr> => <out expr>`\n - Same as `inout` except that the initial value of the register is taken from the value of `<in expr>`.\n - `<out expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register is written to at the end of the asm code.\n - An underscore (`_`) may be specified instead of an expression for `<out expr>`, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).\n - `<in expr>` and `<out expr>` may have different types.\n* `inlateout(<reg>) <expr>` / `inlateout(<reg>) <in expr> => <out expr>`\n - Identical to `inout` except that the register allocator can reuse a register allocated to an `in` (this can happen if the compiler knows the `in` has the same initial value as the `inlateout`).\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n* `const <expr>`\n - `<expr>` must be an integer or floating-point constant expression.\n - The value of the expression is formatted as a string and substituted directly into the asm template string.\n* `sym <path>`\n - `<path>` must refer to a `fn` or `static`.\n - A mangled symbol name referring to the item is substituted into the asm template string.\n - The substituted string does not include any modifiers (e.g. GOT, PLT, relocations, etc).\n - `<path>` is allowed to point to a `#[thread_local]` static, in which case the asm code can combine the symbol with relocations (e.g. `@plt`, `@TPOFF`) to read from thread-local data.\n\nOperand expressions are evaluated from left to right, just like function call arguments. After the `asm!` has executed, outputs are written to in left to right order. This is significant if two outputs point to the same place: that place will contain the value of the rightmost output.\n\n## Register operands\n\nInput and output operands can be specified either as an explicit register or as a register class from which the register allocator can select a register. Explicit registers are specified as string literals (e.g. `\"eax\"`) while register classes are specified as identifiers (e.g. `reg`). Using string literals for register names enables support for architectures that use special characters in register names, such as MIPS (`$0`, `$1`, etc).\n\nNote that explicit registers treat register aliases (e.g. `r14` vs `lr` on ARM) and smaller views of a register (e.g. `eax` vs `rax`) as equivalent to the base register. It is a compile-time error to use the same explicit register for two input operands or two output operands. Additionally, it is also a compile-time error to use overlapping registers (e.g. ARM VFP) in input operands or in output operands.\n\nOnly the following types are allowed as operands for inline assembly:\n- Integers (signed and unsigned)\n- Floating-point numbers\n- Pointers (thin only)\n- Function pointers\n- SIMD vectors (structs defined with `#[repr(simd)]` and which implement `Copy`). This includes architecture-specific vector types defined in `std::arch` such as `__m128` (x86) or `int8x16_t` (ARM).\n\nHere is the list of currently supported register classes:\n\n| Architecture | Register class | Registers | LLVM constraint code |\n| ------------ | -------------- | --------- | -------------------- |\n| x86 | `reg` | `ax`, `bx`, `cx`, `dx`, `si`, `di`, `r[8-15]` (x86-64 only) | `r` |\n| x86 | `reg_abcd` | `ax`, `bx`, `cx`, `dx` | `Q` |\n| x86-32 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `ah`, `bh`, `ch`, `dh` | `q` |\n| x86-64 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `sil`, `dil`, `r[8-15]b`, `ah`\\*, `bh`\\*, `ch`\\*, `dh`\\* | `q` |\n| x86 | `xmm_reg` | `xmm[0-7]` (x86) `xmm[0-15]` (x86-64) | `x` |\n| x86 | `ymm_reg` | `ymm[0-7]` (x86) `ymm[0-15]` (x86-64) | `x` |\n| x86 | `zmm_reg` | `zmm[0-7]` (x86) `zmm[0-31]` (x86-64) | `v` |\n| x86 | `kreg` | `k[1-7]` | `Yk` |\n| AArch64 | `reg` | `x[0-28]`, `x30` | `r` |\n| AArch64 | `vreg` | `v[0-31]` | `w` |\n| AArch64 | `vreg_low16` | `v[0-15]` | `x` |\n| ARM | `reg` | `r[0-5]` `r7`\\*, `r[8-10]`, `r11`\\*, `r12`, `r14` | `r` |\n| ARM (Thumb) | `reg_thumb` | `r[0-r7]` | `l` |\n| ARM (ARM) | `reg_thumb` | `r[0-r10]`, `r12`, `r14` | `l` |\n| ARM | `sreg` | `s[0-31]` | `t` |\n| ARM | `sreg_low16` | `s[0-15]` | `x` |\n| ARM | `dreg` | `d[0-31]` | `w` |\n| ARM | `dreg_low16` | `d[0-15]` | `t` |\n| ARM | `dreg_low8` | `d[0-8]` | `x` |\n| ARM | `qreg` | `q[0-15]` | `w` |\n| ARM | `qreg_low8` | `q[0-7]` | `t` |\n| ARM | `qreg_low4` | `q[0-3]` | `x` |\n| MIPS | `reg` | `$[2-25]` | `r` |\n| MIPS | `freg` | `$f[0-31]` | `f` |\n| NVPTX | `reg16` | None\\* | `h` |\n| NVPTX | `reg32` | None\\* | `r` |\n| NVPTX | `reg64` | None\\* | `l` |\n| RISC-V | `reg` | `x1`, `x[5-7]`, `x[9-15]`, `x[16-31]` (non-RV32E) | `r` |\n| RISC-V | `freg` | `f[0-31]` | `f` |\n| Hexagon | `reg` | `r[0-28]` | `r` |\n\n> **Note**: On x86 we treat `reg_byte` differently from `reg` because the compiler can allocate `al` and `ah` separately whereas `reg` reserves the whole register.\n>\n> Note #2: On x86-64 the high byte registers (e.g. `ah`) are only available when used as an explicit register. Specifying the `reg_byte` register class for an operand will always allocate a low byte register.\n>\n> Note #3: NVPTX doesn't have a fixed register set, so named registers are not supported.\n>\n> Note #4: On ARM the frame pointer is either `r7` or `r11` depending on the platform.\n\nAdditional register classes may be added in the future based on demand (e.g. MMX, x87, etc).\n\nEach register class has constraints on which value types they can be used with. This is necessary because the way a value is loaded into a register depends on its type. For example, on big-endian systems, loading a `i32x4` and a `i8x16` into a SIMD register may result in different register contents even if the byte-wise memory representation of both values is identical. The availability of supported types for a particular register class may depend on what target features are currently enabled.\n\n| Architecture | Register class | Target feature | Allowed types |\n| ------------ | -------------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `i16`, `i32`, `f32` |\n| x86-64 | `reg` | None | `i16`, `i32`, `f32`, `i64`, `f64` |\n| x86 | `reg_byte` | None | `i8` |\n| x86 | `xmm_reg` | `sse` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| x86 | `ymm_reg` | `avx` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` <br> `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` |\n| x86 | `zmm_reg` | `avx512f` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` <br> `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` <br> `i8x64`, `i16x32`, `i32x16`, `i64x8`, `f32x16`, `f64x8` |\n| x86 | `kreg` | `axv512f` | `i8`, `i16` |\n| x86 | `kreg` | `axv512bw` | `i32`, `i64` |\n| AArch64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| AArch64 | `vreg` | `fp` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`, <br> `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| ARM | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| ARM | `sreg` | `vfp2` | `i32`, `f32` |\n| ARM | `dreg` | `vfp2` | `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2` |\n| ARM | `qreg` | `neon` | `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4` |\n| MIPS32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| MIPS32 | `freg` | None | `f32`, `f64` |\n| MIPS64 | `reg` | None | `i8`, `i16`, `i32`, `i64`, `f32`, `f64` |\n| MIPS64 | `freg` | None | `f32`, `f64` |\n| NVPTX | `reg16` | None | `i8`, `i16` |\n| NVPTX | `reg32` | None | `i8`, `i16`, `i32`, `f32` |\n| NVPTX | `reg64` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| RISC-V64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V | `freg` | `f` | `f32` |\n| RISC-V | `freg` | `d` | `f64` |\n| Hexagon | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n\n> **Note**: For the purposes of the above table pointers, function pointers and `isize`/`usize` are treated as the equivalent integer type (`i16`/`i32`/`i64` depending on the target).\n\nIf a value is of a smaller size than the register it is allocated in then the upper bits of that register will have an undefined value for inputs and will be ignored for outputs. The only exception is the `freg` register class on RISC-V where `f32` values are NaN-boxed in a `f64` as required by the RISC-V architecture.\n\nWhen separate input and output expressions are specified for an `inout` operand, both expressions must have the same type. The only exception is if both operands are pointers or integers, in which case they are only required to have the same size. This restriction exists because the register allocators in LLVM and GCC sometimes cannot handle tied operands with different types.\n\n## Register names\n\nSome registers have multiple names. These are all treated by the compiler as identical to the base register name. Here is the list of all supported register aliases:\n\n| Architecture | Base register | Aliases |\n| ------------ | ------------- | ------- |\n| x86 | `ax` | `eax`, `rax` |\n| x86 | `bx` | `ebx`, `rbx` |\n| x86 | `cx` | `ecx`, `rcx` |\n| x86 | `dx` | `edx`, `rdx` |\n| x86 | `si` | `esi`, `rsi` |\n| x86 | `di` | `edi`, `rdi` |\n| x86 | `bp` | `bpl`, `ebp`, `rbp` |\n| x86 | `sp` | `spl`, `esp`, `rsp` |\n| x86 | `ip` | `eip`, `rip` |\n| x86 | `st(0)` | `st` |\n| x86 | `r[8-15]` | `r[8-15]b`, `r[8-15]w`, `r[8-15]d` |\n| x86 | `xmm[0-31]` | `ymm[0-31]`, `zmm[0-31]` |\n| AArch64 | `x[0-30]` | `w[0-30]` |\n| AArch64 | `x29` | `fp` |\n| AArch64 | `x30` | `lr` |\n| AArch64 | `sp` | `wsp` |\n| AArch64 | `xzr` | `wzr` |\n| AArch64 | `v[0-31]` | `b[0-31]`, `h[0-31]`, `s[0-31]`, `d[0-31]`, `q[0-31]` |\n| ARM | `r[0-3]` | `a[1-4]` |\n| ARM | `r[4-9]` | `v[1-6]` |\n| ARM | `r9` | `rfp` |\n| ARM | `r10` | `sl` |\n| ARM | `r11` | `fp` |\n| ARM | `r12` | `ip` |\n| ARM | `r13` | `sp` |\n| ARM | `r14` | `lr` |\n| ARM | `r15` | `pc` |\n| RISC-V | `x0` | `zero` |\n| RISC-V | `x1` | `ra` |\n| RISC-V | `x2` | `sp` |\n| RISC-V | `x3` | `gp` |\n| RISC-V | `x4` | `tp` |\n| RISC-V | `x[5-7]` | `t[0-2]` |\n| RISC-V | `x8` | `fp`, `s0` |\n| RISC-V | `x9` | `s1` |\n| RISC-V | `x[10-17]` | `a[0-7]` |\n| RISC-V | `x[18-27]` | `s[2-11]` |\n| RISC-V | `x[28-31]` | `t[3-6]` |\n| RISC-V | `f[0-7]` | `ft[0-7]` |\n| RISC-V | `f[8-9]` | `fs[0-1]` |\n| RISC-V | `f[10-17]` | `fa[0-7]` |\n| RISC-V | `f[18-27]` | `fs[2-11]` |\n| RISC-V | `f[28-31]` | `ft[8-11]` |\n| Hexagon | `r29` | `sp` |\n| Hexagon | `r30` | `fr` |\n| Hexagon | `r31` | `lr` |\n\nSome registers cannot be used for input or output operands:\n\n| Architecture | Unsupported register | Reason |\n| ------------ | -------------------- | ------ |\n| All | `sp` | The stack pointer must be restored to its original value at the end of an asm code block. |\n| All | `bp` (x86), `x29` (AArch64), `x8` (RISC-V), `fr` (Hexagon), `$fp` (MIPS) | The frame pointer cannot be used as an input or output. |\n| ARM | `r7` or `r11` | On ARM the frame pointer can be either `r7` or `r11` depending on the target. The frame pointer cannot be used as an input or output. |\n| ARM | `r6` | `r6` is used internally by LLVM as a base pointer and therefore cannot be used as an input or output. |\n| x86 | `k0` | This is a constant zero register which can't be modified. |\n| x86 | `ip` | This is the program counter, not a real register. |\n| x86 | `mm[0-7]` | MMX registers are not currently supported (but may be in the future). |\n| x86 | `st([0-7])` | x87 registers are not currently supported (but may be in the future). |\n| AArch64 | `xzr` | This is a constant zero register which can't be modified. |\n| ARM | `pc` | This is the program counter, not a real register. |\n| MIPS | `$0` or `$zero` | This is a constant zero register which can't be modified. |\n| MIPS | `$1` or `$at` | Reserved for assembler. |\n| MIPS | `$26`/`$k0`, `$27`/`$k1` | OS-reserved registers. |\n| MIPS | `$28`/`$gp` | Global pointer cannot be used as inputs or outputs. |\n| MIPS | `$ra` | Return address cannot be used as inputs or outputs. |\n| RISC-V | `x0` | This is a constant zero register which can't be modified. |\n| RISC-V | `gp`, `tp` | These registers are reserved and cannot be used as inputs or outputs. |\n| Hexagon | `lr` | This is the link register which cannot be used as an input or output. |\n\nIn some cases LLVM will allocate a \"reserved register\" for `reg` operands even though this register cannot be explicitly specified. Assembly code making use of reserved registers should be careful since `reg` operands may alias with those registers. Reserved registers are:\n- The frame pointer on all architectures.\n- `r6` on ARM.\n\n## Template modifiers\n\nThe placeholders can be augmented by modifiers which are specified after the `:` in the curly braces. These modifiers do not affect register allocation, but change the way operands are formatted when inserted into the template string. Only one modifier is allowed per template placeholder.\n\nThe supported modifiers are a subset of LLVM's (and GCC's) [asm template argument modifiers][llvm-argmod], but do not use the same letter codes.\n\n| Architecture | Register class | Modifier | Example output | LLVM modifier |\n| ------------ | -------------- | -------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `eax` | `k` |\n| x86-64 | `reg` | None | `rax` | `q` |\n| x86-32 | `reg_abcd` | `l` | `al` | `b` |\n| x86-64 | `reg` | `l` | `al` | `b` |\n| x86 | `reg_abcd` | `h` | `ah` | `h` |\n| x86 | `reg` | `x` | `ax` | `w` |\n| x86 | `reg` | `e` | `eax` | `k` |\n| x86-64 | `reg` | `r` | `rax` | `q` |\n| x86 | `reg_byte` | None | `al` / `ah` | None |\n| x86 | `xmm_reg` | None | `xmm0` | `x` |\n| x86 | `ymm_reg` | None | `ymm0` | `t` |\n| x86 | `zmm_reg` | None | `zmm0` | `g` |\n| x86 | `*mm_reg` | `x` | `xmm0` | `x` |\n| x86 | `*mm_reg` | `y` | `ymm0` | `t` |\n| x86 | `*mm_reg` | `z` | `zmm0` | `g` |\n| x86 | `kreg` | None | `k1` | None |\n| AArch64 | `reg` | None | `x0` | `x` |\n| AArch64 | `reg` | `w` | `w0` | `w` |\n| AArch64 | `reg` | `x` | `x0` | `x` |\n| AArch64 | `vreg` | None | `v0` | None |\n| AArch64 | `vreg` | `v` | `v0` | None |\n| AArch64 | `vreg` | `b` | `b0` | `b` |\n| AArch64 | `vreg` | `h` | `h0` | `h` |\n| AArch64 | `vreg` | `s` | `s0` | `s` |\n| AArch64 | `vreg` | `d` | `d0` | `d` |\n| AArch64 | `vreg` | `q` | `q0` | `q` |\n| ARM | `reg` | None | `r0` | None |\n| ARM | `sreg` | None | `s0` | None |\n| ARM | `dreg` | None | `d0` | `P` |\n| ARM | `qreg` | None | `q0` | `q` |\n| ARM | `qreg` | `e` / `f` | `d0` / `d1` | `e` / `f` |\n| MIPS | `reg` | None | `$2` | None |\n| MIPS | `freg` | None | `$f0` | None |\n| NVPTX | `reg16` | None | `rs0` | None |\n| NVPTX | `reg32` | None | `r0` | None |\n| NVPTX | `reg64` | None | `rd0` | None |\n| RISC-V | `reg` | None | `x1` | None |\n| RISC-V | `freg` | None | `f0` | None |\n| Hexagon | `reg` | None | `r0` | None |\n\n> Notes:\n> - on ARM `e` / `f`: this prints the low or high doubleword register name of a NEON quad (128-bit) register.\n> - on x86: our behavior for `reg` with no modifiers differs from what GCC does. GCC will infer the modifier based on the operand value type, while we default to the full register size.\n> - on x86 `xmm_reg`: the `x`, `t` and `g` LLVM modifiers are not yet implemented in LLVM (they are supported by GCC only), but this should be a simple change.\n\nAs stated in the previous section, passing an input value smaller than the register width will result in the upper bits of the register containing undefined values. This is not a problem if the inline asm only accesses the lower bits of the register, which can be done by using a template modifier to use a subregister name in the asm code (e.g. `ax` instead of `rax`). Since this an easy pitfall, the compiler will suggest a template modifier to use where appropriate given the input type. If all references to an operand already have modifiers then the warning is suppressed for that operand.\n\n[llvm-argmod]: http://llvm.org/docs/LangRef.html#asm-template-argument-modifiers\n\n## Options\n\nFlags are used to further influence the behavior of the inline assembly block.\nCurrently the following options are defined:\n- `pure`: The `asm` block has no side effects, and its outputs depend only on its direct inputs (i.e. the values themselves, not what they point to) or values read from memory (unless the `nomem` options is also set). This allows the compiler to execute the `asm` block fewer times than specified in the program (e.g. by hoisting it out of a loop) or even eliminate it entirely if the outputs are not used.\n- `nomem`: The `asm` blocks does not read or write to any memory. This allows the compiler to cache the values of modified global variables in registers across the `asm` block since it knows that they are not read or written to by the `asm`.\n- `readonly`: The `asm` block does not write to any memory. This allows the compiler to cache the values of unmodified global variables in registers across the `asm` block since it knows that they are not written to by the `asm`.\n- `preserves_flags`: The `asm` block does not modify the flags register (defined in the rules below). This allows the compiler to avoid recomputing the condition flags after the `asm` block.\n- `noreturn`: The `asm` block never returns, and its return type is defined as `!` (never). Behavior is undefined if execution falls through past the end of the asm code. A `noreturn` asm block behaves just like a function which doesn't return; notably, local variables in scope are not dropped before it is invoked.\n- `nostack`: The `asm` block does not push data to the stack, or write to the stack red-zone (if supported by the target). If this option is *not* used then the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n- `att_syntax`: This option is only valid on x86, and causes the assembler to use the `.att_syntax prefix` mode of the GNU assembler. Register operands are substituted in with a leading `%`.\n\nThe compiler performs some additional checks on options:\n- The `nomem` and `readonly` options are mutually exclusive: it is a compile-time error to specify both.\n- The `pure` option must be combined with either the `nomem` or `readonly` options, otherwise a compile-time error is emitted.\n- It is a compile-time error to specify `pure` on an asm block with no outputs or only discarded outputs (`_`).\n- It is a compile-time error to specify `noreturn` on an asm block with outputs.\n\n## Rules for inline assembly\n\n- Any registers not specified as inputs will contain an undefined value on entry to the asm block.\n - An \"undefined value\" in the context of inline assembly means that the register can (non-deterministically) have any one of the possible values allowed by the architecture. Notably it is not the same as an LLVM `undef` which can have a different value every time you read it (since such a concept does not exist in assembly code).\n- Any registers not specified as outputs must have the same value upon exiting the asm block as they had on entry, otherwise behavior is undefined.\n - This only applies to registers which can be specified as an input or output. Other registers follow target-specific rules.\n - Note that a `lateout` may be allocated to the same register as an `in`, in which case this rule does not apply. Code should not rely on this however since it depends on the results of register allocation.\n- Behavior is undefined if execution unwinds out of an asm block.\n - This also applies if the assembly code calls a function which then unwinds.\n- The set of memory locations that assembly code is allowed the read and write are the same as those allowed for an FFI function.\n - Refer to the unsafe code guidelines for the exact rules.\n - If the `readonly` option is set, then only memory reads are allowed.\n - If the `nomem` option is set then no reads or writes to memory are allowed.\n - These rules do not apply to memory which is private to the asm code, such as stack space allocated within the asm block.\n- The compiler cannot assume that the instructions in the asm are the ones that will actually end up executed.\n - This effectively means that the compiler must treat the `asm!` as a black box and only take the interface specification into account, not the instructions themselves.\n - Runtime code patching is allowed, via target-specific mechanisms (outside the scope of this RFC).\n- Unless the `nostack` option is set, asm code is allowed to use stack space below the stack pointer.\n - On entry to the asm block the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n - You are responsible for making sure you don't overflow the stack (e.g. use stack probing to ensure you hit a guard page).\n - You should adjust the stack pointer when allocating stack memory as required by the target ABI.\n - The stack pointer must be restored to its original value before leaving the asm block.\n- If the `noreturn` option is set then behavior is undefined if execution falls through to the end of the asm block.\n- If the `pure` option is set then behavior is undefined if the `asm` has side-effects other than its direct outputs. Behavior is also undefined if two executions of the `asm` code with the same inputs result in different outputs.\n - When used with the `nomem` option, \"inputs\" are just the direct inputs of the `asm!`.\n - When used with the `readonly` option, \"inputs\" comprise the direct inputs of the `asm!` and any memory that the `asm!` block is allowed to read.\n- These flags registers must be restored upon exiting the asm block if the `preserves_flags` option is set:\n - x86\n - Status flags in `EFLAGS` (CF, PF, AF, ZF, SF, OF).\n - Floating-point status word (all).\n - Floating-point exception flags in `MXCSR` (PE, UE, OE, ZE, DE, IE).\n - ARM\n - Condition flags in `CPSR` (N, Z, C, V)\n - Saturation flag in `CPSR` (Q)\n - Greater than or equal flags in `CPSR` (GE).\n - Condition flags in `FPSCR` (N, Z, C, V)\n - Saturation flag in `FPSCR` (QC)\n - Floating-point exception flags in `FPSCR` (IDC, IXC, UFC, OFC, DZC, IOC).\n - AArch64\n - Condition flags (`NZCV` register).\n - Floating-point status (`FPSR` register).\n - RISC-V\n - Floating-point exception flags in `fcsr` (`fflags`).\n- On x86, the direction flag (DF in `EFLAGS`) is clear on entry to an asm block and must be clear on exit.\n - Behavior is undefined if the direction flag is set on exiting an asm block.\n- The requirement of restoring the stack pointer and non-output registers to their original value only applies when exiting an `asm!` block.\n - This means that `asm!` blocks that never return (even if not marked `noreturn`) don't need to preserve these registers.\n - When returning to a different `asm!` block than you entered (e.g. for context switching), these registers must contain the value they had upon entering the `asm!` block that you are *exiting*.\n - You cannot exit an `asm!` block that has not been entered. Neither can you exit an `asm!` block that has already been exited.\n - You are responsible for switching any target-specific state (e.g. thread-local storage, stack bounds).\n - The set of memory locations that you may access is the intersection of those allowed by the `asm!` blocks you entered and exited.\n- You cannot assume that an `asm!` block will appear exactly once in the output binary. The compiler is allowed to instantiate multiple copies of the `asm!` block, for example when the function containing it is inlined in multiple places.\n - As a consequence, you should only use [local labels] inside inline assembly code. Defining symbols in assembly code may lead to assembler and/or linker errors due to duplicate symbol definitions.\n\n> **Note**: As a general rule, the flags covered by `preserves_flags` are those which are *not* preserved when performing a function call.\n\n[local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels\n" } , LintCompletion { label : "windows_handle" , description : "# `windows_handle`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fd_read" , description : "# `fd_read`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "sort_internals" , description : "# `sort_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "print_internals" , description : "# `print_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "allocator_api" , description : "# `allocator_api`\n\nThe tracking issue for this feature is [#32838]\n\n[#32838]: https://github.com/rust-lang/rust/issues/32838\n\n------------------------\n\nSometimes you want the memory for one collection to use a different\nallocator than the memory for another collection. In this case,\nreplacing the global allocator is not a workable option. Instead,\nyou need to pass in an instance of an `AllocRef` to each collection\nfor which you want a custom allocator.\n\nTBD\n" } , LintCompletion { label : "char_error_internals" , description : "# `char_error_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "flt2dec" , description : "# `flt2dec`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_panic" , description : "# `core_panic`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fn_traits" , description : "# `fn_traits`\n\nThe tracking issue for this feature is [#29625]\n\nSee Also: [`unboxed_closures`](../language-features/unboxed-closures.md)\n\n[#29625]: https://github.com/rust-lang/rust/issues/29625\n\n----\n\nThe `fn_traits` feature allows for implementation of the [`Fn*`] traits\nfor creating custom closure-like types.\n\n[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html\n\n```rust\n#![feature(unboxed_closures)]\n#![feature(fn_traits)]\n\nstruct Adder {\n a: u32\n}\n\nimpl FnOnce<(u32, )> for Adder {\n type Output = u32;\n extern \"rust-call\" fn call_once(self, b: (u32, )) -> Self::Output {\n self.a + b.0\n }\n}\n\nfn main() {\n let adder = Adder { a: 3 };\n assert_eq!(adder(2), 5);\n}\n```\n" } , LintCompletion { label : "global_asm" , description : "# `global_asm`\n\nThe tracking issue for this feature is: [#35119]\n\n[#35119]: https://github.com/rust-lang/rust/issues/35119\n\n------------------------\n\nThe `global_asm!` macro allows the programmer to write arbitrary\nassembly outside the scope of a function body, passing it through\n`rustc` and `llvm` to the assembler. The macro is a no-frills\ninterface to LLVM's concept of [module-level inline assembly]. That is,\nall caveats applicable to LLVM's module-level inline assembly apply\nto `global_asm!`.\n\n[module-level inline assembly]: http://llvm.org/docs/LangRef.html#module-level-inline-assembly\n\n`global_asm!` fills a role not currently satisfied by either `asm!`\nor `#[naked]` functions. The programmer has _all_ features of the\nassembler at their disposal. The linker will expect to resolve any\nsymbols defined in the inline assembly, modulo any symbols marked as\nexternal. It also means syntax for directives and assembly follow the\nconventions of the assembler in your toolchain.\n\nA simple usage looks like this:\n\n```rust,ignore\n# #![feature(global_asm)]\n# you also need relevant target_arch cfgs\nglobal_asm!(include_str!(\"something_neato.s\"));\n```\n\nAnd a more complicated usage looks like this:\n\n```rust,ignore\n# #![feature(global_asm)]\n# #![cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n\npub mod sally {\n global_asm!(r#\"\n .global foo\n foo:\n jmp baz\n \"#);\n\n #[no_mangle]\n pub unsafe extern \"C\" fn baz() {}\n}\n\n// the symbols `foo` and `bar` are global, no matter where\n// `global_asm!` was used.\nextern \"C\" {\n fn foo();\n fn bar();\n}\n\npub mod harry {\n global_asm!(r#\"\n .global bar\n bar:\n jmp quux\n \"#);\n\n #[no_mangle]\n pub unsafe extern \"C\" fn quux() {}\n}\n```\n\nYou may use `global_asm!` multiple times, anywhere in your crate, in\nwhatever way suits you. The effect is as if you concatenated all\nusages and placed the larger, single usage in the crate root.\n\n------------------------\n\nIf you don't need quite as much power and flexibility as\n`global_asm!` provides, and you don't mind restricting your inline\nassembly to `fn` bodies only, you might try the\n[asm](asm.md) feature instead.\n" } , LintCompletion { label : "fd" , description : "# `fd`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "concat_idents" , description : "# `concat_idents`\n\nThe tracking issue for this feature is: [#29599]\n\n[#29599]: https://github.com/rust-lang/rust/issues/29599\n\n------------------------\n\nThe `concat_idents` feature adds a macro for concatenating multiple identifiers\ninto one identifier.\n\n## Examples\n\n```rust\n#![feature(concat_idents)]\n\nfn main() {\n fn foobar() -> u32 { 23 }\n let f = concat_idents!(foo, bar);\n assert_eq!(f(), 23);\n}\n```" } , LintCompletion { label : "derive_eq" , description : "# `derive_eq`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "profiler_runtime_lib" , description : "# `profiler_runtime_lib`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "default_free_fn" , description : "# `default_free_fn`\n\nThe tracking issue for this feature is: [#73014]\n\n[#73014]: https://github.com/rust-lang/rust/issues/73014\n\n------------------------\n\nAdds a free `default()` function to the `std::default` module. This function\njust forwards to [`Default::default()`], but may remove repetition of the word\n\"default\" from the call site.\n\nHere is an example:\n\n```rust\n#![feature(default_free_fn)]\nuse std::default::default;\n\n#[derive(Default)]\nstruct AppConfig {\n foo: FooConfig,\n bar: BarConfig,\n}\n\n#[derive(Default)]\nstruct FooConfig {\n foo: i32,\n}\n\n#[derive(Default)]\nstruct BarConfig {\n bar: f32,\n baz: u8,\n}\n\nfn main() {\n let options = AppConfig {\n foo: default(),\n bar: BarConfig {\n bar: 10.1,\n ..default()\n },\n };\n}\n```\n" } , LintCompletion { label : "int_error_internals" , description : "# `int_error_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "slice_check_range" , description : "# `slice_check_range`\n\nThe tracking issue for this feature is: [#76393]\n\n------------------------\n\nThis adds [`slice::check_range`].\n\n[#76393]: https://github.com/rust-lang/rust/issues/76393\n[`slice::check_range`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.check_range\n" } , LintCompletion { label : "try_trait" , description : "# `try_trait`\n\nThe tracking issue for this feature is: [#42327]\n\n[#42327]: https://github.com/rust-lang/rust/issues/42327\n\n------------------------\n\nThis introduces a new trait `Try` for extending the `?` operator to types\nother than `Result` (a part of [RFC 1859]). The trait provides the canonical\nway to _view_ a type in terms of a success/failure dichotomy. This will\nallow `?` to supplant the `try_opt!` macro on `Option` and the `try_ready!`\nmacro on `Poll`, among other things.\n\n[RFC 1859]: https://github.com/rust-lang/rfcs/pull/1859\n\nHere's an example implementation of the trait:\n\n```rust,ignore\n/// A distinct type to represent the `None` value of an `Option`.\n///\n/// This enables using the `?` operator on `Option`; it's rarely useful alone.\n#[derive(Debug)]\n#[unstable(feature = \"try_trait\", issue = \"42327\")]\npub struct None { _priv: () }\n\n#[unstable(feature = \"try_trait\", issue = \"42327\")]\nimpl<T> ops::Try for Option<T> {\n type Ok = T;\n type Error = None;\n\n fn into_result(self) -> Result<T, None> {\n self.ok_or(None { _priv: () })\n }\n\n fn from_ok(v: T) -> Self {\n Some(v)\n }\n\n fn from_error(_: None) -> Self {\n None\n }\n}\n```\n\nNote the `Error` associated type here is a new marker. The `?` operator\nallows interconversion between different `Try` implementers only when\nthe error type can be converted `Into` the error type of the enclosing\nfunction (or catch block). Having a distinct error type (as opposed to\njust `()`, or similar) restricts this to where it's semantically meaningful.\n" } , LintCompletion { label : "c_variadic" , description : "# `c_variadic`\n\nThe tracking issue for this feature is: [#44930]\n\n[#44930]: https://github.com/rust-lang/rust/issues/44930\n\n------------------------\n\nThe `c_variadic` library feature exposes the `VaList` structure,\nRust's analogue of C's `va_list` type.\n\n## Examples\n\n```rust\n#![feature(c_variadic)]\n\nuse std::ffi::VaList;\n\npub unsafe extern \"C\" fn vadd(n: usize, mut args: VaList) -> usize {\n let mut sum = 0;\n for _ in 0..n {\n sum += args.arg::<usize>();\n }\n sum\n}\n```\n" } , LintCompletion { label : "dec2flt" , description : "# `dec2flt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "set_stdio" , description : "# `set_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_thread_internals" , description : "# `libstd_thread_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_stdio" , description : "# `windows_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "format_args_capture" , description : "# `format_args_capture`\n\nThe tracking issue for this feature is: [#67984]\n\n[#67984]: https://github.com/rust-lang/rust/issues/67984\n\n------------------------\n\nEnables `format_args!` (and macros which use `format_args!` in their implementation, such\nas `format!`, `print!` and `panic!`) to capture variables from the surrounding scope.\nThis avoids the need to pass named parameters when the binding in question\nalready exists in scope.\n\n```rust\n#![feature(format_args_capture)]\n\nlet (person, species, name) = (\"Charlie Brown\", \"dog\", \"Snoopy\");\n\n// captures named argument `person`\nprint!(\"Hello {person}\");\n\n// captures named arguments `species` and `name`\nformat!(\"The {species}'s name is {name}.\");\n```\n\nThis also works for formatting parameters such as width and precision:\n\n```rust\n#![feature(format_args_capture)]\n\nlet precision = 2;\nlet s = format!(\"{:.precision$}\", 1.324223);\n\nassert_eq!(&s, \"1.32\");\n```\n\nA non-exhaustive list of macros which benefit from this functionality include:\n- `format!`\n- `print!` and `println!`\n- `eprint!` and `eprintln!`\n- `write!` and `writeln!`\n- `panic!`\n- `unreachable!`\n- `unimplemented!`\n- `todo!`\n- `assert!` and similar\n- macros in many thirdparty crates, such as `log`\n" } , LintCompletion { label : "thread_local_internals" , description : "# `thread_local_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_private_diy_float" , description : "# `core_private_diy_float`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_io_internals" , description : "# `libstd_io_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_private_bignum" , description : "# `core_private_bignum`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "is_sorted" , description : "# `is_sorted`\n\nThe tracking issue for this feature is: [#53485]\n\n[#53485]: https://github.com/rust-lang/rust/issues/53485\n\n------------------------\n\nAdd the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to `[T]`;\nadd the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to\n`Iterator`.\n" } , LintCompletion { label : "core_intrinsics" , description : "# `core_intrinsics`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "test" , description : "# `test`\n\nThe tracking issue for this feature is: None.\n\n------------------------\n\nThe internals of the `test` crate are unstable, behind the `test` flag. The\nmost widely used part of the `test` crate are benchmark tests, which can test\nthe performance of your code. Let's make our `src/lib.rs` look like this\n(comments elided):\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\n\npub fn add_two(a: i32) -> i32 {\n a + 2\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use test::Bencher;\n\n #[test]\n fn it_works() {\n assert_eq!(4, add_two(2));\n }\n\n #[bench]\n fn bench_add_two(b: &mut Bencher) {\n b.iter(|| add_two(2));\n }\n}\n```\n\nNote the `test` feature gate, which enables this unstable feature.\n\nWe've imported the `test` crate, which contains our benchmarking support.\nWe have a new function as well, with the `bench` attribute. Unlike regular\ntests, which take no arguments, benchmark tests take a `&mut Bencher`. This\n`Bencher` provides an `iter` method, which takes a closure. This closure\ncontains the code we'd like to benchmark.\n\nWe can run benchmark tests with `cargo bench`:\n\n```bash\n$ cargo bench\n Compiling adder v0.0.1 (file:///home/steve/tmp/adder)\n Running target/release/adder-91b3e234d4ed382a\n\nrunning 2 tests\ntest tests::it_works ... ignored\ntest tests::bench_add_two ... bench: 1 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 1 ignored; 1 measured\n```\n\nOur non-benchmark test was ignored. You may have noticed that `cargo bench`\ntakes a bit longer than `cargo test`. This is because Rust runs our benchmark\na number of times, and then takes the average. Because we're doing so little\nwork in this example, we have a `1 ns/iter (+/- 0)`, but this would show\nthe variance if there was one.\n\nAdvice on writing benchmarks:\n\n\n* Move setup code outside the `iter` loop; only put the part you want to measure inside\n* Make the code do \"the same thing\" on each iteration; do not accumulate or change state\n* Make the outer function idempotent too; the benchmark runner is likely to run\n it many times\n* Make the inner `iter` loop short and fast so benchmark runs are fast and the\n calibrator can adjust the run-length at fine resolution\n* Make the code in the `iter` loop do something simple, to assist in pinpointing\n performance improvements (or regressions)\n\n## Gotcha: optimizations\n\nThere's another tricky part to writing benchmarks: benchmarks compiled with\noptimizations activated can be dramatically changed by the optimizer so that\nthe benchmark is no longer benchmarking what one expects. For example, the\ncompiler might recognize that some calculation has no external effects and\nremove it entirely.\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\nuse test::Bencher;\n\n#[bench]\nfn bench_xor_1000_ints(b: &mut Bencher) {\n b.iter(|| {\n (0..1000).fold(0, |old, new| old ^ new);\n });\n}\n```\n\ngives the following results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench: 0 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nThe benchmarking runner offers two ways to avoid this. Either, the closure that\nthe `iter` method receives can return an arbitrary value which forces the\noptimizer to consider the result used and ensures it cannot remove the\ncomputation entirely. This could be done for the example above by adjusting the\n`b.iter` call to\n\n```rust\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n // Note lack of `;` (could also use an explicit `return`).\n (0..1000).fold(0, |old, new| old ^ new)\n});\n```\n\nOr, the other option is to call the generic `test::black_box` function, which\nis an opaque \"black box\" to the optimizer and so forces it to consider any\nargument as used.\n\n```rust\n#![feature(test)]\n\nextern crate test;\n\n# fn main() {\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n let n = test::black_box(1000);\n\n (0..n).fold(0, |a, b| a ^ b)\n})\n# }\n```\n\nNeither of these read or modify the value, and are very cheap for small values.\nLarger values can be passed indirectly to reduce overhead (e.g.\n`black_box(&huge_struct)`).\n\nPerforming either of the above changes gives the following benchmarking results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nHowever, the optimizer can still modify a testcase in an undesirable manner\neven when using either of the above.\n" }] ; 4pub (super) const FEATURES : & [LintCompletion] = & [LintCompletion { label : "non_ascii_idents" , description : "# `non_ascii_idents`\n\nThe tracking issue for this feature is: [#55467]\n\n[#55467]: https://github.com/rust-lang/rust/issues/55467\n\n------------------------\n\nThe `non_ascii_idents` feature adds support for non-ASCII identifiers.\n\n## Examples\n\n```rust\n#![feature(non_ascii_idents)]\n\nconst ε: f64 = 0.00001f64;\nconst Π: f64 = 3.14f64;\n```\n\n## Changes to the language reference\n\n> **<sup>Lexer:<sup>** \n> IDENTIFIER : \n> &nbsp;&nbsp; &nbsp;&nbsp; XID_start XID_continue<sup>\\*</sup> \n> &nbsp;&nbsp; | `_` XID_continue<sup>+</sup> \n\nAn identifier is any nonempty Unicode string of the following form:\n\nEither\n\n * The first character has property [`XID_start`]\n * The remaining characters have property [`XID_continue`]\n\nOr\n\n * The first character is `_`\n * The identifier is more than one character, `_` alone is not an identifier\n * The remaining characters have property [`XID_continue`]\n\nthat does _not_ occur in the set of [strict keywords].\n\n> **Note**: [`XID_start`] and [`XID_continue`] as character properties cover the\n> character ranges used to form the more familiar C and Java language-family\n> identifiers.\n\n[`XID_start`]: http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&abb=on&g=&i=\n[`XID_continue`]: http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&abb=on&g=&i=\n[strict keywords]: ../../reference/keywords.md#strict-keywords\n" } , LintCompletion { label : "custom_test_frameworks" , description : "# `custom_test_frameworks`\n\nThe tracking issue for this feature is: [#50297]\n\n[#50297]: https://github.com/rust-lang/rust/issues/50297\n\n------------------------\n\nThe `custom_test_frameworks` feature allows the use of `#[test_case]` and `#![test_runner]`.\nAny function, const, or static can be annotated with `#[test_case]` causing it to be aggregated (like `#[test]`)\nand be passed to the test runner determined by the `#![test_runner]` crate attribute.\n\n```rust\n#![feature(custom_test_frameworks)]\n#![test_runner(my_runner)]\n\nfn my_runner(tests: &[&i32]) {\n for t in tests {\n if **t == 0 {\n println!(\"PASSED\");\n } else {\n println!(\"FAILED\");\n }\n }\n}\n\n#[test_case]\nconst WILL_PASS: i32 = 0;\n\n#[test_case]\nconst WILL_FAIL: i32 = 4;\n```\n\n" } , LintCompletion { label : "abi_msp430_interrupt" , description : "# `abi_msp430_interrupt`\n\nThe tracking issue for this feature is: [#38487]\n\n[#38487]: https://github.com/rust-lang/rust/issues/38487\n\n------------------------\n\nIn the MSP430 architecture, interrupt handlers have a special calling\nconvention. You can use the `\"msp430-interrupt\"` ABI to make the compiler apply\nthe right calling convention to the interrupt handlers you define.\n\n<!-- NOTE(ignore) this example is specific to the msp430 target -->\n\n``` rust,ignore\n#![feature(abi_msp430_interrupt)]\n#![no_std]\n\n// Place the interrupt handler at the appropriate memory address\n// (Alternatively, you can use `#[used]` and remove `pub` and `#[no_mangle]`)\n#[link_section = \"__interrupt_vector_10\"]\n#[no_mangle]\npub static TIM0_VECTOR: extern \"msp430-interrupt\" fn() = tim0;\n\n// The interrupt handler\nextern \"msp430-interrupt\" fn tim0() {\n // ..\n}\n```\n\n``` text\n$ msp430-elf-objdump -CD ./target/msp430/release/app\nDisassembly of section __interrupt_vector_10:\n\n0000fff2 <TIM0_VECTOR>:\n fff2: 00 c0 interrupt service routine at 0xc000\n\nDisassembly of section .text:\n\n0000c000 <int::tim0>:\n c000: 00 13 reti\n```\n" } , LintCompletion { label : "link_args" , description : "# `link_args`\n\nThe tracking issue for this feature is: [#29596]\n\n[#29596]: https://github.com/rust-lang/rust/issues/29596\n\n------------------------\n\nYou can tell `rustc` how to customize linking, and that is via the `link_args`\nattribute. This attribute is applied to `extern` blocks and specifies raw flags\nwhich need to get passed to the linker when producing an artifact. An example\nusage would be:\n\n```rust,no_run\n#![feature(link_args)]\n\n#[link_args = \"-foo -bar -baz\"]\nextern {}\n# fn main() {}\n```\n\nNote that this feature is currently hidden behind the `feature(link_args)` gate\nbecause this is not a sanctioned way of performing linking. Right now `rustc`\nshells out to the system linker (`gcc` on most systems, `link.exe` on MSVC), so\nit makes sense to provide extra command line arguments, but this will not\nalways be the case. In the future `rustc` may use LLVM directly to link native\nlibraries, in which case `link_args` will have no meaning. You can achieve the\nsame effect as the `link_args` attribute with the `-C link-args` argument to\n`rustc`.\n\nIt is highly recommended to *not* use this attribute, and rather use the more\nformal `#[link(...)]` attribute on `extern` blocks instead.\n" } , LintCompletion { label : "const_eval_limit" , description : "# `const_eval_limit`\n\nThe tracking issue for this feature is: [#67217]\n\n[#67217]: https://github.com/rust-lang/rust/issues/67217\n\nThe `const_eval_limit` allows someone to limit the evaluation steps the CTFE undertakes to evaluate a `const fn`.\n" } , LintCompletion { label : "marker_trait_attr" , description : "# `marker_trait_attr`\n\nThe tracking issue for this feature is: [#29864]\n\n[#29864]: https://github.com/rust-lang/rust/issues/29864\n\n------------------------\n\nNormally, Rust keeps you from adding trait implementations that could\noverlap with each other, as it would be ambiguous which to use. This\nfeature, however, carves out an exception to that rule: a trait can\nopt-in to having overlapping implementations, at the cost that those\nimplementations are not allowed to override anything (and thus the\ntrait itself cannot have any associated items, as they're pointless\nwhen they'd need to do the same thing for every type anyway).\n\n```rust\n#![feature(marker_trait_attr)]\n\n#[marker] trait CheapToClone: Clone {}\n\nimpl<T: Copy> CheapToClone for T {}\n\n// These could potentially overlap with the blanket implementation above,\n// so are only allowed because CheapToClone is a marker trait.\nimpl<T: CheapToClone, U: CheapToClone> CheapToClone for (T, U) {}\nimpl<T: CheapToClone> CheapToClone for std::ops::Range<T> {}\n\nfn cheap_clone<T: CheapToClone>(t: T) -> T {\n t.clone()\n}\n```\n\nThis is expected to replace the unstable `overlapping_marker_traits`\nfeature, which applied to all empty traits (without needing an opt-in).\n" } , LintCompletion { label : "ffi_const" , description : "# `ffi_const`\n\nThe tracking issue for this feature is: [#58328]\n\n------\n\nThe `#[ffi_const]` attribute applies clang's `const` attribute to foreign\nfunctions declarations.\n\nThat is, `#[ffi_const]` functions shall have no effects except for its return\nvalue, which can only depend on the values of the function parameters, and is\nnot affected by changes to the observable state of the program.\n\nApplying the `#[ffi_const]` attribute to a function that violates these\nrequirements is undefined behaviour.\n\nThis attribute enables Rust to perform common optimizations, like sub-expression\nelimination, and it can avoid emitting some calls in repeated invocations of the\nfunction with the same argument values regardless of other operations being\nperformed in between these functions calls (as opposed to `#[ffi_pure]`\nfunctions).\n\n## Pitfalls\n\nA `#[ffi_const]` function can only read global memory that would not affect\nits return value for the whole execution of the program (e.g. immutable global\nmemory). `#[ffi_const]` functions are referentially-transparent and therefore\nmore strict than `#[ffi_pure]` functions.\n\nA common pitfall involves applying the `#[ffi_const]` attribute to a\nfunction that reads memory through pointer arguments which do not necessarily\npoint to immutable global memory.\n\nA `#[ffi_const]` function that returns unit has no effect on the abstract\nmachine's state, and a `#[ffi_const]` function cannot be `#[ffi_pure]`.\n\nA `#[ffi_const]` function must not diverge, neither via a side effect (e.g. a\ncall to `abort`) nor by infinite loops.\n\nWhen translating C headers to Rust FFI, it is worth verifying for which targets\nthe `const` attribute is enabled in those headers, and using the appropriate\n`cfg` macros in the Rust side to match those definitions. While the semantics of\n`const` are implemented identically by many C and C++ compilers, e.g., clang,\n[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily\nimplemented in this way on all of them. It is therefore also worth verifying\nthat the semantics of the C toolchain used to compile the binary being linked\nagainst are compatible with those of the `#[ffi_const]`.\n\n[#58328]: https://github.com/rust-lang/rust/issues/58328\n[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacgigch.html\n[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-const-function-attribute\n[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_const.htm\n" } , LintCompletion { label : "doc_spotlight" , description : "# `doc_spotlight`\n\nThe tracking issue for this feature is: [#45040]\n\nThe `doc_spotlight` feature allows the use of the `spotlight` parameter to the `#[doc]` attribute,\nto \"spotlight\" a specific trait on the return values of functions. Adding a `#[doc(spotlight)]`\nattribute to a trait definition will make rustdoc print extra information for functions which return\na type that implements that trait. This attribute is applied to the `Iterator`, `io::Read`, and\n`io::Write` traits in the standard library.\n\nYou can do this on your own traits, like this:\n\n```\n#![feature(doc_spotlight)]\n\n#[doc(spotlight)]\npub trait MyTrait {}\n\npub struct MyStruct;\nimpl MyTrait for MyStruct {}\n\n/// The docs for this function will have an extra line about `MyStruct` implementing `MyTrait`,\n/// without having to write that yourself!\npub fn my_fn() -> MyStruct { MyStruct }\n```\n\nThis feature was originally implemented in PR [#45039].\n\n[#45040]: https://github.com/rust-lang/rust/issues/45040\n[#45039]: https://github.com/rust-lang/rust/pull/45039\n" } , LintCompletion { label : "compiler_builtins" , description : "# `compiler_builtins`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "lang_items" , description : "# `lang_items`\n\nThe tracking issue for this feature is: None.\n\n------------------------\n\nThe `rustc` compiler has certain pluggable operations, that is,\nfunctionality that isn't hard-coded into the language, but is\nimplemented in libraries, with a special marker to tell the compiler\nit exists. The marker is the attribute `#[lang = \"...\"]` and there are\nvarious different values of `...`, i.e. various different 'lang\nitems'.\n\nFor example, `Box` pointers require two lang items, one for allocation\nand one for deallocation. A freestanding program that uses the `Box`\nsugar for dynamic allocations via `malloc` and `free`:\n\n```rust,ignore\n#![feature(lang_items, box_syntax, start, libc, core_intrinsics)]\n#![no_std]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\nextern crate libc;\n\n#[lang = \"owned_box\"]\npub struct Box<T>(*mut T);\n\n#[lang = \"exchange_malloc\"]\nunsafe fn allocate(size: usize, _align: usize) -> *mut u8 {\n let p = libc::malloc(size as libc::size_t) as *mut u8;\n\n // Check if `malloc` failed:\n if p as usize == 0 {\n intrinsics::abort();\n }\n\n p\n}\n\n#[lang = \"box_free\"]\nunsafe fn box_free<T: ?Sized>(ptr: *mut T) {\n libc::free(ptr as *mut libc::c_void)\n}\n\n#[start]\nfn main(_argc: isize, _argv: *const *const u8) -> isize {\n let _x = box 1;\n\n 0\n}\n\n#[lang = \"eh_personality\"] extern fn rust_eh_personality() {}\n#[lang = \"panic_impl\"] extern fn rust_begin_panic(info: &PanicInfo) -> ! { unsafe { intrinsics::abort() } }\n#[no_mangle] pub extern fn rust_eh_register_frames () {}\n#[no_mangle] pub extern fn rust_eh_unregister_frames () {}\n```\n\nNote the use of `abort`: the `exchange_malloc` lang item is assumed to\nreturn a valid pointer, and so needs to do the check internally.\n\nOther features provided by lang items include:\n\n- overloadable operators via traits: the traits corresponding to the\n `==`, `<`, dereferencing (`*`) and `+` (etc.) operators are all\n marked with lang items; those specific four are `eq`, `ord`,\n `deref`, and `add` respectively.\n- stack unwinding and general failure; the `eh_personality`,\n `panic` and `panic_bounds_checks` lang items.\n- the traits in `std::marker` used to indicate types of\n various kinds; lang items `send`, `sync` and `copy`.\n- the marker types and variance indicators found in\n `std::marker`; lang items `covariant_type`,\n `contravariant_lifetime`, etc.\n\nLang items are loaded lazily by the compiler; e.g. if one never uses\n`Box` then there is no need to define functions for `exchange_malloc`\nand `box_free`. `rustc` will emit an error when an item is needed\nbut not found in the current crate or any that it depends on.\n\nMost lang items are defined by `libcore`, but if you're trying to build\nan executable without the standard library, you'll run into the need\nfor lang items. The rest of this page focuses on this use-case, even though\nlang items are a bit broader than that.\n\n### Using libc\n\nIn order to build a `#[no_std]` executable we will need libc as a dependency.\nWe can specify this using our `Cargo.toml` file:\n\n```toml\n[dependencies]\nlibc = { version = \"0.2.14\", default-features = false }\n```\n\nNote that the default features have been disabled. This is a critical step -\n**the default features of libc include the standard library and so must be\ndisabled.**\n\n### Writing an executable without stdlib\n\nControlling the entry point is possible in two ways: the `#[start]` attribute,\nor overriding the default shim for the C `main` function with your own.\n\nThe function marked `#[start]` is passed the command line parameters\nin the same format as C:\n\n```rust,ignore\n#![feature(lang_items, core_intrinsics)]\n#![feature(start)]\n#![no_std]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\n// Pull in the system libc library for what crt0.o likely requires.\nextern crate libc;\n\n// Entry point for this program.\n#[start]\nfn start(_argc: isize, _argv: *const *const u8) -> isize {\n 0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn rust_eh_personality() {\n}\n\n#[lang = \"panic_impl\"]\n#[no_mangle]\npub extern fn rust_begin_panic(info: &PanicInfo) -> ! {\n unsafe { intrinsics::abort() }\n}\n```\n\nTo override the compiler-inserted `main` shim, one has to disable it\nwith `#![no_main]` and then create the appropriate symbol with the\ncorrect ABI and the correct name, which requires overriding the\ncompiler's name mangling too:\n\n```rust,ignore\n#![feature(lang_items, core_intrinsics)]\n#![feature(start)]\n#![no_std]\n#![no_main]\nuse core::intrinsics;\nuse core::panic::PanicInfo;\n\n// Pull in the system libc library for what crt0.o likely requires.\nextern crate libc;\n\n// Entry point for this program.\n#[no_mangle] // ensure that this symbol is called `main` in the output\npub extern fn main(_argc: i32, _argv: *const *const u8) -> i32 {\n 0\n}\n\n// These functions are used by the compiler, but not\n// for a bare-bones hello world. These are normally\n// provided by libstd.\n#[lang = \"eh_personality\"]\n#[no_mangle]\npub extern fn rust_eh_personality() {\n}\n\n#[lang = \"panic_impl\"]\n#[no_mangle]\npub extern fn rust_begin_panic(info: &PanicInfo) -> ! {\n unsafe { intrinsics::abort() }\n}\n```\n\nIn many cases, you may need to manually link to the `compiler_builtins` crate\nwhen building a `no_std` binary. You may observe this via linker error messages\nsuch as \"```undefined reference to `__rust_probestack'```\".\n\n## More about the language items\n\nThe compiler currently makes a few assumptions about symbols which are\navailable in the executable to call. Normally these functions are provided by\nthe standard library, but without it you must define your own. These symbols\nare called \"language items\", and they each have an internal name, and then a\nsignature that an implementation must conform to.\n\nThe first of these functions, `rust_eh_personality`, is used by the failure\nmechanisms of the compiler. This is often mapped to GCC's personality function\n(see the [libstd implementation][unwind] for more information), but crates\nwhich do not trigger a panic can be assured that this function is never\ncalled. The language item's name is `eh_personality`.\n\n[unwind]: https://github.com/rust-lang/rust/blob/master/src/libpanic_unwind/gcc.rs\n\nThe second function, `rust_begin_panic`, is also used by the failure mechanisms of the\ncompiler. When a panic happens, this controls the message that's displayed on\nthe screen. While the language item's name is `panic_impl`, the symbol name is\n`rust_begin_panic`.\n\nFinally, a `eh_catch_typeinfo` static is needed for certain targets which\nimplement Rust panics on top of C++ exceptions.\n\n## List of all language items\n\nThis is a list of all language items in Rust along with where they are located in\nthe source code.\n\n- Primitives\n - `i8`: `libcore/num/mod.rs`\n - `i16`: `libcore/num/mod.rs`\n - `i32`: `libcore/num/mod.rs`\n - `i64`: `libcore/num/mod.rs`\n - `i128`: `libcore/num/mod.rs`\n - `isize`: `libcore/num/mod.rs`\n - `u8`: `libcore/num/mod.rs`\n - `u16`: `libcore/num/mod.rs`\n - `u32`: `libcore/num/mod.rs`\n - `u64`: `libcore/num/mod.rs`\n - `u128`: `libcore/num/mod.rs`\n - `usize`: `libcore/num/mod.rs`\n - `f32`: `libstd/f32.rs`\n - `f64`: `libstd/f64.rs`\n - `char`: `libcore/char.rs`\n - `slice`: `liballoc/slice.rs`\n - `str`: `liballoc/str.rs`\n - `const_ptr`: `libcore/ptr.rs`\n - `mut_ptr`: `libcore/ptr.rs`\n - `unsafe_cell`: `libcore/cell.rs`\n- Runtime\n - `start`: `libstd/rt.rs`\n - `eh_personality`: `libpanic_unwind/emcc.rs` (EMCC)\n - `eh_personality`: `libpanic_unwind/gcc.rs` (GNU)\n - `eh_personality`: `libpanic_unwind/seh.rs` (SEH)\n - `eh_catch_typeinfo`: `libpanic_unwind/emcc.rs` (EMCC)\n - `panic`: `libcore/panicking.rs`\n - `panic_bounds_check`: `libcore/panicking.rs`\n - `panic_impl`: `libcore/panicking.rs`\n - `panic_impl`: `libstd/panicking.rs`\n- Allocations\n - `owned_box`: `liballoc/boxed.rs`\n - `exchange_malloc`: `liballoc/heap.rs`\n - `box_free`: `liballoc/heap.rs`\n- Operands\n - `not`: `libcore/ops/bit.rs`\n - `bitand`: `libcore/ops/bit.rs`\n - `bitor`: `libcore/ops/bit.rs`\n - `bitxor`: `libcore/ops/bit.rs`\n - `shl`: `libcore/ops/bit.rs`\n - `shr`: `libcore/ops/bit.rs`\n - `bitand_assign`: `libcore/ops/bit.rs`\n - `bitor_assign`: `libcore/ops/bit.rs`\n - `bitxor_assign`: `libcore/ops/bit.rs`\n - `shl_assign`: `libcore/ops/bit.rs`\n - `shr_assign`: `libcore/ops/bit.rs`\n - `deref`: `libcore/ops/deref.rs`\n - `deref_mut`: `libcore/ops/deref.rs`\n - `index`: `libcore/ops/index.rs`\n - `index_mut`: `libcore/ops/index.rs`\n - `add`: `libcore/ops/arith.rs`\n - `sub`: `libcore/ops/arith.rs`\n - `mul`: `libcore/ops/arith.rs`\n - `div`: `libcore/ops/arith.rs`\n - `rem`: `libcore/ops/arith.rs`\n - `neg`: `libcore/ops/arith.rs`\n - `add_assign`: `libcore/ops/arith.rs`\n - `sub_assign`: `libcore/ops/arith.rs`\n - `mul_assign`: `libcore/ops/arith.rs`\n - `div_assign`: `libcore/ops/arith.rs`\n - `rem_assign`: `libcore/ops/arith.rs`\n - `eq`: `libcore/cmp.rs`\n - `ord`: `libcore/cmp.rs`\n- Functions\n - `fn`: `libcore/ops/function.rs`\n - `fn_mut`: `libcore/ops/function.rs`\n - `fn_once`: `libcore/ops/function.rs`\n - `generator_state`: `libcore/ops/generator.rs`\n - `generator`: `libcore/ops/generator.rs`\n- Other\n - `coerce_unsized`: `libcore/ops/unsize.rs`\n - `drop`: `libcore/ops/drop.rs`\n - `drop_in_place`: `libcore/ptr.rs`\n - `clone`: `libcore/clone.rs`\n - `copy`: `libcore/marker.rs`\n - `send`: `libcore/marker.rs`\n - `sized`: `libcore/marker.rs`\n - `unsize`: `libcore/marker.rs`\n - `sync`: `libcore/marker.rs`\n - `phantom_data`: `libcore/marker.rs`\n - `discriminant_kind`: `libcore/marker.rs`\n - `freeze`: `libcore/marker.rs`\n - `debug_trait`: `libcore/fmt/mod.rs`\n - `non_zero`: `libcore/nonzero.rs`\n - `arc`: `liballoc/sync.rs`\n - `rc`: `liballoc/rc.rs`\n" } , LintCompletion { label : "member_constraints" , description : "# `member_constraints`\n\nThe tracking issue for this feature is: [#61997]\n\n[#61997]: https://github.com/rust-lang/rust/issues/61997\n\n------------------------\n\nThe `member_constraints` feature gate lets you use `impl Trait` syntax with\nmultiple unrelated lifetime parameters.\n\nA simple example is:\n\n```rust\n#![feature(member_constraints)]\n\ntrait Trait<'a, 'b> { }\nimpl<T> Trait<'_, '_> for T {}\n\nfn foo<'a, 'b>(x: &'a u32, y: &'b u32) -> impl Trait<'a, 'b> {\n (x, y)\n}\n\nfn main() { }\n```\n\nWithout the `member_constraints` feature gate, the above example is an\nerror because both `'a` and `'b` appear in the impl Trait bounds, but\nneither outlives the other.\n" } , LintCompletion { label : "crate_visibility_modifier" , description : "# `crate_visibility_modifier`\n\nThe tracking issue for this feature is: [#53120]\n\n[#53120]: https://github.com/rust-lang/rust/issues/53120\n\n-----\n\nThe `crate_visibility_modifier` feature allows the `crate` keyword to be used\nas a visibility modifier synonymous to `pub(crate)`, indicating that a type\n(function, _&c._) is to be visible to the entire enclosing crate, but not to\nother crates.\n\n```rust\n#![feature(crate_visibility_modifier)]\n\ncrate struct Foo {\n bar: usize,\n}\n```\n" } , LintCompletion { label : "try_blocks" , description : "# `try_blocks`\n\nThe tracking issue for this feature is: [#31436]\n\n[#31436]: https://github.com/rust-lang/rust/issues/31436\n\n------------------------\n\nThe `try_blocks` feature adds support for `try` blocks. A `try`\nblock creates a new scope one can use the `?` operator in.\n\n```rust,edition2018\n#![feature(try_blocks)]\n\nuse std::num::ParseIntError;\n\nlet result: Result<i32, ParseIntError> = try {\n \"1\".parse::<i32>()?\n + \"2\".parse::<i32>()?\n + \"3\".parse::<i32>()?\n};\nassert_eq!(result, Ok(6));\n\nlet result: Result<i32, ParseIntError> = try {\n \"1\".parse::<i32>()?\n + \"foo\".parse::<i32>()?\n + \"3\".parse::<i32>()?\n};\nassert!(result.is_err());\n```\n" } , LintCompletion { label : "const_in_array_repeat_expressions" , description : "# `const_in_array_repeat_expressions`\n\nThe tracking issue for this feature is: [#49147]\n\n[#49147]: https://github.com/rust-lang/rust/issues/49147\n\n------------------------\n\nRelaxes the rules for repeat expressions, `[x; N]` such that `x` may also be `const` (strictly\nspeaking rvalue promotable), in addition to `typeof(x): Copy`. The result of `[x; N]` where `x` is\n`const` is itself also `const`.\n" } , LintCompletion { label : "negative_impls" , description : "# `negative_impls`\n\nThe tracking issue for this feature is [#68318].\n\n[#68318]: https://github.com/rust-lang/rust/issues/68318\n\n----\n\nWith the feature gate `negative_impls`, you can write negative impls as well as positive ones:\n\n```rust\n#![feature(negative_impls)]\ntrait DerefMut { }\nimpl<T: ?Sized> !DerefMut for &T { }\n```\n\nNegative impls indicate a semver guarantee that the given trait will not be implemented for the given types. Negative impls play an additional purpose for auto traits, described below.\n\nNegative impls have the following characteristics:\n\n* They do not have any items.\n* They must obey the orphan rules as if they were a positive impl.\n* They cannot \"overlap\" with any positive impls.\n\n## Semver interaction\n\nIt is a breaking change to remove a negative impl. Negative impls are a commitment not to implement the given trait for the named types.\n\n## Orphan and overlap rules\n\nNegative impls must obey the same orphan rules as a positive impl. This implies you cannot add a negative impl for types defined in upstream crates and so forth.\n\nSimilarly, negative impls cannot overlap with positive impls, again using the same \"overlap\" check that we ordinarily use to determine if two impls overlap. (Note that positive impls typically cannot overlap with one another either, except as permitted by specialization.)\n\n## Interaction with auto traits\n\nDeclaring a negative impl `impl !SomeAutoTrait for SomeType` for an\nauto-trait serves two purposes:\n\n* as with any trait, it declares that `SomeType` will never implement `SomeAutoTrait`;\n* it disables the automatic `SomeType: SomeAutoTrait` impl that would otherwise have been generated.\n\nNote that, at present, there is no way to indicate that a given type\ndoes not implement an auto trait *but that it may do so in the\nfuture*. For ordinary types, this is done by simply not declaring any\nimpl at all, but that is not an option for auto traits. A workaround\nis that one could embed a marker type as one of the fields, where the\nmarker type is `!AutoTrait`.\n\n## Immediate uses\n\nNegative impls are used to declare that `&T: !DerefMut` and `&mut T: !Clone`, as required to fix the soundness of `Pin` described in [#66544](https://github.com/rust-lang/rust/issues/66544).\n\nThis serves two purposes:\n\n* For proving the correctness of unsafe code, we can use that impl as evidence that no `DerefMut` or `Clone` impl exists.\n* It prevents downstream crates from creating such impls.\n" } , LintCompletion { label : "c_variadic" , description : "# `c_variadic`\n\nThe tracking issue for this feature is: [#44930]\n\n[#44930]: https://github.com/rust-lang/rust/issues/44930\n\n------------------------\n\nThe `c_variadic` language feature enables C-variadic functions to be\ndefined in Rust. The may be called both from within Rust and via FFI.\n\n## Examples\n\n```rust\n#![feature(c_variadic)]\n\npub unsafe extern \"C\" fn add(n: usize, mut args: ...) -> usize {\n let mut sum = 0;\n for _ in 0..n {\n sum += args.arg::<usize>();\n }\n sum\n}\n```\n" } , LintCompletion { label : "profiler_runtime" , description : "# `profiler_runtime`\n\nThe tracking issue for this feature is: [#42524](https://github.com/rust-lang/rust/issues/42524).\n\n------------------------\n" } , LintCompletion { label : "box_syntax" , description : "# `box_syntax`\n\nThe tracking issue for this feature is: [#49733]\n\n[#49733]: https://github.com/rust-lang/rust/issues/49733\n\nSee also [`box_patterns`](box-patterns.md)\n\n------------------------\n\nCurrently the only stable way to create a `Box` is via the `Box::new` method.\nAlso it is not possible in stable Rust to destructure a `Box` in a match\npattern. The unstable `box` keyword can be used to create a `Box`. An example\nusage would be:\n\n```rust\n#![feature(box_syntax)]\n\nfn main() {\n let b = box 5;\n}\n```\n" } , LintCompletion { label : "ffi_pure" , description : "# `ffi_pure`\n\nThe tracking issue for this feature is: [#58329]\n\n------\n\nThe `#[ffi_pure]` attribute applies clang's `pure` attribute to foreign\nfunctions declarations.\n\nThat is, `#[ffi_pure]` functions shall have no effects except for its return\nvalue, which shall not change across two consecutive function calls with\nthe same parameters.\n\nApplying the `#[ffi_pure]` attribute to a function that violates these\nrequirements is undefined behavior.\n\nThis attribute enables Rust to perform common optimizations, like sub-expression\nelimination and loop optimizations. Some common examples of pure functions are\n`strlen` or `memcmp`.\n\nThese optimizations are only applicable when the compiler can prove that no\nprogram state observable by the `#[ffi_pure]` function has changed between calls\nof the function, which could alter the result. See also the `#[ffi_const]`\nattribute, which provides stronger guarantees regarding the allowable behavior\nof a function, enabling further optimization.\n\n## Pitfalls\n\nA `#[ffi_pure]` function can read global memory through the function\nparameters (e.g. pointers), globals, etc. `#[ffi_pure]` functions are not\nreferentially-transparent, and are therefore more relaxed than `#[ffi_const]`\nfunctions.\n\nHowever, accesing global memory through volatile or atomic reads can violate the\nrequirement that two consecutive function calls shall return the same value.\n\nA `pure` function that returns unit has no effect on the abstract machine's\nstate.\n\nA `#[ffi_pure]` function must not diverge, neither via a side effect (e.g. a\ncall to `abort`) nor by infinite loops.\n\nWhen translating C headers to Rust FFI, it is worth verifying for which targets\nthe `pure` attribute is enabled in those headers, and using the appropriate\n`cfg` macros in the Rust side to match those definitions. While the semantics of\n`pure` are implemented identically by many C and C++ compilers, e.g., clang,\n[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily\nimplemented in this way on all of them. It is therefore also worth verifying\nthat the semantics of the C toolchain used to compile the binary being linked\nagainst are compatible with those of the `#[ffi_pure]`.\n\n\n[#58329]: https://github.com/rust-lang/rust/issues/58329\n[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacigdac.html\n[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-pure-function-attribute\n[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_pure.htm\n" } , LintCompletion { label : "arbitrary_enum_discriminant" , description : "# `arbitrary_enum_discriminant`\n\nThe tracking issue for this feature is: [#60553]\n\n[#60553]: https://github.com/rust-lang/rust/issues/60553\n\n------------------------\n\nThe `arbitrary_enum_discriminant` feature permits tuple-like and\nstruct-like enum variants with `#[repr(<int-type>)]` to have explicit discriminants.\n\n## Examples\n\n```rust\n#![feature(arbitrary_enum_discriminant)]\n\n#[allow(dead_code)]\n#[repr(u8)]\nenum Enum {\n Unit = 3,\n Tuple(u16) = 2,\n Struct {\n a: u8,\n b: u16,\n } = 1,\n}\n\nimpl Enum {\n fn tag(&self) -> u8 {\n unsafe { *(self as *const Self as *const u8) }\n }\n}\n\nassert_eq!(3, Enum::Unit.tag());\nassert_eq!(2, Enum::Tuple(5).tag());\nassert_eq!(1, Enum::Struct{a: 7, b: 11}.tag());\n```\n" } , LintCompletion { label : "unsized_locals" , description : "# `unsized_locals`\n\nThe tracking issue for this feature is: [#48055]\n\n[#48055]: https://github.com/rust-lang/rust/issues/48055\n\n------------------------\n\nThis implements [RFC1909]. When turned on, you can have unsized arguments and locals:\n\n[RFC1909]: https://github.com/rust-lang/rfcs/blob/master/text/1909-unsized-rvalues.md\n\n```rust\n#![feature(unsized_locals)]\n\nuse std::any::Any;\n\nfn main() {\n let x: Box<dyn Any> = Box::new(42);\n let x: dyn Any = *x;\n // ^ unsized local variable\n // ^^ unsized temporary\n foo(x);\n}\n\nfn foo(_: dyn Any) {}\n// ^^^^^^ unsized argument\n```\n\nThe RFC still forbids the following unsized expressions:\n\n```rust,ignore\n#![feature(unsized_locals)]\n\nuse std::any::Any;\n\nstruct MyStruct<T: ?Sized> {\n content: T,\n}\n\nstruct MyTupleStruct<T: ?Sized>(T);\n\nfn answer() -> Box<dyn Any> {\n Box::new(42)\n}\n\nfn main() {\n // You CANNOT have unsized statics.\n static X: dyn Any = *answer(); // ERROR\n const Y: dyn Any = *answer(); // ERROR\n\n // You CANNOT have struct initialized unsized.\n MyStruct { content: *answer() }; // ERROR\n MyTupleStruct(*answer()); // ERROR\n (42, *answer()); // ERROR\n\n // You CANNOT have unsized return types.\n fn my_function() -> dyn Any { *answer() } // ERROR\n\n // You CAN have unsized local variables...\n let mut x: dyn Any = *answer(); // OK\n // ...but you CANNOT reassign to them.\n x = *answer(); // ERROR\n\n // You CANNOT even initialize them separately.\n let y: dyn Any; // OK\n y = *answer(); // ERROR\n\n // Not mentioned in the RFC, but by-move captured variables are also Sized.\n let x: dyn Any = *answer();\n (move || { // ERROR\n let y = x;\n })();\n\n // You CAN create a closure with unsized arguments,\n // but you CANNOT call it.\n // This is an implementation detail and may be changed in the future.\n let f = |x: dyn Any| {};\n f(*answer()); // ERROR\n}\n```\n\n## By-value trait objects\n\nWith this feature, you can have by-value `self` arguments without `Self: Sized` bounds.\n\n```rust\n#![feature(unsized_locals)]\n\ntrait Foo {\n fn foo(self) {}\n}\n\nimpl<T: ?Sized> Foo for T {}\n\nfn main() {\n let slice: Box<[i32]> = Box::new([1, 2, 3]);\n <[i32] as Foo>::foo(*slice);\n}\n```\n\nAnd `Foo` will also be object-safe.\n\n```rust\n#![feature(unsized_locals)]\n\ntrait Foo {\n fn foo(self) {}\n}\n\nimpl<T: ?Sized> Foo for T {}\n\nfn main () {\n let slice: Box<dyn Foo> = Box::new([1, 2, 3]);\n // doesn't compile yet\n <dyn Foo as Foo>::foo(*slice);\n}\n```\n\nOne of the objectives of this feature is to allow `Box<dyn FnOnce>`.\n\n## Variable length arrays\n\nThe RFC also describes an extension to the array literal syntax: `[e; dyn n]`. In the syntax, `n` isn't necessarily a constant expression. The array is dynamically allocated on the stack and has the type of `[T]`, instead of `[T; n]`.\n\n```rust,ignore\n#![feature(unsized_locals)]\n\nfn mergesort<T: Ord>(a: &mut [T]) {\n let mut tmp = [T; dyn a.len()];\n // ...\n}\n\nfn main() {\n let mut a = [3, 1, 5, 6];\n mergesort(&mut a);\n assert_eq!(a, [1, 3, 5, 6]);\n}\n```\n\nVLAs are not implemented yet. The syntax isn't final, either. We may need an alternative syntax for Rust 2015 because, in Rust 2015, expressions like `[e; dyn(1)]` would be ambiguous. One possible alternative proposed in the RFC is `[e; n]`: if `n` captures one or more local variables, then it is considered as `[e; dyn n]`.\n\n## Advisory on stack usage\n\nIt's advised not to casually use the `#![feature(unsized_locals)]` feature. Typical use-cases are:\n\n- When you need a by-value trait objects.\n- When you really need a fast allocation of small temporary arrays.\n\nAnother pitfall is repetitive allocation and temporaries. Currently the compiler simply extends the stack frame every time it encounters an unsized assignment. So for example, the code\n\n```rust\n#![feature(unsized_locals)]\n\nfn main() {\n let x: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);\n let _x = {{{{{{{{{{*x}}}}}}}}}};\n}\n```\n\nand the code\n\n```rust\n#![feature(unsized_locals)]\n\nfn main() {\n for _ in 0..10 {\n let x: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);\n let _x = *x;\n }\n}\n```\n\nwill unnecessarily extend the stack frame.\n" } , LintCompletion { label : "cfg_sanitize" , description : "# `cfg_sanitize`\n\nThe tracking issue for this feature is: [#39699]\n\n[#39699]: https://github.com/rust-lang/rust/issues/39699\n\n------------------------\n\nThe `cfg_sanitize` feature makes it possible to execute different code\ndepending on whether a particular sanitizer is enabled or not.\n\n## Examples\n\n```rust\n#![feature(cfg_sanitize)]\n\n#[cfg(sanitize = \"thread\")]\nfn a() {\n // ...\n}\n\n#[cfg(not(sanitize = \"thread\"))]\nfn a() {\n // ...\n}\n\nfn b() {\n if cfg!(sanitize = \"leak\") {\n // ...\n } else {\n // ...\n }\n}\n```\n" } , LintCompletion { label : "cmse_nonsecure_entry" , description : "# `cmse_nonsecure_entry`\n\nThe tracking issue for this feature is: [#75835]\n\n[#75835]: https://github.com/rust-lang/rust/issues/75835\n\n------------------------\n\nThe [TrustZone-M\nfeature](https://developer.arm.com/documentation/100690/latest/) is available\nfor targets with the Armv8-M architecture profile (`thumbv8m` in their target\nname).\nLLVM, the Rust compiler and the linker are providing\n[support](https://developer.arm.com/documentation/ecm0359818/latest/) for the\nTrustZone-M feature.\n\nOne of the things provided, with this unstable feature, is the\n`cmse_nonsecure_entry` attribute. This attribute marks a Secure function as an\nentry function (see [section\n5.4](https://developer.arm.com/documentation/ecm0359818/latest/) for details).\nWith this attribute, the compiler will do the following:\n* add a special symbol on the function which is the `__acle_se_` prefix and the\n standard function name\n* constrain the number of parameters to avoid using the Non-Secure stack\n* before returning from the function, clear registers that might contain Secure\n information\n* use the `BXNS` instruction to return\n\nBecause the stack can not be used to pass parameters, there will be compilation\nerrors if:\n* the total size of all parameters is too big (for example more than four 32\n bits integers)\n* the entry function is not using a C ABI\n\nThe special symbol `__acle_se_` will be used by the linker to generate a secure\ngateway veneer.\n\n<!-- NOTE(ignore) this example is specific to thumbv8m targets -->\n\n``` rust,ignore\n#![feature(cmse_nonsecure_entry)]\n\n#[no_mangle]\n#[cmse_nonsecure_entry]\npub extern \"C\" fn entry_function(input: u32) -> u32 {\n input + 6\n}\n```\n\n``` text\n$ rustc --emit obj --crate-type lib --target thumbv8m.main-none-eabi function.rs\n$ arm-none-eabi-objdump -D function.o\n\n00000000 <entry_function>:\n 0: b580 push {r7, lr}\n 2: 466f mov r7, sp\n 4: b082 sub sp, #8\n 6: 9001 str r0, [sp, #4]\n 8: 1d81 adds r1, r0, #6\n a: 460a mov r2, r1\n c: 4281 cmp r1, r0\n e: 9200 str r2, [sp, #0]\n 10: d30b bcc.n 2a <entry_function+0x2a>\n 12: e7ff b.n 14 <entry_function+0x14>\n 14: 9800 ldr r0, [sp, #0]\n 16: b002 add sp, #8\n 18: e8bd 4080 ldmia.w sp!, {r7, lr}\n 1c: 4671 mov r1, lr\n 1e: 4672 mov r2, lr\n 20: 4673 mov r3, lr\n 22: 46f4 mov ip, lr\n 24: f38e 8800 msr CPSR_f, lr\n 28: 4774 bxns lr\n 2a: f240 0000 movw r0, #0\n 2e: f2c0 0000 movt r0, #0\n 32: f240 0200 movw r2, #0\n 36: f2c0 0200 movt r2, #0\n 3a: 211c movs r1, #28\n 3c: f7ff fffe bl 0 <_ZN4core9panicking5panic17h5c028258ca2fb3f5E>\n 40: defe udf #254 ; 0xfe\n```\n" } , LintCompletion { label : "cfg_version" , description : "# `cfg_version`\n\nThe tracking issue for this feature is: [#64796]\n\n[#64796]: https://github.com/rust-lang/rust/issues/64796\n\n------------------------\n\nThe `cfg_version` feature makes it possible to execute different code\ndepending on the compiler version.\n\n## Examples\n\n```rust\n#![feature(cfg_version)]\n\n#[cfg(version(\"1.42\"))]\nfn a() {\n // ...\n}\n\n#[cfg(not(version(\"1.42\")))]\nfn a() {\n // ...\n}\n\nfn b() {\n if cfg!(version(\"1.42\")) {\n // ...\n } else {\n // ...\n }\n}\n```\n" } , LintCompletion { label : "unsized_tuple_coercion" , description : "# `unsized_tuple_coercion`\n\nThe tracking issue for this feature is: [#42877]\n\n[#42877]: https://github.com/rust-lang/rust/issues/42877\n\n------------------------\n\nThis is a part of [RFC0401]. According to the RFC, there should be an implementation like this:\n\n```rust,ignore\nimpl<..., T, U: ?Sized> Unsized<(..., U)> for (..., T) where T: Unsized<U> {}\n```\n\nThis implementation is currently gated behind `#[feature(unsized_tuple_coercion)]` to avoid insta-stability. Therefore you can use it like this:\n\n```rust\n#![feature(unsized_tuple_coercion)]\n\nfn main() {\n let x : ([i32; 3], [i32; 3]) = ([1, 2, 3], [4, 5, 6]);\n let y : &([i32; 3], [i32]) = &x;\n assert_eq!(y.1[0], 4);\n}\n```\n\n[RFC0401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md\n" } , LintCompletion { label : "generators" , description : "# `generators`\n\nThe tracking issue for this feature is: [#43122]\n\n[#43122]: https://github.com/rust-lang/rust/issues/43122\n\n------------------------\n\nThe `generators` feature gate in Rust allows you to define generator or\ncoroutine literals. A generator is a \"resumable function\" that syntactically\nresembles a closure but compiles to much different semantics in the compiler\nitself. The primary feature of a generator is that it can be suspended during\nexecution to be resumed at a later date. Generators use the `yield` keyword to\n\"return\", and then the caller can `resume` a generator to resume execution just\nafter the `yield` keyword.\n\nGenerators are an extra-unstable feature in the compiler right now. Added in\n[RFC 2033] they're mostly intended right now as a information/constraint\ngathering phase. The intent is that experimentation can happen on the nightly\ncompiler before actual stabilization. A further RFC will be required to\nstabilize generators/coroutines and will likely contain at least a few small\ntweaks to the overall design.\n\n[RFC 2033]: https://github.com/rust-lang/rfcs/pull/2033\n\nA syntactical example of a generator is:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::{Generator, GeneratorState};\nuse std::pin::Pin;\n\nfn main() {\n let mut generator = || {\n yield 1;\n return \"foo\"\n };\n\n match Pin::new(&mut generator).resume(()) {\n GeneratorState::Yielded(1) => {}\n _ => panic!(\"unexpected value from resume\"),\n }\n match Pin::new(&mut generator).resume(()) {\n GeneratorState::Complete(\"foo\") => {}\n _ => panic!(\"unexpected value from resume\"),\n }\n}\n```\n\nGenerators are closure-like literals which can contain a `yield` statement. The\n`yield` statement takes an optional expression of a value to yield out of the\ngenerator. All generator literals implement the `Generator` trait in the\n`std::ops` module. The `Generator` trait has one main method, `resume`, which\nresumes execution of the generator at the previous suspension point.\n\nAn example of the control flow of generators is that the following example\nprints all numbers in order:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::Generator;\nuse std::pin::Pin;\n\nfn main() {\n let mut generator = || {\n println!(\"2\");\n yield;\n println!(\"4\");\n };\n\n println!(\"1\");\n Pin::new(&mut generator).resume(());\n println!(\"3\");\n Pin::new(&mut generator).resume(());\n println!(\"5\");\n}\n```\n\nAt this time the main intended use case of generators is an implementation\nprimitive for async/await syntax, but generators will likely be extended to\nergonomic implementations of iterators and other primitives in the future.\nFeedback on the design and usage is always appreciated!\n\n### The `Generator` trait\n\nThe `Generator` trait in `std::ops` currently looks like:\n\n```rust\n# #![feature(arbitrary_self_types, generator_trait)]\n# use std::ops::GeneratorState;\n# use std::pin::Pin;\n\npub trait Generator<R = ()> {\n type Yield;\n type Return;\n fn resume(self: Pin<&mut Self>, resume: R) -> GeneratorState<Self::Yield, Self::Return>;\n}\n```\n\nThe `Generator::Yield` type is the type of values that can be yielded with the\n`yield` statement. The `Generator::Return` type is the returned type of the\ngenerator. This is typically the last expression in a generator's definition or\nany value passed to `return` in a generator. The `resume` function is the entry\npoint for executing the `Generator` itself.\n\nThe return value of `resume`, `GeneratorState`, looks like:\n\n```rust\npub enum GeneratorState<Y, R> {\n Yielded(Y),\n Complete(R),\n}\n```\n\nThe `Yielded` variant indicates that the generator can later be resumed. This\ncorresponds to a `yield` point in a generator. The `Complete` variant indicates\nthat the generator is complete and cannot be resumed again. Calling `resume`\nafter a generator has returned `Complete` will likely result in a panic of the\nprogram.\n\n### Closure-like semantics\n\nThe closure-like syntax for generators alludes to the fact that they also have\nclosure-like semantics. Namely:\n\n* When created, a generator executes no code. A closure literal does not\n actually execute any of the closure's code on construction, and similarly a\n generator literal does not execute any code inside the generator when\n constructed.\n\n* Generators can capture outer variables by reference or by move, and this can\n be tweaked with the `move` keyword at the beginning of the closure. Like\n closures all generators will have an implicit environment which is inferred by\n the compiler. Outer variables can be moved into a generator for use as the\n generator progresses.\n\n* Generator literals produce a value with a unique type which implements the\n `std::ops::Generator` trait. This allows actual execution of the generator\n through the `Generator::resume` method as well as also naming it in return\n types and such.\n\n* Traits like `Send` and `Sync` are automatically implemented for a `Generator`\n depending on the captured variables of the environment. Unlike closures,\n generators also depend on variables live across suspension points. This means\n that although the ambient environment may be `Send` or `Sync`, the generator\n itself may not be due to internal variables live across `yield` points being\n not-`Send` or not-`Sync`. Note that generators do\n not implement traits like `Copy` or `Clone` automatically.\n\n* Whenever a generator is dropped it will drop all captured environment\n variables.\n\n### Generators as state machines\n\nIn the compiler, generators are currently compiled as state machines. Each\n`yield` expression will correspond to a different state that stores all live\nvariables over that suspension point. Resumption of a generator will dispatch on\nthe current state and then execute internally until a `yield` is reached, at\nwhich point all state is saved off in the generator and a value is returned.\n\nLet's take a look at an example to see what's going on here:\n\n```rust\n#![feature(generators, generator_trait)]\n\nuse std::ops::Generator;\nuse std::pin::Pin;\n\nfn main() {\n let ret = \"foo\";\n let mut generator = move || {\n yield 1;\n return ret\n };\n\n Pin::new(&mut generator).resume(());\n Pin::new(&mut generator).resume(());\n}\n```\n\nThis generator literal will compile down to something similar to:\n\n```rust\n#![feature(arbitrary_self_types, generators, generator_trait)]\n\nuse std::ops::{Generator, GeneratorState};\nuse std::pin::Pin;\n\nfn main() {\n let ret = \"foo\";\n let mut generator = {\n enum __Generator {\n Start(&'static str),\n Yield1(&'static str),\n Done,\n }\n\n impl Generator for __Generator {\n type Yield = i32;\n type Return = &'static str;\n\n fn resume(mut self: Pin<&mut Self>, resume: ()) -> GeneratorState<i32, &'static str> {\n use std::mem;\n match mem::replace(&mut *self, __Generator::Done) {\n __Generator::Start(s) => {\n *self = __Generator::Yield1(s);\n GeneratorState::Yielded(1)\n }\n\n __Generator::Yield1(s) => {\n *self = __Generator::Done;\n GeneratorState::Complete(s)\n }\n\n __Generator::Done => {\n panic!(\"generator resumed after completion\")\n }\n }\n }\n }\n\n __Generator::Start(ret)\n };\n\n Pin::new(&mut generator).resume(());\n Pin::new(&mut generator).resume(());\n}\n```\n\nNotably here we can see that the compiler is generating a fresh type,\n`__Generator` in this case. This type has a number of states (represented here\nas an `enum`) corresponding to each of the conceptual states of the generator.\nAt the beginning we're closing over our outer variable `foo` and then that\nvariable is also live over the `yield` point, so it's stored in both states.\n\nWhen the generator starts it'll immediately yield 1, but it saves off its state\njust before it does so indicating that it has reached the yield point. Upon\nresuming again we'll execute the `return ret` which returns the `Complete`\nstate.\n\nHere we can also note that the `Done` state, if resumed, panics immediately as\nit's invalid to resume a completed generator. It's also worth noting that this\nis just a rough desugaring, not a normative specification for what the compiler\ndoes.\n" } , LintCompletion { label : "transparent_unions" , description : "# `transparent_unions`\n\nThe tracking issue for this feature is [#60405]\n\n[#60405]: https://github.com/rust-lang/rust/issues/60405\n\n----\n\nThe `transparent_unions` feature allows you mark `union`s as\n`#[repr(transparent)]`. A `union` may be `#[repr(transparent)]` in exactly the\nsame conditions in which a `struct` may be `#[repr(transparent)]` (generally,\nthis means the `union` must have exactly one non-zero-sized field). Some\nconcrete illustrations follow.\n\n```rust\n#![feature(transparent_unions)]\n\n// This union has the same representation as `f32`.\n#[repr(transparent)]\nunion SingleFieldUnion {\n field: f32,\n}\n\n// This union has the same representation as `usize`.\n#[repr(transparent)]\nunion MultiFieldUnion {\n field: usize,\n nothing: (),\n}\n```\n\nFor consistency with transparent `struct`s, `union`s must have exactly one\nnon-zero-sized field. If all fields are zero-sized, the `union` must not be\n`#[repr(transparent)]`:\n\n```rust\n#![feature(transparent_unions)]\n\n// This (non-transparent) union is already valid in stable Rust:\npub union GoodUnion {\n pub nothing: (),\n}\n\n// Error: transparent union needs exactly one non-zero-sized field, but has 0\n// #[repr(transparent)]\n// pub union BadUnion {\n// pub nothing: (),\n// }\n```\n\nThe one exception is if the `union` is generic over `T` and has a field of type\n`T`, it may be `#[repr(transparent)]` even if `T` is a zero-sized type:\n\n```rust\n#![feature(transparent_unions)]\n\n// This union has the same representation as `T`.\n#[repr(transparent)]\npub union GenericUnion<T: Copy> { // Unions with non-`Copy` fields are unstable.\n pub field: T,\n pub nothing: (),\n}\n\n// This is okay even though `()` is a zero-sized type.\npub const THIS_IS_OKAY: GenericUnion<()> = GenericUnion { field: () };\n```\n\nLike transarent `struct`s, a transparent `union` of type `U` has the same\nlayout, size, and ABI as its single non-ZST field. If it is generic over a type\n`T`, and all its fields are ZSTs except for exactly one field of type `T`, then\nit has the same layout and ABI as `T` (even if `T` is a ZST when monomorphized).\n\nLike transparent `struct`s, transparent `union`s are FFI-safe if and only if\ntheir underlying representation type is also FFI-safe.\n\nA `union` may not be eligible for the same nonnull-style optimizations that a\n`struct` or `enum` (with the same fields) are eligible for. Adding\n`#[repr(transparent)]` to `union` does not change this. To give a more concrete\nexample, it is unspecified whether `size_of::<T>()` is equal to\n`size_of::<Option<T>>()`, where `T` is a `union` (regardless of whether or not\nit is transparent). The Rust compiler is free to perform this optimization if\npossible, but is not required to, and different compiler versions may differ in\ntheir application of these optimizations.\n" } , LintCompletion { label : "plugin_registrar" , description : "# `plugin_registrar`\n\nThe tracking issue for this feature is: [#29597]\n\n[#29597]: https://github.com/rust-lang/rust/issues/29597\n\nThis feature is part of \"compiler plugins.\" It will often be used with the\n[`plugin`] and `rustc_private` features as well. For more details, see\ntheir docs.\n\n[`plugin`]: plugin.md\n\n------------------------\n" } , LintCompletion { label : "or_patterns" , description : "# `or_patterns`\n\nThe tracking issue for this feature is: [#54883]\n\n[#54883]: https://github.com/rust-lang/rust/issues/54883\n\n------------------------\n\nThe `or_pattern` language feature allows `|` to be arbitrarily nested within\na pattern, for example, `Some(A(0) | B(1 | 2))` becomes a valid pattern.\n\n## Examples\n\n```rust,ignore\n#![feature(or_patterns)]\n\npub enum Foo {\n Bar,\n Baz,\n Quux,\n}\n\npub fn example(maybe_foo: Option<Foo>) {\n match maybe_foo {\n Some(Foo::Bar | Foo::Baz) => {\n println!(\"The value contained `Bar` or `Baz`\");\n }\n Some(_) => {\n println!(\"The value did not contain `Bar` or `Baz`\");\n }\n None => {\n println!(\"The value was `None`\");\n }\n }\n}\n```\n" } , LintCompletion { label : "repr128" , description : "# `repr128`\n\nThe tracking issue for this feature is: [#56071]\n\n[#56071]: https://github.com/rust-lang/rust/issues/56071\n\n------------------------\n\nThe `repr128` feature adds support for `#[repr(u128)]` on `enum`s.\n\n```rust\n#![feature(repr128)]\n\n#[repr(u128)]\nenum Foo {\n Bar(u64),\n}\n```\n" } , LintCompletion { label : "unboxed_closures" , description : "# `unboxed_closures`\n\nThe tracking issue for this feature is [#29625]\n\nSee Also: [`fn_traits`](../library-features/fn-traits.md)\n\n[#29625]: https://github.com/rust-lang/rust/issues/29625\n\n----\n\nThe `unboxed_closures` feature allows you to write functions using the `\"rust-call\"` ABI,\nrequired for implementing the [`Fn*`] family of traits. `\"rust-call\"` functions must have \nexactly one (non self) argument, a tuple representing the argument list.\n\n[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html\n\n```rust\n#![feature(unboxed_closures)]\n\nextern \"rust-call\" fn add_args(args: (u32, u32)) -> u32 {\n args.0 + args.1\n}\n\nfn main() {}\n```\n" } , LintCompletion { label : "link_cfg" , description : "# `link_cfg`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "rustc_attrs" , description : "# `rustc_attrs`\n\nThis feature has no tracking issue, and is therefore internal to\nthe compiler, not being intended for general use.\n\nNote: `rustc_attrs` enables many rustc-internal attributes and this page\nonly discuss a few of them.\n\n------------------------\n\nThe `rustc_attrs` feature allows debugging rustc type layouts by using\n`#[rustc_layout(...)]` to debug layout at compile time (it even works\nwith `cargo check`) as an alternative to `rustc -Z print-type-sizes`\nthat is way more verbose.\n\nOptions provided by `#[rustc_layout(...)]` are `debug`, `size`, `align`,\n`abi`. Note that it only works on sized types without generics.\n\n## Examples\n\n```rust,ignore\n#![feature(rustc_attrs)]\n\n#[rustc_layout(abi, size)]\npub enum X {\n Y(u8, u8, u8),\n Z(isize),\n}\n```\n\nWhen that is compiled, the compiler will error with something like\n\n```text\nerror: abi: Aggregate { sized: true }\n --> src/lib.rs:4:1\n |\n4 | / pub enum T {\n5 | | Y(u8, u8, u8),\n6 | | Z(isize),\n7 | | }\n | |_^\n\nerror: size: Size { raw: 16 }\n --> src/lib.rs:4:1\n |\n4 | / pub enum T {\n5 | | Y(u8, u8, u8),\n6 | | Z(isize),\n7 | | }\n | |_^\n\nerror: aborting due to 2 previous errors\n```\n" } , LintCompletion { label : "box_patterns" , description : "# `box_patterns`\n\nThe tracking issue for this feature is: [#29641]\n\n[#29641]: https://github.com/rust-lang/rust/issues/29641\n\nSee also [`box_syntax`](box-syntax.md)\n\n------------------------\n\nBox patterns let you match on `Box<T>`s:\n\n\n```rust\n#![feature(box_patterns)]\n\nfn main() {\n let b = Some(Box::new(5));\n match b {\n Some(box n) if n < 0 => {\n println!(\"Box contains negative number {}\", n);\n },\n Some(box n) if n >= 0 => {\n println!(\"Box contains non-negative number {}\", n);\n },\n None => {\n println!(\"No box\");\n },\n _ => unreachable!()\n }\n}\n```\n" } , LintCompletion { label : "infer_static_outlives_requirements" , description : "# `infer_static_outlives_requirements`\n\nThe tracking issue for this feature is: [#54185]\n\n[#54185]: https://github.com/rust-lang/rust/issues/54185\n\n------------------------\nThe `infer_static_outlives_requirements` feature indicates that certain\n`'static` outlives requirements can be inferred by the compiler rather than\nstating them explicitly.\n\nNote: It is an accompanying feature to `infer_outlives_requirements`,\nwhich must be enabled to infer outlives requirements.\n\nFor example, currently generic struct definitions that contain\nreferences, require where-clauses of the form T: 'static. By using\nthis feature the outlives predicates will be inferred, although\nthey may still be written explicitly.\n\n```rust,ignore (pseudo-Rust)\nstruct Foo<U> where U: 'static { // <-- currently required\n bar: Bar<U>\n}\nstruct Bar<T: 'static> {\n x: T,\n}\n```\n\n\n## Examples:\n\n```rust,ignore (pseudo-Rust)\n#![feature(infer_outlives_requirements)]\n#![feature(infer_static_outlives_requirements)]\n\n#[rustc_outlives]\n// Implicitly infer U: 'static\nstruct Foo<U> {\n bar: Bar<U>\n}\nstruct Bar<T: 'static> {\n x: T,\n}\n```\n\n" } , LintCompletion { label : "trait_alias" , description : "# `trait_alias`\n\nThe tracking issue for this feature is: [#41517]\n\n[#41517]: https://github.com/rust-lang/rust/issues/41517\n\n------------------------\n\nThe `trait_alias` feature adds support for trait aliases. These allow aliases\nto be created for one or more traits (currently just a single regular trait plus\nany number of auto-traits), and used wherever traits would normally be used as\neither bounds or trait objects.\n\n```rust\n#![feature(trait_alias)]\n\ntrait Foo = std::fmt::Debug + Send;\ntrait Bar = Foo + Sync;\n\n// Use trait alias as bound on type parameter.\nfn foo<T: Foo>(v: &T) {\n println!(\"{:?}\", v);\n}\n\npub fn main() {\n foo(&1);\n\n // Use trait alias for trait objects.\n let a: &Bar = &123;\n println!(\"{:?}\", a);\n let b = Box::new(456) as Box<dyn Foo>;\n println!(\"{:?}\", b);\n}\n```\n" } , LintCompletion { label : "const_fn" , description : "# `const_fn`\n\nThe tracking issue for this feature is: [#57563]\n\n[#57563]: https://github.com/rust-lang/rust/issues/57563\n\n------------------------\n\nThe `const_fn` feature allows marking free functions and inherent methods as\n`const`, enabling them to be called in constants contexts, with constant\narguments.\n\n## Examples\n\n```rust\n#![feature(const_fn)]\n\nconst fn double(x: i32) -> i32 {\n x * 2\n}\n\nconst FIVE: i32 = 5;\nconst TEN: i32 = double(FIVE);\n\nfn main() {\n assert_eq!(5, FIVE);\n assert_eq!(10, TEN);\n}\n```\n" } , LintCompletion { label : "doc_cfg" , description : "# `doc_cfg`\n\nThe tracking issue for this feature is: [#43781]\n\n------\n\nThe `doc_cfg` feature allows an API be documented as only available in some specific platforms.\nThis attribute has two effects:\n\n1. In the annotated item's documentation, there will be a message saying \"This is supported on\n (platform) only\".\n\n2. The item's doc-tests will only run on the specific platform.\n\nIn addition to allowing the use of the `#[doc(cfg)]` attribute, this feature enables the use of a\nspecial conditional compilation flag, `#[cfg(doc)]`, set whenever building documentation on your\ncrate.\n\nThis feature was introduced as part of PR [#43348] to allow the platform-specific parts of the\nstandard library be documented.\n\n```rust\n#![feature(doc_cfg)]\n\n#[cfg(any(windows, doc))]\n#[doc(cfg(windows))]\n/// The application's icon in the notification area (a.k.a. system tray).\n///\n/// # Examples\n///\n/// ```no_run\n/// extern crate my_awesome_ui_library;\n/// use my_awesome_ui_library::current_app;\n/// use my_awesome_ui_library::windows::notification;\n///\n/// let icon = current_app().get::<notification::Icon>();\n/// icon.show();\n/// icon.show_message(\"Hello\");\n/// ```\npub struct Icon {\n // ...\n}\n```\n\n[#43781]: https://github.com/rust-lang/rust/issues/43781\n[#43348]: https://github.com/rust-lang/rust/issues/43348\n" } , LintCompletion { label : "allocator_internals" , description : "# `allocator_internals`\n\nThis feature does not have a tracking issue, it is an unstable implementation\ndetail of the `global_allocator` feature not intended for use outside the\ncompiler.\n\n------------------------\n" } , LintCompletion { label : "doc_masked" , description : "# `doc_masked`\n\nThe tracking issue for this feature is: [#44027]\n\n-----\n\nThe `doc_masked` feature allows a crate to exclude types from a given crate from appearing in lists\nof trait implementations. The specifics of the feature are as follows:\n\n1. When rustdoc encounters an `extern crate` statement annotated with a `#[doc(masked)]` attribute,\n it marks the crate as being masked.\n\n2. When listing traits a given type implements, rustdoc ensures that traits from masked crates are\n not emitted into the documentation.\n\n3. When listing types that implement a given trait, rustdoc ensures that types from masked crates\n are not emitted into the documentation.\n\nThis feature was introduced in PR [#44026] to ensure that compiler-internal and\nimplementation-specific types and traits were not included in the standard library's documentation.\nSuch types would introduce broken links into the documentation.\n\n[#44026]: https://github.com/rust-lang/rust/pull/44026\n[#44027]: https://github.com/rust-lang/rust/pull/44027\n" } , LintCompletion { label : "no_sanitize" , description : "# `no_sanitize`\n\nThe tracking issue for this feature is: [#39699]\n\n[#39699]: https://github.com/rust-lang/rust/issues/39699\n\n------------------------\n\nThe `no_sanitize` attribute can be used to selectively disable sanitizer\ninstrumentation in an annotated function. This might be useful to: avoid\ninstrumentation overhead in a performance critical function, or avoid\ninstrumenting code that contains constructs unsupported by given sanitizer.\n\nThe precise effect of this annotation depends on particular sanitizer in use.\nFor example, with `no_sanitize(thread)`, the thread sanitizer will no longer\ninstrument non-atomic store / load operations, but it will instrument atomic\noperations to avoid reporting false positives and provide meaning full stack\ntraces.\n\n## Examples\n\n``` rust\n#![feature(no_sanitize)]\n\n#[no_sanitize(address)]\nfn foo() {\n // ...\n}\n```\n" } , LintCompletion { label : "intrinsics" , description : "# `intrinsics`\n\nThe tracking issue for this feature is: None.\n\nIntrinsics are never intended to be stable directly, but intrinsics are often\nexported in some sort of stable manner. Prefer using the stable interfaces to\nthe intrinsic directly when you can.\n\n------------------------\n\n\nThese are imported as if they were FFI functions, with the special\n`rust-intrinsic` ABI. For example, if one was in a freestanding\ncontext, but wished to be able to `transmute` between types, and\nperform efficient pointer arithmetic, one would import those functions\nvia a declaration like\n\n```rust\n#![feature(intrinsics)]\n# fn main() {}\n\nextern \"rust-intrinsic\" {\n fn transmute<T, U>(x: T) -> U;\n\n fn offset<T>(dst: *const T, offset: isize) -> *const T;\n}\n```\n\nAs with any other FFI functions, these are always `unsafe` to call.\n\n" } , LintCompletion { label : "external_doc" , description : "# `external_doc`\n\nThe tracking issue for this feature is: [#44732]\n\nThe `external_doc` feature allows the use of the `include` parameter to the `#[doc]` attribute, to\ninclude external files in documentation. Use the attribute in place of, or in addition to, regular\ndoc comments and `#[doc]` attributes, and `rustdoc` will load the given file when it renders\ndocumentation for your crate.\n\nWith the following files in the same directory:\n\n`external-doc.md`:\n\n```markdown\n# My Awesome Type\n\nThis is the documentation for this spectacular type.\n```\n\n`lib.rs`:\n\n```no_run (needs-external-files)\n#![feature(external_doc)]\n\n#[doc(include = \"external-doc.md\")]\npub struct MyAwesomeType;\n```\n\n`rustdoc` will load the file `external-doc.md` and use it as the documentation for the `MyAwesomeType`\nstruct.\n\nWhen locating files, `rustdoc` will base paths in the `src/` directory, as if they were alongside the\n`lib.rs` for your crate. So if you want a `docs/` folder to live alongside the `src/` directory,\nstart your paths with `../docs/` for `rustdoc` to properly find the file.\n\nThis feature was proposed in [RFC #1990] and initially implemented in PR [#44781].\n\n[#44732]: https://github.com/rust-lang/rust/issues/44732\n[RFC #1990]: https://github.com/rust-lang/rfcs/pull/1990\n[#44781]: https://github.com/rust-lang/rust/pull/44781\n" } , LintCompletion { label : "inline_const" , description : "# `inline_const`\n\nThe tracking issue for this feature is: [#76001]\n\n------\n\nThis feature allows you to use inline constant expressions. For example, you can\nturn this code:\n\n```rust\n# fn add_one(x: i32) -> i32 { x + 1 }\nconst MY_COMPUTATION: i32 = 1 + 2 * 3 / 4;\n\nfn main() {\n let x = add_one(MY_COMPUTATION);\n}\n```\n\ninto this code:\n\n```rust\n#![feature(inline_const)]\n\n# fn add_one(x: i32) -> i32 { x + 1 }\nfn main() {\n let x = add_one(const { 1 + 2 * 3 / 4 });\n}\n```\n\nYou can also use inline constant expressions in patterns:\n\n```rust\n#![feature(inline_const)]\n\nconst fn one() -> i32 { 1 }\n\nlet some_int = 3;\nmatch some_int {\n const { 1 + 2 } => println!(\"Matched 1 + 2\"),\n const { one() } => println!(\"Matched const fn returning 1\"),\n _ => println!(\"Didn't match anything :(\"),\n}\n```\n\n[#76001]: https://github.com/rust-lang/rust/issues/76001\n" } , LintCompletion { label : "abi_thiscall" , description : "# `abi_thiscall`\n\nThe tracking issue for this feature is: [#42202]\n\n[#42202]: https://github.com/rust-lang/rust/issues/42202\n\n------------------------\n\nThe MSVC ABI on x86 Windows uses the `thiscall` calling convention for C++\ninstance methods by default; it is identical to the usual (C) calling\nconvention on x86 Windows except that the first parameter of the method,\nthe `this` pointer, is passed in the ECX register.\n" } , LintCompletion { label : "plugin" , description : "# `plugin`\n\nThe tracking issue for this feature is: [#29597]\n\n[#29597]: https://github.com/rust-lang/rust/issues/29597\n\n\nThis feature is part of \"compiler plugins.\" It will often be used with the\n[`plugin_registrar`] and `rustc_private` features.\n\n[`plugin_registrar`]: plugin-registrar.md\n\n------------------------\n\n`rustc` can load compiler plugins, which are user-provided libraries that\nextend the compiler's behavior with new lint checks, etc.\n\nA plugin is a dynamic library crate with a designated *registrar* function that\nregisters extensions with `rustc`. Other crates can load these extensions using\nthe crate attribute `#![plugin(...)]`. See the\n`rustc_driver::plugin` documentation for more about the\nmechanics of defining and loading a plugin.\n\nIn the vast majority of cases, a plugin should *only* be used through\n`#![plugin]` and not through an `extern crate` item. Linking a plugin would\npull in all of librustc_ast and librustc as dependencies of your crate. This is\ngenerally unwanted unless you are building another plugin.\n\nThe usual practice is to put compiler plugins in their own crate, separate from\nany `macro_rules!` macros or ordinary Rust code meant to be used by consumers\nof a library.\n\n# Lint plugins\n\nPlugins can extend [Rust's lint\ninfrastructure](../../reference/attributes/diagnostics.md#lint-check-attributes) with\nadditional checks for code style, safety, etc. Now let's write a plugin\n[`lint-plugin-test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui-fulldeps/auxiliary/lint-plugin-test.rs)\nthat warns about any item named `lintme`.\n\n```rust,ignore\n#![feature(plugin_registrar)]\n#![feature(box_syntax, rustc_private)]\n\nextern crate rustc_ast;\n\n// Load rustc as a plugin to get macros\nextern crate rustc_driver;\n#[macro_use]\nextern crate rustc_lint;\n#[macro_use]\nextern crate rustc_session;\n\nuse rustc_driver::plugin::Registry;\nuse rustc_lint::{EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};\nuse rustc_ast::ast;\ndeclare_lint!(TEST_LINT, Warn, \"Warn about items named 'lintme'\");\n\ndeclare_lint_pass!(Pass => [TEST_LINT]);\n\nimpl EarlyLintPass for Pass {\n fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {\n if it.ident.name.as_str() == \"lintme\" {\n cx.lint(TEST_LINT, |lint| {\n lint.build(\"item is named 'lintme'\").set_span(it.span).emit()\n });\n }\n }\n}\n\n#[plugin_registrar]\npub fn plugin_registrar(reg: &mut Registry) {\n reg.lint_store.register_lints(&[&TEST_LINT]);\n reg.lint_store.register_early_pass(|| box Pass);\n}\n```\n\nThen code like\n\n```rust,ignore\n#![feature(plugin)]\n#![plugin(lint_plugin_test)]\n\nfn lintme() { }\n```\n\nwill produce a compiler warning:\n\n```txt\nfoo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default\nfoo.rs:4 fn lintme() { }\n ^~~~~~~~~~~~~~~\n```\n\nThe components of a lint plugin are:\n\n* one or more `declare_lint!` invocations, which define static `Lint` structs;\n\n* a struct holding any state needed by the lint pass (here, none);\n\n* a `LintPass`\n implementation defining how to check each syntax element. A single\n `LintPass` may call `span_lint` for several different `Lint`s, but should\n register them all through the `get_lints` method.\n\nLint passes are syntax traversals, but they run at a late stage of compilation\nwhere type information is available. `rustc`'s [built-in\nlints](https://github.com/rust-lang/rust/blob/master/src/librustc_session/lint/builtin.rs)\nmostly use the same infrastructure as lint plugins, and provide examples of how\nto access type information.\n\nLints defined by plugins are controlled by the usual [attributes and compiler\nflags](../../reference/attributes/diagnostics.md#lint-check-attributes), e.g.\n`#[allow(test_lint)]` or `-A test-lint`. These identifiers are derived from the\nfirst argument to `declare_lint!`, with appropriate case and punctuation\nconversion.\n\nYou can run `rustc -W help foo.rs` to see a list of lints known to `rustc`,\nincluding those provided by plugins loaded by `foo.rs`.\n" } , LintCompletion { label : "optin_builtin_traits" , description : "# `optin_builtin_traits`\n\nThe tracking issue for this feature is [#13231] \n\n[#13231]: https://github.com/rust-lang/rust/issues/13231\n\n----\n\nThe `optin_builtin_traits` feature gate allows you to define auto traits.\n\nAuto traits, like [`Send`] or [`Sync`] in the standard library, are marker traits\nthat are automatically implemented for every type, unless the type, or a type it contains, \nhas explicitly opted out via a negative impl. (Negative impls are separately controlled\nby the `negative_impls` feature.)\n\n[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html\n[`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html\n\n```rust,ignore\nimpl !Trait for Type\n```\n\nExample:\n\n```rust\n#![feature(negative_impls)]\n#![feature(optin_builtin_traits)]\n\nauto trait Valid {}\n\nstruct True;\nstruct False;\n\nimpl !Valid for False {}\n\nstruct MaybeValid<T>(T);\n\nfn must_be_valid<T: Valid>(_t: T) { }\n\nfn main() {\n // works\n must_be_valid( MaybeValid(True) );\n \n // compiler error - trait bound not satisfied\n // must_be_valid( MaybeValid(False) );\n}\n```\n\n## Automatic trait implementations\n\nWhen a type is declared as an `auto trait`, we will automatically\ncreate impls for every struct/enum/union, unless an explicit impl is\nprovided. These automatic impls contain a where clause for each field\nof the form `T: AutoTrait`, where `T` is the type of the field and\n`AutoTrait` is the auto trait in question. As an example, consider the\nstruct `List` and the auto trait `Send`:\n\n```rust\nstruct List<T> {\n data: T,\n next: Option<Box<List<T>>>,\n}\n```\n\nPresuming that there is no explicit impl of `Send` for `List`, the\ncompiler will supply an automatic impl of the form:\n\n```rust\nstruct List<T> {\n data: T,\n next: Option<Box<List<T>>>,\n}\n\nunsafe impl<T> Send for List<T>\nwhere\n T: Send, // from the field `data`\n Option<Box<List<T>>>: Send, // from the field `next`\n{ }\n```\n\nExplicit impls may be either positive or negative. They take the form:\n\n```rust,ignore\nimpl<...> AutoTrait for StructName<..> { }\nimpl<...> !AutoTrait for StructName<..> { }\n```\n\n## Coinduction: Auto traits permit cyclic matching\n\nUnlike ordinary trait matching, auto traits are **coinductive**. This\nmeans, in short, that cycles which occur in trait matching are\nconsidered ok. As an example, consider the recursive struct `List`\nintroduced in the previous section. In attempting to determine whether\n`List: Send`, we would wind up in a cycle: to apply the impl, we must\nshow that `Option<Box<List>>: Send`, which will in turn require\n`Box<List>: Send` and then finally `List: Send` again. Under ordinary\ntrait matching, this cycle would be an error, but for an auto trait it\nis considered a successful match.\n\n## Items\n\nAuto traits cannot have any trait items, such as methods or associated types. This ensures that we can generate default implementations.\n\n## Supertraits\n\nAuto traits cannot have supertraits. This is for soundness reasons, as the interaction of coinduction with implied bounds is difficult to reconcile.\n\n" } , LintCompletion { label : "impl_trait_in_bindings" , description : "# `impl_trait_in_bindings`\n\nThe tracking issue for this feature is: [#63065]\n\n[#63065]: https://github.com/rust-lang/rust/issues/63065\n\n------------------------\n\nThe `impl_trait_in_bindings` feature gate lets you use `impl Trait` syntax in\n`let`, `static`, and `const` bindings.\n\nA simple example is:\n\n```rust\n#![feature(impl_trait_in_bindings)]\n\nuse std::fmt::Debug;\n\nfn main() {\n let a: impl Debug + Clone = 42;\n let b = a.clone();\n println!(\"{:?}\", b); // prints `42`\n}\n```\n\nNote however that because the types of `a` and `b` are opaque in the above\nexample, calling inherent methods or methods outside of the specified traits\n(e.g., `a.abs()` or `b.abs()`) is not allowed, and yields an error.\n" } , LintCompletion { label : "abi_ptx" , description : "# `abi_ptx`\n\nThe tracking issue for this feature is: [#38788]\n\n[#38788]: https://github.com/rust-lang/rust/issues/38788\n\n------------------------\n\nWhen emitting PTX code, all vanilla Rust functions (`fn`) get translated to\n\"device\" functions. These functions are *not* callable from the host via the\nCUDA API so a crate with only device functions is not too useful!\n\nOTOH, \"global\" functions *can* be called by the host; you can think of them\nas the real public API of your crate. To produce a global function use the\n`\"ptx-kernel\"` ABI.\n\n<!-- NOTE(ignore) this example is specific to the nvptx targets -->\n\n``` rust,ignore\n#![feature(abi_ptx)]\n#![no_std]\n\npub unsafe extern \"ptx-kernel\" fn global_function() {\n device_function();\n}\n\npub fn device_function() {\n // ..\n}\n```\n\n``` text\n$ xargo rustc --target nvptx64-nvidia-cuda --release -- --emit=asm\n\n$ cat $(find -name '*.s')\n//\n// Generated by LLVM NVPTX Back-End\n//\n\n.version 3.2\n.target sm_20\n.address_size 64\n\n // .globl _ZN6kernel15global_function17h46111ebe6516b382E\n\n.visible .entry _ZN6kernel15global_function17h46111ebe6516b382E()\n{\n\n\n ret;\n}\n\n // .globl _ZN6kernel15device_function17hd6a0e4993bbf3f78E\n.visible .func _ZN6kernel15device_function17hd6a0e4993bbf3f78E()\n{\n\n\n ret;\n}\n```\n" } , LintCompletion { label : "dec2flt" , description : "# `dec2flt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "int_error_internals" , description : "# `int_error_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "llvm_asm" , description : "# `llvm_asm`\n\nThe tracking issue for this feature is: [#70173]\n\n[#70173]: https://github.com/rust-lang/rust/issues/70173\n\n------------------------\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `llvm_asm!` macro.\n\n```rust,ignore\nllvm_asm!(assembly template\n : output operands\n : input operands\n : clobbers\n : options\n );\n```\n\nAny use of `llvm_asm` is feature gated (requires `#![feature(llvm_asm)]` on the\ncrate to allow) and of course requires an `unsafe` block.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but\n> all platforms are supported.\n\n## Assembly template\n\nThe `assembly template` is the only required parameter and must be a\nliteral string (i.e. `\"\"`)\n\n```rust\n#![feature(llvm_asm)]\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn foo() {\n unsafe {\n llvm_asm!(\"NOP\");\n }\n}\n\n// Other platforms:\n#[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\nfn foo() { /* ... */ }\n\nfn main() {\n // ...\n foo();\n // ...\n}\n```\n\n(The `feature(llvm_asm)` and `#[cfg]`s are omitted from now on.)\n\nOutput operands, input operands, clobbers and options are all optional\nbut you must add the right number of `:` if you skip them:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nllvm_asm!(\"xor %eax, %eax\"\n :\n :\n : \"eax\"\n );\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nWhitespace also doesn't matter:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\nllvm_asm!(\"xor %eax, %eax\" ::: \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## Operands\n\nInput and output operands follow the same format: `:\n\"constraints1\"(expr1), \"constraints2\"(expr2), ...\"`. Output operand\nexpressions must be mutable place, or not yet assigned:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\nfn add(a: i32, b: i32) -> i32 {\n let c: i32;\n unsafe {\n llvm_asm!(\"add $2, $0\"\n : \"=r\"(c)\n : \"0\"(a), \"r\"(b)\n );\n }\n c\n}\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn add(a: i32, b: i32) -> i32 { a + b }\n\nfn main() {\n assert_eq!(add(3, 14159), 14162)\n}\n```\n\nIf you would like to use real operands in this position, however,\nyou are required to put curly braces `{}` around the register that\nyou want, and you are required to put the specific size of the\noperand. This is useful for very low level programming, where\nwhich register you use is important:\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# unsafe fn read_byte_in(port: u16) -> u8 {\nlet result: u8;\nllvm_asm!(\"in %dx, %al\" : \"={al}\"(result) : \"{dx}\"(port));\nresult\n# }\n```\n\n## Clobbers\n\nSome instructions modify registers which might otherwise have held\ndifferent values so we use the clobbers list to indicate to the\ncompiler not to assume any values loaded into those registers will\nstay valid.\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() { unsafe {\n// Put the value 0x200 in eax:\nllvm_asm!(\"mov $$0x200, %eax\" : /* no outputs */ : /* no inputs */ : \"eax\");\n# } }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\nInput and output registers need not be listed since that information\nis already communicated by the given constraints. Otherwise, any other\nregisters used either implicitly or explicitly should be listed.\n\nIf the assembly changes the condition code register `cc` should be\nspecified as one of the clobbers. Similarly, if the assembly modifies\nmemory, `memory` should also be specified.\n\n## Options\n\nThe last section, `options` is specific to Rust. The format is comma\nseparated literal strings (i.e. `:\"foo\", \"bar\", \"baz\"`). It's used to\nspecify some extra info about the inline assembly:\n\nCurrent valid options are:\n\n1. `volatile` - specifying this is analogous to\n `__asm__ __volatile__ (...)` in gcc/clang.\n2. `alignstack` - certain instructions expect the stack to be\n aligned a certain way (i.e. SSE) and specifying this indicates to\n the compiler to insert its usual stack alignment code\n3. `intel` - use intel syntax instead of the default AT&T.\n\n```rust\n# #![feature(llvm_asm)]\n# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n# fn main() {\nlet result: i32;\nunsafe {\n llvm_asm!(\"mov eax, 2\" : \"={eax}\"(result) : : : \"intel\")\n}\nprintln!(\"eax is currently {}\", result);\n# }\n# #[cfg(not(any(target_arch = \"x86\", target_arch = \"x86_64\")))]\n# fn main() {}\n```\n\n## More Information\n\nThe current implementation of the `llvm_asm!` macro is a direct binding to [LLVM's\ninline assembler expressions][llvm-docs], so be sure to check out [their\ndocumentation as well][llvm-docs] for more information about clobbers,\nconstraints, etc.\n\n[llvm-docs]: http://llvm.org/docs/LangRef.html#inline-assembler-expressions\n\nIf you need more power and don't mind losing some of the niceties of\n`llvm_asm!`, check out [global_asm](global-asm.md).\n" } , LintCompletion { label : "default_free_fn" , description : "# `default_free_fn`\n\nThe tracking issue for this feature is: [#73014]\n\n[#73014]: https://github.com/rust-lang/rust/issues/73014\n\n------------------------\n\nAdds a free `default()` function to the `std::default` module. This function\njust forwards to [`Default::default()`], but may remove repetition of the word\n\"default\" from the call site.\n\n[`Default::default()`]: https://doc.rust-lang.org/nightly/std/default/trait.Default.html#tymethod.default\n\nHere is an example:\n\n```rust\n#![feature(default_free_fn)]\nuse std::default::default;\n\n#[derive(Default)]\nstruct AppConfig {\n foo: FooConfig,\n bar: BarConfig,\n}\n\n#[derive(Default)]\nstruct FooConfig {\n foo: i32,\n}\n\n#[derive(Default)]\nstruct BarConfig {\n bar: f32,\n baz: u8,\n}\n\nfn main() {\n let options = AppConfig {\n foo: default(),\n bar: BarConfig {\n bar: 10.1,\n ..default()\n },\n };\n}\n```\n" } , LintCompletion { label : "libstd_thread_internals" , description : "# `libstd_thread_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "char_error_internals" , description : "# `char_error_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_handle" , description : "# `windows_handle`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "global_asm" , description : "# `global_asm`\n\nThe tracking issue for this feature is: [#35119]\n\n[#35119]: https://github.com/rust-lang/rust/issues/35119\n\n------------------------\n\nThe `global_asm!` macro allows the programmer to write arbitrary\nassembly outside the scope of a function body, passing it through\n`rustc` and `llvm` to the assembler. The macro is a no-frills\ninterface to LLVM's concept of [module-level inline assembly]. That is,\nall caveats applicable to LLVM's module-level inline assembly apply\nto `global_asm!`.\n\n[module-level inline assembly]: http://llvm.org/docs/LangRef.html#module-level-inline-assembly\n\n`global_asm!` fills a role not currently satisfied by either `asm!`\nor `#[naked]` functions. The programmer has _all_ features of the\nassembler at their disposal. The linker will expect to resolve any\nsymbols defined in the inline assembly, modulo any symbols marked as\nexternal. It also means syntax for directives and assembly follow the\nconventions of the assembler in your toolchain.\n\nA simple usage looks like this:\n\n```rust,ignore\n# #![feature(global_asm)]\n# you also need relevant target_arch cfgs\nglobal_asm!(include_str!(\"something_neato.s\"));\n```\n\nAnd a more complicated usage looks like this:\n\n```rust,ignore\n# #![feature(global_asm)]\n# #![cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\n\npub mod sally {\n global_asm!(r#\"\n .global foo\n foo:\n jmp baz\n \"#);\n\n #[no_mangle]\n pub unsafe extern \"C\" fn baz() {}\n}\n\n// the symbols `foo` and `bar` are global, no matter where\n// `global_asm!` was used.\nextern \"C\" {\n fn foo();\n fn bar();\n}\n\npub mod harry {\n global_asm!(r#\"\n .global bar\n bar:\n jmp quux\n \"#);\n\n #[no_mangle]\n pub unsafe extern \"C\" fn quux() {}\n}\n```\n\nYou may use `global_asm!` multiple times, anywhere in your crate, in\nwhatever way suits you. The effect is as if you concatenated all\nusages and placed the larger, single usage in the crate root.\n\n------------------------\n\nIf you don't need quite as much power and flexibility as\n`global_asm!` provides, and you don't mind restricting your inline\nassembly to `fn` bodies only, you might try the\n[asm](asm.md) feature instead.\n" } , LintCompletion { label : "windows_c" , description : "# `windows_c`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "asm" , description : "# `asm`\n\nThe tracking issue for this feature is: [#72016]\n\n[#72016]: https://github.com/rust-lang/rust/issues/72016\n\n------------------------\n\nFor extremely low-level manipulations and performance reasons, one\nmight wish to control the CPU directly. Rust supports using inline\nassembly to do this via the `asm!` macro.\n\n# Guide-level explanation\n[guide-level-explanation]: #guide-level-explanation\n\nRust provides support for inline assembly via the `asm!` macro.\nIt can be used to embed handwritten assembly in the assembly output generated by the compiler.\nGenerally this should not be necessary, but might be where the required performance or timing\ncannot be otherwise achieved. Accessing low level hardware primitives, e.g. in kernel code, may also demand this functionality.\n\n> **Note**: the examples here are given in x86/x86-64 assembly, but other architectures are also supported.\n\nInline assembly is currently supported on the following architectures:\n- x86 and x86-64\n- ARM\n- AArch64\n- RISC-V\n- NVPTX\n- Hexagon\n- MIPS32r2 and MIPS64r2\n\n## Basic usage\n\nLet us start with the simplest possible example:\n\n```rust,allow_fail\n# #![feature(asm)]\nunsafe {\n asm!(\"nop\");\n}\n```\n\nThis will insert a NOP (no operation) instruction into the assembly generated by the compiler.\nNote that all `asm!` invocations have to be inside an `unsafe` block, as they could insert\narbitrary instructions and break various invariants. The instructions to be inserted are listed\nin the first argument of the `asm!` macro as a string literal.\n\n## Inputs and outputs\n\nNow inserting an instruction that does nothing is rather boring. Let us do something that\nactually acts on data:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet x: u64;\nunsafe {\n asm!(\"mov {}, 5\", out(reg) x);\n}\nassert_eq!(x, 5);\n```\n\nThis will write the value `5` into the `u64` variable `x`.\nYou can see that the string literal we use to specify instructions is actually a template string.\nIt is governed by the same rules as Rust [format strings][format-syntax].\nThe arguments that are inserted into the template however look a bit different then you may\nbe familiar with. First we need to specify if the variable is an input or an output of the\ninline assembly. In this case it is an output. We declared this by writing `out`.\nWe also need to specify in what kind of register the assembly expects the variable.\nIn this case we put it in an arbitrary general purpose register by specifying `reg`.\nThe compiler will choose an appropriate register to insert into\nthe template and will read the variable from there after the inline assembly finishes executing.\n\nLet us see another example that also uses an input:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet i: u64 = 3;\nlet o: u64;\nunsafe {\n asm!(\n \"mov {0}, {1}\",\n \"add {0}, {number}\",\n out(reg) o,\n in(reg) i,\n number = const 5,\n );\n}\nassert_eq!(o, 8);\n```\n\nThis will add `5` to the input in variable `i` and write the result to variable `o`.\nThe particular way this assembly does this is first copying the value from `i` to the output,\nand then adding `5` to it.\n\nThe example shows a few things:\n\nFirst, we can see that `asm!` allows multiple template string arguments; each\none is treated as a separate line of assembly code, as if they were all joined\ntogether with newlines between them. This makes it easy to format assembly\ncode.\n\nSecond, we can see that inputs are declared by writing `in` instead of `out`.\n\nThird, one of our operands has a type we haven't seen yet, `const`.\nThis tells the compiler to expand this argument to value directly inside the assembly template.\nThis is only possible for constants and literals.\n\nFourth, we can see that we can specify an argument number, or name as in any format string.\nFor inline assembly templates this is particularly useful as arguments are often used more than once.\nFor more complex inline assembly using this facility is generally recommended, as it improves\nreadability, and allows reordering instructions without changing the argument order.\n\nWe can further refine the above example to avoid the `mov` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut x: u64 = 3;\nunsafe {\n asm!(\"add {0}, {number}\", inout(reg) x, number = const 5);\n}\nassert_eq!(x, 8);\n```\n\nWe can see that `inout` is used to specify an argument that is both input and output.\nThis is different from specifying an input and output separately in that it is guaranteed to assign both to the same register.\n\nIt is also possible to specify different variables for the input and output parts of an `inout` operand:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet x: u64 = 3;\nlet y: u64;\nunsafe {\n asm!(\"add {0}, {number}\", inout(reg) x => y, number = const 5);\n}\nassert_eq!(y, 8);\n```\n\n## Late output operands\n\nThe Rust compiler is conservative with its allocation of operands. It is assumed that an `out`\ncan be written at any time, and can therefore not share its location with any other argument.\nHowever, to guarantee optimal performance it is important to use as few registers as possible,\nso they won't have to be saved and reloaded around the inline assembly block.\nTo achieve this Rust provides a `lateout` specifier. This can be used on any output that is\nwritten only after all inputs have been consumed.\nThere is also a `inlateout` variant of this specifier.\n\nHere is an example where `inlateout` *cannot* be used:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nlet c: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n \"add {0}, {2}\",\n inout(reg) a,\n in(reg) b,\n in(reg) c,\n );\n}\nassert_eq!(a, 12);\n```\n\nHere the compiler is free to allocate the same register for inputs `b` and `c` since it knows they have the same value. However it must allocate a separate register for `a` since it uses `inout` and not `inlateout`. If `inlateout` was used, then `a` and `c` could be allocated to the same register, in which case the first instruction to overwrite the value of `c` and cause the assembly code to produce the wrong result.\n\nHowever the following example can use `inlateout` since the output is only modified after all input registers have been read:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\"add {0}, {1}\", inlateout(reg) a, in(reg) b);\n}\nassert_eq!(a, 8);\n```\n\nAs you can see, this assembly fragment will still work correctly if `a` and `b` are assigned to the same register.\n\n## Explicit register operands\n\nSome instructions require that the operands be in a specific register.\nTherefore, Rust inline assembly provides some more specific constraint specifiers.\nWhile `reg` is generally available on any architecture, these are highly architecture specific. E.g. for x86 the general purpose registers `eax`, `ebx`, `ecx`, `edx`, `ebp`, `esi`, and `edi`\namong others can be addressed by their name.\n\n```rust,allow_fail,no_run\n# #![feature(asm)]\nlet cmd = 0xd1;\nunsafe {\n asm!(\"out 0x64, eax\", in(\"eax\") cmd);\n}\n```\n\nIn this example we call the `out` instruction to output the content of the `cmd` variable\nto port `0x64`. Since the `out` instruction only accepts `eax` (and its sub registers) as operand\nwe had to use the `eax` constraint specifier.\n\nNote that unlike other operand types, explicit register operands cannot be used in the template string: you can't use `{}` and should write the register name directly instead. Also, they must appear at the end of the operand list after all other operand types.\n\nConsider this example which uses the x86 `mul` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nfn mul(a: u64, b: u64) -> u128 {\n let lo: u64;\n let hi: u64;\n\n unsafe {\n asm!(\n // The x86 mul instruction takes rax as an implicit input and writes\n // the 128-bit result of the multiplication to rax:rdx.\n \"mul {}\",\n in(reg) a,\n inlateout(\"rax\") b => lo,\n lateout(\"rdx\") hi\n );\n }\n\n ((hi as u128) << 64) + lo as u128\n}\n```\n\nThis uses the `mul` instruction to multiply two 64-bit inputs with a 128-bit result.\nThe only explicit operand is a register, that we fill from the variable `a`.\nThe second operand is implicit, and must be the `rax` register, which we fill from the variable `b`.\nThe lower 64 bits of the result are stored in `rax` from which we fill the variable `lo`.\nThe higher 64 bits are stored in `rdx` from which we fill the variable `hi`.\n\n## Clobbered registers\n\nIn many cases inline assembly will modify state that is not needed as an output.\nUsually this is either because we have to use a scratch register in the assembly,\nor instructions modify state that we don't need to further examine.\nThis state is generally referred to as being \"clobbered\".\nWe need to tell the compiler about this since it may need to save and restore this state\naround the inline assembly block.\n\n```rust,allow_fail\n# #![feature(asm)]\nlet ebx: u32;\nlet ecx: u32;\n\nunsafe {\n asm!(\n \"cpuid\",\n // EAX 4 selects the \"Deterministic Cache Parameters\" CPUID leaf\n inout(\"eax\") 4 => _,\n // ECX 0 selects the L0 cache information.\n inout(\"ecx\") 0 => ecx,\n lateout(\"ebx\") ebx,\n lateout(\"edx\") _,\n );\n}\n\nprintln!(\n \"L1 Cache: {}\",\n ((ebx >> 22) + 1) * (((ebx >> 12) & 0x3ff) + 1) * ((ebx & 0xfff) + 1) * (ecx + 1)\n);\n```\n\nIn the example above we use the `cpuid` instruction to get the L1 cache size.\nThis instruction writes to `eax`, `ebx`, `ecx`, and `edx`, but for the cache size we only care about the contents of `ebx` and `ecx`.\n\nHowever we still need to tell the compiler that `eax` and `edx` have been modified so that it can save any values that were in these registers before the asm. This is done by declaring these as outputs but with `_` instead of a variable name, which indicates that the output value is to be discarded.\n\nThis can also be used with a general register class (e.g. `reg`) to obtain a scratch register for use inside the asm code:\n\n```rust,allow_fail\n# #![feature(asm)]\n// Multiply x by 6 using shifts and adds\nlet mut x: u64 = 4;\nunsafe {\n asm!(\n \"mov {tmp}, {x}\",\n \"shl {tmp}, 1\",\n \"shl {x}, 2\",\n \"add {x}, {tmp}\",\n x = inout(reg) x,\n tmp = out(reg) _,\n );\n}\nassert_eq!(x, 4 * 6);\n```\n\n## Symbol operands\n\nA special operand type, `sym`, allows you to use the symbol name of a `fn` or `static` in inline assembly code.\nThis allows you to call a function or access a global variable without needing to keep its address in a register.\n\n```rust,allow_fail\n# #![feature(asm)]\nextern \"C\" fn foo(arg: i32) {\n println!(\"arg = {}\", arg);\n}\n\nfn call_foo(arg: i32) {\n unsafe {\n asm!(\n \"call {}\",\n sym foo,\n // 1st argument in rdi, which is caller-saved\n inout(\"rdi\") arg => _,\n // All caller-saved registers must be marked as clobberred\n out(\"rax\") _, out(\"rcx\") _, out(\"rdx\") _, out(\"rsi\") _,\n out(\"r8\") _, out(\"r9\") _, out(\"r10\") _, out(\"r11\") _,\n out(\"xmm0\") _, out(\"xmm1\") _, out(\"xmm2\") _, out(\"xmm3\") _,\n out(\"xmm4\") _, out(\"xmm5\") _, out(\"xmm6\") _, out(\"xmm7\") _,\n out(\"xmm8\") _, out(\"xmm9\") _, out(\"xmm10\") _, out(\"xmm11\") _,\n out(\"xmm12\") _, out(\"xmm13\") _, out(\"xmm14\") _, out(\"xmm15\") _,\n )\n }\n}\n```\n\nNote that the `fn` or `static` item does not need to be public or `#[no_mangle]`:\nthe compiler will automatically insert the appropriate mangled symbol name into the assembly code.\n\n## Register template modifiers\n\nIn some cases, fine control is needed over the way a register name is formatted when inserted into the template string. This is needed when an architecture's assembly language has several names for the same register, each typically being a \"view\" over a subset of the register (e.g. the low 32 bits of a 64-bit register).\n\nBy default the compiler will always choose the name that refers to the full register size (e.g. `rax` on x86-64, `eax` on x86, etc).\n\nThis default can be overriden by using modifiers on the template string operands, just like you would with format strings:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut x: u16 = 0xab;\n\nunsafe {\n asm!(\"mov {0:h}, {0:l}\", inout(reg_abcd) x);\n}\n\nassert_eq!(x, 0xabab);\n```\n\nIn this example, we use the `reg_abcd` register class to restrict the register allocator to the 4 legacy x86 register (`ax`, `bx`, `cx`, `dx`) of which the first two bytes can be addressed independently.\n\nLet us assume that the register allocator has chosen to allocate `x` in the `ax` register.\nThe `h` modifier will emit the register name for the high byte of that register and the `l` modifier will emit the register name for the low byte. The asm code will therefore be expanded as `mov ah, al` which copies the low byte of the value into the high byte.\n\nIf you use a smaller data type (e.g. `u16`) with an operand and forget the use template modifiers, the compiler will emit a warning and suggest the correct modifier to use.\n\n## Memory address operands\n\nSometimes assembly instructions require operands passed via memory addresses/memory locations.\nYou have to manually use the memory address syntax specified by the respectively architectures.\nFor example, in x86/x86_64 and intel assembly syntax, you should wrap inputs/outputs in `[]`\nto indicate they are memory operands:\n\n```rust,allow_fail\n# #![feature(asm, llvm_asm)]\n# fn load_fpu_control_word(control: u16) {\nunsafe {\n asm!(\"fldcw [{}]\", in(reg) &control, options(nostack));\n\n // Previously this would have been written with the deprecated `llvm_asm!` like this\n llvm_asm!(\"fldcw $0\" :: \"m\" (control) :: \"volatile\");\n}\n# }\n```\n\n## Options\n\nBy default, an inline assembly block is treated the same way as an external FFI function call with a custom calling convention: it may read/write memory, have observable side effects, etc. However in many cases, it is desirable to give the compiler more information about what the assembly code is actually doing so that it can optimize better.\n\nLet's take our previous example of an `add` instruction:\n\n```rust,allow_fail\n# #![feature(asm)]\nlet mut a: u64 = 4;\nlet b: u64 = 4;\nunsafe {\n asm!(\n \"add {0}, {1}\",\n inlateout(reg) a, in(reg) b,\n options(pure, nomem, nostack),\n );\n}\nassert_eq!(a, 8);\n```\n\nOptions can be provided as an optional final argument to the `asm!` macro. We specified three options here:\n- `pure` means that the asm code has no observable side effects and that its output depends only on its inputs. This allows the compiler optimizer to call the inline asm fewer times or even eliminate it entirely.\n- `nomem` means that the asm code does not read or write to memory. By default the compiler will assume that inline assembly can read or write any memory address that is accessible to it (e.g. through a pointer passed as an operand, or a global).\n- `nostack` means that the asm code does not push any data onto the stack. This allows the compiler to use optimizations such as the stack red zone on x86-64 to avoid stack pointer adjustments.\n\nThese allow the compiler to better optimize code using `asm!`, for example by eliminating pure `asm!` blocks whose outputs are not needed.\n\nSee the reference for the full list of available options and their effects.\n\n# Reference-level explanation\n[reference-level-explanation]: #reference-level-explanation\n\nInline assembler is implemented as an unsafe macro `asm!()`.\nThe first argument to this macro is a template string literal used to build the final assembly.\nThe following arguments specify input and output operands.\nWhen required, options are specified as the final argument.\n\nThe following ABNF specifies the general syntax:\n\n```ignore\ndir_spec := \"in\" / \"out\" / \"lateout\" / \"inout\" / \"inlateout\"\nreg_spec := <register class> / \"<explicit register>\"\noperand_expr := expr / \"_\" / expr \"=>\" expr / expr \"=>\" \"_\"\nreg_operand := dir_spec \"(\" reg_spec \")\" operand_expr\noperand := reg_operand / \"const\" const_expr / \"sym\" path\noption := \"pure\" / \"nomem\" / \"readonly\" / \"preserves_flags\" / \"noreturn\" / \"nostack\" / \"att_syntax\"\noptions := \"options(\" option *[\",\" option] [\",\"] \")\"\nasm := \"asm!(\" format_string *(\",\" format_string) *(\",\" [ident \"=\"] operand) [\",\" options] [\",\"] \")\"\n```\n\nThe macro will initially be supported only on ARM, AArch64, Hexagon, x86, x86-64 and RISC-V targets. Support for more targets may be added in the future. The compiler will emit an error if `asm!` is used on an unsupported target.\n\n[format-syntax]: https://doc.rust-lang.org/std/fmt/#syntax\n\n## Template string arguments\n\nThe assembler template uses the same syntax as [format strings][format-syntax] (i.e. placeholders are specified by curly braces). The corresponding arguments are accessed in order, by index, or by name. However, implicit named arguments (introduced by [RFC #2795][rfc-2795]) are not supported.\n\nAn `asm!` invocation may have one or more template string arguments; an `asm!` with multiple template string arguments is treated as if all the strings were concatenated with a `\\n` between them. The expected usage is for each template string argument to correspond to a line of assembly code. All template string arguments must appear before any other arguments.\n\nAs with format strings, named arguments must appear after positional arguments. Explicit register operands must appear at the end of the operand list, after named arguments if any.\n\nExplicit register operands cannot be used by placeholders in the template string. All other named and positional operands must appear at least once in the template string, otherwise a compiler error is generated.\n\nThe exact assembly code syntax is target-specific and opaque to the compiler except for the way operands are substituted into the template string to form the code passed to the assembler.\n\nThe 5 targets specified in this RFC (x86, ARM, AArch64, RISC-V, Hexagon) all use the assembly code syntax of the GNU assembler (GAS). On x86, the `.intel_syntax noprefix` mode of GAS is used by default. On ARM, the `.syntax unified` mode is used. These targets impose an additional restriction on the assembly code: any assembler state (e.g. the current section which can be changed with `.section`) must be restored to its original value at the end of the asm string. Assembly code that does not conform to the GAS syntax will result in assembler-specific behavior.\n\n[rfc-2795]: https://github.com/rust-lang/rfcs/pull/2795\n\n## Operand type\n\nSeveral types of operands are supported:\n\n* `in(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `<expr>` at the start of the asm code.\n - The allocated register must contain the same value at the end of the asm code (except if a `lateout` is allocated to the same register).\n* `out(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain an undefined value at the start of the asm code.\n - `<expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register is written to at the end of the asm code.\n - An underscore (`_`) may be specified instead of an expression, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).\n* `lateout(<reg>) <expr>`\n - Identical to `out` except that the register allocator can reuse a register allocated to an `in`.\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n* `inout(<reg>) <expr>`\n - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.\n - The allocated register will contain the value of `<expr>` at the start of the asm code.\n - `<expr>` must be a mutable initialized place expression, to which the contents of the allocated register is written to at the end of the asm code.\n* `inout(<reg>) <in expr> => <out expr>`\n - Same as `inout` except that the initial value of the register is taken from the value of `<in expr>`.\n - `<out expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register is written to at the end of the asm code.\n - An underscore (`_`) may be specified instead of an expression for `<out expr>`, which will cause the contents of the register to be discarded at the end of the asm code (effectively acting as a clobber).\n - `<in expr>` and `<out expr>` may have different types.\n* `inlateout(<reg>) <expr>` / `inlateout(<reg>) <in expr> => <out expr>`\n - Identical to `inout` except that the register allocator can reuse a register allocated to an `in` (this can happen if the compiler knows the `in` has the same initial value as the `inlateout`).\n - You should only write to the register after all inputs are read, otherwise you may clobber an input.\n* `const <expr>`\n - `<expr>` must be an integer or floating-point constant expression.\n - The value of the expression is formatted as a string and substituted directly into the asm template string.\n* `sym <path>`\n - `<path>` must refer to a `fn` or `static`.\n - A mangled symbol name referring to the item is substituted into the asm template string.\n - The substituted string does not include any modifiers (e.g. GOT, PLT, relocations, etc).\n - `<path>` is allowed to point to a `#[thread_local]` static, in which case the asm code can combine the symbol with relocations (e.g. `@plt`, `@TPOFF`) to read from thread-local data.\n\nOperand expressions are evaluated from left to right, just like function call arguments. After the `asm!` has executed, outputs are written to in left to right order. This is significant if two outputs point to the same place: that place will contain the value of the rightmost output.\n\n## Register operands\n\nInput and output operands can be specified either as an explicit register or as a register class from which the register allocator can select a register. Explicit registers are specified as string literals (e.g. `\"eax\"`) while register classes are specified as identifiers (e.g. `reg`). Using string literals for register names enables support for architectures that use special characters in register names, such as MIPS (`$0`, `$1`, etc).\n\nNote that explicit registers treat register aliases (e.g. `r14` vs `lr` on ARM) and smaller views of a register (e.g. `eax` vs `rax`) as equivalent to the base register. It is a compile-time error to use the same explicit register for two input operands or two output operands. Additionally, it is also a compile-time error to use overlapping registers (e.g. ARM VFP) in input operands or in output operands.\n\nOnly the following types are allowed as operands for inline assembly:\n- Integers (signed and unsigned)\n- Floating-point numbers\n- Pointers (thin only)\n- Function pointers\n- SIMD vectors (structs defined with `#[repr(simd)]` and which implement `Copy`). This includes architecture-specific vector types defined in `std::arch` such as `__m128` (x86) or `int8x16_t` (ARM).\n\nHere is the list of currently supported register classes:\n\n| Architecture | Register class | Registers | LLVM constraint code |\n| ------------ | -------------- | --------- | -------------------- |\n| x86 | `reg` | `ax`, `bx`, `cx`, `dx`, `si`, `di`, `r[8-15]` (x86-64 only) | `r` |\n| x86 | `reg_abcd` | `ax`, `bx`, `cx`, `dx` | `Q` |\n| x86-32 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `ah`, `bh`, `ch`, `dh` | `q` |\n| x86-64 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `sil`, `dil`, `r[8-15]b`, `ah`\\*, `bh`\\*, `ch`\\*, `dh`\\* | `q` |\n| x86 | `xmm_reg` | `xmm[0-7]` (x86) `xmm[0-15]` (x86-64) | `x` |\n| x86 | `ymm_reg` | `ymm[0-7]` (x86) `ymm[0-15]` (x86-64) | `x` |\n| x86 | `zmm_reg` | `zmm[0-7]` (x86) `zmm[0-31]` (x86-64) | `v` |\n| x86 | `kreg` | `k[1-7]` | `Yk` |\n| AArch64 | `reg` | `x[0-28]`, `x30` | `r` |\n| AArch64 | `vreg` | `v[0-31]` | `w` |\n| AArch64 | `vreg_low16` | `v[0-15]` | `x` |\n| ARM | `reg` | `r[0-5]` `r7`\\*, `r[8-10]`, `r11`\\*, `r12`, `r14` | `r` |\n| ARM (Thumb) | `reg_thumb` | `r[0-r7]` | `l` |\n| ARM (ARM) | `reg_thumb` | `r[0-r10]`, `r12`, `r14` | `l` |\n| ARM | `sreg` | `s[0-31]` | `t` |\n| ARM | `sreg_low16` | `s[0-15]` | `x` |\n| ARM | `dreg` | `d[0-31]` | `w` |\n| ARM | `dreg_low16` | `d[0-15]` | `t` |\n| ARM | `dreg_low8` | `d[0-8]` | `x` |\n| ARM | `qreg` | `q[0-15]` | `w` |\n| ARM | `qreg_low8` | `q[0-7]` | `t` |\n| ARM | `qreg_low4` | `q[0-3]` | `x` |\n| MIPS | `reg` | `$[2-25]` | `r` |\n| MIPS | `freg` | `$f[0-31]` | `f` |\n| NVPTX | `reg16` | None\\* | `h` |\n| NVPTX | `reg32` | None\\* | `r` |\n| NVPTX | `reg64` | None\\* | `l` |\n| RISC-V | `reg` | `x1`, `x[5-7]`, `x[9-15]`, `x[16-31]` (non-RV32E) | `r` |\n| RISC-V | `freg` | `f[0-31]` | `f` |\n| Hexagon | `reg` | `r[0-28]` | `r` |\n\n> **Note**: On x86 we treat `reg_byte` differently from `reg` because the compiler can allocate `al` and `ah` separately whereas `reg` reserves the whole register.\n>\n> Note #2: On x86-64 the high byte registers (e.g. `ah`) are only available when used as an explicit register. Specifying the `reg_byte` register class for an operand will always allocate a low byte register.\n>\n> Note #3: NVPTX doesn't have a fixed register set, so named registers are not supported.\n>\n> Note #4: On ARM the frame pointer is either `r7` or `r11` depending on the platform.\n\nAdditional register classes may be added in the future based on demand (e.g. MMX, x87, etc).\n\nEach register class has constraints on which value types they can be used with. This is necessary because the way a value is loaded into a register depends on its type. For example, on big-endian systems, loading a `i32x4` and a `i8x16` into a SIMD register may result in different register contents even if the byte-wise memory representation of both values is identical. The availability of supported types for a particular register class may depend on what target features are currently enabled.\n\n| Architecture | Register class | Target feature | Allowed types |\n| ------------ | -------------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `i16`, `i32`, `f32` |\n| x86-64 | `reg` | None | `i16`, `i32`, `f32`, `i64`, `f64` |\n| x86 | `reg_byte` | None | `i8` |\n| x86 | `xmm_reg` | `sse` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| x86 | `ymm_reg` | `avx` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` <br> `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` |\n| x86 | `zmm_reg` | `avx512f` | `i32`, `f32`, `i64`, `f64`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` <br> `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` <br> `i8x64`, `i16x32`, `i32x16`, `i64x8`, `f32x16`, `f64x8` |\n| x86 | `kreg` | `axv512f` | `i8`, `i16` |\n| x86 | `kreg` | `axv512bw` | `i32`, `i64` |\n| AArch64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| AArch64 | `vreg` | `fp` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`, <br> `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`, <br> `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` |\n| ARM | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| ARM | `sreg` | `vfp2` | `i32`, `f32` |\n| ARM | `dreg` | `vfp2` | `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2` |\n| ARM | `qreg` | `neon` | `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4` |\n| MIPS32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| MIPS32 | `freg` | None | `f32`, `f64` |\n| MIPS64 | `reg` | None | `i8`, `i16`, `i32`, `i64`, `f32`, `f64` |\n| MIPS64 | `freg` | None | `f32`, `f64` |\n| NVPTX | `reg16` | None | `i8`, `i16` |\n| NVPTX | `reg32` | None | `i8`, `i16`, `i32`, `f32` |\n| NVPTX | `reg64` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V32 | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n| RISC-V64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64` |\n| RISC-V | `freg` | `f` | `f32` |\n| RISC-V | `freg` | `d` | `f64` |\n| Hexagon | `reg` | None | `i8`, `i16`, `i32`, `f32` |\n\n> **Note**: For the purposes of the above table pointers, function pointers and `isize`/`usize` are treated as the equivalent integer type (`i16`/`i32`/`i64` depending on the target).\n\nIf a value is of a smaller size than the register it is allocated in then the upper bits of that register will have an undefined value for inputs and will be ignored for outputs. The only exception is the `freg` register class on RISC-V where `f32` values are NaN-boxed in a `f64` as required by the RISC-V architecture.\n\nWhen separate input and output expressions are specified for an `inout` operand, both expressions must have the same type. The only exception is if both operands are pointers or integers, in which case they are only required to have the same size. This restriction exists because the register allocators in LLVM and GCC sometimes cannot handle tied operands with different types.\n\n## Register names\n\nSome registers have multiple names. These are all treated by the compiler as identical to the base register name. Here is the list of all supported register aliases:\n\n| Architecture | Base register | Aliases |\n| ------------ | ------------- | ------- |\n| x86 | `ax` | `eax`, `rax` |\n| x86 | `bx` | `ebx`, `rbx` |\n| x86 | `cx` | `ecx`, `rcx` |\n| x86 | `dx` | `edx`, `rdx` |\n| x86 | `si` | `esi`, `rsi` |\n| x86 | `di` | `edi`, `rdi` |\n| x86 | `bp` | `bpl`, `ebp`, `rbp` |\n| x86 | `sp` | `spl`, `esp`, `rsp` |\n| x86 | `ip` | `eip`, `rip` |\n| x86 | `st(0)` | `st` |\n| x86 | `r[8-15]` | `r[8-15]b`, `r[8-15]w`, `r[8-15]d` |\n| x86 | `xmm[0-31]` | `ymm[0-31]`, `zmm[0-31]` |\n| AArch64 | `x[0-30]` | `w[0-30]` |\n| AArch64 | `x29` | `fp` |\n| AArch64 | `x30` | `lr` |\n| AArch64 | `sp` | `wsp` |\n| AArch64 | `xzr` | `wzr` |\n| AArch64 | `v[0-31]` | `b[0-31]`, `h[0-31]`, `s[0-31]`, `d[0-31]`, `q[0-31]` |\n| ARM | `r[0-3]` | `a[1-4]` |\n| ARM | `r[4-9]` | `v[1-6]` |\n| ARM | `r9` | `rfp` |\n| ARM | `r10` | `sl` |\n| ARM | `r11` | `fp` |\n| ARM | `r12` | `ip` |\n| ARM | `r13` | `sp` |\n| ARM | `r14` | `lr` |\n| ARM | `r15` | `pc` |\n| RISC-V | `x0` | `zero` |\n| RISC-V | `x1` | `ra` |\n| RISC-V | `x2` | `sp` |\n| RISC-V | `x3` | `gp` |\n| RISC-V | `x4` | `tp` |\n| RISC-V | `x[5-7]` | `t[0-2]` |\n| RISC-V | `x8` | `fp`, `s0` |\n| RISC-V | `x9` | `s1` |\n| RISC-V | `x[10-17]` | `a[0-7]` |\n| RISC-V | `x[18-27]` | `s[2-11]` |\n| RISC-V | `x[28-31]` | `t[3-6]` |\n| RISC-V | `f[0-7]` | `ft[0-7]` |\n| RISC-V | `f[8-9]` | `fs[0-1]` |\n| RISC-V | `f[10-17]` | `fa[0-7]` |\n| RISC-V | `f[18-27]` | `fs[2-11]` |\n| RISC-V | `f[28-31]` | `ft[8-11]` |\n| Hexagon | `r29` | `sp` |\n| Hexagon | `r30` | `fr` |\n| Hexagon | `r31` | `lr` |\n\nSome registers cannot be used for input or output operands:\n\n| Architecture | Unsupported register | Reason |\n| ------------ | -------------------- | ------ |\n| All | `sp` | The stack pointer must be restored to its original value at the end of an asm code block. |\n| All | `bp` (x86), `x29` (AArch64), `x8` (RISC-V), `fr` (Hexagon), `$fp` (MIPS) | The frame pointer cannot be used as an input or output. |\n| ARM | `r7` or `r11` | On ARM the frame pointer can be either `r7` or `r11` depending on the target. The frame pointer cannot be used as an input or output. |\n| ARM | `r6` | `r6` is used internally by LLVM as a base pointer and therefore cannot be used as an input or output. |\n| x86 | `k0` | This is a constant zero register which can't be modified. |\n| x86 | `ip` | This is the program counter, not a real register. |\n| x86 | `mm[0-7]` | MMX registers are not currently supported (but may be in the future). |\n| x86 | `st([0-7])` | x87 registers are not currently supported (but may be in the future). |\n| AArch64 | `xzr` | This is a constant zero register which can't be modified. |\n| ARM | `pc` | This is the program counter, not a real register. |\n| MIPS | `$0` or `$zero` | This is a constant zero register which can't be modified. |\n| MIPS | `$1` or `$at` | Reserved for assembler. |\n| MIPS | `$26`/`$k0`, `$27`/`$k1` | OS-reserved registers. |\n| MIPS | `$28`/`$gp` | Global pointer cannot be used as inputs or outputs. |\n| MIPS | `$ra` | Return address cannot be used as inputs or outputs. |\n| RISC-V | `x0` | This is a constant zero register which can't be modified. |\n| RISC-V | `gp`, `tp` | These registers are reserved and cannot be used as inputs or outputs. |\n| Hexagon | `lr` | This is the link register which cannot be used as an input or output. |\n\nIn some cases LLVM will allocate a \"reserved register\" for `reg` operands even though this register cannot be explicitly specified. Assembly code making use of reserved registers should be careful since `reg` operands may alias with those registers. Reserved registers are:\n- The frame pointer on all architectures.\n- `r6` on ARM.\n\n## Template modifiers\n\nThe placeholders can be augmented by modifiers which are specified after the `:` in the curly braces. These modifiers do not affect register allocation, but change the way operands are formatted when inserted into the template string. Only one modifier is allowed per template placeholder.\n\nThe supported modifiers are a subset of LLVM's (and GCC's) [asm template argument modifiers][llvm-argmod], but do not use the same letter codes.\n\n| Architecture | Register class | Modifier | Example output | LLVM modifier |\n| ------------ | -------------- | -------- | -------------- | ------------- |\n| x86-32 | `reg` | None | `eax` | `k` |\n| x86-64 | `reg` | None | `rax` | `q` |\n| x86-32 | `reg_abcd` | `l` | `al` | `b` |\n| x86-64 | `reg` | `l` | `al` | `b` |\n| x86 | `reg_abcd` | `h` | `ah` | `h` |\n| x86 | `reg` | `x` | `ax` | `w` |\n| x86 | `reg` | `e` | `eax` | `k` |\n| x86-64 | `reg` | `r` | `rax` | `q` |\n| x86 | `reg_byte` | None | `al` / `ah` | None |\n| x86 | `xmm_reg` | None | `xmm0` | `x` |\n| x86 | `ymm_reg` | None | `ymm0` | `t` |\n| x86 | `zmm_reg` | None | `zmm0` | `g` |\n| x86 | `*mm_reg` | `x` | `xmm0` | `x` |\n| x86 | `*mm_reg` | `y` | `ymm0` | `t` |\n| x86 | `*mm_reg` | `z` | `zmm0` | `g` |\n| x86 | `kreg` | None | `k1` | None |\n| AArch64 | `reg` | None | `x0` | `x` |\n| AArch64 | `reg` | `w` | `w0` | `w` |\n| AArch64 | `reg` | `x` | `x0` | `x` |\n| AArch64 | `vreg` | None | `v0` | None |\n| AArch64 | `vreg` | `v` | `v0` | None |\n| AArch64 | `vreg` | `b` | `b0` | `b` |\n| AArch64 | `vreg` | `h` | `h0` | `h` |\n| AArch64 | `vreg` | `s` | `s0` | `s` |\n| AArch64 | `vreg` | `d` | `d0` | `d` |\n| AArch64 | `vreg` | `q` | `q0` | `q` |\n| ARM | `reg` | None | `r0` | None |\n| ARM | `sreg` | None | `s0` | None |\n| ARM | `dreg` | None | `d0` | `P` |\n| ARM | `qreg` | None | `q0` | `q` |\n| ARM | `qreg` | `e` / `f` | `d0` / `d1` | `e` / `f` |\n| MIPS | `reg` | None | `$2` | None |\n| MIPS | `freg` | None | `$f0` | None |\n| NVPTX | `reg16` | None | `rs0` | None |\n| NVPTX | `reg32` | None | `r0` | None |\n| NVPTX | `reg64` | None | `rd0` | None |\n| RISC-V | `reg` | None | `x1` | None |\n| RISC-V | `freg` | None | `f0` | None |\n| Hexagon | `reg` | None | `r0` | None |\n\n> Notes:\n> - on ARM `e` / `f`: this prints the low or high doubleword register name of a NEON quad (128-bit) register.\n> - on x86: our behavior for `reg` with no modifiers differs from what GCC does. GCC will infer the modifier based on the operand value type, while we default to the full register size.\n> - on x86 `xmm_reg`: the `x`, `t` and `g` LLVM modifiers are not yet implemented in LLVM (they are supported by GCC only), but this should be a simple change.\n\nAs stated in the previous section, passing an input value smaller than the register width will result in the upper bits of the register containing undefined values. This is not a problem if the inline asm only accesses the lower bits of the register, which can be done by using a template modifier to use a subregister name in the asm code (e.g. `ax` instead of `rax`). Since this an easy pitfall, the compiler will suggest a template modifier to use where appropriate given the input type. If all references to an operand already have modifiers then the warning is suppressed for that operand.\n\n[llvm-argmod]: http://llvm.org/docs/LangRef.html#asm-template-argument-modifiers\n\n## Options\n\nFlags are used to further influence the behavior of the inline assembly block.\nCurrently the following options are defined:\n- `pure`: The `asm` block has no side effects, and its outputs depend only on its direct inputs (i.e. the values themselves, not what they point to) or values read from memory (unless the `nomem` options is also set). This allows the compiler to execute the `asm` block fewer times than specified in the program (e.g. by hoisting it out of a loop) or even eliminate it entirely if the outputs are not used.\n- `nomem`: The `asm` blocks does not read or write to any memory. This allows the compiler to cache the values of modified global variables in registers across the `asm` block since it knows that they are not read or written to by the `asm`.\n- `readonly`: The `asm` block does not write to any memory. This allows the compiler to cache the values of unmodified global variables in registers across the `asm` block since it knows that they are not written to by the `asm`.\n- `preserves_flags`: The `asm` block does not modify the flags register (defined in the rules below). This allows the compiler to avoid recomputing the condition flags after the `asm` block.\n- `noreturn`: The `asm` block never returns, and its return type is defined as `!` (never). Behavior is undefined if execution falls through past the end of the asm code. A `noreturn` asm block behaves just like a function which doesn't return; notably, local variables in scope are not dropped before it is invoked.\n- `nostack`: The `asm` block does not push data to the stack, or write to the stack red-zone (if supported by the target). If this option is *not* used then the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n- `att_syntax`: This option is only valid on x86, and causes the assembler to use the `.att_syntax prefix` mode of the GNU assembler. Register operands are substituted in with a leading `%`.\n\nThe compiler performs some additional checks on options:\n- The `nomem` and `readonly` options are mutually exclusive: it is a compile-time error to specify both.\n- The `pure` option must be combined with either the `nomem` or `readonly` options, otherwise a compile-time error is emitted.\n- It is a compile-time error to specify `pure` on an asm block with no outputs or only discarded outputs (`_`).\n- It is a compile-time error to specify `noreturn` on an asm block with outputs.\n\n## Rules for inline assembly\n\n- Any registers not specified as inputs will contain an undefined value on entry to the asm block.\n - An \"undefined value\" in the context of inline assembly means that the register can (non-deterministically) have any one of the possible values allowed by the architecture. Notably it is not the same as an LLVM `undef` which can have a different value every time you read it (since such a concept does not exist in assembly code).\n- Any registers not specified as outputs must have the same value upon exiting the asm block as they had on entry, otherwise behavior is undefined.\n - This only applies to registers which can be specified as an input or output. Other registers follow target-specific rules.\n - Note that a `lateout` may be allocated to the same register as an `in`, in which case this rule does not apply. Code should not rely on this however since it depends on the results of register allocation.\n- Behavior is undefined if execution unwinds out of an asm block.\n - This also applies if the assembly code calls a function which then unwinds.\n- The set of memory locations that assembly code is allowed the read and write are the same as those allowed for an FFI function.\n - Refer to the unsafe code guidelines for the exact rules.\n - If the `readonly` option is set, then only memory reads are allowed.\n - If the `nomem` option is set then no reads or writes to memory are allowed.\n - These rules do not apply to memory which is private to the asm code, such as stack space allocated within the asm block.\n- The compiler cannot assume that the instructions in the asm are the ones that will actually end up executed.\n - This effectively means that the compiler must treat the `asm!` as a black box and only take the interface specification into account, not the instructions themselves.\n - Runtime code patching is allowed, via target-specific mechanisms (outside the scope of this RFC).\n- Unless the `nostack` option is set, asm code is allowed to use stack space below the stack pointer.\n - On entry to the asm block the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.\n - You are responsible for making sure you don't overflow the stack (e.g. use stack probing to ensure you hit a guard page).\n - You should adjust the stack pointer when allocating stack memory as required by the target ABI.\n - The stack pointer must be restored to its original value before leaving the asm block.\n- If the `noreturn` option is set then behavior is undefined if execution falls through to the end of the asm block.\n- If the `pure` option is set then behavior is undefined if the `asm` has side-effects other than its direct outputs. Behavior is also undefined if two executions of the `asm` code with the same inputs result in different outputs.\n - When used with the `nomem` option, \"inputs\" are just the direct inputs of the `asm!`.\n - When used with the `readonly` option, \"inputs\" comprise the direct inputs of the `asm!` and any memory that the `asm!` block is allowed to read.\n- These flags registers must be restored upon exiting the asm block if the `preserves_flags` option is set:\n - x86\n - Status flags in `EFLAGS` (CF, PF, AF, ZF, SF, OF).\n - Floating-point status word (all).\n - Floating-point exception flags in `MXCSR` (PE, UE, OE, ZE, DE, IE).\n - ARM\n - Condition flags in `CPSR` (N, Z, C, V)\n - Saturation flag in `CPSR` (Q)\n - Greater than or equal flags in `CPSR` (GE).\n - Condition flags in `FPSCR` (N, Z, C, V)\n - Saturation flag in `FPSCR` (QC)\n - Floating-point exception flags in `FPSCR` (IDC, IXC, UFC, OFC, DZC, IOC).\n - AArch64\n - Condition flags (`NZCV` register).\n - Floating-point status (`FPSR` register).\n - RISC-V\n - Floating-point exception flags in `fcsr` (`fflags`).\n- On x86, the direction flag (DF in `EFLAGS`) is clear on entry to an asm block and must be clear on exit.\n - Behavior is undefined if the direction flag is set on exiting an asm block.\n- The requirement of restoring the stack pointer and non-output registers to their original value only applies when exiting an `asm!` block.\n - This means that `asm!` blocks that never return (even if not marked `noreturn`) don't need to preserve these registers.\n - When returning to a different `asm!` block than you entered (e.g. for context switching), these registers must contain the value they had upon entering the `asm!` block that you are *exiting*.\n - You cannot exit an `asm!` block that has not been entered. Neither can you exit an `asm!` block that has already been exited.\n - You are responsible for switching any target-specific state (e.g. thread-local storage, stack bounds).\n - The set of memory locations that you may access is the intersection of those allowed by the `asm!` blocks you entered and exited.\n- You cannot assume that an `asm!` block will appear exactly once in the output binary. The compiler is allowed to instantiate multiple copies of the `asm!` block, for example when the function containing it is inlined in multiple places.\n - As a consequence, you should only use [local labels] inside inline assembly code. Defining symbols in assembly code may lead to assembler and/or linker errors due to duplicate symbol definitions.\n\n> **Note**: As a general rule, the flags covered by `preserves_flags` are those which are *not* preserved when performing a function call.\n\n[local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels\n" } , LintCompletion { label : "allocator_api" , description : "# `allocator_api`\n\nThe tracking issue for this feature is [#32838]\n\n[#32838]: https://github.com/rust-lang/rust/issues/32838\n\n------------------------\n\nSometimes you want the memory for one collection to use a different\nallocator than the memory for another collection. In this case,\nreplacing the global allocator is not a workable option. Instead,\nyou need to pass in an instance of an `AllocRef` to each collection\nfor which you want a custom allocator.\n\nTBD\n" } , LintCompletion { label : "set_stdio" , description : "# `set_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_sys_internals" , description : "# `libstd_sys_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "concat_idents" , description : "# `concat_idents`\n\nThe tracking issue for this feature is: [#29599]\n\n[#29599]: https://github.com/rust-lang/rust/issues/29599\n\n------------------------\n\nThe `concat_idents` feature adds a macro for concatenating multiple identifiers\ninto one identifier.\n\n## Examples\n\n```rust\n#![feature(concat_idents)]\n\nfn main() {\n fn foobar() -> u32 { 23 }\n let f = concat_idents!(foo, bar);\n assert_eq!(f(), 23);\n}\n```" } , LintCompletion { label : "format_args_capture" , description : "# `format_args_capture`\n\nThe tracking issue for this feature is: [#67984]\n\n[#67984]: https://github.com/rust-lang/rust/issues/67984\n\n------------------------\n\nEnables `format_args!` (and macros which use `format_args!` in their implementation, such\nas `format!`, `print!` and `panic!`) to capture variables from the surrounding scope.\nThis avoids the need to pass named parameters when the binding in question\nalready exists in scope.\n\n```rust\n#![feature(format_args_capture)]\n\nlet (person, species, name) = (\"Charlie Brown\", \"dog\", \"Snoopy\");\n\n// captures named argument `person`\nprint!(\"Hello {person}\");\n\n// captures named arguments `species` and `name`\nformat!(\"The {species}'s name is {name}.\");\n```\n\nThis also works for formatting parameters such as width and precision:\n\n```rust\n#![feature(format_args_capture)]\n\nlet precision = 2;\nlet s = format!(\"{:.precision$}\", 1.324223);\n\nassert_eq!(&s, \"1.32\");\n```\n\nA non-exhaustive list of macros which benefit from this functionality include:\n- `format!`\n- `print!` and `println!`\n- `eprint!` and `eprintln!`\n- `write!` and `writeln!`\n- `panic!`\n- `unreachable!`\n- `unimplemented!`\n- `todo!`\n- `assert!` and similar\n- macros in many thirdparty crates, such as `log`\n" } , LintCompletion { label : "is_sorted" , description : "# `is_sorted`\n\nThe tracking issue for this feature is: [#53485]\n\n[#53485]: https://github.com/rust-lang/rust/issues/53485\n\n------------------------\n\nAdd the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to `[T]`;\nadd the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to\n`Iterator`.\n" } , LintCompletion { label : "sort_internals" , description : "# `sort_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "c_variadic" , description : "# `c_variadic`\n\nThe tracking issue for this feature is: [#44930]\n\n[#44930]: https://github.com/rust-lang/rust/issues/44930\n\n------------------------\n\nThe `c_variadic` library feature exposes the `VaList` structure,\nRust's analogue of C's `va_list` type.\n\n## Examples\n\n```rust\n#![feature(c_variadic)]\n\nuse std::ffi::VaList;\n\npub unsafe extern \"C\" fn vadd(n: usize, mut args: VaList) -> usize {\n let mut sum = 0;\n for _ in 0..n {\n sum += args.arg::<usize>();\n }\n sum\n}\n```\n" } , LintCompletion { label : "trace_macros" , description : "# `trace_macros`\n\nThe tracking issue for this feature is [#29598].\n\n[#29598]: https://github.com/rust-lang/rust/issues/29598\n\n------------------------\n\nWith `trace_macros` you can trace the expansion of macros in your code.\n\n## Examples\n\n```rust\n#![feature(trace_macros)]\n\nfn main() {\n trace_macros!(true);\n println!(\"Hello, Rust!\");\n trace_macros!(false);\n}\n```\n\nThe `cargo build` output:\n\n```txt\nnote: trace_macro\n --> src/main.rs:5:5\n |\n5 | println!(\"Hello, Rust!\");\n | ^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n = note: expanding `println! { \"Hello, Rust!\" }`\n = note: to `print ! ( concat ! ( \"Hello, Rust!\" , \"\\n\" ) )`\n = note: expanding `print! { concat ! ( \"Hello, Rust!\" , \"\\n\" ) }`\n = note: to `$crate :: io :: _print ( format_args ! ( concat ! ( \"Hello, Rust!\" , \"\\n\" ) )\n )`\n\n Finished dev [unoptimized + debuginfo] target(s) in 0.60 secs\n```\n" } , LintCompletion { label : "c_void_variant" , description : "# `c_void_variant`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_panic" , description : "# `core_panic`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fmt_internals" , description : "# `fmt_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "rt" , description : "# `rt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "thread_local_internals" , description : "# `thread_local_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_intrinsics" , description : "# `core_intrinsics`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "update_panic_count" , description : "# `update_panic_count`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "profiler_runtime_lib" , description : "# `profiler_runtime_lib`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_private_bignum" , description : "# `core_private_bignum`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "core_private_diy_float" , description : "# `core_private_diy_float`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "str_internals" , description : "# `str_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "derive_clone_copy" , description : "# `derive_clone_copy`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fn_traits" , description : "# `fn_traits`\n\nThe tracking issue for this feature is [#29625]\n\nSee Also: [`unboxed_closures`](../language-features/unboxed-closures.md)\n\n[#29625]: https://github.com/rust-lang/rust/issues/29625\n\n----\n\nThe `fn_traits` feature allows for implementation of the [`Fn*`] traits\nfor creating custom closure-like types.\n\n[`Fn*`]: https://doc.rust-lang.org/std/ops/trait.Fn.html\n\n```rust\n#![feature(unboxed_closures)]\n#![feature(fn_traits)]\n\nstruct Adder {\n a: u32\n}\n\nimpl FnOnce<(u32, )> for Adder {\n type Output = u32;\n extern \"rust-call\" fn call_once(self, b: (u32, )) -> Self::Output {\n self.a + b.0\n }\n}\n\nfn main() {\n let adder = Adder { a: 3 };\n assert_eq!(adder(2), 5);\n}\n```\n" } , LintCompletion { label : "fd_read" , description : "# `fd_read`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_net" , description : "# `windows_net`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "derive_eq" , description : "# `derive_eq`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "windows_stdio" , description : "# `windows_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "test" , description : "# `test`\n\nThe tracking issue for this feature is: None.\n\n------------------------\n\nThe internals of the `test` crate are unstable, behind the `test` flag. The\nmost widely used part of the `test` crate are benchmark tests, which can test\nthe performance of your code. Let's make our `src/lib.rs` look like this\n(comments elided):\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\n\npub fn add_two(a: i32) -> i32 {\n a + 2\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use test::Bencher;\n\n #[test]\n fn it_works() {\n assert_eq!(4, add_two(2));\n }\n\n #[bench]\n fn bench_add_two(b: &mut Bencher) {\n b.iter(|| add_two(2));\n }\n}\n```\n\nNote the `test` feature gate, which enables this unstable feature.\n\nWe've imported the `test` crate, which contains our benchmarking support.\nWe have a new function as well, with the `bench` attribute. Unlike regular\ntests, which take no arguments, benchmark tests take a `&mut Bencher`. This\n`Bencher` provides an `iter` method, which takes a closure. This closure\ncontains the code we'd like to benchmark.\n\nWe can run benchmark tests with `cargo bench`:\n\n```bash\n$ cargo bench\n Compiling adder v0.0.1 (file:///home/steve/tmp/adder)\n Running target/release/adder-91b3e234d4ed382a\n\nrunning 2 tests\ntest tests::it_works ... ignored\ntest tests::bench_add_two ... bench: 1 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 1 ignored; 1 measured\n```\n\nOur non-benchmark test was ignored. You may have noticed that `cargo bench`\ntakes a bit longer than `cargo test`. This is because Rust runs our benchmark\na number of times, and then takes the average. Because we're doing so little\nwork in this example, we have a `1 ns/iter (+/- 0)`, but this would show\nthe variance if there was one.\n\nAdvice on writing benchmarks:\n\n\n* Move setup code outside the `iter` loop; only put the part you want to measure inside\n* Make the code do \"the same thing\" on each iteration; do not accumulate or change state\n* Make the outer function idempotent too; the benchmark runner is likely to run\n it many times\n* Make the inner `iter` loop short and fast so benchmark runs are fast and the\n calibrator can adjust the run-length at fine resolution\n* Make the code in the `iter` loop do something simple, to assist in pinpointing\n performance improvements (or regressions)\n\n## Gotcha: optimizations\n\nThere's another tricky part to writing benchmarks: benchmarks compiled with\noptimizations activated can be dramatically changed by the optimizer so that\nthe benchmark is no longer benchmarking what one expects. For example, the\ncompiler might recognize that some calculation has no external effects and\nremove it entirely.\n\n```rust,ignore\n#![feature(test)]\n\nextern crate test;\nuse test::Bencher;\n\n#[bench]\nfn bench_xor_1000_ints(b: &mut Bencher) {\n b.iter(|| {\n (0..1000).fold(0, |old, new| old ^ new);\n });\n}\n```\n\ngives the following results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench: 0 ns/iter (+/- 0)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nThe benchmarking runner offers two ways to avoid this. Either, the closure that\nthe `iter` method receives can return an arbitrary value which forces the\noptimizer to consider the result used and ensures it cannot remove the\ncomputation entirely. This could be done for the example above by adjusting the\n`b.iter` call to\n\n```rust\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n // Note lack of `;` (could also use an explicit `return`).\n (0..1000).fold(0, |old, new| old ^ new)\n});\n```\n\nOr, the other option is to call the generic `test::black_box` function, which\nis an opaque \"black box\" to the optimizer and so forces it to consider any\nargument as used.\n\n```rust\n#![feature(test)]\n\nextern crate test;\n\n# fn main() {\n# struct X;\n# impl X { fn iter<T, F>(&self, _: F) where F: FnMut() -> T {} } let b = X;\nb.iter(|| {\n let n = test::black_box(1000);\n\n (0..n).fold(0, |a, b| a ^ b)\n})\n# }\n```\n\nNeither of these read or modify the value, and are very cheap for small values.\nLarger values can be passed indirectly to reduce overhead (e.g.\n`black_box(&huge_struct)`).\n\nPerforming either of the above changes gives the following benchmarking results\n\n```text\nrunning 1 test\ntest bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3)\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 1 measured\n```\n\nHowever, the optimizer can still modify a testcase in an undesirable manner\neven when using either of the above.\n" } , LintCompletion { label : "flt2dec" , description : "# `flt2dec`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "libstd_io_internals" , description : "# `libstd_io_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "fd" , description : "# `fd`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "print_internals" , description : "# `print_internals`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } , LintCompletion { label : "range_bounds_assert_len" , description : "# `range_bounds_assert_len`\n\nThe tracking issue for this feature is: [#76393]\n\n------------------------\n\nThis adds [`RangeBounds::assert_len`].\n\n[#76393]: https://github.com/rust-lang/rust/issues/76393\n[`RangeBounds::assert_len`]: https://doc.rust-lang.org/nightly/std/ops/trait.RangeBounds.html#method.assert_len\n" } , LintCompletion { label : "try_trait" , description : "# `try_trait`\n\nThe tracking issue for this feature is: [#42327]\n\n[#42327]: https://github.com/rust-lang/rust/issues/42327\n\n------------------------\n\nThis introduces a new trait `Try` for extending the `?` operator to types\nother than `Result` (a part of [RFC 1859]). The trait provides the canonical\nway to _view_ a type in terms of a success/failure dichotomy. This will\nallow `?` to supplant the `try_opt!` macro on `Option` and the `try_ready!`\nmacro on `Poll`, among other things.\n\n[RFC 1859]: https://github.com/rust-lang/rfcs/pull/1859\n\nHere's an example implementation of the trait:\n\n```rust,ignore\n/// A distinct type to represent the `None` value of an `Option`.\n///\n/// This enables using the `?` operator on `Option`; it's rarely useful alone.\n#[derive(Debug)]\n#[unstable(feature = \"try_trait\", issue = \"42327\")]\npub struct None { _priv: () }\n\n#[unstable(feature = \"try_trait\", issue = \"42327\")]\nimpl<T> ops::Try for Option<T> {\n type Ok = T;\n type Error = None;\n\n fn into_result(self) -> Result<T, None> {\n self.ok_or(None { _priv: () })\n }\n\n fn from_ok(v: T) -> Self {\n Some(v)\n }\n\n fn from_error(_: None) -> Self {\n None\n }\n}\n```\n\nNote the `Error` associated type here is a new marker. The `?` operator\nallows interconversion between different `Try` implementers only when\nthe error type can be converted `Into` the error type of the enclosing\nfunction (or catch block). Having a distinct error type (as opposed to\njust `()`, or similar) restricts this to where it's semantically meaningful.\n" }] ;
5pub (super) const CLIPPY_LINTS : & [LintCompletion] = & [LintCompletion { label : "clippy::absurd_extreme_comparisons" , description : "Checks for comparisons where one side of the relation is\\neither the minimum or maximum value for its type and warns if it involves a\\ncase that is always true or always false. Only integer and boolean types are\\nchecked." } , LintCompletion { label : "clippy::almost_swapped" , description : "Checks for `foo = bar; bar = foo` sequences." } , LintCompletion { label : "clippy::approx_constant" , description : "Checks for floating point literals that approximate\\nconstants which are defined in\\n[`std::f32::consts`](https://doc.rust-lang.org/stable/std/f32/consts/#constants)\\nor\\n[`std::f64::consts`](https://doc.rust-lang.org/stable/std/f64/consts/#constants),\\nrespectively, suggesting to use the predefined constant." } , LintCompletion { label : "clippy::as_conversions" , description : "Checks for usage of `as` conversions." } , LintCompletion { label : "clippy::assertions_on_constants" , description : "Checks for `assert!(true)` and `assert!(false)` calls." } , LintCompletion { label : "clippy::assign_op_pattern" , description : "Checks for `a = a op b` or `a = b commutative_op a`\\npatterns." } , LintCompletion { label : "clippy::assign_ops" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::async_yields_async" , description : "Checks for async blocks that yield values of types\\nthat can themselves be awaited." } , LintCompletion { label : "clippy::await_holding_lock" , description : "Checks for calls to await while holding a\\nnon-async-aware MutexGuard." } , LintCompletion { label : "clippy::bad_bit_mask" , description : "Checks for incompatible bit masks in comparisons.\\n\\nThe formula for detecting if an expression of the type `_ <bit_op> m\\n<cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of\\n{`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following\\ntable:\\n\\n|Comparison |Bit Op|Example |is always|Formula |\\n|------------|------|------------|---------|----------------------|\\n|`==` or `!=`| `&` |`x & 2 == 3`|`false` |`c & m != c` |\\n|`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |\\n|`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |\\n|`==` or `!=`| `|` |`x | 1 == 0`|`false` |`c | m != c` |\\n|`<` or `>=`| `|` |`x | 1 < 1` |`false` |`m >= c` |\\n|`<=` or `>` | `|` |`x | 1 > 0` |`true` |`m > c` |" } , LintCompletion { label : "clippy::bind_instead_of_map" , description : "Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or\\n`_.or_else(|x| Err(y))`." } , LintCompletion { label : "clippy::blacklisted_name" , description : "Checks for usage of blacklisted names for variables, such\\nas `foo`." } , LintCompletion { label : "clippy::blanket_clippy_restriction_lints" , description : "Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category." } , LintCompletion { label : "clippy::blocks_in_if_conditions" , description : "Checks for `if` conditions that use blocks containing an\\nexpression, statements or conditions that use closures with blocks." } , LintCompletion { label : "clippy::bool_comparison" , description : "Checks for expressions of the form `x == true`,\\n`x != true` and order comparisons such as `x < true` (or vice versa) and\\nsuggest using the variable directly." } , LintCompletion { label : "clippy::borrow_interior_mutable_const" , description : "Checks if `const` items which is interior mutable (e.g.,\\ncontains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly." } , LintCompletion { label : "clippy::borrowed_box" , description : "Checks for use of `&Box<T>` anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::box_vec" , description : "Checks for use of `Box<Vec<_>>` anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::boxed_local" , description : "Checks for usage of `Box<T>` where an unboxed `T` would\\nwork fine." } , LintCompletion { label : "clippy::builtin_type_shadow" , description : "Warns if a generic shadows a built-in type." } , LintCompletion { label : "clippy::cargo_common_metadata" , description : "Checks to see if all common metadata is defined in\\n`Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata" } , LintCompletion { label : "clippy::cast_lossless" , description : "Checks for casts between numerical types that may\\nbe replaced by safe conversion functions." } , LintCompletion { label : "clippy::cast_possible_truncation" , description : "Checks for casts between numerical types that may\\ntruncate large values. This is expected behavior, so the cast is `Allow` by\\ndefault." } , LintCompletion { label : "clippy::cast_possible_wrap" , description : "Checks for casts from an unsigned type to a signed type of\\nthe same size. Performing such a cast is a 'no-op' for the compiler,\\ni.e., nothing is changed at the bit level, and the binary representation of\\nthe value is reinterpreted. This can cause wrapping if the value is too big\\nfor the target signed type. However, the cast works as defined, so this lint\\nis `Allow` by default." } , LintCompletion { label : "clippy::cast_precision_loss" , description : "Checks for casts from any numerical to a float type where\\nthe receiving type cannot store all values from the original type without\\nrounding errors. This possible rounding is to be expected, so this lint is\\n`Allow` by default.\\n\\nBasically, this warns on casting any integer with 32 or more bits to `f32`\\nor any 64-bit integer to `f64`." } , LintCompletion { label : "clippy::cast_ptr_alignment" , description : "Checks for casts from a less-strictly-aligned pointer to a\\nmore-strictly-aligned pointer" } , LintCompletion { label : "clippy::cast_ref_to_mut" , description : "Checks for casts of `&T` to `&mut T` anywhere in the code." } , LintCompletion { label : "clippy::cast_sign_loss" , description : "Checks for casts from a signed to an unsigned numerical\\ntype. In this case, negative values wrap around to large positive values,\\nwhich can be quite surprising in practice. However, as the cast works as\\ndefined, this lint is `Allow` by default." } , LintCompletion { label : "clippy::char_lit_as_u8" , description : "Checks for expressions where a character literal is cast\\nto `u8` and suggests using a byte literal instead." } , LintCompletion { label : "clippy::chars_last_cmp" , description : "Checks for usage of `_.chars().last()` or\\n`_.chars().next_back()` on a `str` to check if it ends with a given char." } , LintCompletion { label : "clippy::chars_next_cmp" , description : "Checks for usage of `.chars().next()` on a `str` to check\\nif it starts with a given char." } , LintCompletion { label : "clippy::checked_conversions" , description : "Checks for explicit bounds checking when casting." } , LintCompletion { label : "clippy::clone_double_ref" , description : "Checks for usage of `.clone()` on an `&&T`." } , LintCompletion { label : "clippy::clone_on_copy" , description : "Checks for usage of `.clone()` on a `Copy` type." } , LintCompletion { label : "clippy::clone_on_ref_ptr" , description : "Checks for usage of `.clone()` on a ref-counted pointer,\\n(`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified\\nfunction syntax instead (e.g., `Rc::clone(foo)`)." } , LintCompletion { label : "clippy::cmp_nan" , description : "Checks for comparisons to NaN." } , LintCompletion { label : "clippy::cmp_null" , description : "This lint checks for equality comparisons with `ptr::null`" } , LintCompletion { label : "clippy::cmp_owned" , description : "Checks for conversions to owned values just for the sake\\nof a comparison." } , LintCompletion { label : "clippy::cognitive_complexity" , description : "Checks for methods with high cognitive complexity." } , LintCompletion { label : "clippy::collapsible_if" , description : "Checks for nested `if` statements which can be collapsed\\nby `&&`-combining their conditions and for `else { if ... }` expressions\\nthat\\ncan be collapsed to `else if ...`." } , LintCompletion { label : "clippy::comparison_chain" , description : "Checks comparison chains written with `if` that can be\\nrewritten with `match` and `cmp`." } , LintCompletion { label : "clippy::copy_iterator" , description : "Checks for types that implement `Copy` as well as\\n`Iterator`." } , LintCompletion { label : "clippy::create_dir" , description : "Checks usage of `std::fs::create_dir` and suggest using `std::fs::create_dir_all` instead." } , LintCompletion { label : "clippy::crosspointer_transmute" , description : "Checks for transmutes between a type `T` and `*T`." } , LintCompletion { label : "clippy::dbg_macro" , description : "Checks for usage of dbg!() macro." } , LintCompletion { label : "clippy::debug_assert_with_mut_call" , description : "Checks for function/method calls with a mutable\\nparameter in `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` macros." } , LintCompletion { label : "clippy::decimal_literal_representation" , description : "Warns if there is a better representation for a numeric literal." } , LintCompletion { label : "clippy::declare_interior_mutable_const" , description : "Checks for declaration of `const` items which is interior\\nmutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.)." } , LintCompletion { label : "clippy::default_trait_access" , description : "Checks for literal calls to `Default::default()`." } , LintCompletion { label : "clippy::deprecated_cfg_attr" , description : "Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it\\nwith `#[rustfmt::skip]`." } , LintCompletion { label : "clippy::deprecated_semver" , description : "Checks for `#[deprecated]` annotations with a `since`\\nfield that is not a valid semantic version." } , LintCompletion { label : "clippy::deref_addrof" , description : "Checks for usage of `*&` and `*&mut` in expressions." } , LintCompletion { label : "clippy::derive_hash_xor_eq" , description : "Checks for deriving `Hash` but implementing `PartialEq`\\nexplicitly or vice versa." } , LintCompletion { label : "clippy::derive_ord_xor_partial_ord" , description : "Checks for deriving `Ord` but implementing `PartialOrd`\\nexplicitly or vice versa." } , LintCompletion { label : "clippy::disallowed_method" , description : "Lints for specific trait methods defined in clippy.toml" } , LintCompletion { label : "clippy::diverging_sub_expression" , description : "Checks for diverging calls that are not match arms or\\nstatements." } , LintCompletion { label : "clippy::doc_markdown" , description : "Checks for the presence of `_`, `::` or camel-case words\\noutside ticks in documentation." } , LintCompletion { label : "clippy::double_comparisons" , description : "Checks for double comparisons that could be simplified to a single expression." } , LintCompletion { label : "clippy::double_must_use" , description : "Checks for a [`#[must_use]`] attribute without\\nfurther information on functions and methods that return a type already\\nmarked as `#[must_use]`.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::double_neg" , description : "Detects expressions of the form `--x`." } , LintCompletion { label : "clippy::double_parens" , description : "Checks for unnecessary double parentheses." } , LintCompletion { label : "clippy::drop_bounds" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::drop_copy" , description : "Checks for calls to `std::mem::drop` with a value\\nthat derives the Copy trait" } , LintCompletion { label : "clippy::drop_ref" , description : "Checks for calls to `std::mem::drop` with a reference\\ninstead of an owned value." } , LintCompletion { label : "clippy::duplicate_underscore_argument" , description : "Checks for function arguments having the similar names\\ndiffering by an underscore." } , LintCompletion { label : "clippy::duration_subsec" , description : "Checks for calculation of subsecond microseconds or milliseconds\\nfrom other `Duration` methods." } , LintCompletion { label : "clippy::else_if_without_else" , description : "Checks for usage of if expressions with an `else if` branch,\\nbut without a final `else` branch." } , LintCompletion { label : "clippy::empty_enum" , description : "Checks for `enum`s with no variants." } , LintCompletion { label : "clippy::empty_line_after_outer_attr" , description : "Checks for empty lines after outer attributes" } , LintCompletion { label : "clippy::empty_loop" , description : "Checks for empty `loop` expressions." } , LintCompletion { label : "clippy::enum_clike_unportable_variant" , description : "Checks for C-like enumerations that are\\n`repr(isize/usize)` and have values that don't fit into an `i32`." } , LintCompletion { label : "clippy::enum_glob_use" , description : "Checks for `use Enum::*`." } , LintCompletion { label : "clippy::enum_variant_names" , description : "Detects enumeration variants that are prefixed or suffixed\\nby the same characters." } , LintCompletion { label : "clippy::eq_op" , description : "Checks for equal operands to comparison, logical and\\nbitwise, difference and division binary operators (`==`, `>`, etc., `&&`,\\n`||`, `&`, `|`, `^`, `-` and `/`)." } , LintCompletion { label : "clippy::erasing_op" , description : "Checks for erasing operations, e.g., `x * 0`." } , LintCompletion { label : "clippy::eval_order_dependence" , description : "Checks for a read and a write to the same variable where\\nwhether the read occurs before or after the write depends on the evaluation\\norder of sub-expressions." } , LintCompletion { label : "clippy::excessive_precision" , description : "Checks for float literals with a precision greater\\nthan that supported by the underlying type." } , LintCompletion { label : "clippy::exit" , description : "`exit()` terminates the program and doesn't provide a\\nstack trace." } , LintCompletion { label : "clippy::expect_fun_call" , description : "Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,\\netc., and suggests to use `unwrap_or_else` instead" } , LintCompletion { label : "clippy::expect_used" , description : "Checks for `.expect()` calls on `Option`s and `Result`s." } , LintCompletion { label : "clippy::expl_impl_clone_on_copy" , description : "Checks for explicit `Clone` implementations for `Copy`\\ntypes." } , LintCompletion { label : "clippy::explicit_counter_loop" , description : "Checks `for` loops over slices with an explicit counter\\nand suggests the use of `.enumerate()`." } , LintCompletion { label : "clippy::explicit_deref_methods" , description : "Checks for explicit `deref()` or `deref_mut()` method calls." } , LintCompletion { label : "clippy::explicit_into_iter_loop" , description : "Checks for loops on `y.into_iter()` where `y` will do, and\\nsuggests the latter." } , LintCompletion { label : "clippy::explicit_iter_loop" , description : "Checks for loops on `x.iter()` where `&x` will do, and\\nsuggests the latter." } , LintCompletion { label : "clippy::explicit_write" , description : "Checks for usage of `write!()` / `writeln()!` which can be\\nreplaced with `(e)print!()` / `(e)println!()`" } , LintCompletion { label : "clippy::extend_from_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::extra_unused_lifetimes" , description : "Checks for lifetimes in generics that are never used\\nanywhere else." } , LintCompletion { label : "clippy::fallible_impl_from" , description : "Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`" } , LintCompletion { label : "clippy::filetype_is_file" , description : "Checks for `FileType::is_file()`." } , LintCompletion { label : "clippy::filter_map" , description : "Checks for usage of `_.filter(_).map(_)`,\\n`_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar." } , LintCompletion { label : "clippy::filter_map_next" , description : "Checks for usage of `_.filter_map(_).next()`." } , LintCompletion { label : "clippy::filter_next" , description : "Checks for usage of `_.filter(_).next()`." } , LintCompletion { label : "clippy::find_map" , description : "Checks for usage of `_.find(_).map(_)`." } , LintCompletion { label : "clippy::flat_map_identity" , description : "Checks for usage of `flat_map(|x| x)`." } , LintCompletion { label : "clippy::float_arithmetic" , description : "Checks for float arithmetic." } , LintCompletion { label : "clippy::float_cmp" , description : "Checks for (in-)equality comparisons on floating-point\\nvalues (apart from zero), except in functions called `*eq*` (which probably\\nimplement equality for a type involving floats)." } , LintCompletion { label : "clippy::float_cmp_const" , description : "Checks for (in-)equality comparisons on floating-point\\nvalue and constant, except in functions called `*eq*` (which probably\\nimplement equality for a type involving floats)." } , LintCompletion { label : "clippy::float_equality_without_abs" , description : "Checks for statements of the form `(a - b) < f32::EPSILON` or\\n`(a - b) < f64::EPSILON`. Notes the missing `.abs()`." } , LintCompletion { label : "clippy::fn_address_comparisons" , description : "Checks for comparisons with an address of a function item." } , LintCompletion { label : "clippy::fn_params_excessive_bools" , description : "Checks for excessive use of\\nbools in function definitions." } , LintCompletion { label : "clippy::fn_to_numeric_cast" , description : "Checks for casts of function pointers to something other than usize" } , LintCompletion { label : "clippy::fn_to_numeric_cast_with_truncation" , description : "Checks for casts of a function pointer to a numeric type not wide enough to\\nstore address." } , LintCompletion { label : "clippy::for_kv_map" , description : "Checks for iterating a map (`HashMap` or `BTreeMap`) and\\nignoring either the keys or values." } , LintCompletion { label : "clippy::for_loops_over_fallibles" , description : "Checks for `for` loops over `Option` or `Result` values." } , LintCompletion { label : "clippy::forget_copy" , description : "Checks for calls to `std::mem::forget` with a value that\\nderives the Copy trait" } , LintCompletion { label : "clippy::forget_ref" , description : "Checks for calls to `std::mem::forget` with a reference\\ninstead of an owned value." } , LintCompletion { label : "clippy::future_not_send" , description : "This lint requires Future implementations returned from\\nfunctions and methods to implement the `Send` marker trait. It is mostly\\nused by library authors (public and internal) that target an audience where\\nmultithreaded executors are likely to be used for running these Futures." } , LintCompletion { label : "clippy::get_last_with_len" , description : "Checks for using `x.get(x.len() - 1)` instead of\\n`x.last()`." } , LintCompletion { label : "clippy::get_unwrap" , description : "Checks for use of `.get().unwrap()` (or\\n`.get_mut().unwrap`) on a standard library type which implements `Index`" } , LintCompletion { label : "clippy::identity_op" , description : "Checks for identity operations, e.g., `x + 0`." } , LintCompletion { label : "clippy::if_let_mutex" , description : "Checks for `Mutex::lock` calls in `if let` expression\\nwith lock calls in any of the else blocks." } , LintCompletion { label : "clippy::if_let_redundant_pattern_matching" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::if_let_some_result" , description : "* Checks for unnecessary `ok()` in if let." } , LintCompletion { label : "clippy::if_not_else" , description : "Checks for usage of `!` or `!=` in an if condition with an\\nelse branch." } , LintCompletion { label : "clippy::if_same_then_else" , description : "Checks for `if/else` with the same body as the *then* part\\nand the *else* part." } , LintCompletion { label : "clippy::ifs_same_cond" , description : "Checks for consecutive `if`s with the same condition." } , LintCompletion { label : "clippy::implicit_hasher" , description : "Checks for public `impl` or `fn` missing generalization\\nover different hashers and implicitly defaulting to the default hashing\\nalgorithm (`SipHash`)." } , LintCompletion { label : "clippy::implicit_return" , description : "Checks for missing return statements at the end of a block." } , LintCompletion { label : "clippy::implicit_saturating_sub" , description : "Checks for implicit saturating subtraction." } , LintCompletion { label : "clippy::imprecise_flops" , description : "Looks for floating-point expressions that\\ncan be expressed using built-in methods to improve accuracy\\nat the cost of performance." } , LintCompletion { label : "clippy::inconsistent_digit_grouping" , description : "Warns if an integral or floating-point constant is\\ngrouped inconsistently with underscores." } , LintCompletion { label : "clippy::indexing_slicing" , description : "Checks for usage of indexing or slicing. Arrays are special cases, this lint\\ndoes report on arrays if we can tell that slicing operations are in bounds and does not\\nlint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint." } , LintCompletion { label : "clippy::ineffective_bit_mask" , description : "Checks for bit masks in comparisons which can be removed\\nwithout changing the outcome. The basic structure can be seen in the\\nfollowing table:\\n\\n|Comparison| Bit Op |Example |equals |\\n|----------|---------|-----------|-------|\\n|`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|\\n|`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|" } , LintCompletion { label : "clippy::inefficient_to_string" , description : "Checks for usage of `.to_string()` on an `&&T` where\\n`T` implements `ToString` directly (like `&&str` or `&&String`)." } , LintCompletion { label : "clippy::infallible_destructuring_match" , description : "Checks for matches being used to destructure a single-variant enum\\nor tuple struct where a `let` will suffice." } , LintCompletion { label : "clippy::infinite_iter" , description : "Checks for iteration that is guaranteed to be infinite." } , LintCompletion { label : "clippy::inherent_to_string" , description : "Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`." } , LintCompletion { label : "clippy::inherent_to_string_shadow_display" , description : "Checks for the definition of inherent methods with a signature of `to_string(&self) -> String` and if the type implementing this method also implements the `Display` trait." } , LintCompletion { label : "clippy::inline_always" , description : "Checks for items annotated with `#[inline(always)]`,\\nunless the annotated function is empty or simply panics." } , LintCompletion { label : "clippy::inline_asm_x86_att_syntax" , description : "Checks for usage of AT&T x86 assembly syntax." } , LintCompletion { label : "clippy::inline_asm_x86_intel_syntax" , description : "Checks for usage of Intel x86 assembly syntax." } , LintCompletion { label : "clippy::inline_fn_without_body" , description : "Checks for `#[inline]` on trait methods without bodies" } , LintCompletion { label : "clippy::int_plus_one" , description : "Checks for usage of `x >= y + 1` or `x - 1 >= y` (and `<=`) in a block" } , LintCompletion { label : "clippy::integer_arithmetic" , description : "Checks for integer arithmetic operations which could overflow or panic.\\n\\nSpecifically, checks for any operators (`+`, `-`, `*`, `<<`, etc) which are capable\\nof overflowing according to the [Rust\\nReference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow),\\nor which can panic (`/`, `%`). No bounds analysis or sophisticated reasoning is\\nattempted." } , LintCompletion { label : "clippy::integer_division" , description : "Checks for division of integers" } , LintCompletion { label : "clippy::into_iter_on_array" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::into_iter_on_ref" , description : "Checks for `into_iter` calls on references which should be replaced by `iter`\\nor `iter_mut`." } , LintCompletion { label : "clippy::invalid_atomic_ordering" , description : "Checks for usage of invalid atomic\\nordering in atomic loads/stores/exchanges/updates and\\nmemory fences." } , LintCompletion { label : "clippy::invalid_ref" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::invalid_regex" , description : "Checks [regex](https://crates.io/crates/regex) creation\\n(with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct\\nregex syntax." } , LintCompletion { label : "clippy::invalid_upcast_comparisons" , description : "Checks for comparisons where the relation is always either\\ntrue or false, but where one side has been upcast so that the comparison is\\nnecessary. Only integer types are checked." } , LintCompletion { label : "clippy::invisible_characters" , description : "Checks for invisible Unicode characters in the code." } , LintCompletion { label : "clippy::items_after_statements" , description : "Checks for items declared after some statement in a block." } , LintCompletion { label : "clippy::iter_cloned_collect" , description : "Checks for the use of `.cloned().collect()` on slice to\\ncreate a `Vec`." } , LintCompletion { label : "clippy::iter_next_loop" , description : "Checks for loops on `x.next()`." } , LintCompletion { label : "clippy::iter_next_slice" , description : "Checks for usage of `iter().next()` on a Slice or an Array" } , LintCompletion { label : "clippy::iter_nth" , description : "Checks for use of `.iter().nth()` (and the related\\n`.iter_mut().nth()`) on standard library types with O(1) element access." } , LintCompletion { label : "clippy::iter_nth_zero" , description : "Checks for the use of `iter.nth(0)`." } , LintCompletion { label : "clippy::iter_skip_next" , description : "Checks for use of `.skip(x).next()` on iterators." } , LintCompletion { label : "clippy::iterator_step_by_zero" , description : "Checks for calling `.step_by(0)` on iterators which panics." } , LintCompletion { label : "clippy::just_underscores_and_digits" , description : "Checks if you have variables whose name consists of just\\nunderscores and digits." } , LintCompletion { label : "clippy::large_const_arrays" , description : "Checks for large `const` arrays that should\\nbe defined as `static` instead." } , LintCompletion { label : "clippy::large_digit_groups" , description : "Warns if the digits of an integral or floating-point\\nconstant are grouped into groups that\\nare too large." } , LintCompletion { label : "clippy::large_enum_variant" , description : "Checks for large size differences between variants on\\n`enum`s." } , LintCompletion { label : "clippy::large_stack_arrays" , description : "Checks for local arrays that may be too large." } , LintCompletion { label : "clippy::len_without_is_empty" , description : "Checks for items that implement `.len()` but not\\n`.is_empty()`." } , LintCompletion { label : "clippy::len_zero" , description : "Checks for getting the length of something via `.len()`\\njust to compare to zero, and suggests using `.is_empty()` where applicable." } , LintCompletion { label : "clippy::let_and_return" , description : "Checks for `let`-bindings, which are subsequently\\nreturned." } , LintCompletion { label : "clippy::let_underscore_lock" , description : "Checks for `let _ = sync_lock`" } , LintCompletion { label : "clippy::let_underscore_must_use" , description : "Checks for `let _ = <expr>`\\nwhere expr is #[must_use]" } , LintCompletion { label : "clippy::let_unit_value" , description : "Checks for binding a unit value." } , LintCompletion { label : "clippy::linkedlist" , description : "Checks for usage of any `LinkedList`, suggesting to use a\\n`Vec` or a `VecDeque` (formerly called `RingBuf`)." } , LintCompletion { label : "clippy::logic_bug" , description : "Checks for boolean expressions that contain terminals that\\ncan be eliminated." } , LintCompletion { label : "clippy::lossy_float_literal" , description : "Checks for whole number float literals that\\ncannot be represented as the underlying type without loss." } , LintCompletion { label : "clippy::macro_use_imports" , description : "Checks for `#[macro_use] use...`." } , LintCompletion { label : "clippy::main_recursion" , description : "Checks for recursion using the entrypoint." } , LintCompletion { label : "clippy::manual_async_fn" , description : "It checks for manual implementations of `async` functions." } , LintCompletion { label : "clippy::manual_memcpy" , description : "Checks for for-loops that manually copy items between\\nslices that could be optimized by having a memcpy." } , LintCompletion { label : "clippy::manual_non_exhaustive" , description : "Checks for manual implementations of the non-exhaustive pattern." } , LintCompletion { label : "clippy::manual_saturating_arithmetic" , description : "Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`." } , LintCompletion { label : "clippy::manual_strip" , description : "Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using\\nthe pattern's length." } , LintCompletion { label : "clippy::manual_swap" , description : "Checks for manual swapping." } , LintCompletion { label : "clippy::manual_unwrap_or" , description : "Finds patterns that reimplement `Option::unwrap_or`." } , LintCompletion { label : "clippy::many_single_char_names" , description : "Checks for too many variables whose name consists of a\\nsingle character." } , LintCompletion { label : "clippy::map_clone" , description : "Checks for usage of `iterator.map(|x| x.clone())` and suggests\\n`iterator.cloned()` instead" } , LintCompletion { label : "clippy::map_entry" , description : "Checks for uses of `contains_key` + `insert` on `HashMap`\\nor `BTreeMap`." } , LintCompletion { label : "clippy::map_err_ignore" , description : "Checks for instances of `map_err(|_| Some::Enum)`" } , LintCompletion { label : "clippy::map_flatten" , description : "Checks for usage of `_.map(_).flatten(_)`," } , LintCompletion { label : "clippy::map_identity" , description : "Checks for instances of `map(f)` where `f` is the identity function." } , LintCompletion { label : "clippy::map_unwrap_or" , description : "Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or\\n`result.map(_).unwrap_or_else(_)`." } , LintCompletion { label : "clippy::match_as_ref" , description : "Checks for match which is used to add a reference to an\\n`Option` value." } , LintCompletion { label : "clippy::match_bool" , description : "Checks for matches where match expression is a `bool`. It\\nsuggests to replace the expression with an `if...else` block." } , LintCompletion { label : "clippy::match_like_matches_macro" , description : "Checks for `match` or `if let` expressions producing a\\n`bool` that could be written using `matches!`" } , LintCompletion { label : "clippy::match_on_vec_items" , description : "Checks for `match vec[idx]` or `match vec[n..m]`." } , LintCompletion { label : "clippy::match_overlapping_arm" , description : "Checks for overlapping match arms." } , LintCompletion { label : "clippy::match_ref_pats" , description : "Checks for matches where all arms match a reference,\\nsuggesting to remove the reference and deref the matched expression\\ninstead. It also checks for `if let &foo = bar` blocks." } , LintCompletion { label : "clippy::match_same_arms" , description : "Checks for `match` with identical arm bodies." } , LintCompletion { label : "clippy::match_single_binding" , description : "Checks for useless match that binds to only one value." } , LintCompletion { label : "clippy::match_wild_err_arm" , description : "Checks for arm which matches all errors with `Err(_)`\\nand take drastic actions like `panic!`." } , LintCompletion { label : "clippy::match_wildcard_for_single_variants" , description : "Checks for wildcard enum matches for a single variant." } , LintCompletion { label : "clippy::maybe_infinite_iter" , description : "Checks for iteration that may be infinite." } , LintCompletion { label : "clippy::mem_discriminant_non_enum" , description : "Checks for calls of `mem::discriminant()` on a non-enum type." } , LintCompletion { label : "clippy::mem_forget" , description : "Checks for usage of `std::mem::forget(t)` where `t` is\\n`Drop`." } , LintCompletion { label : "clippy::mem_replace_option_with_none" , description : "Checks for `mem::replace()` on an `Option` with\\n`None`." } , LintCompletion { label : "clippy::mem_replace_with_default" , description : "Checks for `std::mem::replace` on a value of type\\n`T` with `T::default()`." } , LintCompletion { label : "clippy::mem_replace_with_uninit" , description : "Checks for `mem::replace(&mut _, mem::uninitialized())`\\nand `mem::replace(&mut _, mem::zeroed())`." } , LintCompletion { label : "clippy::min_max" , description : "Checks for expressions where `std::cmp::min` and `max` are\\nused to clamp values, but switched so that the result is constant." } , LintCompletion { label : "clippy::misaligned_transmute" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::mismatched_target_os" , description : "Checks for cfg attributes having operating systems used in target family position." } , LintCompletion { label : "clippy::misrefactored_assign_op" , description : "Checks for `a op= a op b` or `a op= b op a` patterns." } , LintCompletion { label : "clippy::missing_const_for_fn" , description : "Suggests the use of `const` in functions and methods where possible." } , LintCompletion { label : "clippy::missing_docs_in_private_items" , description : "Warns if there is missing doc for any documentable item\\n(public or private)." } , LintCompletion { label : "clippy::missing_errors_doc" , description : "Checks the doc comments of publicly visible functions that\\nreturn a `Result` type and warns if there is no `# Errors` section." } , LintCompletion { label : "clippy::missing_inline_in_public_items" , description : "it lints if an exported function, method, trait method with default impl,\\nor trait method impl is not `#[inline]`." } , LintCompletion { label : "clippy::missing_safety_doc" , description : "Checks for the doc comments of publicly visible\\nunsafe functions and warns if there is no `# Safety` section." } , LintCompletion { label : "clippy::mistyped_literal_suffixes" , description : "Warns for mistyped suffix in literals" } , LintCompletion { label : "clippy::mixed_case_hex_literals" , description : "Warns on hexadecimal literals with mixed-case letter\\ndigits." } , LintCompletion { label : "clippy::module_inception" , description : "Checks for modules that have the same name as their\\nparent module" } , LintCompletion { label : "clippy::module_name_repetitions" , description : "Detects type names that are prefixed or suffixed by the\\ncontaining module's name." } , LintCompletion { label : "clippy::modulo_arithmetic" , description : "Checks for modulo arithmetic." } , LintCompletion { label : "clippy::modulo_one" , description : "Checks for getting the remainder of a division by one." } , LintCompletion { label : "clippy::multiple_crate_versions" , description : "Checks to see if multiple versions of a crate are being\\nused." } , LintCompletion { label : "clippy::multiple_inherent_impl" , description : "Checks for multiple inherent implementations of a struct" } , LintCompletion { label : "clippy::must_use_candidate" , description : "Checks for public functions that have no\\n[`#[must_use]`] attribute, but return something not already marked\\nmust-use, have no mutable arg and mutate no statics.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::must_use_unit" , description : "Checks for a [`#[must_use]`] attribute on\\nunit-returning functions and methods.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::mut_from_ref" , description : "This lint checks for functions that take immutable\\nreferences and return mutable ones." } , LintCompletion { label : "clippy::mut_mut" , description : "Checks for instances of `mut mut` references." } , LintCompletion { label : "clippy::mut_range_bound" , description : "Checks for loops which have a range bound that is a mutable variable" } , LintCompletion { label : "clippy::mutable_key_type" , description : "Checks for sets/maps with mutable key types." } , LintCompletion { label : "clippy::mutex_atomic" , description : "Checks for usages of `Mutex<X>` where an atomic will do." } , LintCompletion { label : "clippy::mutex_integer" , description : "Checks for usages of `Mutex<X>` where `X` is an integral\\ntype." } , LintCompletion { label : "clippy::naive_bytecount" , description : "Checks for naive byte counts" } , LintCompletion { label : "clippy::needless_arbitrary_self_type" , description : "The lint checks for `self` in fn parameters that\\nspecify the `Self`-type explicitly" } , LintCompletion { label : "clippy::needless_bool" , description : "Checks for expressions of the form `if c { true } else {\\nfalse }` (or vice versa) and suggests using the condition directly." } , LintCompletion { label : "clippy::needless_borrow" , description : "Checks for address of operations (`&`) that are going to\\nbe dereferenced immediately by the compiler." } , LintCompletion { label : "clippy::needless_borrowed_reference" , description : "Checks for useless borrowed references." } , LintCompletion { label : "clippy::needless_collect" , description : "Checks for functions collecting an iterator when collect\\nis not needed." } , LintCompletion { label : "clippy::needless_continue" , description : "The lint checks for `if`-statements appearing in loops\\nthat contain a `continue` statement in either their main blocks or their\\n`else`-blocks, when omitting the `else`-block possibly with some\\nrearrangement of code can make the code easier to understand." } , LintCompletion { label : "clippy::needless_doctest_main" , description : "Checks for `fn main() { .. }` in doctests" } , LintCompletion { label : "clippy::needless_lifetimes" , description : "Checks for lifetime annotations which can be removed by\\nrelying on lifetime elision." } , LintCompletion { label : "clippy::needless_pass_by_value" , description : "Checks for functions taking arguments by value, but not\\nconsuming them in its\\nbody." } , LintCompletion { label : "clippy::needless_range_loop" , description : "Checks for looping over the range of `0..len` of some\\ncollection just to get the values by index." } , LintCompletion { label : "clippy::needless_return" , description : "Checks for return statements at the end of a block." } , LintCompletion { label : "clippy::needless_update" , description : "Checks for needlessly including a base struct on update\\nwhen all fields are changed anyway." } , LintCompletion { label : "clippy::neg_cmp_op_on_partial_ord" , description : "Checks for the usage of negated comparison operators on types which only implement\\n`PartialOrd` (e.g., `f64`)." } , LintCompletion { label : "clippy::neg_multiply" , description : "Checks for multiplication by -1 as a form of negation." } , LintCompletion { label : "clippy::never_loop" , description : "Checks for loops that will always `break`, `return` or\\n`continue` an outer loop." } , LintCompletion { label : "clippy::new_ret_no_self" , description : "Checks for `new` not returning a type that contains `Self`." } , LintCompletion { label : "clippy::new_without_default" , description : "Checks for types with a `fn new() -> Self` method and no\\nimplementation of\\n[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)." } , LintCompletion { label : "clippy::no_effect" , description : "Checks for statements which have no effect." } , LintCompletion { label : "clippy::non_ascii_literal" , description : "Checks for non-ASCII characters in string literals." } , LintCompletion { label : "clippy::nonminimal_bool" , description : "Checks for boolean expressions that can be written more\\nconcisely." } , LintCompletion { label : "clippy::nonsensical_open_options" , description : "Checks for duplicate open options as well as combinations\\nthat make no sense." } , LintCompletion { label : "clippy::not_unsafe_ptr_arg_deref" , description : "Checks for public functions that dereference raw pointer\\narguments but are not marked unsafe." } , LintCompletion { label : "clippy::ok_expect" , description : "Checks for usage of `ok().expect(..)`." } , LintCompletion { label : "clippy::op_ref" , description : "Checks for arguments to `==` which have their address\\ntaken to satisfy a bound\\nand suggests to dereference the other argument instead" } , LintCompletion { label : "clippy::option_as_ref_deref" , description : "Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str)." } , LintCompletion { label : "clippy::option_env_unwrap" , description : "Checks for usage of `option_env!(...).unwrap()` and\\nsuggests usage of the `env!` macro." } , LintCompletion { label : "clippy::option_if_let_else" , description : "Lints usage of `if let Some(v) = ... { y } else { x }` which is more\\nidiomatically done with `Option::map_or` (if the else bit is a pure\\nexpression) or `Option::map_or_else` (if the else bit is an impure\\nexpression)." } , LintCompletion { label : "clippy::option_map_or_none" , description : "Checks for usage of `_.map_or(None, _)`." } , LintCompletion { label : "clippy::option_map_unit_fn" , description : "Checks for usage of `option.map(f)` where f is a function\\nor closure that returns the unit type `()`." } , LintCompletion { label : "clippy::option_option" , description : "Checks for use of `Option<Option<_>>` in function signatures and type\\ndefinitions" } , LintCompletion { label : "clippy::or_fun_call" , description : "Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,\\netc., and suggests to use `or_else`, `unwrap_or_else`, etc., or\\n`unwrap_or_default` instead." } , LintCompletion { label : "clippy::out_of_bounds_indexing" , description : "Checks for out of bounds array indexing with a constant\\nindex." } , LintCompletion { label : "clippy::overflow_check_conditional" , description : "Detects classic underflow/overflow checks." } , LintCompletion { label : "clippy::panic" , description : "Checks for usage of `panic!`." } , LintCompletion { label : "clippy::panic_in_result_fn" , description : "Checks for usage of `panic!`, `unimplemented!`, `todo!` or `unreachable!` in a function of type result." } , LintCompletion { label : "clippy::panic_params" , description : "Checks for missing parameters in `panic!`." } , LintCompletion { label : "clippy::panicking_unwrap" , description : "Checks for calls of `unwrap[_err]()` that will always fail." } , LintCompletion { label : "clippy::partialeq_ne_impl" , description : "Checks for manual re-implementations of `PartialEq::ne`." } , LintCompletion { label : "clippy::path_buf_push_overwrite" , description : "* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)\\ncalls on `PathBuf` that can cause overwrites." } , LintCompletion { label : "clippy::pattern_type_mismatch" , description : "Checks for patterns that aren't exact representations of the types\\nthey are applied to.\\n\\nTo satisfy this lint, you will have to adjust either the expression that is matched\\nagainst or the pattern itself, as well as the bindings that are introduced by the\\nadjusted patterns. For matching you will have to either dereference the expression\\nwith the `*` operator, or amend the patterns to explicitly match against `&<pattern>`\\nor `&mut <pattern>` depending on the reference mutability. For the bindings you need\\nto use the inverse. You can leave them as plain bindings if you wish for the value\\nto be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct\\na reference into the matched structure.\\n\\nIf you are looking for a way to learn about ownership semantics in more detail, it\\nis recommended to look at IDE options available to you to highlight types, lifetimes\\nand reference semantics in your code. The available tooling would expose these things\\nin a general way even outside of the various pattern matching mechanics. Of course\\nthis lint can still be used to highlight areas of interest and ensure a good understanding\\nof ownership semantics." } , LintCompletion { label : "clippy::possible_missing_comma" , description : "Checks for possible missing comma in an array. It lints if\\nan array element is a binary operator expression and it lies on two lines." } , LintCompletion { label : "clippy::precedence" , description : "Checks for operations where precedence may be unclear\\nand suggests to add parentheses. Currently it catches the following:\\n* mixed usage of arithmetic and bit shifting/combining operators without\\nparentheses\\n* a \\\"negative\\\" numeric literal (which is really a unary `-` followed by a\\nnumeric literal)\\n followed by a method call" } , LintCompletion { label : "clippy::print_literal" , description : "This lint warns about the use of literals as `print!`/`println!` args." } , LintCompletion { label : "clippy::print_stdout" , description : "Checks for printing on *stdout*. The purpose of this lint\\nis to catch debugging remnants." } , LintCompletion { label : "clippy::print_with_newline" , description : "This lint warns when you use `print!()` with a format\\nstring that ends in a newline." } , LintCompletion { label : "clippy::println_empty_string" , description : "This lint warns when you use `println!(\\\"\\\")` to\\nprint a newline." } , LintCompletion { label : "clippy::ptr_arg" , description : "This lint checks for function arguments of type `&String`\\nor `&Vec` unless the references are mutable. It will also suggest you\\nreplace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`\\ncalls." } , LintCompletion { label : "clippy::ptr_eq" , description : "Use `std::ptr::eq` when applicable" } , LintCompletion { label : "clippy::ptr_offset_with_cast" , description : "Checks for usage of the `offset` pointer method with a `usize` casted to an\\n`isize`." } , LintCompletion { label : "clippy::pub_enum_variant_names" , description : "Detects public enumeration variants that are\\nprefixed or suffixed by the same characters." } , LintCompletion { label : "clippy::question_mark" , description : "Checks for expressions that could be replaced by the question mark operator." } , LintCompletion { label : "clippy::range_minus_one" , description : "Checks for inclusive ranges where 1 is subtracted from\\nthe upper bound, e.g., `x..=(y-1)`." } , LintCompletion { label : "clippy::range_plus_one" , description : "Checks for exclusive ranges where 1 is added to the\\nupper bound, e.g., `x..(y+1)`." } , LintCompletion { label : "clippy::range_step_by_zero" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::range_zip_with_len" , description : "Checks for zipping a collection with the range of\\n`0.._.len()`." } , LintCompletion { label : "clippy::rc_buffer" , description : "Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`." } , LintCompletion { label : "clippy::redundant_allocation" , description : "Checks for use of redundant allocations anywhere in the code." } , LintCompletion { label : "clippy::redundant_clone" , description : "Checks for a redundant `clone()` (and its relatives) which clones an owned\\nvalue that is going to be dropped without further use." } , LintCompletion { label : "clippy::redundant_closure" , description : "Checks for closures which just call another function where\\nthe function can be called directly. `unsafe` functions or calls where types\\nget adjusted are ignored." } , LintCompletion { label : "clippy::redundant_closure_call" , description : "Detects closures called in the same expression where they\\nare defined." } , LintCompletion { label : "clippy::redundant_closure_for_method_calls" , description : "Checks for closures which only invoke a method on the closure\\nargument and can be replaced by referencing the method directly." } , LintCompletion { label : "clippy::redundant_field_names" , description : "Checks for fields in struct literals where shorthands\\ncould be used." } , LintCompletion { label : "clippy::redundant_pattern" , description : "Checks for patterns in the form `name @ _`." } , LintCompletion { label : "clippy::redundant_pattern_matching" , description : "Lint for redundant pattern matching over `Result` or\\n`Option`" } , LintCompletion { label : "clippy::redundant_pub_crate" , description : "Checks for items declared `pub(crate)` that are not crate visible because they\\nare inside a private module." } , LintCompletion { label : "clippy::redundant_static_lifetimes" , description : "Checks for constants and statics with an explicit `'static` lifetime." } , LintCompletion { label : "clippy::ref_in_deref" , description : "Checks for references in expressions that use\\nauto dereference." } , LintCompletion { label : "clippy::regex_macro" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::repeat_once" , description : "Checks for usage of `.repeat(1)` and suggest the following method for each types.\\n- `.to_string()` for `str`\\n- `.clone()` for `String`\\n- `.to_vec()` for `slice`" } , LintCompletion { label : "clippy::replace_consts" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::rest_pat_in_fully_bound_structs" , description : "Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched." } , LintCompletion { label : "clippy::result_map_or_into_option" , description : "Checks for usage of `_.map_or(None, Some)`." } , LintCompletion { label : "clippy::result_map_unit_fn" , description : "Checks for usage of `result.map(f)` where f is a function\\nor closure that returns the unit type `()`." } , LintCompletion { label : "clippy::result_unit_err" , description : "Checks for public functions that return a `Result`\\nwith an `Err` type of `()`. It suggests using a custom type that\\nimplements [`std::error::Error`]." } , LintCompletion { label : "clippy::reversed_empty_ranges" , description : "Checks for range expressions `x..y` where both `x` and `y`\\nare constant and `x` is greater or equal to `y`." } , LintCompletion { label : "clippy::same_functions_in_if_condition" , description : "Checks for consecutive `if`s with the same function call." } , LintCompletion { label : "clippy::same_item_push" , description : "Checks whether a for loop is being used to push a constant\\nvalue into a Vec." } , LintCompletion { label : "clippy::search_is_some" , description : "Checks for an iterator search (such as `find()`,\\n`position()`, or `rposition()`) followed by a call to `is_some()`." } , LintCompletion { label : "clippy::self_assignment" , description : "Checks for explicit self-assignments." } , LintCompletion { label : "clippy::serde_api_misuse" , description : "Checks for mis-uses of the serde API." } , LintCompletion { label : "clippy::shadow_reuse" , description : "Checks for bindings that shadow other bindings already in\\nscope, while reusing the original value." } , LintCompletion { label : "clippy::shadow_same" , description : "Checks for bindings that shadow other bindings already in\\nscope, while just changing reference level or mutability." } , LintCompletion { label : "clippy::shadow_unrelated" , description : "Checks for bindings that shadow other bindings already in\\nscope, either without a initialization or with one that does not even use\\nthe original value." } , LintCompletion { label : "clippy::short_circuit_statement" , description : "Checks for the use of short circuit boolean conditions as\\na\\nstatement." } , LintCompletion { label : "clippy::should_assert_eq" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::should_implement_trait" , description : "Checks for methods that should live in a trait\\nimplementation of a `std` trait (see [llogiq's blog\\npost](http://llogiq.github.io/2015/07/30/traits.html) for further\\ninformation) instead of an inherent implementation." } , LintCompletion { label : "clippy::similar_names" , description : "Checks for names that are very similar and thus confusing." } , LintCompletion { label : "clippy::single_char_pattern" , description : "Checks for string methods that receive a single-character\\n`str` as an argument, e.g., `_.split(\\\"x\\\")`." } , LintCompletion { label : "clippy::single_char_push_str" , description : "Warns when using `push_str` with a single-character string literal,\\nand `push` with a `char` would work fine." } , LintCompletion { label : "clippy::single_component_path_imports" , description : "Checking for imports with single component use path." } , LintCompletion { label : "clippy::single_match" , description : "Checks for matches with a single arm where an `if let`\\nwill usually suffice." } , LintCompletion { label : "clippy::single_match_else" , description : "Checks for matches with two arms where an `if let else` will\\nusually suffice." } , LintCompletion { label : "clippy::skip_while_next" , description : "Checks for usage of `_.skip_while(condition).next()`." } , LintCompletion { label : "clippy::slow_vector_initialization" , description : "Checks slow zero-filled vector initialization" } , LintCompletion { label : "clippy::stable_sort_primitive" , description : "When sorting primitive values (integers, bools, chars, as well\\nas arrays, slices, and tuples of such items), it is better to\\nuse an unstable sort than a stable sort." } , LintCompletion { label : "clippy::str_to_string" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::string_add" , description : "Checks for all instances of `x + _` where `x` is of type\\n`String`, but only if [`string_add_assign`](#string_add_assign) does *not*\\nmatch." } , LintCompletion { label : "clippy::string_add_assign" , description : "Checks for string appends of the form `x = x + y` (without\\n`let`!)." } , LintCompletion { label : "clippy::string_extend_chars" , description : "Checks for the use of `.extend(s.chars())` where s is a\\n`&str` or `String`." } , LintCompletion { label : "clippy::string_lit_as_bytes" , description : "Checks for the `as_bytes` method called on string literals\\nthat contain only ASCII characters." } , LintCompletion { label : "clippy::string_to_string" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::struct_excessive_bools" , description : "Checks for excessive\\nuse of bools in structs." } , LintCompletion { label : "clippy::suboptimal_flops" , description : "Looks for floating-point expressions that\\ncan be expressed using built-in methods to improve both\\naccuracy and performance." } , LintCompletion { label : "clippy::suspicious_arithmetic_impl" , description : "Lints for suspicious operations in impls of arithmetic operators, e.g.\\nsubtracting elements in an Add impl." } , LintCompletion { label : "clippy::suspicious_assignment_formatting" , description : "Checks for use of the non-existent `=*`, `=!` and `=-`\\noperators." } , LintCompletion { label : "clippy::suspicious_else_formatting" , description : "Checks for formatting of `else`. It lints if the `else`\\nis followed immediately by a newline or the `else` seems to be missing." } , LintCompletion { label : "clippy::suspicious_map" , description : "Checks for calls to `map` followed by a `count`." } , LintCompletion { label : "clippy::suspicious_op_assign_impl" , description : "Lints for suspicious operations in impls of OpAssign, e.g.\\nsubtracting elements in an AddAssign impl." } , LintCompletion { label : "clippy::suspicious_unary_op_formatting" , description : "Checks the formatting of a unary operator on the right hand side\\nof a binary operator. It lints if there is no space between the binary and unary operators,\\nbut there is a space between the unary and its operand." } , LintCompletion { label : "clippy::tabs_in_doc_comments" , description : "Checks doc comments for usage of tab characters." } , LintCompletion { label : "clippy::temporary_assignment" , description : "Checks for construction of a structure or tuple just to\\nassign a value in it." } , LintCompletion { label : "clippy::temporary_cstring_as_ptr" , description : "Checks for getting the inner pointer of a temporary\\n`CString`." } , LintCompletion { label : "clippy::to_digit_is_some" , description : "Checks for `.to_digit(..).is_some()` on `char`s." } , LintCompletion { label : "clippy::to_string_in_display" , description : "Checks for uses of `to_string()` in `Display` traits." } , LintCompletion { label : "clippy::todo" , description : "Checks for usage of `todo!`." } , LintCompletion { label : "clippy::too_many_arguments" , description : "Checks for functions with too many parameters." } , LintCompletion { label : "clippy::too_many_lines" , description : "Checks for functions with a large amount of lines." } , LintCompletion { label : "clippy::toplevel_ref_arg" , description : "Checks for function arguments and let bindings denoted as\\n`ref`." } , LintCompletion { label : "clippy::trait_duplication_in_bounds" , description : "Checks for cases where generics are being used and multiple\\nsyntax specifications for trait bounds are used simultaneously." } , LintCompletion { label : "clippy::transmute_bytes_to_str" , description : "Checks for transmutes from a `&[u8]` to a `&str`." } , LintCompletion { label : "clippy::transmute_float_to_int" , description : "Checks for transmutes from a float to an integer." } , LintCompletion { label : "clippy::transmute_int_to_bool" , description : "Checks for transmutes from an integer to a `bool`." } , LintCompletion { label : "clippy::transmute_int_to_char" , description : "Checks for transmutes from an integer to a `char`." } , LintCompletion { label : "clippy::transmute_int_to_float" , description : "Checks for transmutes from an integer to a float." } , LintCompletion { label : "clippy::transmute_ptr_to_ptr" , description : "Checks for transmutes from a pointer to a pointer, or\\nfrom a reference to a reference." } , LintCompletion { label : "clippy::transmute_ptr_to_ref" , description : "Checks for transmutes from a pointer to a reference." } , LintCompletion { label : "clippy::transmutes_expressible_as_ptr_casts" , description : "Checks for transmutes that could be a pointer cast." } , LintCompletion { label : "clippy::transmuting_null" , description : "Checks for transmute calls which would receive a null pointer." } , LintCompletion { label : "clippy::trivial_regex" , description : "Checks for trivial [regex](https://crates.io/crates/regex)\\ncreation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`)." } , LintCompletion { label : "clippy::trivially_copy_pass_by_ref" , description : "Checks for functions taking arguments by reference, where\\nthe argument type is `Copy` and small enough to be more efficient to always\\npass by value." } , LintCompletion { label : "clippy::try_err" , description : "Checks for usages of `Err(x)?`." } , LintCompletion { label : "clippy::type_complexity" , description : "Checks for types used in structs, parameters and `let`\\ndeclarations above a certain complexity threshold." } , LintCompletion { label : "clippy::type_repetition_in_bounds" , description : "This lint warns about unnecessary type repetitions in trait bounds" } , LintCompletion { label : "clippy::unicode_not_nfc" , description : "Checks for string literals that contain Unicode in a form\\nthat is not equal to its\\n[NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms)." } , LintCompletion { label : "clippy::unimplemented" , description : "Checks for usage of `unimplemented!`." } , LintCompletion { label : "clippy::uninit_assumed_init" , description : "Checks for `MaybeUninit::uninit().assume_init()`." } , LintCompletion { label : "clippy::unit_arg" , description : "Checks for passing a unit value as an argument to a function without using a\\nunit literal (`()`)." } , LintCompletion { label : "clippy::unit_cmp" , description : "Checks for comparisons to unit. This includes all binary\\ncomparisons (like `==` and `<`) and asserts." } , LintCompletion { label : "clippy::unit_return_expecting_ord" , description : "Checks for functions that expect closures of type\\nFn(...) -> Ord where the implemented closure returns the unit type.\\nThe lint also suggests to remove the semi-colon at the end of the statement if present." } , LintCompletion { label : "clippy::unknown_clippy_lints" , description : "Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy\\nlints and if those lints exist in clippy. If there is an uppercase letter in the lint name\\n(not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase\\nthe lint name." } , LintCompletion { label : "clippy::unnecessary_cast" , description : "Checks for casts to the same type." } , LintCompletion { label : "clippy::unnecessary_filter_map" , description : "Checks for `filter_map` calls which could be replaced by `filter` or `map`.\\nMore specifically it checks if the closure provided is only performing one of the\\nfilter or map operations and suggests the appropriate option." } , LintCompletion { label : "clippy::unnecessary_fold" , description : "Checks for using `fold` when a more succinct alternative exists.\\nSpecifically, this checks for `fold`s which could be replaced by `any`, `all`,\\n`sum` or `product`." } , LintCompletion { label : "clippy::unnecessary_lazy_evaluations" , description : "As the counterpart to `or_fun_call`, this lint looks for unnecessary\\nlazily evaluated closures on `Option` and `Result`.\\n\\nThis lint suggests changing the following functions, when eager evaluation results in\\nsimpler code:\\n - `unwrap_or_else` to `unwrap_or`\\n - `and_then` to `and`\\n - `or_else` to `or`\\n - `get_or_insert_with` to `get_or_insert`\\n - `ok_or_else` to `ok_or`" } , LintCompletion { label : "clippy::unnecessary_mut_passed" , description : "Detects passing a mutable reference to a function that only\\nrequires an immutable reference." } , LintCompletion { label : "clippy::unnecessary_operation" , description : "Checks for expression statements that can be reduced to a\\nsub-expression." } , LintCompletion { label : "clippy::unnecessary_sort_by" , description : "Detects uses of `Vec::sort_by` passing in a closure\\nwhich compares the two arguments, either directly or indirectly." } , LintCompletion { label : "clippy::unnecessary_unwrap" , description : "Checks for calls of `unwrap[_err]()` that cannot fail." } , LintCompletion { label : "clippy::unneeded_field_pattern" , description : "Checks for structure field patterns bound to wildcards." } , LintCompletion { label : "clippy::unneeded_wildcard_pattern" , description : "Checks for tuple patterns with a wildcard\\npattern (`_`) is next to a rest pattern (`..`).\\n\\n_NOTE_: While `_, ..` means there is at least one element left, `..`\\nmeans there are 0 or more elements left. This can make a difference\\nwhen refactoring, but shouldn't result in errors in the refactored code,\\nsince the wildcard pattern isn't used anyway." } , LintCompletion { label : "clippy::unnested_or_patterns" , description : "Checks for unnested or-patterns, e.g., `Some(0) | Some(2)` and\\nsuggests replacing the pattern with a nested one, `Some(0 | 2)`.\\n\\nAnother way to think of this is that it rewrites patterns in\\n*disjunctive normal form (DNF)* into *conjunctive normal form (CNF)*." } , LintCompletion { label : "clippy::unreachable" , description : "Checks for usage of `unreachable!`." } , LintCompletion { label : "clippy::unreadable_literal" , description : "Warns if a long integral or floating-point constant does\\nnot contain underscores." } , LintCompletion { label : "clippy::unsafe_derive_deserialize" , description : "Checks for deriving `serde::Deserialize` on a type that\\nhas methods using `unsafe`." } , LintCompletion { label : "clippy::unsafe_removed_from_name" , description : "Checks for imports that remove \\\"unsafe\\\" from an item's\\nname." } , LintCompletion { label : "clippy::unsafe_vector_initialization" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unseparated_literal_suffix" , description : "Warns if literal suffixes are not separated by an\\nunderscore." } , LintCompletion { label : "clippy::unsound_collection_transmute" , description : "Checks for transmutes between collections whose\\ntypes have different ABI, size or alignment." } , LintCompletion { label : "clippy::unstable_as_mut_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unstable_as_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_collect" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_io_amount" , description : "Checks for unused written/read amount." } , LintCompletion { label : "clippy::unused_label" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_self" , description : "Checks methods that contain a `self` argument but don't use it" } , LintCompletion { label : "clippy::unused_unit" , description : "Checks for unit (`()`) expressions that can be removed." } , LintCompletion { label : "clippy::unwrap_in_result" , description : "Checks for functions of type Result that contain `expect()` or `unwrap()`" } , LintCompletion { label : "clippy::unwrap_used" , description : "Checks for `.unwrap()` calls on `Option`s and on `Result`s." } , LintCompletion { label : "clippy::use_debug" , description : "Checks for use of `Debug` formatting. The purpose of this\\nlint is to catch debugging remnants." } , LintCompletion { label : "clippy::use_self" , description : "Checks for unnecessary repetition of structure name when a\\nreplacement with `Self` is applicable." } , LintCompletion { label : "clippy::used_underscore_binding" , description : "Checks for the use of bindings with a single leading\\nunderscore." } , LintCompletion { label : "clippy::useless_asref" , description : "Checks for usage of `.as_ref()` or `.as_mut()` where the\\ntypes before and after the call are the same." } , LintCompletion { label : "clippy::useless_attribute" , description : "Checks for `extern crate` and `use` items annotated with\\nlint attributes.\\n\\nThis lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,\\n`#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and\\n`#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on\\n`extern crate` items with a `#[macro_use]` attribute." } , LintCompletion { label : "clippy::useless_conversion" , description : "Checks for `Into`, `TryInto`, `From`, `TryFrom`,`IntoIter` calls\\nthat useless converts to the same type as caller." } , LintCompletion { label : "clippy::useless_format" , description : "Checks for the use of `format!(\\\"string literal with no\\nargument\\\")` and `format!(\\\"{}\\\", foo)` where `foo` is a string." } , LintCompletion { label : "clippy::useless_let_if_seq" , description : "Checks for variable declarations immediately followed by a\\nconditional affectation." } , LintCompletion { label : "clippy::useless_transmute" , description : "Checks for transmutes to the original type of the object\\nand transmutes that could be a cast." } , LintCompletion { label : "clippy::useless_vec" , description : "Checks for usage of `&vec![..]` when using `&[..]` would\\nbe possible." } , LintCompletion { label : "clippy::vec_box" , description : "Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::vec_resize_to_zero" , description : "Finds occurrences of `Vec::resize(0, an_int)`" } , LintCompletion { label : "clippy::verbose_bit_mask" , description : "Checks for bit masks that can be replaced by a call\\nto `trailing_zeros`" } , LintCompletion { label : "clippy::verbose_file_reads" , description : "Checks for use of File::read_to_end and File::read_to_string." } , LintCompletion { label : "clippy::vtable_address_comparisons" , description : "Checks for comparisons with an address of a trait vtable." } , LintCompletion { label : "clippy::while_immutable_condition" , description : "Checks whether variables used within while loop condition\\ncan be (and are) mutated in the body." } , LintCompletion { label : "clippy::while_let_loop" , description : "Detects `loop + match` combinations that are easier\\nwritten as a `while let` loop." } , LintCompletion { label : "clippy::while_let_on_iterator" , description : "Checks for `while let` expressions on iterators." } , LintCompletion { label : "clippy::wildcard_dependencies" , description : "Checks for wildcard dependencies in the `Cargo.toml`." } , LintCompletion { label : "clippy::wildcard_enum_match_arm" , description : "Checks for wildcard enum matches using `_`." } , LintCompletion { label : "clippy::wildcard_imports" , description : "Checks for wildcard imports `use _::*`." } , LintCompletion { label : "clippy::wildcard_in_or_patterns" , description : "Checks for wildcard pattern used with others patterns in same match arm." } , LintCompletion { label : "clippy::write_literal" , description : "This lint warns about the use of literals as `write!`/`writeln!` args." } , LintCompletion { label : "clippy::write_with_newline" , description : "This lint warns when you use `write!()` with a format\\nstring that\\nends in a newline." } , LintCompletion { label : "clippy::writeln_empty_string" , description : "This lint warns when you use `writeln!(buf, \\\"\\\")` to\\nprint a newline." } , LintCompletion { label : "clippy::wrong_pub_self_convention" , description : "This is the same as\\n[`wrong_self_convention`](#wrong_self_convention), but for public items." } , LintCompletion { label : "clippy::wrong_self_convention" , description : "Checks for methods with certain name prefixes and which\\ndoesn't match how self is taken. The actual rules are:\\n\\n|Prefix |`self` taken |\\n|-------|----------------------|\\n|`as_` |`&self` or `&mut self`|\\n|`from_`| none |\\n|`into_`|`self` |\\n|`is_` |`&self` or none |\\n|`to_` |`&self` |" } , LintCompletion { label : "clippy::wrong_transmute" , description : "Checks for transmutes that can't ever be correct on any\\narchitecture." } , LintCompletion { label : "clippy::zero_divided_by_zero" , description : "Checks for `0.0 / 0.0`." } , LintCompletion { label : "clippy::zero_prefixed_literal" , description : "Warns if an integral constant literal starts with `0`." } , LintCompletion { label : "clippy::zero_ptr" , description : "Catch casts from `0` to some pointer type" } , LintCompletion { label : "clippy::zst_offset" , description : "Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to\\nzero-sized types" }] ; 5pub (super) const CLIPPY_LINTS : & [LintCompletion] = & [LintCompletion { label : "clippy::absurd_extreme_comparisons" , description : "Checks for comparisons where one side of the relation is\\neither the minimum or maximum value for its type and warns if it involves a\\ncase that is always true or always false. Only integer and boolean types are\\nchecked." } , LintCompletion { label : "clippy::almost_swapped" , description : "Checks for `foo = bar; bar = foo` sequences." } , LintCompletion { label : "clippy::approx_constant" , description : "Checks for floating point literals that approximate\\nconstants which are defined in\\n[`std::f32::consts`](https://doc.rust-lang.org/stable/std/f32/consts/#constants)\\nor\\n[`std::f64::consts`](https://doc.rust-lang.org/stable/std/f64/consts/#constants),\\nrespectively, suggesting to use the predefined constant." } , LintCompletion { label : "clippy::as_conversions" , description : "Checks for usage of `as` conversions." } , LintCompletion { label : "clippy::assertions_on_constants" , description : "Checks for `assert!(true)` and `assert!(false)` calls." } , LintCompletion { label : "clippy::assign_op_pattern" , description : "Checks for `a = a op b` or `a = b commutative_op a`\\npatterns." } , LintCompletion { label : "clippy::assign_ops" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::async_yields_async" , description : "Checks for async blocks that yield values of types\\nthat can themselves be awaited." } , LintCompletion { label : "clippy::await_holding_lock" , description : "Checks for calls to await while holding a\\nnon-async-aware MutexGuard." } , LintCompletion { label : "clippy::bad_bit_mask" , description : "Checks for incompatible bit masks in comparisons.\\n\\nThe formula for detecting if an expression of the type `_ <bit_op> m\\n<cmp_op> c` (where `<bit_op>` is one of {`&`, `|`} and `<cmp_op>` is one of\\n{`!=`, `>=`, `>`, `!=`, `>=`, `>`}) can be determined from the following\\ntable:\\n\\n|Comparison |Bit Op|Example |is always|Formula |\\n|------------|------|------------|---------|----------------------|\\n|`==` or `!=`| `&` |`x & 2 == 3`|`false` |`c & m != c` |\\n|`<` or `>=`| `&` |`x & 2 < 3` |`true` |`m < c` |\\n|`>` or `<=`| `&` |`x & 1 > 1` |`false` |`m <= c` |\\n|`==` or `!=`| `|` |`x | 1 == 0`|`false` |`c | m != c` |\\n|`<` or `>=`| `|` |`x | 1 < 1` |`false` |`m >= c` |\\n|`<=` or `>` | `|` |`x | 1 > 0` |`true` |`m > c` |" } , LintCompletion { label : "clippy::bind_instead_of_map" , description : "Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or\\n`_.or_else(|x| Err(y))`." } , LintCompletion { label : "clippy::blacklisted_name" , description : "Checks for usage of blacklisted names for variables, such\\nas `foo`." } , LintCompletion { label : "clippy::blanket_clippy_restriction_lints" , description : "Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category." } , LintCompletion { label : "clippy::blocks_in_if_conditions" , description : "Checks for `if` conditions that use blocks containing an\\nexpression, statements or conditions that use closures with blocks." } , LintCompletion { label : "clippy::bool_comparison" , description : "Checks for expressions of the form `x == true`,\\n`x != true` and order comparisons such as `x < true` (or vice versa) and\\nsuggest using the variable directly." } , LintCompletion { label : "clippy::borrow_interior_mutable_const" , description : "Checks if `const` items which is interior mutable (e.g.,\\ncontains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly." } , LintCompletion { label : "clippy::borrowed_box" , description : "Checks for use of `&Box<T>` anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::box_vec" , description : "Checks for use of `Box<Vec<_>>` anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::boxed_local" , description : "Checks for usage of `Box<T>` where an unboxed `T` would\\nwork fine." } , LintCompletion { label : "clippy::builtin_type_shadow" , description : "Warns if a generic shadows a built-in type." } , LintCompletion { label : "clippy::cargo_common_metadata" , description : "Checks to see if all common metadata is defined in\\n`Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata" } , LintCompletion { label : "clippy::cast_lossless" , description : "Checks for casts between numerical types that may\\nbe replaced by safe conversion functions." } , LintCompletion { label : "clippy::cast_possible_truncation" , description : "Checks for casts between numerical types that may\\ntruncate large values. This is expected behavior, so the cast is `Allow` by\\ndefault." } , LintCompletion { label : "clippy::cast_possible_wrap" , description : "Checks for casts from an unsigned type to a signed type of\\nthe same size. Performing such a cast is a 'no-op' for the compiler,\\ni.e., nothing is changed at the bit level, and the binary representation of\\nthe value is reinterpreted. This can cause wrapping if the value is too big\\nfor the target signed type. However, the cast works as defined, so this lint\\nis `Allow` by default." } , LintCompletion { label : "clippy::cast_precision_loss" , description : "Checks for casts from any numerical to a float type where\\nthe receiving type cannot store all values from the original type without\\nrounding errors. This possible rounding is to be expected, so this lint is\\n`Allow` by default.\\n\\nBasically, this warns on casting any integer with 32 or more bits to `f32`\\nor any 64-bit integer to `f64`." } , LintCompletion { label : "clippy::cast_ptr_alignment" , description : "Checks for casts from a less-strictly-aligned pointer to a\\nmore-strictly-aligned pointer" } , LintCompletion { label : "clippy::cast_ref_to_mut" , description : "Checks for casts of `&T` to `&mut T` anywhere in the code." } , LintCompletion { label : "clippy::cast_sign_loss" , description : "Checks for casts from a signed to an unsigned numerical\\ntype. In this case, negative values wrap around to large positive values,\\nwhich can be quite surprising in practice. However, as the cast works as\\ndefined, this lint is `Allow` by default." } , LintCompletion { label : "clippy::char_lit_as_u8" , description : "Checks for expressions where a character literal is cast\\nto `u8` and suggests using a byte literal instead." } , LintCompletion { label : "clippy::chars_last_cmp" , description : "Checks for usage of `_.chars().last()` or\\n`_.chars().next_back()` on a `str` to check if it ends with a given char." } , LintCompletion { label : "clippy::chars_next_cmp" , description : "Checks for usage of `.chars().next()` on a `str` to check\\nif it starts with a given char." } , LintCompletion { label : "clippy::checked_conversions" , description : "Checks for explicit bounds checking when casting." } , LintCompletion { label : "clippy::clone_double_ref" , description : "Checks for usage of `.clone()` on an `&&T`." } , LintCompletion { label : "clippy::clone_on_copy" , description : "Checks for usage of `.clone()` on a `Copy` type." } , LintCompletion { label : "clippy::clone_on_ref_ptr" , description : "Checks for usage of `.clone()` on a ref-counted pointer,\\n(`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified\\nfunction syntax instead (e.g., `Rc::clone(foo)`)." } , LintCompletion { label : "clippy::cmp_nan" , description : "Checks for comparisons to NaN." } , LintCompletion { label : "clippy::cmp_null" , description : "This lint checks for equality comparisons with `ptr::null`" } , LintCompletion { label : "clippy::cmp_owned" , description : "Checks for conversions to owned values just for the sake\\nof a comparison." } , LintCompletion { label : "clippy::cognitive_complexity" , description : "Checks for methods with high cognitive complexity." } , LintCompletion { label : "clippy::collapsible_if" , description : "Checks for nested `if` statements which can be collapsed\\nby `&&`-combining their conditions and for `else { if ... }` expressions\\nthat\\ncan be collapsed to `else if ...`." } , LintCompletion { label : "clippy::comparison_chain" , description : "Checks comparison chains written with `if` that can be\\nrewritten with `match` and `cmp`." } , LintCompletion { label : "clippy::copy_iterator" , description : "Checks for types that implement `Copy` as well as\\n`Iterator`." } , LintCompletion { label : "clippy::create_dir" , description : "Checks usage of `std::fs::create_dir` and suggest using `std::fs::create_dir_all` instead." } , LintCompletion { label : "clippy::crosspointer_transmute" , description : "Checks for transmutes between a type `T` and `*T`." } , LintCompletion { label : "clippy::dbg_macro" , description : "Checks for usage of dbg!() macro." } , LintCompletion { label : "clippy::debug_assert_with_mut_call" , description : "Checks for function/method calls with a mutable\\nparameter in `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` macros." } , LintCompletion { label : "clippy::decimal_literal_representation" , description : "Warns if there is a better representation for a numeric literal." } , LintCompletion { label : "clippy::declare_interior_mutable_const" , description : "Checks for declaration of `const` items which is interior\\nmutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.)." } , LintCompletion { label : "clippy::default_trait_access" , description : "Checks for literal calls to `Default::default()`." } , LintCompletion { label : "clippy::deprecated_cfg_attr" , description : "Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it\\nwith `#[rustfmt::skip]`." } , LintCompletion { label : "clippy::deprecated_semver" , description : "Checks for `#[deprecated]` annotations with a `since`\\nfield that is not a valid semantic version." } , LintCompletion { label : "clippy::deref_addrof" , description : "Checks for usage of `*&` and `*&mut` in expressions." } , LintCompletion { label : "clippy::derive_hash_xor_eq" , description : "Checks for deriving `Hash` but implementing `PartialEq`\\nexplicitly or vice versa." } , LintCompletion { label : "clippy::derive_ord_xor_partial_ord" , description : "Checks for deriving `Ord` but implementing `PartialOrd`\\nexplicitly or vice versa." } , LintCompletion { label : "clippy::disallowed_method" , description : "Lints for specific trait methods defined in clippy.toml" } , LintCompletion { label : "clippy::diverging_sub_expression" , description : "Checks for diverging calls that are not match arms or\\nstatements." } , LintCompletion { label : "clippy::doc_markdown" , description : "Checks for the presence of `_`, `::` or camel-case words\\noutside ticks in documentation." } , LintCompletion { label : "clippy::double_comparisons" , description : "Checks for double comparisons that could be simplified to a single expression." } , LintCompletion { label : "clippy::double_must_use" , description : "Checks for a [`#[must_use]`] attribute without\\nfurther information on functions and methods that return a type already\\nmarked as `#[must_use]`.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::double_neg" , description : "Detects expressions of the form `--x`." } , LintCompletion { label : "clippy::double_parens" , description : "Checks for unnecessary double parentheses." } , LintCompletion { label : "clippy::drop_bounds" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::drop_copy" , description : "Checks for calls to `std::mem::drop` with a value\\nthat derives the Copy trait" } , LintCompletion { label : "clippy::drop_ref" , description : "Checks for calls to `std::mem::drop` with a reference\\ninstead of an owned value." } , LintCompletion { label : "clippy::duplicate_underscore_argument" , description : "Checks for function arguments having the similar names\\ndiffering by an underscore." } , LintCompletion { label : "clippy::duration_subsec" , description : "Checks for calculation of subsecond microseconds or milliseconds\\nfrom other `Duration` methods." } , LintCompletion { label : "clippy::else_if_without_else" , description : "Checks for usage of if expressions with an `else if` branch,\\nbut without a final `else` branch." } , LintCompletion { label : "clippy::empty_enum" , description : "Checks for `enum`s with no variants." } , LintCompletion { label : "clippy::empty_line_after_outer_attr" , description : "Checks for empty lines after outer attributes" } , LintCompletion { label : "clippy::empty_loop" , description : "Checks for empty `loop` expressions." } , LintCompletion { label : "clippy::enum_clike_unportable_variant" , description : "Checks for C-like enumerations that are\\n`repr(isize/usize)` and have values that don't fit into an `i32`." } , LintCompletion { label : "clippy::enum_glob_use" , description : "Checks for `use Enum::*`." } , LintCompletion { label : "clippy::enum_variant_names" , description : "Detects enumeration variants that are prefixed or suffixed\\nby the same characters." } , LintCompletion { label : "clippy::eq_op" , description : "Checks for equal operands to comparison, logical and\\nbitwise, difference and division binary operators (`==`, `>`, etc., `&&`,\\n`||`, `&`, `|`, `^`, `-` and `/`)." } , LintCompletion { label : "clippy::erasing_op" , description : "Checks for erasing operations, e.g., `x * 0`." } , LintCompletion { label : "clippy::eval_order_dependence" , description : "Checks for a read and a write to the same variable where\\nwhether the read occurs before or after the write depends on the evaluation\\norder of sub-expressions." } , LintCompletion { label : "clippy::excessive_precision" , description : "Checks for float literals with a precision greater\\nthan that supported by the underlying type." } , LintCompletion { label : "clippy::exit" , description : "`exit()` terminates the program and doesn't provide a\\nstack trace." } , LintCompletion { label : "clippy::expect_fun_call" , description : "Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,\\netc., and suggests to use `unwrap_or_else` instead" } , LintCompletion { label : "clippy::expect_used" , description : "Checks for `.expect()` calls on `Option`s and `Result`s." } , LintCompletion { label : "clippy::expl_impl_clone_on_copy" , description : "Checks for explicit `Clone` implementations for `Copy`\\ntypes." } , LintCompletion { label : "clippy::explicit_counter_loop" , description : "Checks `for` loops over slices with an explicit counter\\nand suggests the use of `.enumerate()`." } , LintCompletion { label : "clippy::explicit_deref_methods" , description : "Checks for explicit `deref()` or `deref_mut()` method calls." } , LintCompletion { label : "clippy::explicit_into_iter_loop" , description : "Checks for loops on `y.into_iter()` where `y` will do, and\\nsuggests the latter." } , LintCompletion { label : "clippy::explicit_iter_loop" , description : "Checks for loops on `x.iter()` where `&x` will do, and\\nsuggests the latter." } , LintCompletion { label : "clippy::explicit_write" , description : "Checks for usage of `write!()` / `writeln()!` which can be\\nreplaced with `(e)print!()` / `(e)println!()`" } , LintCompletion { label : "clippy::extend_from_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::extra_unused_lifetimes" , description : "Checks for lifetimes in generics that are never used\\nanywhere else." } , LintCompletion { label : "clippy::fallible_impl_from" , description : "Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`" } , LintCompletion { label : "clippy::filetype_is_file" , description : "Checks for `FileType::is_file()`." } , LintCompletion { label : "clippy::filter_map" , description : "Checks for usage of `_.filter(_).map(_)`,\\n`_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar." } , LintCompletion { label : "clippy::filter_map_next" , description : "Checks for usage of `_.filter_map(_).next()`." } , LintCompletion { label : "clippy::filter_next" , description : "Checks for usage of `_.filter(_).next()`." } , LintCompletion { label : "clippy::find_map" , description : "Checks for usage of `_.find(_).map(_)`." } , LintCompletion { label : "clippy::flat_map_identity" , description : "Checks for usage of `flat_map(|x| x)`." } , LintCompletion { label : "clippy::float_arithmetic" , description : "Checks for float arithmetic." } , LintCompletion { label : "clippy::float_cmp" , description : "Checks for (in-)equality comparisons on floating-point\\nvalues (apart from zero), except in functions called `*eq*` (which probably\\nimplement equality for a type involving floats)." } , LintCompletion { label : "clippy::float_cmp_const" , description : "Checks for (in-)equality comparisons on floating-point\\nvalue and constant, except in functions called `*eq*` (which probably\\nimplement equality for a type involving floats)." } , LintCompletion { label : "clippy::float_equality_without_abs" , description : "Checks for statements of the form `(a - b) < f32::EPSILON` or\\n`(a - b) < f64::EPSILON`. Notes the missing `.abs()`." } , LintCompletion { label : "clippy::fn_address_comparisons" , description : "Checks for comparisons with an address of a function item." } , LintCompletion { label : "clippy::fn_params_excessive_bools" , description : "Checks for excessive use of\\nbools in function definitions." } , LintCompletion { label : "clippy::fn_to_numeric_cast" , description : "Checks for casts of function pointers to something other than usize" } , LintCompletion { label : "clippy::fn_to_numeric_cast_with_truncation" , description : "Checks for casts of a function pointer to a numeric type not wide enough to\\nstore address." } , LintCompletion { label : "clippy::for_kv_map" , description : "Checks for iterating a map (`HashMap` or `BTreeMap`) and\\nignoring either the keys or values." } , LintCompletion { label : "clippy::for_loops_over_fallibles" , description : "Checks for `for` loops over `Option` or `Result` values." } , LintCompletion { label : "clippy::forget_copy" , description : "Checks for calls to `std::mem::forget` with a value that\\nderives the Copy trait" } , LintCompletion { label : "clippy::forget_ref" , description : "Checks for calls to `std::mem::forget` with a reference\\ninstead of an owned value." } , LintCompletion { label : "clippy::future_not_send" , description : "This lint requires Future implementations returned from\\nfunctions and methods to implement the `Send` marker trait. It is mostly\\nused by library authors (public and internal) that target an audience where\\nmultithreaded executors are likely to be used for running these Futures." } , LintCompletion { label : "clippy::get_last_with_len" , description : "Checks for using `x.get(x.len() - 1)` instead of\\n`x.last()`." } , LintCompletion { label : "clippy::get_unwrap" , description : "Checks for use of `.get().unwrap()` (or\\n`.get_mut().unwrap`) on a standard library type which implements `Index`" } , LintCompletion { label : "clippy::identity_op" , description : "Checks for identity operations, e.g., `x + 0`." } , LintCompletion { label : "clippy::if_let_mutex" , description : "Checks for `Mutex::lock` calls in `if let` expression\\nwith lock calls in any of the else blocks." } , LintCompletion { label : "clippy::if_let_redundant_pattern_matching" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::if_let_some_result" , description : "* Checks for unnecessary `ok()` in if let." } , LintCompletion { label : "clippy::if_not_else" , description : "Checks for usage of `!` or `!=` in an if condition with an\\nelse branch." } , LintCompletion { label : "clippy::if_same_then_else" , description : "Checks for `if/else` with the same body as the *then* part\\nand the *else* part." } , LintCompletion { label : "clippy::ifs_same_cond" , description : "Checks for consecutive `if`s with the same condition." } , LintCompletion { label : "clippy::implicit_hasher" , description : "Checks for public `impl` or `fn` missing generalization\\nover different hashers and implicitly defaulting to the default hashing\\nalgorithm (`SipHash`)." } , LintCompletion { label : "clippy::implicit_return" , description : "Checks for missing return statements at the end of a block." } , LintCompletion { label : "clippy::implicit_saturating_sub" , description : "Checks for implicit saturating subtraction." } , LintCompletion { label : "clippy::imprecise_flops" , description : "Looks for floating-point expressions that\\ncan be expressed using built-in methods to improve accuracy\\nat the cost of performance." } , LintCompletion { label : "clippy::inconsistent_digit_grouping" , description : "Warns if an integral or floating-point constant is\\ngrouped inconsistently with underscores." } , LintCompletion { label : "clippy::indexing_slicing" , description : "Checks for usage of indexing or slicing. Arrays are special cases, this lint\\ndoes report on arrays if we can tell that slicing operations are in bounds and does not\\nlint on constant `usize` indexing on arrays because that is handled by rustc's `const_err` lint." } , LintCompletion { label : "clippy::ineffective_bit_mask" , description : "Checks for bit masks in comparisons which can be removed\\nwithout changing the outcome. The basic structure can be seen in the\\nfollowing table:\\n\\n|Comparison| Bit Op |Example |equals |\\n|----------|---------|-----------|-------|\\n|`>` / `<=`|`|` / `^`|`x | 2 > 3`|`x > 3`|\\n|`<` / `>=`|`|` / `^`|`x ^ 1 < 4`|`x < 4`|" } , LintCompletion { label : "clippy::inefficient_to_string" , description : "Checks for usage of `.to_string()` on an `&&T` where\\n`T` implements `ToString` directly (like `&&str` or `&&String`)." } , LintCompletion { label : "clippy::infallible_destructuring_match" , description : "Checks for matches being used to destructure a single-variant enum\\nor tuple struct where a `let` will suffice." } , LintCompletion { label : "clippy::infinite_iter" , description : "Checks for iteration that is guaranteed to be infinite." } , LintCompletion { label : "clippy::inherent_to_string" , description : "Checks for the definition of inherent methods with a signature of `to_string(&self) -> String`." } , LintCompletion { label : "clippy::inherent_to_string_shadow_display" , description : "Checks for the definition of inherent methods with a signature of `to_string(&self) -> String` and if the type implementing this method also implements the `Display` trait." } , LintCompletion { label : "clippy::inline_always" , description : "Checks for items annotated with `#[inline(always)]`,\\nunless the annotated function is empty or simply panics." } , LintCompletion { label : "clippy::inline_asm_x86_att_syntax" , description : "Checks for usage of AT&T x86 assembly syntax." } , LintCompletion { label : "clippy::inline_asm_x86_intel_syntax" , description : "Checks for usage of Intel x86 assembly syntax." } , LintCompletion { label : "clippy::inline_fn_without_body" , description : "Checks for `#[inline]` on trait methods without bodies" } , LintCompletion { label : "clippy::int_plus_one" , description : "Checks for usage of `x >= y + 1` or `x - 1 >= y` (and `<=`) in a block" } , LintCompletion { label : "clippy::integer_arithmetic" , description : "Checks for integer arithmetic operations which could overflow or panic.\\n\\nSpecifically, checks for any operators (`+`, `-`, `*`, `<<`, etc) which are capable\\nof overflowing according to the [Rust\\nReference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow),\\nor which can panic (`/`, `%`). No bounds analysis or sophisticated reasoning is\\nattempted." } , LintCompletion { label : "clippy::integer_division" , description : "Checks for division of integers" } , LintCompletion { label : "clippy::into_iter_on_array" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::into_iter_on_ref" , description : "Checks for `into_iter` calls on references which should be replaced by `iter`\\nor `iter_mut`." } , LintCompletion { label : "clippy::invalid_atomic_ordering" , description : "Checks for usage of invalid atomic\\nordering in atomic loads/stores/exchanges/updates and\\nmemory fences." } , LintCompletion { label : "clippy::invalid_ref" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::invalid_regex" , description : "Checks [regex](https://crates.io/crates/regex) creation\\n(with `Regex::new`,`RegexBuilder::new` or `RegexSet::new`) for correct\\nregex syntax." } , LintCompletion { label : "clippy::invalid_upcast_comparisons" , description : "Checks for comparisons where the relation is always either\\ntrue or false, but where one side has been upcast so that the comparison is\\nnecessary. Only integer types are checked." } , LintCompletion { label : "clippy::invisible_characters" , description : "Checks for invisible Unicode characters in the code." } , LintCompletion { label : "clippy::items_after_statements" , description : "Checks for items declared after some statement in a block." } , LintCompletion { label : "clippy::iter_cloned_collect" , description : "Checks for the use of `.cloned().collect()` on slice to\\ncreate a `Vec`." } , LintCompletion { label : "clippy::iter_next_loop" , description : "Checks for loops on `x.next()`." } , LintCompletion { label : "clippy::iter_next_slice" , description : "Checks for usage of `iter().next()` on a Slice or an Array" } , LintCompletion { label : "clippy::iter_nth" , description : "Checks for use of `.iter().nth()` (and the related\\n`.iter_mut().nth()`) on standard library types with O(1) element access." } , LintCompletion { label : "clippy::iter_nth_zero" , description : "Checks for the use of `iter.nth(0)`." } , LintCompletion { label : "clippy::iter_skip_next" , description : "Checks for use of `.skip(x).next()` on iterators." } , LintCompletion { label : "clippy::iterator_step_by_zero" , description : "Checks for calling `.step_by(0)` on iterators which panics." } , LintCompletion { label : "clippy::just_underscores_and_digits" , description : "Checks if you have variables whose name consists of just\\nunderscores and digits." } , LintCompletion { label : "clippy::large_const_arrays" , description : "Checks for large `const` arrays that should\\nbe defined as `static` instead." } , LintCompletion { label : "clippy::large_digit_groups" , description : "Warns if the digits of an integral or floating-point\\nconstant are grouped into groups that\\nare too large." } , LintCompletion { label : "clippy::large_enum_variant" , description : "Checks for large size differences between variants on\\n`enum`s." } , LintCompletion { label : "clippy::large_stack_arrays" , description : "Checks for local arrays that may be too large." } , LintCompletion { label : "clippy::large_types_passed_by_value" , description : "Checks for functions taking arguments by value, where\\nthe argument type is `Copy` and large enough to be worth considering\\npassing by reference. Does not trigger if the function is being exported,\\nbecause that might induce API breakage, if the parameter is declared as mutable,\\nor if the argument is a `self`." } , LintCompletion { label : "clippy::len_without_is_empty" , description : "Checks for items that implement `.len()` but not\\n`.is_empty()`." } , LintCompletion { label : "clippy::len_zero" , description : "Checks for getting the length of something via `.len()`\\njust to compare to zero, and suggests using `.is_empty()` where applicable." } , LintCompletion { label : "clippy::let_and_return" , description : "Checks for `let`-bindings, which are subsequently\\nreturned." } , LintCompletion { label : "clippy::let_underscore_lock" , description : "Checks for `let _ = sync_lock`" } , LintCompletion { label : "clippy::let_underscore_must_use" , description : "Checks for `let _ = <expr>`\\nwhere expr is #[must_use]" } , LintCompletion { label : "clippy::let_unit_value" , description : "Checks for binding a unit value." } , LintCompletion { label : "clippy::linkedlist" , description : "Checks for usage of any `LinkedList`, suggesting to use a\\n`Vec` or a `VecDeque` (formerly called `RingBuf`)." } , LintCompletion { label : "clippy::logic_bug" , description : "Checks for boolean expressions that contain terminals that\\ncan be eliminated." } , LintCompletion { label : "clippy::lossy_float_literal" , description : "Checks for whole number float literals that\\ncannot be represented as the underlying type without loss." } , LintCompletion { label : "clippy::macro_use_imports" , description : "Checks for `#[macro_use] use...`." } , LintCompletion { label : "clippy::main_recursion" , description : "Checks for recursion using the entrypoint." } , LintCompletion { label : "clippy::manual_async_fn" , description : "It checks for manual implementations of `async` functions." } , LintCompletion { label : "clippy::manual_memcpy" , description : "Checks for for-loops that manually copy items between\\nslices that could be optimized by having a memcpy." } , LintCompletion { label : "clippy::manual_non_exhaustive" , description : "Checks for manual implementations of the non-exhaustive pattern." } , LintCompletion { label : "clippy::manual_saturating_arithmetic" , description : "Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`." } , LintCompletion { label : "clippy::manual_strip" , description : "Suggests using `strip_{prefix,suffix}` over `str::{starts,ends}_with` and slicing using\\nthe pattern's length." } , LintCompletion { label : "clippy::manual_swap" , description : "Checks for manual swapping." } , LintCompletion { label : "clippy::manual_unwrap_or" , description : "Finds patterns that reimplement `Option::unwrap_or` or `Result::unwrap_or`." } , LintCompletion { label : "clippy::many_single_char_names" , description : "Checks for too many variables whose name consists of a\\nsingle character." } , LintCompletion { label : "clippy::map_clone" , description : "Checks for usage of `iterator.map(|x| x.clone())` and suggests\\n`iterator.cloned()` instead" } , LintCompletion { label : "clippy::map_entry" , description : "Checks for uses of `contains_key` + `insert` on `HashMap`\\nor `BTreeMap`." } , LintCompletion { label : "clippy::map_err_ignore" , description : "Checks for instances of `map_err(|_| Some::Enum)`" } , LintCompletion { label : "clippy::map_flatten" , description : "Checks for usage of `_.map(_).flatten(_)`," } , LintCompletion { label : "clippy::map_identity" , description : "Checks for instances of `map(f)` where `f` is the identity function." } , LintCompletion { label : "clippy::map_unwrap_or" , description : "Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or\\n`result.map(_).unwrap_or_else(_)`." } , LintCompletion { label : "clippy::match_as_ref" , description : "Checks for match which is used to add a reference to an\\n`Option` value." } , LintCompletion { label : "clippy::match_bool" , description : "Checks for matches where match expression is a `bool`. It\\nsuggests to replace the expression with an `if...else` block." } , LintCompletion { label : "clippy::match_like_matches_macro" , description : "Checks for `match` or `if let` expressions producing a\\n`bool` that could be written using `matches!`" } , LintCompletion { label : "clippy::match_on_vec_items" , description : "Checks for `match vec[idx]` or `match vec[n..m]`." } , LintCompletion { label : "clippy::match_overlapping_arm" , description : "Checks for overlapping match arms." } , LintCompletion { label : "clippy::match_ref_pats" , description : "Checks for matches where all arms match a reference,\\nsuggesting to remove the reference and deref the matched expression\\ninstead. It also checks for `if let &foo = bar` blocks." } , LintCompletion { label : "clippy::match_same_arms" , description : "Checks for `match` with identical arm bodies." } , LintCompletion { label : "clippy::match_single_binding" , description : "Checks for useless match that binds to only one value." } , LintCompletion { label : "clippy::match_wild_err_arm" , description : "Checks for arm which matches all errors with `Err(_)`\\nand take drastic actions like `panic!`." } , LintCompletion { label : "clippy::match_wildcard_for_single_variants" , description : "Checks for wildcard enum matches for a single variant." } , LintCompletion { label : "clippy::maybe_infinite_iter" , description : "Checks for iteration that may be infinite." } , LintCompletion { label : "clippy::mem_discriminant_non_enum" , description : "Checks for calls of `mem::discriminant()` on a non-enum type." } , LintCompletion { label : "clippy::mem_forget" , description : "Checks for usage of `std::mem::forget(t)` where `t` is\\n`Drop`." } , LintCompletion { label : "clippy::mem_replace_option_with_none" , description : "Checks for `mem::replace()` on an `Option` with\\n`None`." } , LintCompletion { label : "clippy::mem_replace_with_default" , description : "Checks for `std::mem::replace` on a value of type\\n`T` with `T::default()`." } , LintCompletion { label : "clippy::mem_replace_with_uninit" , description : "Checks for `mem::replace(&mut _, mem::uninitialized())`\\nand `mem::replace(&mut _, mem::zeroed())`." } , LintCompletion { label : "clippy::min_max" , description : "Checks for expressions where `std::cmp::min` and `max` are\\nused to clamp values, but switched so that the result is constant." } , LintCompletion { label : "clippy::misaligned_transmute" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::mismatched_target_os" , description : "Checks for cfg attributes having operating systems used in target family position." } , LintCompletion { label : "clippy::misrefactored_assign_op" , description : "Checks for `a op= a op b` or `a op= b op a` patterns." } , LintCompletion { label : "clippy::missing_const_for_fn" , description : "Suggests the use of `const` in functions and methods where possible." } , LintCompletion { label : "clippy::missing_docs_in_private_items" , description : "Warns if there is missing doc for any documentable item\\n(public or private)." } , LintCompletion { label : "clippy::missing_errors_doc" , description : "Checks the doc comments of publicly visible functions that\\nreturn a `Result` type and warns if there is no `# Errors` section." } , LintCompletion { label : "clippy::missing_inline_in_public_items" , description : "it lints if an exported function, method, trait method with default impl,\\nor trait method impl is not `#[inline]`." } , LintCompletion { label : "clippy::missing_safety_doc" , description : "Checks for the doc comments of publicly visible\\nunsafe functions and warns if there is no `# Safety` section." } , LintCompletion { label : "clippy::mistyped_literal_suffixes" , description : "Warns for mistyped suffix in literals" } , LintCompletion { label : "clippy::mixed_case_hex_literals" , description : "Warns on hexadecimal literals with mixed-case letter\\ndigits." } , LintCompletion { label : "clippy::module_inception" , description : "Checks for modules that have the same name as their\\nparent module" } , LintCompletion { label : "clippy::module_name_repetitions" , description : "Detects type names that are prefixed or suffixed by the\\ncontaining module's name." } , LintCompletion { label : "clippy::modulo_arithmetic" , description : "Checks for modulo arithmetic." } , LintCompletion { label : "clippy::modulo_one" , description : "Checks for getting the remainder of a division by one." } , LintCompletion { label : "clippy::multiple_crate_versions" , description : "Checks to see if multiple versions of a crate are being\\nused." } , LintCompletion { label : "clippy::multiple_inherent_impl" , description : "Checks for multiple inherent implementations of a struct" } , LintCompletion { label : "clippy::must_use_candidate" , description : "Checks for public functions that have no\\n[`#[must_use]`] attribute, but return something not already marked\\nmust-use, have no mutable arg and mutate no statics.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::must_use_unit" , description : "Checks for a [`#[must_use]`] attribute on\\nunit-returning functions and methods.\\n\\n[`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute" } , LintCompletion { label : "clippy::mut_from_ref" , description : "This lint checks for functions that take immutable\\nreferences and return mutable ones." } , LintCompletion { label : "clippy::mut_mut" , description : "Checks for instances of `mut mut` references." } , LintCompletion { label : "clippy::mut_range_bound" , description : "Checks for loops which have a range bound that is a mutable variable" } , LintCompletion { label : "clippy::mutable_key_type" , description : "Checks for sets/maps with mutable key types." } , LintCompletion { label : "clippy::mutex_atomic" , description : "Checks for usages of `Mutex<X>` where an atomic will do." } , LintCompletion { label : "clippy::mutex_integer" , description : "Checks for usages of `Mutex<X>` where `X` is an integral\\ntype." } , LintCompletion { label : "clippy::naive_bytecount" , description : "Checks for naive byte counts" } , LintCompletion { label : "clippy::needless_arbitrary_self_type" , description : "The lint checks for `self` in fn parameters that\\nspecify the `Self`-type explicitly" } , LintCompletion { label : "clippy::needless_bool" , description : "Checks for expressions of the form `if c { true } else {\\nfalse }` (or vice versa) and suggests using the condition directly." } , LintCompletion { label : "clippy::needless_borrow" , description : "Checks for address of operations (`&`) that are going to\\nbe dereferenced immediately by the compiler." } , LintCompletion { label : "clippy::needless_borrowed_reference" , description : "Checks for useless borrowed references." } , LintCompletion { label : "clippy::needless_collect" , description : "Checks for functions collecting an iterator when collect\\nis not needed." } , LintCompletion { label : "clippy::needless_continue" , description : "The lint checks for `if`-statements appearing in loops\\nthat contain a `continue` statement in either their main blocks or their\\n`else`-blocks, when omitting the `else`-block possibly with some\\nrearrangement of code can make the code easier to understand." } , LintCompletion { label : "clippy::needless_doctest_main" , description : "Checks for `fn main() { .. }` in doctests" } , LintCompletion { label : "clippy::needless_lifetimes" , description : "Checks for lifetime annotations which can be removed by\\nrelying on lifetime elision." } , LintCompletion { label : "clippy::needless_pass_by_value" , description : "Checks for functions taking arguments by value, but not\\nconsuming them in its\\nbody." } , LintCompletion { label : "clippy::needless_range_loop" , description : "Checks for looping over the range of `0..len` of some\\ncollection just to get the values by index." } , LintCompletion { label : "clippy::needless_return" , description : "Checks for return statements at the end of a block." } , LintCompletion { label : "clippy::needless_update" , description : "Checks for needlessly including a base struct on update\\nwhen all fields are changed anyway." } , LintCompletion { label : "clippy::neg_cmp_op_on_partial_ord" , description : "Checks for the usage of negated comparison operators on types which only implement\\n`PartialOrd` (e.g., `f64`)." } , LintCompletion { label : "clippy::neg_multiply" , description : "Checks for multiplication by -1 as a form of negation." } , LintCompletion { label : "clippy::never_loop" , description : "Checks for loops that will always `break`, `return` or\\n`continue` an outer loop." } , LintCompletion { label : "clippy::new_ret_no_self" , description : "Checks for `new` not returning a type that contains `Self`." } , LintCompletion { label : "clippy::new_without_default" , description : "Checks for types with a `fn new() -> Self` method and no\\nimplementation of\\n[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html)." } , LintCompletion { label : "clippy::no_effect" , description : "Checks for statements which have no effect." } , LintCompletion { label : "clippy::non_ascii_literal" , description : "Checks for non-ASCII characters in string literals." } , LintCompletion { label : "clippy::nonminimal_bool" , description : "Checks for boolean expressions that can be written more\\nconcisely." } , LintCompletion { label : "clippy::nonsensical_open_options" , description : "Checks for duplicate open options as well as combinations\\nthat make no sense." } , LintCompletion { label : "clippy::not_unsafe_ptr_arg_deref" , description : "Checks for public functions that dereference raw pointer\\narguments but are not marked unsafe." } , LintCompletion { label : "clippy::ok_expect" , description : "Checks for usage of `ok().expect(..)`." } , LintCompletion { label : "clippy::op_ref" , description : "Checks for arguments to `==` which have their address\\ntaken to satisfy a bound\\nand suggests to dereference the other argument instead" } , LintCompletion { label : "clippy::option_as_ref_deref" , description : "Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str)." } , LintCompletion { label : "clippy::option_env_unwrap" , description : "Checks for usage of `option_env!(...).unwrap()` and\\nsuggests usage of the `env!` macro." } , LintCompletion { label : "clippy::option_if_let_else" , description : "Lints usage of `if let Some(v) = ... { y } else { x }` which is more\\nidiomatically done with `Option::map_or` (if the else bit is a pure\\nexpression) or `Option::map_or_else` (if the else bit is an impure\\nexpression)." } , LintCompletion { label : "clippy::option_map_or_none" , description : "Checks for usage of `_.map_or(None, _)`." } , LintCompletion { label : "clippy::option_map_unit_fn" , description : "Checks for usage of `option.map(f)` where f is a function\\nor closure that returns the unit type `()`." } , LintCompletion { label : "clippy::option_option" , description : "Checks for use of `Option<Option<_>>` in function signatures and type\\ndefinitions" } , LintCompletion { label : "clippy::or_fun_call" , description : "Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,\\netc., and suggests to use `or_else`, `unwrap_or_else`, etc., or\\n`unwrap_or_default` instead." } , LintCompletion { label : "clippy::out_of_bounds_indexing" , description : "Checks for out of bounds array indexing with a constant\\nindex." } , LintCompletion { label : "clippy::overflow_check_conditional" , description : "Detects classic underflow/overflow checks." } , LintCompletion { label : "clippy::panic" , description : "Checks for usage of `panic!`." } , LintCompletion { label : "clippy::panic_in_result_fn" , description : "Checks for usage of `panic!`, `unimplemented!`, `todo!` or `unreachable!` in a function of type result." } , LintCompletion { label : "clippy::panic_params" , description : "Checks for missing parameters in `panic!`." } , LintCompletion { label : "clippy::panicking_unwrap" , description : "Checks for calls of `unwrap[_err]()` that will always fail." } , LintCompletion { label : "clippy::partialeq_ne_impl" , description : "Checks for manual re-implementations of `PartialEq::ne`." } , LintCompletion { label : "clippy::path_buf_push_overwrite" , description : "* Checks for [push](https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.push)\\ncalls on `PathBuf` that can cause overwrites." } , LintCompletion { label : "clippy::pattern_type_mismatch" , description : "Checks for patterns that aren't exact representations of the types\\nthey are applied to.\\n\\nTo satisfy this lint, you will have to adjust either the expression that is matched\\nagainst or the pattern itself, as well as the bindings that are introduced by the\\nadjusted patterns. For matching you will have to either dereference the expression\\nwith the `*` operator, or amend the patterns to explicitly match against `&<pattern>`\\nor `&mut <pattern>` depending on the reference mutability. For the bindings you need\\nto use the inverse. You can leave them as plain bindings if you wish for the value\\nto be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct\\na reference into the matched structure.\\n\\nIf you are looking for a way to learn about ownership semantics in more detail, it\\nis recommended to look at IDE options available to you to highlight types, lifetimes\\nand reference semantics in your code. The available tooling would expose these things\\nin a general way even outside of the various pattern matching mechanics. Of course\\nthis lint can still be used to highlight areas of interest and ensure a good understanding\\nof ownership semantics." } , LintCompletion { label : "clippy::possible_missing_comma" , description : "Checks for possible missing comma in an array. It lints if\\nan array element is a binary operator expression and it lies on two lines." } , LintCompletion { label : "clippy::precedence" , description : "Checks for operations where precedence may be unclear\\nand suggests to add parentheses. Currently it catches the following:\\n* mixed usage of arithmetic and bit shifting/combining operators without\\nparentheses\\n* a \\\"negative\\\" numeric literal (which is really a unary `-` followed by a\\nnumeric literal)\\n followed by a method call" } , LintCompletion { label : "clippy::print_literal" , description : "This lint warns about the use of literals as `print!`/`println!` args." } , LintCompletion { label : "clippy::print_stdout" , description : "Checks for printing on *stdout*. The purpose of this lint\\nis to catch debugging remnants." } , LintCompletion { label : "clippy::print_with_newline" , description : "This lint warns when you use `print!()` with a format\\nstring that ends in a newline." } , LintCompletion { label : "clippy::println_empty_string" , description : "This lint warns when you use `println!(\\\"\\\")` to\\nprint a newline." } , LintCompletion { label : "clippy::ptr_arg" , description : "This lint checks for function arguments of type `&String`\\nor `&Vec` unless the references are mutable. It will also suggest you\\nreplace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`\\ncalls." } , LintCompletion { label : "clippy::ptr_eq" , description : "Use `std::ptr::eq` when applicable" } , LintCompletion { label : "clippy::ptr_offset_with_cast" , description : "Checks for usage of the `offset` pointer method with a `usize` casted to an\\n`isize`." } , LintCompletion { label : "clippy::pub_enum_variant_names" , description : "Detects public enumeration variants that are\\nprefixed or suffixed by the same characters." } , LintCompletion { label : "clippy::question_mark" , description : "Checks for expressions that could be replaced by the question mark operator." } , LintCompletion { label : "clippy::range_minus_one" , description : "Checks for inclusive ranges where 1 is subtracted from\\nthe upper bound, e.g., `x..=(y-1)`." } , LintCompletion { label : "clippy::range_plus_one" , description : "Checks for exclusive ranges where 1 is added to the\\nupper bound, e.g., `x..(y+1)`." } , LintCompletion { label : "clippy::range_step_by_zero" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::range_zip_with_len" , description : "Checks for zipping a collection with the range of\\n`0.._.len()`." } , LintCompletion { label : "clippy::rc_buffer" , description : "Checks for `Rc<T>` and `Arc<T>` when `T` is a mutable buffer type such as `String` or `Vec`." } , LintCompletion { label : "clippy::redundant_allocation" , description : "Checks for use of redundant allocations anywhere in the code." } , LintCompletion { label : "clippy::redundant_clone" , description : "Checks for a redundant `clone()` (and its relatives) which clones an owned\\nvalue that is going to be dropped without further use." } , LintCompletion { label : "clippy::redundant_closure" , description : "Checks for closures which just call another function where\\nthe function can be called directly. `unsafe` functions or calls where types\\nget adjusted are ignored." } , LintCompletion { label : "clippy::redundant_closure_call" , description : "Detects closures called in the same expression where they\\nare defined." } , LintCompletion { label : "clippy::redundant_closure_for_method_calls" , description : "Checks for closures which only invoke a method on the closure\\nargument and can be replaced by referencing the method directly." } , LintCompletion { label : "clippy::redundant_field_names" , description : "Checks for fields in struct literals where shorthands\\ncould be used." } , LintCompletion { label : "clippy::redundant_pattern" , description : "Checks for patterns in the form `name @ _`." } , LintCompletion { label : "clippy::redundant_pattern_matching" , description : "Lint for redundant pattern matching over `Result` or\\n`Option`" } , LintCompletion { label : "clippy::redundant_pub_crate" , description : "Checks for items declared `pub(crate)` that are not crate visible because they\\nare inside a private module." } , LintCompletion { label : "clippy::redundant_static_lifetimes" , description : "Checks for constants and statics with an explicit `'static` lifetime." } , LintCompletion { label : "clippy::ref_in_deref" , description : "Checks for references in expressions that use\\nauto dereference." } , LintCompletion { label : "clippy::regex_macro" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::repeat_once" , description : "Checks for usage of `.repeat(1)` and suggest the following method for each types.\\n- `.to_string()` for `str`\\n- `.clone()` for `String`\\n- `.to_vec()` for `slice`" } , LintCompletion { label : "clippy::replace_consts" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::rest_pat_in_fully_bound_structs" , description : "Checks for unnecessary '..' pattern binding on struct when all fields are explicitly matched." } , LintCompletion { label : "clippy::result_map_or_into_option" , description : "Checks for usage of `_.map_or(None, Some)`." } , LintCompletion { label : "clippy::result_map_unit_fn" , description : "Checks for usage of `result.map(f)` where f is a function\\nor closure that returns the unit type `()`." } , LintCompletion { label : "clippy::result_unit_err" , description : "Checks for public functions that return a `Result`\\nwith an `Err` type of `()`. It suggests using a custom type that\\nimplements [`std::error::Error`]." } , LintCompletion { label : "clippy::reversed_empty_ranges" , description : "Checks for range expressions `x..y` where both `x` and `y`\\nare constant and `x` is greater or equal to `y`." } , LintCompletion { label : "clippy::same_functions_in_if_condition" , description : "Checks for consecutive `if`s with the same function call." } , LintCompletion { label : "clippy::same_item_push" , description : "Checks whether a for loop is being used to push a constant\\nvalue into a Vec." } , LintCompletion { label : "clippy::search_is_some" , description : "Checks for an iterator search (such as `find()`,\\n`position()`, or `rposition()`) followed by a call to `is_some()`." } , LintCompletion { label : "clippy::self_assignment" , description : "Checks for explicit self-assignments." } , LintCompletion { label : "clippy::serde_api_misuse" , description : "Checks for mis-uses of the serde API." } , LintCompletion { label : "clippy::shadow_reuse" , description : "Checks for bindings that shadow other bindings already in\\nscope, while reusing the original value." } , LintCompletion { label : "clippy::shadow_same" , description : "Checks for bindings that shadow other bindings already in\\nscope, while just changing reference level or mutability." } , LintCompletion { label : "clippy::shadow_unrelated" , description : "Checks for bindings that shadow other bindings already in\\nscope, either without a initialization or with one that does not even use\\nthe original value." } , LintCompletion { label : "clippy::short_circuit_statement" , description : "Checks for the use of short circuit boolean conditions as\\na\\nstatement." } , LintCompletion { label : "clippy::should_assert_eq" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::should_implement_trait" , description : "Checks for methods that should live in a trait\\nimplementation of a `std` trait (see [llogiq's blog\\npost](http://llogiq.github.io/2015/07/30/traits.html) for further\\ninformation) instead of an inherent implementation." } , LintCompletion { label : "clippy::similar_names" , description : "Checks for names that are very similar and thus confusing." } , LintCompletion { label : "clippy::single_char_pattern" , description : "Checks for string methods that receive a single-character\\n`str` as an argument, e.g., `_.split(\\\"x\\\")`." } , LintCompletion { label : "clippy::single_char_push_str" , description : "Warns when using `push_str` with a single-character string literal,\\nand `push` with a `char` would work fine." } , LintCompletion { label : "clippy::single_component_path_imports" , description : "Checking for imports with single component use path." } , LintCompletion { label : "clippy::single_match" , description : "Checks for matches with a single arm where an `if let`\\nwill usually suffice." } , LintCompletion { label : "clippy::single_match_else" , description : "Checks for matches with two arms where an `if let else` will\\nusually suffice." } , LintCompletion { label : "clippy::skip_while_next" , description : "Checks for usage of `_.skip_while(condition).next()`." } , LintCompletion { label : "clippy::slow_vector_initialization" , description : "Checks slow zero-filled vector initialization" } , LintCompletion { label : "clippy::stable_sort_primitive" , description : "When sorting primitive values (integers, bools, chars, as well\\nas arrays, slices, and tuples of such items), it is better to\\nuse an unstable sort than a stable sort." } , LintCompletion { label : "clippy::str_to_string" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::string_add" , description : "Checks for all instances of `x + _` where `x` is of type\\n`String`, but only if [`string_add_assign`](#string_add_assign) does *not*\\nmatch." } , LintCompletion { label : "clippy::string_add_assign" , description : "Checks for string appends of the form `x = x + y` (without\\n`let`!)." } , LintCompletion { label : "clippy::string_extend_chars" , description : "Checks for the use of `.extend(s.chars())` where s is a\\n`&str` or `String`." } , LintCompletion { label : "clippy::string_lit_as_bytes" , description : "Checks for the `as_bytes` method called on string literals\\nthat contain only ASCII characters." } , LintCompletion { label : "clippy::string_to_string" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::struct_excessive_bools" , description : "Checks for excessive\\nuse of bools in structs." } , LintCompletion { label : "clippy::suboptimal_flops" , description : "Looks for floating-point expressions that\\ncan be expressed using built-in methods to improve both\\naccuracy and performance." } , LintCompletion { label : "clippy::suspicious_arithmetic_impl" , description : "Lints for suspicious operations in impls of arithmetic operators, e.g.\\nsubtracting elements in an Add impl." } , LintCompletion { label : "clippy::suspicious_assignment_formatting" , description : "Checks for use of the non-existent `=*`, `=!` and `=-`\\noperators." } , LintCompletion { label : "clippy::suspicious_else_formatting" , description : "Checks for formatting of `else`. It lints if the `else`\\nis followed immediately by a newline or the `else` seems to be missing." } , LintCompletion { label : "clippy::suspicious_map" , description : "Checks for calls to `map` followed by a `count`." } , LintCompletion { label : "clippy::suspicious_op_assign_impl" , description : "Lints for suspicious operations in impls of OpAssign, e.g.\\nsubtracting elements in an AddAssign impl." } , LintCompletion { label : "clippy::suspicious_unary_op_formatting" , description : "Checks the formatting of a unary operator on the right hand side\\nof a binary operator. It lints if there is no space between the binary and unary operators,\\nbut there is a space between the unary and its operand." } , LintCompletion { label : "clippy::tabs_in_doc_comments" , description : "Checks doc comments for usage of tab characters." } , LintCompletion { label : "clippy::temporary_assignment" , description : "Checks for construction of a structure or tuple just to\\nassign a value in it." } , LintCompletion { label : "clippy::temporary_cstring_as_ptr" , description : "Checks for getting the inner pointer of a temporary\\n`CString`." } , LintCompletion { label : "clippy::to_digit_is_some" , description : "Checks for `.to_digit(..).is_some()` on `char`s." } , LintCompletion { label : "clippy::to_string_in_display" , description : "Checks for uses of `to_string()` in `Display` traits." } , LintCompletion { label : "clippy::todo" , description : "Checks for usage of `todo!`." } , LintCompletion { label : "clippy::too_many_arguments" , description : "Checks for functions with too many parameters." } , LintCompletion { label : "clippy::too_many_lines" , description : "Checks for functions with a large amount of lines." } , LintCompletion { label : "clippy::toplevel_ref_arg" , description : "Checks for function arguments and let bindings denoted as\\n`ref`." } , LintCompletion { label : "clippy::trait_duplication_in_bounds" , description : "Checks for cases where generics are being used and multiple\\nsyntax specifications for trait bounds are used simultaneously." } , LintCompletion { label : "clippy::transmute_bytes_to_str" , description : "Checks for transmutes from a `&[u8]` to a `&str`." } , LintCompletion { label : "clippy::transmute_float_to_int" , description : "Checks for transmutes from a float to an integer." } , LintCompletion { label : "clippy::transmute_int_to_bool" , description : "Checks for transmutes from an integer to a `bool`." } , LintCompletion { label : "clippy::transmute_int_to_char" , description : "Checks for transmutes from an integer to a `char`." } , LintCompletion { label : "clippy::transmute_int_to_float" , description : "Checks for transmutes from an integer to a float." } , LintCompletion { label : "clippy::transmute_ptr_to_ptr" , description : "Checks for transmutes from a pointer to a pointer, or\\nfrom a reference to a reference." } , LintCompletion { label : "clippy::transmute_ptr_to_ref" , description : "Checks for transmutes from a pointer to a reference." } , LintCompletion { label : "clippy::transmutes_expressible_as_ptr_casts" , description : "Checks for transmutes that could be a pointer cast." } , LintCompletion { label : "clippy::transmuting_null" , description : "Checks for transmute calls which would receive a null pointer." } , LintCompletion { label : "clippy::trivial_regex" , description : "Checks for trivial [regex](https://crates.io/crates/regex)\\ncreation (with `Regex::new`, `RegexBuilder::new` or `RegexSet::new`)." } , LintCompletion { label : "clippy::trivially_copy_pass_by_ref" , description : "Checks for functions taking arguments by reference, where\\nthe argument type is `Copy` and small enough to be more efficient to always\\npass by value." } , LintCompletion { label : "clippy::try_err" , description : "Checks for usages of `Err(x)?`." } , LintCompletion { label : "clippy::type_complexity" , description : "Checks for types used in structs, parameters and `let`\\ndeclarations above a certain complexity threshold." } , LintCompletion { label : "clippy::type_repetition_in_bounds" , description : "This lint warns about unnecessary type repetitions in trait bounds" } , LintCompletion { label : "clippy::unicode_not_nfc" , description : "Checks for string literals that contain Unicode in a form\\nthat is not equal to its\\n[NFC-recomposition](http://www.unicode.org/reports/tr15/#Norm_Forms)." } , LintCompletion { label : "clippy::unimplemented" , description : "Checks for usage of `unimplemented!`." } , LintCompletion { label : "clippy::uninit_assumed_init" , description : "Checks for `MaybeUninit::uninit().assume_init()`." } , LintCompletion { label : "clippy::unit_arg" , description : "Checks for passing a unit value as an argument to a function without using a\\nunit literal (`()`)." } , LintCompletion { label : "clippy::unit_cmp" , description : "Checks for comparisons to unit. This includes all binary\\ncomparisons (like `==` and `<`) and asserts." } , LintCompletion { label : "clippy::unit_return_expecting_ord" , description : "Checks for functions that expect closures of type\\nFn(...) -> Ord where the implemented closure returns the unit type.\\nThe lint also suggests to remove the semi-colon at the end of the statement if present." } , LintCompletion { label : "clippy::unknown_clippy_lints" , description : "Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy\\nlints and if those lints exist in clippy. If there is an uppercase letter in the lint name\\n(not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase\\nthe lint name." } , LintCompletion { label : "clippy::unnecessary_cast" , description : "Checks for casts to the same type, casts of int literals to integer types\\nand casts of float literals to float types." } , LintCompletion { label : "clippy::unnecessary_filter_map" , description : "Checks for `filter_map` calls which could be replaced by `filter` or `map`.\\nMore specifically it checks if the closure provided is only performing one of the\\nfilter or map operations and suggests the appropriate option." } , LintCompletion { label : "clippy::unnecessary_fold" , description : "Checks for using `fold` when a more succinct alternative exists.\\nSpecifically, this checks for `fold`s which could be replaced by `any`, `all`,\\n`sum` or `product`." } , LintCompletion { label : "clippy::unnecessary_lazy_evaluations" , description : "As the counterpart to `or_fun_call`, this lint looks for unnecessary\\nlazily evaluated closures on `Option` and `Result`.\\n\\nThis lint suggests changing the following functions, when eager evaluation results in\\nsimpler code:\\n - `unwrap_or_else` to `unwrap_or`\\n - `and_then` to `and`\\n - `or_else` to `or`\\n - `get_or_insert_with` to `get_or_insert`\\n - `ok_or_else` to `ok_or`" } , LintCompletion { label : "clippy::unnecessary_mut_passed" , description : "Detects passing a mutable reference to a function that only\\nrequires an immutable reference." } , LintCompletion { label : "clippy::unnecessary_operation" , description : "Checks for expression statements that can be reduced to a\\nsub-expression." } , LintCompletion { label : "clippy::unnecessary_sort_by" , description : "Detects uses of `Vec::sort_by` passing in a closure\\nwhich compares the two arguments, either directly or indirectly." } , LintCompletion { label : "clippy::unnecessary_unwrap" , description : "Checks for calls of `unwrap[_err]()` that cannot fail." } , LintCompletion { label : "clippy::unneeded_field_pattern" , description : "Checks for structure field patterns bound to wildcards." } , LintCompletion { label : "clippy::unneeded_wildcard_pattern" , description : "Checks for tuple patterns with a wildcard\\npattern (`_`) is next to a rest pattern (`..`).\\n\\n_NOTE_: While `_, ..` means there is at least one element left, `..`\\nmeans there are 0 or more elements left. This can make a difference\\nwhen refactoring, but shouldn't result in errors in the refactored code,\\nsince the wildcard pattern isn't used anyway." } , LintCompletion { label : "clippy::unnested_or_patterns" , description : "Checks for unnested or-patterns, e.g., `Some(0) | Some(2)` and\\nsuggests replacing the pattern with a nested one, `Some(0 | 2)`.\\n\\nAnother way to think of this is that it rewrites patterns in\\n*disjunctive normal form (DNF)* into *conjunctive normal form (CNF)*." } , LintCompletion { label : "clippy::unreachable" , description : "Checks for usage of `unreachable!`." } , LintCompletion { label : "clippy::unreadable_literal" , description : "Warns if a long integral or floating-point constant does\\nnot contain underscores." } , LintCompletion { label : "clippy::unsafe_derive_deserialize" , description : "Checks for deriving `serde::Deserialize` on a type that\\nhas methods using `unsafe`." } , LintCompletion { label : "clippy::unsafe_removed_from_name" , description : "Checks for imports that remove \\\"unsafe\\\" from an item's\\nname." } , LintCompletion { label : "clippy::unsafe_vector_initialization" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unseparated_literal_suffix" , description : "Warns if literal suffixes are not separated by an\\nunderscore." } , LintCompletion { label : "clippy::unsound_collection_transmute" , description : "Checks for transmutes between collections whose\\ntypes have different ABI, size or alignment." } , LintCompletion { label : "clippy::unstable_as_mut_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unstable_as_slice" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_collect" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_io_amount" , description : "Checks for unused written/read amount." } , LintCompletion { label : "clippy::unused_label" , description : "Nothing. This lint has been deprecated." } , LintCompletion { label : "clippy::unused_self" , description : "Checks methods that contain a `self` argument but don't use it" } , LintCompletion { label : "clippy::unused_unit" , description : "Checks for unit (`()`) expressions that can be removed." } , LintCompletion { label : "clippy::unwrap_in_result" , description : "Checks for functions of type Result that contain `expect()` or `unwrap()`" } , LintCompletion { label : "clippy::unwrap_used" , description : "Checks for `.unwrap()` calls on `Option`s and on `Result`s." } , LintCompletion { label : "clippy::use_debug" , description : "Checks for use of `Debug` formatting. The purpose of this\\nlint is to catch debugging remnants." } , LintCompletion { label : "clippy::use_self" , description : "Checks for unnecessary repetition of structure name when a\\nreplacement with `Self` is applicable." } , LintCompletion { label : "clippy::used_underscore_binding" , description : "Checks for the use of bindings with a single leading\\nunderscore." } , LintCompletion { label : "clippy::useless_asref" , description : "Checks for usage of `.as_ref()` or `.as_mut()` where the\\ntypes before and after the call are the same." } , LintCompletion { label : "clippy::useless_attribute" , description : "Checks for `extern crate` and `use` items annotated with\\nlint attributes.\\n\\nThis lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,\\n`#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and\\n`#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on\\n`extern crate` items with a `#[macro_use]` attribute." } , LintCompletion { label : "clippy::useless_conversion" , description : "Checks for `Into`, `TryInto`, `From`, `TryFrom`,`IntoIter` calls\\nthat useless converts to the same type as caller." } , LintCompletion { label : "clippy::useless_format" , description : "Checks for the use of `format!(\\\"string literal with no\\nargument\\\")` and `format!(\\\"{}\\\", foo)` where `foo` is a string." } , LintCompletion { label : "clippy::useless_let_if_seq" , description : "Checks for variable declarations immediately followed by a\\nconditional affectation." } , LintCompletion { label : "clippy::useless_transmute" , description : "Checks for transmutes to the original type of the object\\nand transmutes that could be a cast." } , LintCompletion { label : "clippy::useless_vec" , description : "Checks for usage of `&vec![..]` when using `&[..]` would\\nbe possible." } , LintCompletion { label : "clippy::vec_box" , description : "Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.\\nCheck the [Box documentation](https://doc.rust-lang.org/std/boxed/index.html) for more information." } , LintCompletion { label : "clippy::vec_resize_to_zero" , description : "Finds occurrences of `Vec::resize(0, an_int)`" } , LintCompletion { label : "clippy::verbose_bit_mask" , description : "Checks for bit masks that can be replaced by a call\\nto `trailing_zeros`" } , LintCompletion { label : "clippy::verbose_file_reads" , description : "Checks for use of File::read_to_end and File::read_to_string." } , LintCompletion { label : "clippy::vtable_address_comparisons" , description : "Checks for comparisons with an address of a trait vtable." } , LintCompletion { label : "clippy::while_immutable_condition" , description : "Checks whether variables used within while loop condition\\ncan be (and are) mutated in the body." } , LintCompletion { label : "clippy::while_let_loop" , description : "Detects `loop + match` combinations that are easier\\nwritten as a `while let` loop." } , LintCompletion { label : "clippy::while_let_on_iterator" , description : "Checks for `while let` expressions on iterators." } , LintCompletion { label : "clippy::wildcard_dependencies" , description : "Checks for wildcard dependencies in the `Cargo.toml`." } , LintCompletion { label : "clippy::wildcard_enum_match_arm" , description : "Checks for wildcard enum matches using `_`." } , LintCompletion { label : "clippy::wildcard_imports" , description : "Checks for wildcard imports `use _::*`." } , LintCompletion { label : "clippy::wildcard_in_or_patterns" , description : "Checks for wildcard pattern used with others patterns in same match arm." } , LintCompletion { label : "clippy::write_literal" , description : "This lint warns about the use of literals as `write!`/`writeln!` args." } , LintCompletion { label : "clippy::write_with_newline" , description : "This lint warns when you use `write!()` with a format\\nstring that\\nends in a newline." } , LintCompletion { label : "clippy::writeln_empty_string" , description : "This lint warns when you use `writeln!(buf, \\\"\\\")` to\\nprint a newline." } , LintCompletion { label : "clippy::wrong_pub_self_convention" , description : "This is the same as\\n[`wrong_self_convention`](#wrong_self_convention), but for public items." } , LintCompletion { label : "clippy::wrong_self_convention" , description : "Checks for methods with certain name prefixes and which\\ndoesn't match how self is taken. The actual rules are:\\n\\n|Prefix |`self` taken |\\n|-------|----------------------|\\n|`as_` |`&self` or `&mut self`|\\n|`from_`| none |\\n|`into_`|`self` |\\n|`is_` |`&self` or none |\\n|`to_` |`&self` |" } , LintCompletion { label : "clippy::wrong_transmute" , description : "Checks for transmutes that can't ever be correct on any\\narchitecture." } , LintCompletion { label : "clippy::zero_divided_by_zero" , description : "Checks for `0.0 / 0.0`." } , LintCompletion { label : "clippy::zero_prefixed_literal" , description : "Warns if an integral constant literal starts with `0`." } , LintCompletion { label : "clippy::zero_ptr" , description : "Catch casts from `0` to some pointer type" } , LintCompletion { label : "clippy::zst_offset" , description : "Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to\\nzero-sized types" }] ;
diff --git a/crates/completion/src/completion_item.rs b/crates/completion/src/item.rs
index 2e1ca0e59..6d1d085f4 100644
--- a/crates/completion/src/completion_item.rs
+++ b/crates/completion/src/item.rs
@@ -6,7 +6,7 @@ use hir::{Documentation, Mutability};
6use syntax::TextRange; 6use syntax::TextRange;
7use text_edit::TextEdit; 7use text_edit::TextEdit;
8 8
9use crate::completion_config::SnippetCap; 9use crate::config::SnippetCap;
10 10
11/// `CompletionItem` describes a single completion variant in the editor pop-up. 11/// `CompletionItem` describes a single completion variant in the editor pop-up.
12/// It is basically a POD with various properties. To construct a 12/// It is basically a POD with various properties. To construct a
@@ -272,10 +272,6 @@ pub(crate) struct Builder {
272} 272}
273 273
274impl Builder { 274impl Builder {
275 pub(crate) fn add_to(self, acc: &mut Completions) {
276 acc.add(self.build())
277 }
278
279 pub(crate) fn build(self) -> CompletionItem { 275 pub(crate) fn build(self) -> CompletionItem {
280 let label = self.label; 276 let label = self.label;
281 let text_edit = match self.text_edit { 277 let text_edit = match self.text_edit {
@@ -376,28 +372,3 @@ impl<'a> Into<CompletionItem> for Builder {
376 self.build() 372 self.build()
377 } 373 }
378} 374}
379
380/// Represents an in-progress set of completions being built.
381#[derive(Debug, Default)]
382pub struct Completions {
383 buf: Vec<CompletionItem>,
384}
385
386impl Completions {
387 pub fn add(&mut self, item: impl Into<CompletionItem>) {
388 self.buf.push(item.into())
389 }
390 pub fn add_all<I>(&mut self, items: I)
391 where
392 I: IntoIterator,
393 I::Item: Into<CompletionItem>,
394 {
395 items.into_iter().for_each(|item| self.add(item.into()))
396 }
397}
398
399impl Into<Vec<CompletionItem>> for Completions {
400 fn into(self) -> Vec<CompletionItem> {
401 self.buf
402 }
403}
diff --git a/crates/completion/src/lib.rs b/crates/completion/src/lib.rs
index b72fd249d..89c0a9978 100644
--- a/crates/completion/src/lib.rs
+++ b/crates/completion/src/lib.rs
@@ -1,39 +1,23 @@
1//! `completions` crate provides utilities for generating completions of user input. 1//! `completions` crate provides utilities for generating completions of user input.
2 2
3mod completion_config; 3mod config;
4mod completion_item; 4mod item;
5mod completion_context; 5mod context;
6mod presentation;
7mod patterns; 6mod patterns;
8mod generated_lint_completions; 7mod generated_lint_completions;
9#[cfg(test)] 8#[cfg(test)]
10mod test_utils; 9mod test_utils;
11 10
12mod complete_attribute; 11mod completions;
13mod complete_dot;
14mod complete_record;
15mod complete_pattern;
16mod complete_fn_param;
17mod complete_keyword;
18mod complete_snippet;
19mod complete_qualified_path;
20mod complete_unqualified_path;
21mod complete_postfix;
22mod complete_macro_in_item_position;
23mod complete_trait_impl;
24mod complete_mod;
25 12
26use ide_db::base_db::FilePosition; 13use ide_db::base_db::FilePosition;
27use ide_db::RootDatabase; 14use ide_db::RootDatabase;
28 15
29use crate::{ 16use crate::{completions::Completions, context::CompletionContext, item::CompletionKind};
30 completion_context::CompletionContext,
31 completion_item::{CompletionKind, Completions},
32};
33 17
34pub use crate::{ 18pub use crate::{
35 completion_config::CompletionConfig, 19 config::CompletionConfig,
36 completion_item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat}, 20 item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat},
37}; 21};
38 22
39//FIXME: split the following feature into fine-grained features. 23//FIXME: split the following feature into fine-grained features.
@@ -118,28 +102,28 @@ pub fn completions(
118 } 102 }
119 103
120 let mut acc = Completions::default(); 104 let mut acc = Completions::default();
121 complete_attribute::complete_attribute(&mut acc, &ctx); 105 completions::attribute::complete_attribute(&mut acc, &ctx);
122 complete_fn_param::complete_fn_param(&mut acc, &ctx); 106 completions::fn_param::complete_fn_param(&mut acc, &ctx);
123 complete_keyword::complete_expr_keyword(&mut acc, &ctx); 107 completions::keyword::complete_expr_keyword(&mut acc, &ctx);
124 complete_keyword::complete_use_tree_keyword(&mut acc, &ctx); 108 completions::keyword::complete_use_tree_keyword(&mut acc, &ctx);
125 complete_snippet::complete_expr_snippet(&mut acc, &ctx); 109 completions::snippet::complete_expr_snippet(&mut acc, &ctx);
126 complete_snippet::complete_item_snippet(&mut acc, &ctx); 110 completions::snippet::complete_item_snippet(&mut acc, &ctx);
127 complete_qualified_path::complete_qualified_path(&mut acc, &ctx); 111 completions::qualified_path::complete_qualified_path(&mut acc, &ctx);
128 complete_unqualified_path::complete_unqualified_path(&mut acc, &ctx); 112 completions::unqualified_path::complete_unqualified_path(&mut acc, &ctx);
129 complete_dot::complete_dot(&mut acc, &ctx); 113 completions::dot::complete_dot(&mut acc, &ctx);
130 complete_record::complete_record(&mut acc, &ctx); 114 completions::record::complete_record(&mut acc, &ctx);
131 complete_pattern::complete_pattern(&mut acc, &ctx); 115 completions::pattern::complete_pattern(&mut acc, &ctx);
132 complete_postfix::complete_postfix(&mut acc, &ctx); 116 completions::postfix::complete_postfix(&mut acc, &ctx);
133 complete_macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx); 117 completions::macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
134 complete_trait_impl::complete_trait_impl(&mut acc, &ctx); 118 completions::trait_impl::complete_trait_impl(&mut acc, &ctx);
135 complete_mod::complete_mod(&mut acc, &ctx); 119 completions::mod_::complete_mod(&mut acc, &ctx);
136 120
137 Some(acc) 121 Some(acc)
138} 122}
139 123
140#[cfg(test)] 124#[cfg(test)]
141mod tests { 125mod tests {
142 use crate::completion_config::CompletionConfig; 126 use crate::config::CompletionConfig;
143 use crate::test_utils; 127 use crate::test_utils;
144 128
145 struct DetailAndDocumentation<'a> { 129 struct DetailAndDocumentation<'a> {
diff --git a/crates/completion/src/test_utils.rs b/crates/completion/src/test_utils.rs
index b02556797..4c1b1a839 100644
--- a/crates/completion/src/test_utils.rs
+++ b/crates/completion/src/test_utils.rs
@@ -8,7 +8,7 @@ use stdx::{format_to, trim_indent};
8use syntax::{AstNode, NodeOrToken, SyntaxElement}; 8use syntax::{AstNode, NodeOrToken, SyntaxElement};
9use test_utils::{assert_eq_text, RangeOrOffset}; 9use test_utils::{assert_eq_text, RangeOrOffset};
10 10
11use crate::{completion_item::CompletionKind, CompletionConfig, CompletionItem}; 11use crate::{item::CompletionKind, CompletionConfig, CompletionItem};
12 12
13/// Creates analysis from a multi-file fixture, returns positions marked with <|>. 13/// Creates analysis from a multi-file fixture, returns positions marked with <|>.
14pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) { 14pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) {
@@ -32,10 +32,8 @@ pub(crate) fn do_completion_with_config(
32 code: &str, 32 code: &str,
33 kind: CompletionKind, 33 kind: CompletionKind,
34) -> Vec<CompletionItem> { 34) -> Vec<CompletionItem> {
35 let mut kind_completions: Vec<CompletionItem> = get_all_completion_items(config, code) 35 let mut kind_completions: Vec<CompletionItem> =
36 .into_iter() 36 get_all_items(config, code).into_iter().filter(|c| c.completion_kind == kind).collect();
37 .filter(|c| c.completion_kind == kind)
38 .collect();
39 kind_completions.sort_by(|l, r| l.label().cmp(r.label())); 37 kind_completions.sort_by(|l, r| l.label().cmp(r.label()));
40 kind_completions 38 kind_completions
41} 39}
@@ -49,10 +47,8 @@ pub(crate) fn completion_list_with_config(
49 code: &str, 47 code: &str,
50 kind: CompletionKind, 48 kind: CompletionKind,
51) -> String { 49) -> String {
52 let mut kind_completions: Vec<CompletionItem> = get_all_completion_items(config, code) 50 let mut kind_completions: Vec<CompletionItem> =
53 .into_iter() 51 get_all_items(config, code).into_iter().filter(|c| c.completion_kind == kind).collect();
54 .filter(|c| c.completion_kind == kind)
55 .collect();
56 kind_completions.sort_by_key(|c| c.label().to_owned()); 52 kind_completions.sort_by_key(|c| c.label().to_owned());
57 let label_width = kind_completions 53 let label_width = kind_completions
58 .iter() 54 .iter()
@@ -121,10 +117,7 @@ pub(crate) fn check_pattern_is_not_applicable(code: &str, check: fn(SyntaxElemen
121 assert!(!check(NodeOrToken::Token(token))); 117 assert!(!check(NodeOrToken::Token(token)));
122} 118}
123 119
124pub(crate) fn get_all_completion_items( 120pub(crate) fn get_all_items(config: CompletionConfig, code: &str) -> Vec<CompletionItem> {
125 config: CompletionConfig,
126 code: &str,
127) -> Vec<CompletionItem> {
128 let (db, position) = position(code); 121 let (db, position) = position(code);
129 crate::completions(&db, &config, position).unwrap().into() 122 crate::completions(&db, &config, position).unwrap().into()
130} 123}
diff --git a/crates/hir/src/code_model.rs b/crates/hir/src/code_model.rs
index 63c1a8ebf..30a5e4580 100644
--- a/crates/hir/src/code_model.rs
+++ b/crates/hir/src/code_model.rs
@@ -4,7 +4,6 @@ use std::{iter, sync::Arc};
4use arrayvec::ArrayVec; 4use arrayvec::ArrayVec;
5use base_db::{CrateDisplayName, CrateId, Edition, FileId}; 5use base_db::{CrateDisplayName, CrateId, Edition, FileId};
6use either::Either; 6use either::Either;
7use hir_def::find_path::PrefixKind;
8use hir_def::{ 7use hir_def::{
9 adt::ReprKind, 8 adt::ReprKind,
10 adt::StructKind, 9 adt::StructKind,
@@ -12,16 +11,18 @@ use hir_def::{
12 builtin_type::BuiltinType, 11 builtin_type::BuiltinType,
13 expr::{BindingAnnotation, Pat, PatId}, 12 expr::{BindingAnnotation, Pat, PatId},
14 import_map, 13 import_map,
14 item_tree::ItemTreeNode,
15 lang_item::LangItemTarget, 15 lang_item::LangItemTarget,
16 path::ModPath, 16 path::ModPath,
17 per_ns::PerNs, 17 per_ns::PerNs,
18 resolver::{HasResolver, Resolver}, 18 resolver::{HasResolver, Resolver},
19 src::HasSource as _, 19 src::HasSource as _,
20 type_ref::{Mutability, TypeRef}, 20 type_ref::{Mutability, TypeRef},
21 AdtId, AssocContainerId, AttrDefId, ConstId, DefWithBodyId, EnumId, FunctionId, GenericDefId, 21 AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, DefWithBodyId, EnumId,
22 HasModule, ImplId, LocalEnumVariantId, LocalFieldId, LocalModuleId, Lookup, ModuleId, StaticId, 22 FunctionId, GenericDefId, HasModule, ImplId, LocalEnumVariantId, LocalFieldId, LocalModuleId,
23 StructId, TraitId, TypeAliasId, TypeParamId, UnionId, 23 Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId,
24}; 24};
25use hir_def::{find_path::PrefixKind, item_scope::ItemInNs, visibility::Visibility};
25use hir_expand::{ 26use hir_expand::{
26 diagnostics::DiagnosticSink, 27 diagnostics::DiagnosticSink,
27 name::{name, AsName}, 28 name::{name, AsName},
@@ -275,11 +276,6 @@ impl ModuleDef {
275 } 276 }
276} 277}
277 278
278pub use hir_def::{
279 attr::Attrs, item_scope::ItemInNs, item_tree::ItemTreeNode, visibility::Visibility,
280 AssocItemId, AssocItemLoc,
281};
282
283impl Module { 279impl Module {
284 pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module { 280 pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module {
285 Module { id: ModuleId { krate: krate.id, local_id: crate_module_id } } 281 Module { id: ModuleId { krate: krate.id, local_id: crate_module_id } }
@@ -1398,7 +1394,7 @@ impl Type {
1398 }; 1394 };
1399 1395
1400 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; 1396 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1401 method_resolution::implements_trait( 1397 method_resolution::implements_trait_unique(
1402 &canonical_ty, 1398 &canonical_ty,
1403 db, 1399 db,
1404 self.ty.environment.clone(), 1400 self.ty.environment.clone(),
diff --git a/crates/hir/src/from_id.rs b/crates/hir/src/from_id.rs
index 033f53ac2..265ef6d1f 100644
--- a/crates/hir/src/from_id.rs
+++ b/crates/hir/src/from_id.rs
@@ -4,13 +4,13 @@
4//! are splitting the hir. 4//! are splitting the hir.
5 5
6use hir_def::{ 6use hir_def::{
7 expr::PatId, AdtId, AssocItemId, DefWithBodyId, EnumVariantId, FieldId, GenericDefId, 7 expr::PatId, item_scope::ItemInNs, AdtId, AssocItemId, DefWithBodyId, EnumVariantId, FieldId,
8 ModuleDefId, VariantId, 8 GenericDefId, ModuleDefId, VariantId,
9}; 9};
10 10
11use crate::{ 11use crate::{
12 code_model::ItemInNs, Adt, AssocItem, DefWithBody, EnumVariant, Field, GenericDef, Local, 12 Adt, AssocItem, DefWithBody, EnumVariant, Field, GenericDef, Local, MacroDef, ModuleDef,
13 MacroDef, ModuleDef, VariantDef, 13 VariantDef,
14}; 14};
15 15
16macro_rules! from_id { 16macro_rules! from_id {
diff --git a/crates/hir/src/has_source.rs b/crates/hir/src/has_source.rs
index 3bad2338a..c77494152 100644
--- a/crates/hir/src/has_source.rs
+++ b/crates/hir/src/has_source.rs
@@ -6,6 +6,7 @@ use hir_def::{
6 src::{HasChildSource, HasSource as _}, 6 src::{HasChildSource, HasSource as _},
7 Lookup, VariantId, 7 Lookup, VariantId,
8}; 8};
9use hir_expand::InFile;
9use syntax::ast; 10use syntax::ast;
10 11
11use crate::{ 12use crate::{
@@ -13,8 +14,6 @@ use crate::{
13 Module, Static, Struct, Trait, TypeAlias, TypeParam, Union, 14 Module, Static, Struct, Trait, TypeAlias, TypeParam, Union,
14}; 15};
15 16
16pub use hir_expand::InFile;
17
18pub trait HasSource { 17pub trait HasSource {
19 type Ast; 18 type Ast;
20 fn source(self, db: &dyn HirDatabase) -> InFile<Self::Ast>; 19 fn source(self, db: &dyn HirDatabase) -> InFile<Self::Ast>;
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index 4094a76cb..0d184379f 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -36,7 +36,7 @@ pub use crate::{
36 Access, Adt, AsAssocItem, AssocItem, AssocItemContainer, Callable, CallableKind, Const, 36 Access, Adt, AsAssocItem, AssocItem, AssocItemContainer, Callable, CallableKind, Const,
37 Crate, CrateDependency, DefWithBody, Enum, EnumVariant, Field, FieldSource, Function, 37 Crate, CrateDependency, DefWithBody, Enum, EnumVariant, Field, FieldSource, Function,
38 GenericDef, HasVisibility, ImplDef, Local, MacroDef, Module, ModuleDef, ScopeDef, Static, 38 GenericDef, HasVisibility, ImplDef, Local, MacroDef, Module, ModuleDef, ScopeDef, Static,
39 Struct, Trait, Type, TypeAlias, TypeParam, Union, VariantDef, Visibility, 39 Struct, Trait, Type, TypeAlias, TypeParam, Union, VariantDef,
40 }, 40 },
41 has_source::HasSource, 41 has_source::HasSource,
42 semantics::{original_range, PathResolution, Semantics, SemanticsScope}, 42 semantics::{original_range, PathResolution, Semantics, SemanticsScope},
@@ -53,6 +53,7 @@ pub use hir_def::{
53 nameres::ModuleSource, 53 nameres::ModuleSource,
54 path::{ModPath, PathKind}, 54 path::{ModPath, PathKind},
55 type_ref::{Mutability, TypeRef}, 55 type_ref::{Mutability, TypeRef},
56 visibility::Visibility,
56}; 57};
57pub use hir_expand::{ 58pub use hir_expand::{
58 name::known, name::AsName, name::Name, HirFileId, InFile, MacroCallId, MacroCallLoc, 59 name::known, name::AsName, name::Name, HirFileId, InFile, MacroCallId, MacroCallLoc,
diff --git a/crates/hir_def/src/body/diagnostics.rs b/crates/hir_def/src/body/diagnostics.rs
index cfa47d189..e57bdc133 100644
--- a/crates/hir_def/src/body/diagnostics.rs
+++ b/crates/hir_def/src/body/diagnostics.rs
@@ -5,12 +5,12 @@ use hir_expand::diagnostics::DiagnosticSink;
5use crate::diagnostics::InactiveCode; 5use crate::diagnostics::InactiveCode;
6 6
7#[derive(Debug, Eq, PartialEq)] 7#[derive(Debug, Eq, PartialEq)]
8pub enum BodyDiagnostic { 8pub(crate) enum BodyDiagnostic {
9 InactiveCode(InactiveCode), 9 InactiveCode(InactiveCode),
10} 10}
11 11
12impl BodyDiagnostic { 12impl BodyDiagnostic {
13 pub fn add_to(&self, sink: &mut DiagnosticSink<'_>) { 13 pub(crate) fn add_to(&self, sink: &mut DiagnosticSink<'_>) {
14 match self { 14 match self {
15 BodyDiagnostic::InactiveCode(diag) => { 15 BodyDiagnostic::InactiveCode(diag) => {
16 sink.push(diag.clone()); 16 sink.push(diag.clone());
diff --git a/crates/hir_def/src/body/lower.rs b/crates/hir_def/src/body/lower.rs
index ddc267b83..1deaa90f2 100644
--- a/crates/hir_def/src/body/lower.rs
+++ b/crates/hir_def/src/body/lower.rs
@@ -45,14 +45,14 @@ pub(crate) struct LowerCtx {
45} 45}
46 46
47impl LowerCtx { 47impl LowerCtx {
48 pub fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self { 48 pub(crate) fn new(db: &dyn DefDatabase, file_id: HirFileId) -> Self {
49 LowerCtx { hygiene: Hygiene::new(db.upcast(), file_id) } 49 LowerCtx { hygiene: Hygiene::new(db.upcast(), file_id) }
50 } 50 }
51 pub fn with_hygiene(hygiene: &Hygiene) -> Self { 51 pub(crate) fn with_hygiene(hygiene: &Hygiene) -> Self {
52 LowerCtx { hygiene: hygiene.clone() } 52 LowerCtx { hygiene: hygiene.clone() }
53 } 53 }
54 54
55 pub fn lower_path(&self, ast: ast::Path) -> Option<Path> { 55 pub(crate) fn lower_path(&self, ast: ast::Path) -> Option<Path> {
56 Path::from_src(ast, &self.hygiene) 56 Path::from_src(ast, &self.hygiene)
57 } 57 }
58} 58}
diff --git a/crates/hir_def/src/lib.rs b/crates/hir_def/src/lib.rs
index f24a1dd77..1b22d1eec 100644
--- a/crates/hir_def/src/lib.rs
+++ b/crates/hir_def/src/lib.rs
@@ -486,12 +486,12 @@ impl AsMacroCall for InFile<&ast::MacroCall> {
486/// Helper wrapper for `AstId` with `ModPath` 486/// Helper wrapper for `AstId` with `ModPath`
487#[derive(Clone, Debug, Eq, PartialEq)] 487#[derive(Clone, Debug, Eq, PartialEq)]
488struct AstIdWithPath<T: ast::AstNode> { 488struct AstIdWithPath<T: ast::AstNode> {
489 pub ast_id: AstId<T>, 489 ast_id: AstId<T>,
490 pub path: path::ModPath, 490 path: path::ModPath,
491} 491}
492 492
493impl<T: ast::AstNode> AstIdWithPath<T> { 493impl<T: ast::AstNode> AstIdWithPath<T> {
494 pub fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> { 494 fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> {
495 AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path } 495 AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
496 } 496 }
497} 497}
diff --git a/crates/hir_def/src/nameres/collector.rs b/crates/hir_def/src/nameres/collector.rs
index f30172d90..59b6644c3 100644
--- a/crates/hir_def/src/nameres/collector.rs
+++ b/crates/hir_def/src/nameres/collector.rs
@@ -122,13 +122,13 @@ enum ImportSource {
122 122
123#[derive(Clone, Debug, Eq, PartialEq)] 123#[derive(Clone, Debug, Eq, PartialEq)]
124struct Import { 124struct Import {
125 pub path: ModPath, 125 path: ModPath,
126 pub alias: Option<ImportAlias>, 126 alias: Option<ImportAlias>,
127 pub visibility: RawVisibility, 127 visibility: RawVisibility,
128 pub is_glob: bool, 128 is_glob: bool,
129 pub is_prelude: bool, 129 is_prelude: bool,
130 pub is_extern_crate: bool, 130 is_extern_crate: bool,
131 pub is_macro_use: bool, 131 is_macro_use: bool,
132 source: ImportSource, 132 source: ImportSource,
133} 133}
134 134
@@ -218,15 +218,18 @@ impl DefCollector<'_> {
218 let item_tree = self.db.item_tree(file_id.into()); 218 let item_tree = self.db.item_tree(file_id.into());
219 let module_id = self.def_map.root; 219 let module_id = self.def_map.root;
220 self.def_map.modules[module_id].origin = ModuleOrigin::CrateRoot { definition: file_id }; 220 self.def_map.modules[module_id].origin = ModuleOrigin::CrateRoot { definition: file_id };
221 ModCollector { 221 let mut root_collector = ModCollector {
222 def_collector: &mut *self, 222 def_collector: &mut *self,
223 macro_depth: 0, 223 macro_depth: 0,
224 module_id, 224 module_id,
225 file_id: file_id.into(), 225 file_id: file_id.into(),
226 item_tree: &item_tree, 226 item_tree: &item_tree,
227 mod_dir: ModDir::root(), 227 mod_dir: ModDir::root(),
228 };
229 if item_tree.top_level_attrs().cfg().map_or(true, |cfg| root_collector.is_cfg_enabled(&cfg))
230 {
231 root_collector.collect(item_tree.top_level_items());
228 } 232 }
229 .collect(item_tree.top_level_items());
230 233
231 // main name resolution fixed-point loop. 234 // main name resolution fixed-point loop.
232 let mut i = 0; 235 let mut i = 0;
diff --git a/crates/hir_def/src/nameres/tests.rs b/crates/hir_def/src/nameres/tests.rs
index 11d84f808..9c19bf572 100644
--- a/crates/hir_def/src/nameres/tests.rs
+++ b/crates/hir_def/src/nameres/tests.rs
@@ -691,3 +691,20 @@ mod tr {
691 "#]], 691 "#]],
692 ); 692 );
693} 693}
694
695#[test]
696fn cfg_the_entire_crate() {
697 check(
698 r#"
699//- /main.rs
700#![cfg(never)]
701
702pub struct S;
703pub enum E {}
704pub fn f() {}
705 "#,
706 expect![[r#"
707 crate
708 "#]],
709 );
710}
diff --git a/crates/hir_def/src/test_db.rs b/crates/hir_def/src/test_db.rs
index 2b36c824a..00fe711fe 100644
--- a/crates/hir_def/src/test_db.rs
+++ b/crates/hir_def/src/test_db.rs
@@ -25,7 +25,7 @@ use crate::{db::DefDatabase, ModuleDefId};
25 crate::db::DefDatabaseStorage 25 crate::db::DefDatabaseStorage
26)] 26)]
27#[derive(Default)] 27#[derive(Default)]
28pub struct TestDB { 28pub(crate) struct TestDB {
29 storage: salsa::Storage<TestDB>, 29 storage: salsa::Storage<TestDB>,
30 events: Mutex<Option<Vec<salsa::Event>>>, 30 events: Mutex<Option<Vec<salsa::Event>>>,
31} 31}
@@ -72,7 +72,7 @@ impl FileLoader for TestDB {
72} 72}
73 73
74impl TestDB { 74impl TestDB {
75 pub fn module_for_file(&self, file_id: FileId) -> crate::ModuleId { 75 pub(crate) fn module_for_file(&self, file_id: FileId) -> crate::ModuleId {
76 for &krate in self.relevant_crates(file_id).iter() { 76 for &krate in self.relevant_crates(file_id).iter() {
77 let crate_def_map = self.crate_def_map(krate); 77 let crate_def_map = self.crate_def_map(krate);
78 for (local_id, data) in crate_def_map.modules.iter() { 78 for (local_id, data) in crate_def_map.modules.iter() {
@@ -84,13 +84,13 @@ impl TestDB {
84 panic!("Can't find module for file") 84 panic!("Can't find module for file")
85 } 85 }
86 86
87 pub fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> { 87 pub(crate) fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> {
88 *self.events.lock().unwrap() = Some(Vec::new()); 88 *self.events.lock().unwrap() = Some(Vec::new());
89 f(); 89 f();
90 self.events.lock().unwrap().take().unwrap() 90 self.events.lock().unwrap().take().unwrap()
91 } 91 }
92 92
93 pub fn log_executed(&self, f: impl FnOnce()) -> Vec<String> { 93 pub(crate) fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
94 let events = self.log(f); 94 let events = self.log(f);
95 events 95 events
96 .into_iter() 96 .into_iter()
@@ -105,7 +105,7 @@ impl TestDB {
105 .collect() 105 .collect()
106 } 106 }
107 107
108 pub fn extract_annotations(&self) -> FxHashMap<FileId, Vec<(TextRange, String)>> { 108 pub(crate) fn extract_annotations(&self) -> FxHashMap<FileId, Vec<(TextRange, String)>> {
109 let mut files = Vec::new(); 109 let mut files = Vec::new();
110 let crate_graph = self.crate_graph(); 110 let crate_graph = self.crate_graph();
111 for krate in crate_graph.iter() { 111 for krate in crate_graph.iter() {
@@ -129,7 +129,7 @@ impl TestDB {
129 .collect() 129 .collect()
130 } 130 }
131 131
132 pub fn diagnostics<F: FnMut(&dyn Diagnostic)>(&self, mut cb: F) { 132 pub(crate) fn diagnostics<F: FnMut(&dyn Diagnostic)>(&self, mut cb: F) {
133 let crate_graph = self.crate_graph(); 133 let crate_graph = self.crate_graph();
134 for krate in crate_graph.iter() { 134 for krate in crate_graph.iter() {
135 let crate_def_map = self.crate_def_map(krate); 135 let crate_def_map = self.crate_def_map(krate);
@@ -148,7 +148,7 @@ impl TestDB {
148 } 148 }
149 } 149 }
150 150
151 pub fn check_diagnostics(&self) { 151 pub(crate) fn check_diagnostics(&self) {
152 let db: &TestDB = self; 152 let db: &TestDB = self;
153 let annotations = db.extract_annotations(); 153 let annotations = db.extract_annotations();
154 assert!(!annotations.is_empty()); 154 assert!(!annotations.is_empty());
diff --git a/crates/hir_expand/src/test_db.rs b/crates/hir_expand/src/test_db.rs
index 86a5d867e..fca501e1f 100644
--- a/crates/hir_expand/src/test_db.rs
+++ b/crates/hir_expand/src/test_db.rs
@@ -14,7 +14,7 @@ use rustc_hash::FxHashSet;
14 crate::db::AstDatabaseStorage 14 crate::db::AstDatabaseStorage
15)] 15)]
16#[derive(Default)] 16#[derive(Default)]
17pub struct TestDB { 17pub(crate) struct TestDB {
18 storage: salsa::Storage<TestDB>, 18 storage: salsa::Storage<TestDB>,
19 events: Mutex<Option<Vec<salsa::Event>>>, 19 events: Mutex<Option<Vec<salsa::Event>>>,
20} 20}
diff --git a/crates/hir_ty/Cargo.toml b/crates/hir_ty/Cargo.toml
index 367a1b98d..fdc65a5c3 100644
--- a/crates/hir_ty/Cargo.toml
+++ b/crates/hir_ty/Cargo.toml
@@ -17,9 +17,9 @@ ena = "0.14.0"
17log = "0.4.8" 17log = "0.4.8"
18rustc-hash = "1.1.0" 18rustc-hash = "1.1.0"
19scoped-tls = "1" 19scoped-tls = "1"
20chalk-solve = { version = "0.34", default-features = false } 20chalk-solve = { version = "0.37", default-features = false }
21chalk-ir = "0.34" 21chalk-ir = "0.37"
22chalk-recursive = "0.34" 22chalk-recursive = "0.37"
23 23
24stdx = { path = "../stdx", version = "0.0.0" } 24stdx = { path = "../stdx", version = "0.0.0" }
25hir_def = { path = "../hir_def", version = "0.0.0" } 25hir_def = { path = "../hir_def", version = "0.0.0" }
diff --git a/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs b/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs
index b0144a289..14e4d92f0 100644
--- a/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs
+++ b/crates/hir_ty/src/diagnostics/decl_check/case_conv.rs
@@ -6,7 +6,7 @@
6 6
7/// Converts an identifier to an UpperCamelCase form. 7/// Converts an identifier to an UpperCamelCase form.
8/// Returns `None` if the string is already is UpperCamelCase. 8/// Returns `None` if the string is already is UpperCamelCase.
9pub fn to_camel_case(ident: &str) -> Option<String> { 9pub(crate) fn to_camel_case(ident: &str) -> Option<String> {
10 if is_camel_case(ident) { 10 if is_camel_case(ident) {
11 return None; 11 return None;
12 } 12 }
@@ -59,7 +59,7 @@ pub fn to_camel_case(ident: &str) -> Option<String> {
59 59
60/// Converts an identifier to a lower_snake_case form. 60/// Converts an identifier to a lower_snake_case form.
61/// Returns `None` if the string is already in lower_snake_case. 61/// Returns `None` if the string is already in lower_snake_case.
62pub fn to_lower_snake_case(ident: &str) -> Option<String> { 62pub(crate) fn to_lower_snake_case(ident: &str) -> Option<String> {
63 if is_lower_snake_case(ident) { 63 if is_lower_snake_case(ident) {
64 return None; 64 return None;
65 } else if is_upper_snake_case(ident) { 65 } else if is_upper_snake_case(ident) {
@@ -71,7 +71,7 @@ pub fn to_lower_snake_case(ident: &str) -> Option<String> {
71 71
72/// Converts an identifier to an UPPER_SNAKE_CASE form. 72/// Converts an identifier to an UPPER_SNAKE_CASE form.
73/// Returns `None` if the string is already is UPPER_SNAKE_CASE. 73/// Returns `None` if the string is already is UPPER_SNAKE_CASE.
74pub fn to_upper_snake_case(ident: &str) -> Option<String> { 74pub(crate) fn to_upper_snake_case(ident: &str) -> Option<String> {
75 if is_upper_snake_case(ident) { 75 if is_upper_snake_case(ident) {
76 return None; 76 return None;
77 } else if is_lower_snake_case(ident) { 77 } else if is_lower_snake_case(ident) {
diff --git a/crates/hir_ty/src/diagnostics/expr.rs b/crates/hir_ty/src/diagnostics/expr.rs
index 278a4b947..434b19354 100644
--- a/crates/hir_ty/src/diagnostics/expr.rs
+++ b/crates/hir_ty/src/diagnostics/expr.rs
@@ -17,17 +17,10 @@ use crate::{
17 ApplicationTy, InferenceResult, Ty, TypeCtor, 17 ApplicationTy, InferenceResult, Ty, TypeCtor,
18}; 18};
19 19
20pub use hir_def::{ 20pub(crate) use hir_def::{
21 body::{ 21 body::{Body, BodySourceMap},
22 scope::{ExprScopes, ScopeEntry, ScopeId}, 22 expr::{Expr, ExprId, MatchArm, Pat, PatId},
23 Body, BodySourceMap, ExprPtr, ExprSource, PatPtr, PatSource, 23 LocalFieldId, VariantId,
24 },
25 expr::{
26 ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, LogicOp,
27 MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement, UnaryOp,
28 },
29 src::HasSource,
30 LocalFieldId, Lookup, VariantId,
31}; 24};
32 25
33pub(super) struct ExprValidator<'a, 'b: 'a> { 26pub(super) struct ExprValidator<'a, 'b: 'a> {
diff --git a/crates/hir_ty/src/diagnostics/unsafe_check.rs b/crates/hir_ty/src/diagnostics/unsafe_check.rs
index 2da9688ca..6dc862826 100644
--- a/crates/hir_ty/src/diagnostics/unsafe_check.rs
+++ b/crates/hir_ty/src/diagnostics/unsafe_check.rs
@@ -59,12 +59,12 @@ impl<'a, 'b> UnsafeValidator<'a, 'b> {
59 } 59 }
60} 60}
61 61
62pub struct UnsafeExpr { 62pub(crate) struct UnsafeExpr {
63 pub expr: ExprId, 63 pub(crate) expr: ExprId,
64 pub inside_unsafe_block: bool, 64 pub(crate) inside_unsafe_block: bool,
65} 65}
66 66
67pub fn unsafe_expressions( 67pub(crate) fn unsafe_expressions(
68 db: &dyn HirDatabase, 68 db: &dyn HirDatabase,
69 infer: &InferenceResult, 69 infer: &InferenceResult,
70 def: DefWithBodyId, 70 def: DefWithBodyId,
diff --git a/crates/hir_ty/src/display.rs b/crates/hir_ty/src/display.rs
index d2e151f25..14e8c0633 100644
--- a/crates/hir_ty/src/display.rs
+++ b/crates/hir_ty/src/display.rs
@@ -26,6 +26,20 @@ pub trait HirDisplay {
26 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>; 26 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>;
27 27
28 /// Returns a `Display`able type that is human-readable. 28 /// Returns a `Display`able type that is human-readable.
29 fn into_displayable<'a>(
30 &'a self,
31 db: &'a dyn HirDatabase,
32 max_size: Option<usize>,
33 omit_verbose_types: bool,
34 display_target: DisplayTarget,
35 ) -> HirDisplayWrapper<'a, Self>
36 where
37 Self: Sized,
38 {
39 HirDisplayWrapper { db, t: self, max_size, omit_verbose_types, display_target }
40 }
41
42 /// Returns a `Display`able type that is human-readable.
29 /// Use this for showing types to the user (e.g. diagnostics) 43 /// Use this for showing types to the user (e.g. diagnostics)
30 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self> 44 fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
31 where 45 where
@@ -82,6 +96,20 @@ pub trait HirDisplay {
82 }; 96 };
83 Ok(result) 97 Ok(result)
84 } 98 }
99
100 /// Returns a String representation of `self` for test purposes
101 fn display_test<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self>
102 where
103 Self: Sized,
104 {
105 HirDisplayWrapper {
106 db,
107 t: self,
108 max_size: None,
109 omit_verbose_types: false,
110 display_target: DisplayTarget::Test,
111 }
112 }
85} 113}
86 114
87impl<'a> HirFormatter<'a> { 115impl<'a> HirFormatter<'a> {
@@ -126,7 +154,7 @@ impl<'a> HirFormatter<'a> {
126} 154}
127 155
128#[derive(Clone, Copy)] 156#[derive(Clone, Copy)]
129enum DisplayTarget { 157pub enum DisplayTarget {
130 /// Display types for inlays, doc popups, autocompletion, etc... 158 /// Display types for inlays, doc popups, autocompletion, etc...
131 /// Showing `{unknown}` or not qualifying paths is fine here. 159 /// Showing `{unknown}` or not qualifying paths is fine here.
132 /// There's no reason for this to fail. 160 /// There's no reason for this to fail.
@@ -134,12 +162,17 @@ enum DisplayTarget {
134 /// Display types for inserting them in source files. 162 /// Display types for inserting them in source files.
135 /// The generated code should compile, so paths need to be qualified. 163 /// The generated code should compile, so paths need to be qualified.
136 SourceCode { module_id: ModuleId }, 164 SourceCode { module_id: ModuleId },
165 /// Only for test purpose to keep real types
166 Test,
137} 167}
138 168
139impl DisplayTarget { 169impl DisplayTarget {
140 fn is_source_code(&self) -> bool { 170 fn is_source_code(&self) -> bool {
141 matches!(self, Self::SourceCode {..}) 171 matches!(self, Self::SourceCode {..})
142 } 172 }
173 fn is_test(&self) -> bool {
174 matches!(self, Self::Test)
175 }
143} 176}
144 177
145#[derive(Debug)] 178#[derive(Debug)]
@@ -213,32 +246,32 @@ impl HirDisplay for ApplicationTy {
213 TypeCtor::Str => write!(f, "str")?, 246 TypeCtor::Str => write!(f, "str")?,
214 TypeCtor::Slice => { 247 TypeCtor::Slice => {
215 let t = self.parameters.as_single(); 248 let t = self.parameters.as_single();
216 write!(f, "[{}]", t.display(f.db))?; 249 write!(f, "[")?;
250 t.hir_fmt(f)?;
251 write!(f, "]")?;
217 } 252 }
218 TypeCtor::Array => { 253 TypeCtor::Array => {
219 let t = self.parameters.as_single(); 254 let t = self.parameters.as_single();
220 write!(f, "[{}; _]", t.display(f.db))?; 255 write!(f, "[")?;
256 t.hir_fmt(f)?;
257 write!(f, "; _]")?;
221 } 258 }
222 TypeCtor::RawPtr(m) => { 259 TypeCtor::RawPtr(m) => {
223 let t = self.parameters.as_single(); 260 let t = self.parameters.as_single();
224 let ty_display = t.display(f.db);
225 261
226 write!(f, "*{}", m.as_keyword_for_ptr())?; 262 write!(f, "*{}", m.as_keyword_for_ptr())?;
227 if matches!(t, Ty::Dyn(predicates) if predicates.len() > 1) { 263 if matches!(t, Ty::Dyn(predicates) if predicates.len() > 1) {
228 write!(f, "(")?; 264 write!(f, "(")?;
229 write!(f, "{}", ty_display)?; 265 t.hir_fmt(f)?;
230 write!(f, ")")?; 266 write!(f, ")")?;
231 } else { 267 } else {
232 write!(f, "{}", ty_display)?; 268 t.hir_fmt(f)?;
233 } 269 }
234 } 270 }
235 TypeCtor::Ref(m) => { 271 TypeCtor::Ref(m) => {
236 let t = self.parameters.as_single(); 272 let t = self.parameters.as_single();
237 let ty_display = if f.omit_verbose_types() { 273 let ty_display =
238 t.display_truncated(f.db, f.max_size) 274 t.into_displayable(f.db, f.max_size, f.omit_verbose_types, f.display_target);
239 } else {
240 t.display(f.db)
241 };
242 275
243 write!(f, "&{}", m.as_keyword_for_ref())?; 276 write!(f, "&{}", m.as_keyword_for_ref())?;
244 if matches!(t, Ty::Dyn(predicates) if predicates.len() > 1) { 277 if matches!(t, Ty::Dyn(predicates) if predicates.len() > 1) {
@@ -253,7 +286,9 @@ impl HirDisplay for ApplicationTy {
253 TypeCtor::Tuple { .. } => { 286 TypeCtor::Tuple { .. } => {
254 let ts = &self.parameters; 287 let ts = &self.parameters;
255 if ts.len() == 1 { 288 if ts.len() == 1 {
256 write!(f, "({},)", ts[0].display(f.db))?; 289 write!(f, "(")?;
290 ts[0].hir_fmt(f)?;
291 write!(f, ",)")?;
257 } else { 292 } else {
258 write!(f, "(")?; 293 write!(f, "(")?;
259 f.write_joined(&*ts.0, ", ")?; 294 f.write_joined(&*ts.0, ", ")?;
@@ -274,11 +309,12 @@ impl HirDisplay for ApplicationTy {
274 write!(f, ")")?; 309 write!(f, ")")?;
275 let ret = sig.ret(); 310 let ret = sig.ret();
276 if *ret != Ty::unit() { 311 if *ret != Ty::unit() {
277 let ret_display = if f.omit_verbose_types() { 312 let ret_display = ret.into_displayable(
278 ret.display_truncated(f.db, f.max_size) 313 f.db,
279 } else { 314 f.max_size,
280 ret.display(f.db) 315 f.omit_verbose_types,
281 }; 316 f.display_target,
317 );
282 write!(f, " -> {}", ret_display)?; 318 write!(f, " -> {}", ret_display)?;
283 } 319 }
284 } 320 }
@@ -310,17 +346,19 @@ impl HirDisplay for ApplicationTy {
310 write!(f, ")")?; 346 write!(f, ")")?;
311 let ret = sig.ret(); 347 let ret = sig.ret();
312 if *ret != Ty::unit() { 348 if *ret != Ty::unit() {
313 let ret_display = if f.omit_verbose_types() { 349 let ret_display = ret.into_displayable(
314 ret.display_truncated(f.db, f.max_size) 350 f.db,
315 } else { 351 f.max_size,
316 ret.display(f.db) 352 f.omit_verbose_types,
317 }; 353 f.display_target,
354 );
355
318 write!(f, " -> {}", ret_display)?; 356 write!(f, " -> {}", ret_display)?;
319 } 357 }
320 } 358 }
321 TypeCtor::Adt(def_id) => { 359 TypeCtor::Adt(def_id) => {
322 match f.display_target { 360 match f.display_target {
323 DisplayTarget::Diagnostics => { 361 DisplayTarget::Diagnostics | DisplayTarget::Test => {
324 let name = match def_id { 362 let name = match def_id {
325 AdtId::StructId(it) => f.db.struct_data(it).name.clone(), 363 AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
326 AdtId::UnionId(it) => f.db.union_data(it).name.clone(), 364 AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
@@ -389,12 +427,23 @@ impl HirDisplay for ApplicationTy {
389 _ => panic!("not an associated type"), 427 _ => panic!("not an associated type"),
390 }; 428 };
391 let trait_ = f.db.trait_data(trait_); 429 let trait_ = f.db.trait_data(trait_);
392 let type_alias = f.db.type_alias_data(type_alias); 430 let type_alias_data = f.db.type_alias_data(type_alias);
393 write!(f, "{}::{}", trait_.name, type_alias.name)?; 431
394 if self.parameters.len() > 0 { 432 // Use placeholder associated types when the target is test (https://rust-lang.github.io/chalk/book/clauses/type_equality.html#placeholder-associated-types)
395 write!(f, "<")?; 433 if f.display_target.is_test() {
396 f.write_joined(&*self.parameters.0, ", ")?; 434 write!(f, "{}::{}", trait_.name, type_alias_data.name)?;
397 write!(f, ">")?; 435 if self.parameters.len() > 0 {
436 write!(f, "<")?;
437 f.write_joined(&*self.parameters.0, ", ")?;
438 write!(f, ">")?;
439 }
440 } else {
441 let projection_ty = ProjectionTy {
442 associated_ty: type_alias,
443 parameters: self.parameters.clone(),
444 };
445
446 projection_ty.hir_fmt(f)?;
398 } 447 }
399 } 448 }
400 TypeCtor::ForeignType(type_alias) => { 449 TypeCtor::ForeignType(type_alias) => {
@@ -439,11 +488,12 @@ impl HirDisplay for ApplicationTy {
439 write!(f, "|")?; 488 write!(f, "|")?;
440 }; 489 };
441 490
442 let ret_display = if f.omit_verbose_types() { 491 let ret_display = sig.ret().into_displayable(
443 sig.ret().display_truncated(f.db, f.max_size) 492 f.db,
444 } else { 493 f.max_size,
445 sig.ret().display(f.db) 494 f.omit_verbose_types,
446 }; 495 f.display_target,
496 );
447 write!(f, " -> {}", ret_display)?; 497 write!(f, " -> {}", ret_display)?;
448 } else { 498 } else {
449 write!(f, "{{closure}}")?; 499 write!(f, "{{closure}}")?;
@@ -461,7 +511,13 @@ impl HirDisplay for ProjectionTy {
461 } 511 }
462 512
463 let trait_ = f.db.trait_data(self.trait_(f.db)); 513 let trait_ = f.db.trait_data(self.trait_(f.db));
464 write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_.name)?; 514 let first_parameter = self.parameters[0].into_displayable(
515 f.db,
516 f.max_size,
517 f.omit_verbose_types,
518 f.display_target,
519 );
520 write!(f, "<{} as {}", first_parameter, trait_.name)?;
465 if self.parameters.len() > 1 { 521 if self.parameters.len() > 1 {
466 write!(f, "<")?; 522 write!(f, "<")?;
467 f.write_joined(&self.parameters[1..], ", ")?; 523 f.write_joined(&self.parameters[1..], ", ")?;
@@ -640,10 +696,10 @@ impl HirDisplay for GenericPredicate {
640 projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?; 696 projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?;
641 write!( 697 write!(
642 f, 698 f,
643 ">::{} = {}", 699 ">::{} = ",
644 f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name, 700 f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name,
645 projection_pred.ty.display(f.db)
646 )?; 701 )?;
702 projection_pred.ty.hir_fmt(f)?;
647 } 703 }
648 GenericPredicate::Error => write!(f, "{{error}}")?, 704 GenericPredicate::Error => write!(f, "{{error}}")?,
649 } 705 }
@@ -654,13 +710,18 @@ impl HirDisplay for GenericPredicate {
654impl HirDisplay for Obligation { 710impl HirDisplay for Obligation {
655 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { 711 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
656 match self { 712 match self {
657 Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), 713 Obligation::Trait(tr) => {
658 Obligation::Projection(proj) => write!( 714 write!(f, "Implements(")?;
659 f, 715 tr.hir_fmt(f)?;
660 "Normalize({} => {})", 716 write!(f, ")")
661 proj.projection_ty.display(f.db), 717 }
662 proj.ty.display(f.db) 718 Obligation::Projection(proj) => {
663 ), 719 write!(f, "Normalize(")?;
720 proj.projection_ty.hir_fmt(f)?;
721 write!(f, " => ")?;
722 proj.ty.hir_fmt(f)?;
723 write!(f, ")")
724 }
664 } 725 }
665 } 726 }
666} 727}
diff --git a/crates/hir_ty/src/infer.rs b/crates/hir_ty/src/infer.rs
index 644ebd42d..a14d67c06 100644
--- a/crates/hir_ty/src/infer.rs
+++ b/crates/hir_ty/src/infer.rs
@@ -94,7 +94,7 @@ enum BindingMode {
94} 94}
95 95
96impl BindingMode { 96impl BindingMode {
97 pub fn convert(annotation: BindingAnnotation) -> BindingMode { 97 fn convert(annotation: BindingAnnotation) -> BindingMode {
98 match annotation { 98 match annotation {
99 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move, 99 BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
100 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared), 100 BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared),
@@ -214,9 +214,9 @@ struct InferenceContext<'a> {
214 214
215#[derive(Clone, Debug)] 215#[derive(Clone, Debug)]
216struct BreakableContext { 216struct BreakableContext {
217 pub may_break: bool, 217 may_break: bool,
218 pub break_ty: Ty, 218 break_ty: Ty,
219 pub label: Option<name::Name>, 219 label: Option<name::Name>,
220} 220}
221 221
222fn find_breakable<'c>( 222fn find_breakable<'c>(
diff --git a/crates/hir_ty/src/infer/expr.rs b/crates/hir_ty/src/infer/expr.rs
index 8ac4cf89a..605951b10 100644
--- a/crates/hir_ty/src/infer/expr.rs
+++ b/crates/hir_ty/src/infer/expr.rs
@@ -107,7 +107,7 @@ impl<'a> InferenceContext<'a> {
107 } 107 }
108 } 108 }
109 109
110 pub fn callable_sig(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> { 110 pub(crate) fn callable_sig(&mut self, ty: &Ty, num_args: usize) -> Option<(Vec<Ty>, Ty)> {
111 match ty.callable_sig(self.db) { 111 match ty.callable_sig(self.db) {
112 Some(sig) => Some((sig.params().to_vec(), sig.ret().clone())), 112 Some(sig) => Some((sig.params().to_vec(), sig.ret().clone())),
113 None => self.callable_sig_from_fn_trait(ty, num_args), 113 None => self.callable_sig_from_fn_trait(ty, num_args),
diff --git a/crates/hir_ty/src/infer/unify.rs b/crates/hir_ty/src/infer/unify.rs
index 2e895d911..76984242e 100644
--- a/crates/hir_ty/src/infer/unify.rs
+++ b/crates/hir_ty/src/infer/unify.rs
@@ -35,7 +35,7 @@ where
35 35
36#[derive(Debug)] 36#[derive(Debug)]
37pub(super) struct Canonicalized<T> { 37pub(super) struct Canonicalized<T> {
38 pub value: Canonical<T>, 38 pub(super) value: Canonical<T>,
39 free_vars: Vec<InferTy>, 39 free_vars: Vec<InferTy>,
40} 40}
41 41
@@ -127,7 +127,7 @@ where
127} 127}
128 128
129impl<T> Canonicalized<T> { 129impl<T> Canonicalized<T> {
130 pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { 130 pub(super) fn decanonicalize_ty(&self, mut ty: Ty) -> Ty {
131 ty.walk_mut_binders( 131 ty.walk_mut_binders(
132 &mut |ty, binders| { 132 &mut |ty, binders| {
133 if let &mut Ty::Bound(bound) = ty { 133 if let &mut Ty::Bound(bound) = ty {
@@ -141,7 +141,11 @@ impl<T> Canonicalized<T> {
141 ty 141 ty
142 } 142 }
143 143
144 pub fn apply_solution(&self, ctx: &mut InferenceContext<'_>, solution: Canonical<Substs>) { 144 pub(super) fn apply_solution(
145 &self,
146 ctx: &mut InferenceContext<'_>,
147 solution: Canonical<Substs>,
148 ) {
145 // the solution may contain new variables, which we need to convert to new inference vars 149 // the solution may contain new variables, which we need to convert to new inference vars
146 let new_vars = Substs( 150 let new_vars = Substs(
147 solution 151 solution
@@ -164,7 +168,7 @@ impl<T> Canonicalized<T> {
164 } 168 }
165} 169}
166 170
167pub fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substs> { 171pub(crate) fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substs> {
168 let mut table = InferenceTable::new(); 172 let mut table = InferenceTable::new();
169 let vars = Substs( 173 let vars = Substs(
170 tys.kinds 174 tys.kinds
@@ -199,41 +203,46 @@ pub(crate) struct InferenceTable {
199} 203}
200 204
201impl InferenceTable { 205impl InferenceTable {
202 pub fn new() -> Self { 206 pub(crate) fn new() -> Self {
203 InferenceTable { var_unification_table: InPlaceUnificationTable::new() } 207 InferenceTable { var_unification_table: InPlaceUnificationTable::new() }
204 } 208 }
205 209
206 pub fn new_type_var(&mut self) -> Ty { 210 pub(crate) fn new_type_var(&mut self) -> Ty {
207 Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) 211 Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown)))
208 } 212 }
209 213
210 pub fn new_integer_var(&mut self) -> Ty { 214 pub(crate) fn new_integer_var(&mut self) -> Ty {
211 Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) 215 Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown)))
212 } 216 }
213 217
214 pub fn new_float_var(&mut self) -> Ty { 218 pub(crate) fn new_float_var(&mut self) -> Ty {
215 Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) 219 Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown)))
216 } 220 }
217 221
218 pub fn new_maybe_never_type_var(&mut self) -> Ty { 222 pub(crate) fn new_maybe_never_type_var(&mut self) -> Ty {
219 Ty::Infer(InferTy::MaybeNeverTypeVar( 223 Ty::Infer(InferTy::MaybeNeverTypeVar(
220 self.var_unification_table.new_key(TypeVarValue::Unknown), 224 self.var_unification_table.new_key(TypeVarValue::Unknown),
221 )) 225 ))
222 } 226 }
223 227
224 pub fn resolve_ty_completely(&mut self, ty: Ty) -> Ty { 228 pub(crate) fn resolve_ty_completely(&mut self, ty: Ty) -> Ty {
225 self.resolve_ty_completely_inner(&mut Vec::new(), ty) 229 self.resolve_ty_completely_inner(&mut Vec::new(), ty)
226 } 230 }
227 231
228 pub fn resolve_ty_as_possible(&mut self, ty: Ty) -> Ty { 232 pub(crate) fn resolve_ty_as_possible(&mut self, ty: Ty) -> Ty {
229 self.resolve_ty_as_possible_inner(&mut Vec::new(), ty) 233 self.resolve_ty_as_possible_inner(&mut Vec::new(), ty)
230 } 234 }
231 235
232 pub fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { 236 pub(crate) fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool {
233 self.unify_inner(ty1, ty2, 0) 237 self.unify_inner(ty1, ty2, 0)
234 } 238 }
235 239
236 pub fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool { 240 pub(crate) fn unify_substs(
241 &mut self,
242 substs1: &Substs,
243 substs2: &Substs,
244 depth: usize,
245 ) -> bool {
237 substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth)) 246 substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth))
238 } 247 }
239 248
@@ -331,7 +340,7 @@ impl InferenceTable {
331 340
332 /// If `ty` is a type variable with known type, returns that type; 341 /// If `ty` is a type variable with known type, returns that type;
333 /// otherwise, return ty. 342 /// otherwise, return ty.
334 pub fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> { 343 pub(crate) fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> {
335 let mut ty = Cow::Borrowed(ty); 344 let mut ty = Cow::Borrowed(ty);
336 // The type variable could resolve to a int/float variable. Hence try 345 // The type variable could resolve to a int/float variable. Hence try
337 // resolving up to three times; each type of variable shouldn't occur 346 // resolving up to three times; each type of variable shouldn't occur
diff --git a/crates/hir_ty/src/lib.rs b/crates/hir_ty/src/lib.rs
index 768d95eff..5a8c97198 100644
--- a/crates/hir_ty/src/lib.rs
+++ b/crates/hir_ty/src/lib.rs
@@ -1,6 +1,5 @@
1//! The type system. We currently use this to infer types for completion, hover 1//! The type system. We currently use this to infer types for completion, hover
2//! information and various assists. 2//! information and various assists.
3
4#[allow(unused)] 3#[allow(unused)]
5macro_rules! eprintln { 4macro_rules! eprintln {
6 ($($tt:tt)*) => { stdx::eprintln!($($tt)*) }; 5 ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
@@ -1115,5 +1114,5 @@ pub struct ReturnTypeImplTraits {
1115 1114
1116#[derive(Clone, PartialEq, Eq, Debug, Hash)] 1115#[derive(Clone, PartialEq, Eq, Debug, Hash)]
1117pub(crate) struct ReturnTypeImplTrait { 1116pub(crate) struct ReturnTypeImplTrait {
1118 pub bounds: Binders<Vec<GenericPredicate>>, 1117 pub(crate) bounds: Binders<Vec<GenericPredicate>>,
1119} 1118}
diff --git a/crates/hir_ty/src/method_resolution.rs b/crates/hir_ty/src/method_resolution.rs
index 8961df404..5a6f0c67f 100644
--- a/crates/hir_ty/src/method_resolution.rs
+++ b/crates/hir_ty/src/method_resolution.rs
@@ -740,6 +740,19 @@ pub fn implements_trait(
740 solution.is_some() 740 solution.is_some()
741} 741}
742 742
743pub fn implements_trait_unique(
744 ty: &Canonical<Ty>,
745 db: &dyn HirDatabase,
746 env: Arc<TraitEnvironment>,
747 krate: CrateId,
748 trait_: TraitId,
749) -> bool {
750 let goal = generic_implements_goal(db, env, trait_, ty.clone());
751 let solution = db.trait_solve(krate, goal);
752
753 matches!(solution, Some(crate::traits::Solution::Unique(_)))
754}
755
743/// This creates Substs for a trait with the given Self type and type variables 756/// This creates Substs for a trait with the given Self type and type variables
744/// for all other parameters, to query Chalk with it. 757/// for all other parameters, to query Chalk with it.
745fn generic_implements_goal( 758fn generic_implements_goal(
diff --git a/crates/hir_ty/src/test_db.rs b/crates/hir_ty/src/test_db.rs
index 15b8435e9..22254b765 100644
--- a/crates/hir_ty/src/test_db.rs
+++ b/crates/hir_ty/src/test_db.rs
@@ -21,7 +21,7 @@ use test_utils::extract_annotations;
21 crate::db::HirDatabaseStorage 21 crate::db::HirDatabaseStorage
22)] 22)]
23#[derive(Default)] 23#[derive(Default)]
24pub struct TestDB { 24pub(crate) struct TestDB {
25 storage: salsa::Storage<TestDB>, 25 storage: salsa::Storage<TestDB>,
26 events: Mutex<Option<Vec<salsa::Event>>>, 26 events: Mutex<Option<Vec<salsa::Event>>>,
27} 27}
@@ -113,13 +113,13 @@ impl TestDB {
113} 113}
114 114
115impl TestDB { 115impl TestDB {
116 pub fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> { 116 pub(crate) fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> {
117 *self.events.lock().unwrap() = Some(Vec::new()); 117 *self.events.lock().unwrap() = Some(Vec::new());
118 f(); 118 f();
119 self.events.lock().unwrap().take().unwrap() 119 self.events.lock().unwrap().take().unwrap()
120 } 120 }
121 121
122 pub fn log_executed(&self, f: impl FnOnce()) -> Vec<String> { 122 pub(crate) fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
123 let events = self.log(f); 123 let events = self.log(f);
124 events 124 events
125 .into_iter() 125 .into_iter()
diff --git a/crates/hir_ty/src/tests.rs b/crates/hir_ty/src/tests.rs
index 0445efc9e..104ef334c 100644
--- a/crates/hir_ty/src/tests.rs
+++ b/crates/hir_ty/src/tests.rs
@@ -74,7 +74,7 @@ fn check_types_impl(ra_fixture: &str, display_source: bool) {
74 let module = db.module_for_file(file_id); 74 let module = db.module_for_file(file_id);
75 ty.display_source_code(&db, module).unwrap() 75 ty.display_source_code(&db, module).unwrap()
76 } else { 76 } else {
77 ty.display(&db).to_string() 77 ty.display_test(&db).to_string()
78 }; 78 };
79 assert_eq!(expected, actual); 79 assert_eq!(expected, actual);
80 checked_one = true; 80 checked_one = true;
@@ -163,7 +163,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
163 macro_prefix, 163 macro_prefix,
164 range, 164 range,
165 ellipsize(text, 15), 165 ellipsize(text, 15),
166 ty.display(&db) 166 ty.display_test(&db)
167 ); 167 );
168 } 168 }
169 if include_mismatches { 169 if include_mismatches {
@@ -179,8 +179,8 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
179 "{}{:?}: expected {}, got {}\n", 179 "{}{:?}: expected {}, got {}\n",
180 macro_prefix, 180 macro_prefix,
181 range, 181 range,
182 mismatch.expected.display(&db), 182 mismatch.expected.display_test(&db),
183 mismatch.actual.display(&db), 183 mismatch.actual.display_test(&db),
184 ); 184 );
185 } 185 }
186 } 186 }
diff --git a/crates/hir_ty/src/traits/chalk.rs b/crates/hir_ty/src/traits/chalk.rs
index cbe5cd7dd..55e2c3a3e 100644
--- a/crates/hir_ty/src/traits/chalk.rs
+++ b/crates/hir_ty/src/traits/chalk.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
3 3
4use log::debug; 4use log::debug;
5 5
6use chalk_ir::{fold::shift::Shift, CanonicalVarKinds, GenericArg, TypeName}; 6use chalk_ir::{fold::shift::Shift, CanonicalVarKinds, GenericArg};
7use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait}; 7use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait};
8 8
9use base_db::{salsa::InternKey, CrateId}; 9use base_db::{salsa::InternKey, CrateId};
@@ -27,7 +27,7 @@ use mapping::{
27 TypeAliasAsValue, 27 TypeAliasAsValue,
28}; 28};
29 29
30pub use self::interner::*; 30pub(crate) use self::interner::*;
31 31
32pub(super) mod tls; 32pub(super) mod tls;
33mod interner; 33mod interner;
@@ -81,7 +81,10 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
81 81
82 let ty: Ty = from_chalk(self.db, parameters[0].assert_ty_ref(&Interner).clone()); 82 let ty: Ty = from_chalk(self.db, parameters[0].assert_ty_ref(&Interner).clone());
83 83
84 fn binder_kind(ty: &Ty, binders: &CanonicalVarKinds<Interner>) -> Option<chalk_ir::TyKind> { 84 fn binder_kind(
85 ty: &Ty,
86 binders: &CanonicalVarKinds<Interner>,
87 ) -> Option<chalk_ir::TyVariableKind> {
85 if let Ty::Bound(bv) = ty { 88 if let Ty::Bound(bv) = ty {
86 let binders = binders.as_slice(&Interner); 89 let binders = binders.as_slice(&Interner);
87 if bv.debruijn == DebruijnIndex::INNERMOST { 90 if bv.debruijn == DebruijnIndex::INNERMOST {
@@ -95,8 +98,8 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
95 98
96 let self_ty_fp = TyFingerprint::for_impl(&ty); 99 let self_ty_fp = TyFingerprint::for_impl(&ty);
97 let fps: &[TyFingerprint] = match binder_kind(&ty, binders) { 100 let fps: &[TyFingerprint] = match binder_kind(&ty, binders) {
98 Some(chalk_ir::TyKind::Integer) => &ALL_INT_FPS, 101 Some(chalk_ir::TyVariableKind::Integer) => &ALL_INT_FPS,
99 Some(chalk_ir::TyKind::Float) => &ALL_FLOAT_FPS, 102 Some(chalk_ir::TyVariableKind::Float) => &ALL_FLOAT_FPS,
100 _ => self_ty_fp.as_ref().map(std::slice::from_ref).unwrap_or(&[]), 103 _ => self_ty_fp.as_ref().map(std::slice::from_ref).unwrap_or(&[]),
101 }; 104 };
102 105
@@ -129,12 +132,8 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
129 debug!("impls_for_trait returned {} impls", result.len()); 132 debug!("impls_for_trait returned {} impls", result.len());
130 result 133 result
131 } 134 }
132 fn impl_provided_for( 135 fn impl_provided_for(&self, auto_trait_id: TraitId, kind: &chalk_ir::TyKind<Interner>) -> bool {
133 &self, 136 debug!("impl_provided_for {:?}, {:?}", auto_trait_id, kind);
134 auto_trait_id: TraitId,
135 application_ty: &chalk_ir::ApplicationTy<Interner>,
136 ) -> bool {
137 debug!("impl_provided_for {:?}, {:?}", auto_trait_id, application_ty);
138 false // FIXME 137 false // FIXME
139 } 138 }
140 fn associated_ty_value(&self, id: AssociatedTyValueId) -> Arc<AssociatedTyValue> { 139 fn associated_ty_value(&self, id: AssociatedTyValueId) -> Arc<AssociatedTyValue> {
@@ -466,7 +465,7 @@ pub(crate) fn struct_datum_query(
466 struct_id: AdtId, 465 struct_id: AdtId,
467) -> Arc<StructDatum> { 466) -> Arc<StructDatum> {
468 debug!("struct_datum {:?}", struct_id); 467 debug!("struct_datum {:?}", struct_id);
469 let type_ctor: TypeCtor = from_chalk(db, TypeName::Adt(struct_id)); 468 let type_ctor = TypeCtor::Adt(from_chalk(db, struct_id));
470 debug!("struct {:?} = {:?}", struct_id, type_ctor); 469 debug!("struct {:?} = {:?}", struct_id, type_ctor);
471 let num_params = type_ctor.num_ty_params(db); 470 let num_params = type_ctor.num_ty_params(db);
472 let upstream = type_ctor.krate(db) != Some(krate); 471 let upstream = type_ctor.krate(db) != Some(krate);
diff --git a/crates/hir_ty/src/traits/chalk/interner.rs b/crates/hir_ty/src/traits/chalk/interner.rs
index f9304b7d0..39569e690 100644
--- a/crates/hir_ty/src/traits/chalk/interner.rs
+++ b/crates/hir_ty/src/traits/chalk/interner.rs
@@ -10,21 +10,21 @@ use std::{fmt, sync::Arc};
10#[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] 10#[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
11pub struct Interner; 11pub struct Interner;
12 12
13pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>; 13pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
14pub type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>; 14pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>;
15pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>; 15pub(crate) type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
16pub type TraitId = chalk_ir::TraitId<Interner>; 16pub(crate) type TraitId = chalk_ir::TraitId<Interner>;
17pub type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>; 17pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>;
18pub type AdtId = chalk_ir::AdtId<Interner>; 18pub(crate) type AdtId = chalk_ir::AdtId<Interner>;
19pub type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>; 19pub(crate) type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>;
20pub type ImplId = chalk_ir::ImplId<Interner>; 20pub(crate) type ImplId = chalk_ir::ImplId<Interner>;
21pub type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>; 21pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>;
22pub type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>; 22pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>;
23pub type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>; 23pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>;
24pub type FnDefId = chalk_ir::FnDefId<Interner>; 24pub(crate) type FnDefId = chalk_ir::FnDefId<Interner>;
25pub type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>; 25pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>;
26pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>; 26pub(crate) type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
27pub type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>; 27pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>;
28 28
29impl chalk_ir::interner::Interner for Interner { 29impl chalk_ir::interner::Interner for Interner {
30 type InternedType = Arc<chalk_ir::TyData<Self>>; 30 type InternedType = Arc<chalk_ir::TyData<Self>>;
@@ -122,13 +122,6 @@ impl chalk_ir::interner::Interner for Interner {
122 tls::with_current_program(|prog| Some(prog?.debug_program_clause_implication(pci, fmt))) 122 tls::with_current_program(|prog| Some(prog?.debug_program_clause_implication(pci, fmt)))
123 } 123 }
124 124
125 fn debug_application_ty(
126 application_ty: &chalk_ir::ApplicationTy<Interner>,
127 fmt: &mut fmt::Formatter<'_>,
128 ) -> Option<fmt::Result> {
129 tls::with_current_program(|prog| Some(prog?.debug_application_ty(application_ty, fmt)))
130 }
131
132 fn debug_substitution( 125 fn debug_substitution(
133 substitution: &chalk_ir::Substitution<Interner>, 126 substitution: &chalk_ir::Substitution<Interner>,
134 fmt: &mut fmt::Formatter<'_>, 127 fmt: &mut fmt::Formatter<'_>,
diff --git a/crates/hir_ty/src/traits/chalk/mapping.rs b/crates/hir_ty/src/traits/chalk/mapping.rs
index dd7affcec..86cbc4c7e 100644
--- a/crates/hir_ty/src/traits/chalk/mapping.rs
+++ b/crates/hir_ty/src/traits/chalk/mapping.rs
@@ -5,7 +5,7 @@
5 5
6use chalk_ir::{ 6use chalk_ir::{
7 cast::Cast, fold::shift::Shift, interner::HasInterner, LifetimeData, PlaceholderIndex, Scalar, 7 cast::Cast, fold::shift::Shift, interner::HasInterner, LifetimeData, PlaceholderIndex, Scalar,
8 TypeName, UniverseIndex, 8 UniverseIndex,
9}; 9};
10use chalk_solve::rust_ir; 10use chalk_solve::rust_ir;
11 11
@@ -32,7 +32,7 @@ impl ToChalk for Ty {
32 TypeCtor::Array => array_to_chalk(db, apply_ty.parameters), 32 TypeCtor::Array => array_to_chalk(db, apply_ty.parameters),
33 TypeCtor::FnPtr { num_args: _, is_varargs } => { 33 TypeCtor::FnPtr { num_args: _, is_varargs } => {
34 let substitution = apply_ty.parameters.to_chalk(db).shifted_in(&Interner); 34 let substitution = apply_ty.parameters.to_chalk(db).shifted_in(&Interner);
35 chalk_ir::TyData::Function(chalk_ir::FnPointer { 35 chalk_ir::TyKind::Function(chalk_ir::FnPointer {
36 num_binders: 0, 36 num_binders: 0,
37 sig: chalk_ir::FnSig { 37 sig: chalk_ir::FnSig {
38 abi: (), 38 abi: (),
@@ -43,10 +43,68 @@ impl ToChalk for Ty {
43 }) 43 })
44 .intern(&Interner) 44 .intern(&Interner)
45 } 45 }
46 _ => { 46 TypeCtor::AssociatedType(type_alias) => {
47 let name = apply_ty.ctor.to_chalk(db); 47 let assoc_type = TypeAliasAsAssocType(type_alias);
48 let assoc_type_id = assoc_type.to_chalk(db);
48 let substitution = apply_ty.parameters.to_chalk(db); 49 let substitution = apply_ty.parameters.to_chalk(db);
49 chalk_ir::ApplicationTy { name, substitution }.cast(&Interner).intern(&Interner) 50 chalk_ir::TyKind::AssociatedType(assoc_type_id, substitution).intern(&Interner)
51 }
52
53 TypeCtor::OpaqueType(impl_trait_id) => {
54 let id = impl_trait_id.to_chalk(db);
55 let substitution = apply_ty.parameters.to_chalk(db);
56 chalk_ir::TyKind::OpaqueType(id, substitution).intern(&Interner)
57 }
58
59 TypeCtor::ForeignType(type_alias) => {
60 let foreign_type = TypeAliasAsForeignType(type_alias);
61 let foreign_type_id = foreign_type.to_chalk(db);
62 chalk_ir::TyKind::Foreign(foreign_type_id).intern(&Interner)
63 }
64
65 TypeCtor::Bool => chalk_ir::TyKind::Scalar(Scalar::Bool).intern(&Interner),
66 TypeCtor::Char => chalk_ir::TyKind::Scalar(Scalar::Char).intern(&Interner),
67 TypeCtor::Int(int_ty) => {
68 chalk_ir::TyKind::Scalar(int_ty_to_chalk(int_ty)).intern(&Interner)
69 }
70 TypeCtor::Float(FloatTy { bitness: FloatBitness::X32 }) => {
71 chalk_ir::TyKind::Scalar(Scalar::Float(chalk_ir::FloatTy::F32))
72 .intern(&Interner)
73 }
74 TypeCtor::Float(FloatTy { bitness: FloatBitness::X64 }) => {
75 chalk_ir::TyKind::Scalar(Scalar::Float(chalk_ir::FloatTy::F64))
76 .intern(&Interner)
77 }
78
79 TypeCtor::Tuple { cardinality } => {
80 let substitution = apply_ty.parameters.to_chalk(db);
81 chalk_ir::TyKind::Tuple(cardinality.into(), substitution).intern(&Interner)
82 }
83 TypeCtor::RawPtr(mutability) => {
84 let ty = apply_ty.parameters[0].clone().to_chalk(db);
85 chalk_ir::TyKind::Raw(mutability.to_chalk(db), ty).intern(&Interner)
86 }
87 TypeCtor::Slice => {
88 chalk_ir::TyKind::Slice(apply_ty.parameters[0].clone().to_chalk(db))
89 .intern(&Interner)
90 }
91 TypeCtor::Str => chalk_ir::TyKind::Str.intern(&Interner),
92 TypeCtor::FnDef(callable_def) => {
93 let id = callable_def.to_chalk(db);
94 let substitution = apply_ty.parameters.to_chalk(db);
95 chalk_ir::TyKind::FnDef(id, substitution).intern(&Interner)
96 }
97 TypeCtor::Never => chalk_ir::TyKind::Never.intern(&Interner),
98
99 TypeCtor::Closure { def, expr } => {
100 let closure_id = db.intern_closure((def, expr));
101 let substitution = apply_ty.parameters.to_chalk(db);
102 chalk_ir::TyKind::Closure(closure_id.into(), substitution).intern(&Interner)
103 }
104
105 TypeCtor::Adt(adt_id) => {
106 let substitution = apply_ty.parameters.to_chalk(db);
107 chalk_ir::TyKind::Adt(chalk_ir::AdtId(adt_id), substitution).intern(&Interner)
50 } 108 }
51 }, 109 },
52 Ty::Projection(proj_ty) => { 110 Ty::Projection(proj_ty) => {
@@ -67,7 +125,7 @@ impl ToChalk for Ty {
67 } 125 }
68 .to_ty::<Interner>(&Interner) 126 .to_ty::<Interner>(&Interner)
69 } 127 }
70 Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx).intern(&Interner), 128 Ty::Bound(idx) => chalk_ir::TyKind::BoundVar(idx).intern(&Interner),
71 Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), 129 Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"),
72 Ty::Dyn(predicates) => { 130 Ty::Dyn(predicates) => {
73 let where_clauses = chalk_ir::QuantifiedWhereClauses::from_iter( 131 let where_clauses = chalk_ir::QuantifiedWhereClauses::from_iter(
@@ -78,55 +136,45 @@ impl ToChalk for Ty {
78 bounds: make_binders(where_clauses, 1), 136 bounds: make_binders(where_clauses, 1),
79 lifetime: LifetimeData::Static.intern(&Interner), 137 lifetime: LifetimeData::Static.intern(&Interner),
80 }; 138 };
81 chalk_ir::TyData::Dyn(bounded_ty).intern(&Interner) 139 chalk_ir::TyKind::Dyn(bounded_ty).intern(&Interner)
82 } 140 }
83 Ty::Opaque(opaque_ty) => { 141 Ty::Opaque(opaque_ty) => {
84 let opaque_ty_id = opaque_ty.opaque_ty_id.to_chalk(db); 142 let opaque_ty_id = opaque_ty.opaque_ty_id.to_chalk(db);
85 let substitution = opaque_ty.parameters.to_chalk(db); 143 let substitution = opaque_ty.parameters.to_chalk(db);
86 chalk_ir::TyData::Alias(chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy { 144 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy {
87 opaque_ty_id, 145 opaque_ty_id,
88 substitution, 146 substitution,
89 })) 147 }))
90 .intern(&Interner) 148 .intern(&Interner)
91 } 149 }
92 Ty::Unknown => { 150 Ty::Unknown => chalk_ir::TyKind::Error.intern(&Interner),
93 let substitution = chalk_ir::Substitution::empty(&Interner);
94 let name = TypeName::Error;
95 chalk_ir::ApplicationTy { name, substitution }.cast(&Interner).intern(&Interner)
96 }
97 } 151 }
98 } 152 }
99 fn from_chalk(db: &dyn HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self { 153 fn from_chalk(db: &dyn HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self {
100 match chalk.data(&Interner).clone() { 154 match chalk.data(&Interner).kind.clone() {
101 chalk_ir::TyData::Apply(apply_ty) => match apply_ty.name { 155 chalk_ir::TyKind::Error => Ty::Unknown,
102 TypeName::Error => Ty::Unknown, 156 chalk_ir::TyKind::Array(ty, _size) => {
103 TypeName::Ref(m) => ref_from_chalk(db, m, apply_ty.substitution), 157 Ty::apply(TypeCtor::Array, Substs::single(from_chalk(db, ty)))
104 TypeName::Array => array_from_chalk(db, apply_ty.substitution), 158 }
105 _ => { 159 chalk_ir::TyKind::Placeholder(idx) => {
106 let ctor = from_chalk(db, apply_ty.name);
107 let parameters = from_chalk(db, apply_ty.substitution);
108 Ty::Apply(ApplicationTy { ctor, parameters })
109 }
110 },
111 chalk_ir::TyData::Placeholder(idx) => {
112 assert_eq!(idx.ui, UniverseIndex::ROOT); 160 assert_eq!(idx.ui, UniverseIndex::ROOT);
113 let interned_id = crate::db::GlobalTypeParamId::from_intern_id( 161 let interned_id = crate::db::GlobalTypeParamId::from_intern_id(
114 crate::salsa::InternId::from(idx.idx), 162 crate::salsa::InternId::from(idx.idx),
115 ); 163 );
116 Ty::Placeholder(db.lookup_intern_type_param_id(interned_id)) 164 Ty::Placeholder(db.lookup_intern_type_param_id(interned_id))
117 } 165 }
118 chalk_ir::TyData::Alias(chalk_ir::AliasTy::Projection(proj)) => { 166 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Projection(proj)) => {
119 let associated_ty = 167 let associated_ty =
120 from_chalk::<TypeAliasAsAssocType, _>(db, proj.associated_ty_id).0; 168 from_chalk::<TypeAliasAsAssocType, _>(db, proj.associated_ty_id).0;
121 let parameters = from_chalk(db, proj.substitution); 169 let parameters = from_chalk(db, proj.substitution);
122 Ty::Projection(ProjectionTy { associated_ty, parameters }) 170 Ty::Projection(ProjectionTy { associated_ty, parameters })
123 } 171 }
124 chalk_ir::TyData::Alias(chalk_ir::AliasTy::Opaque(opaque_ty)) => { 172 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(opaque_ty)) => {
125 let impl_trait_id = from_chalk(db, opaque_ty.opaque_ty_id); 173 let impl_trait_id = from_chalk(db, opaque_ty.opaque_ty_id);
126 let parameters = from_chalk(db, opaque_ty.substitution); 174 let parameters = from_chalk(db, opaque_ty.substitution);
127 Ty::Opaque(OpaqueTy { opaque_ty_id: impl_trait_id, parameters }) 175 Ty::Opaque(OpaqueTy { opaque_ty_id: impl_trait_id, parameters })
128 } 176 }
129 chalk_ir::TyData::Function(chalk_ir::FnPointer { 177 chalk_ir::TyKind::Function(chalk_ir::FnPointer {
130 num_binders, 178 num_binders,
131 sig: chalk_ir::FnSig { variadic, .. }, 179 sig: chalk_ir::FnSig { variadic, .. },
132 substitution, 180 substitution,
@@ -145,9 +193,9 @@ impl ToChalk for Ty {
145 parameters, 193 parameters,
146 }) 194 })
147 } 195 }
148 chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx), 196 chalk_ir::TyKind::BoundVar(idx) => Ty::Bound(idx),
149 chalk_ir::TyData::InferenceVar(_iv, _kind) => Ty::Unknown, 197 chalk_ir::TyKind::InferenceVar(_iv, _kind) => Ty::Unknown,
150 chalk_ir::TyData::Dyn(where_clauses) => { 198 chalk_ir::TyKind::Dyn(where_clauses) => {
151 assert_eq!(where_clauses.bounds.binders.len(&Interner), 1); 199 assert_eq!(where_clauses.bounds.binders.len(&Interner), 1);
152 let predicates = where_clauses 200 let predicates = where_clauses
153 .bounds 201 .bounds
@@ -157,10 +205,76 @@ impl ToChalk for Ty {
157 .collect(); 205 .collect();
158 Ty::Dyn(predicates) 206 Ty::Dyn(predicates)
159 } 207 }
208
209 chalk_ir::TyKind::Adt(struct_id, subst) => {
210 apply_ty_from_chalk(db, TypeCtor::Adt(struct_id.0), subst)
211 }
212 chalk_ir::TyKind::AssociatedType(type_id, subst) => apply_ty_from_chalk(
213 db,
214 TypeCtor::AssociatedType(from_chalk::<TypeAliasAsAssocType, _>(db, type_id).0),
215 subst,
216 ),
217 chalk_ir::TyKind::OpaqueType(opaque_type_id, subst) => {
218 apply_ty_from_chalk(db, TypeCtor::OpaqueType(from_chalk(db, opaque_type_id)), subst)
219 }
220
221 chalk_ir::TyKind::Scalar(Scalar::Bool) => Ty::simple(TypeCtor::Bool),
222 chalk_ir::TyKind::Scalar(Scalar::Char) => Ty::simple(TypeCtor::Char),
223 chalk_ir::TyKind::Scalar(Scalar::Int(int_ty)) => Ty::simple(TypeCtor::Int(IntTy {
224 signedness: Signedness::Signed,
225 bitness: bitness_from_chalk_int(int_ty),
226 })),
227 chalk_ir::TyKind::Scalar(Scalar::Uint(uint_ty)) => Ty::simple(TypeCtor::Int(IntTy {
228 signedness: Signedness::Unsigned,
229 bitness: bitness_from_chalk_uint(uint_ty),
230 })),
231 chalk_ir::TyKind::Scalar(Scalar::Float(chalk_ir::FloatTy::F32)) => {
232 Ty::simple(TypeCtor::Float(FloatTy { bitness: FloatBitness::X32 }))
233 }
234 chalk_ir::TyKind::Scalar(Scalar::Float(chalk_ir::FloatTy::F64)) => {
235 Ty::simple(TypeCtor::Float(FloatTy { bitness: FloatBitness::X64 }))
236 }
237 chalk_ir::TyKind::Tuple(cardinality, subst) => {
238 apply_ty_from_chalk(db, TypeCtor::Tuple { cardinality: cardinality as u16 }, subst)
239 }
240 chalk_ir::TyKind::Raw(mutability, ty) => {
241 Ty::apply_one(TypeCtor::RawPtr(from_chalk(db, mutability)), from_chalk(db, ty))
242 }
243 chalk_ir::TyKind::Slice(ty) => Ty::apply_one(TypeCtor::Slice, from_chalk(db, ty)),
244 chalk_ir::TyKind::Ref(mutability, _lifetime, ty) => {
245 Ty::apply_one(TypeCtor::Ref(from_chalk(db, mutability)), from_chalk(db, ty))
246 }
247 chalk_ir::TyKind::Str => Ty::simple(TypeCtor::Str),
248 chalk_ir::TyKind::Never => Ty::simple(TypeCtor::Never),
249
250 chalk_ir::TyKind::FnDef(fn_def_id, subst) => {
251 let callable_def = from_chalk(db, fn_def_id);
252 apply_ty_from_chalk(db, TypeCtor::FnDef(callable_def), subst)
253 }
254
255 chalk_ir::TyKind::Closure(id, subst) => {
256 let id: crate::db::ClosureId = id.into();
257 let (def, expr) = db.lookup_intern_closure(id);
258 apply_ty_from_chalk(db, TypeCtor::Closure { def, expr }, subst)
259 }
260
261 chalk_ir::TyKind::Foreign(foreign_def_id) => Ty::simple(TypeCtor::ForeignType(
262 from_chalk::<TypeAliasAsForeignType, _>(db, foreign_def_id).0,
263 )),
264 chalk_ir::TyKind::Generator(_, _) => unimplemented!(), // FIXME
265 chalk_ir::TyKind::GeneratorWitness(_, _) => unimplemented!(), // FIXME
160 } 266 }
161 } 267 }
162} 268}
163 269
270fn apply_ty_from_chalk(
271 db: &dyn HirDatabase,
272 ctor: TypeCtor,
273 subst: chalk_ir::Substitution<Interner>,
274) -> Ty {
275 Ty::Apply(ApplicationTy { ctor, parameters: from_chalk(db, subst) })
276}
277
164/// We currently don't model lifetimes, but Chalk does. So, we have to insert a 278/// We currently don't model lifetimes, but Chalk does. So, we have to insert a
165/// fake lifetime here, because Chalks built-in logic may expect it to be there. 279/// fake lifetime here, because Chalks built-in logic may expect it to be there.
166fn ref_to_chalk( 280fn ref_to_chalk(
@@ -170,60 +284,21 @@ fn ref_to_chalk(
170) -> chalk_ir::Ty<Interner> { 284) -> chalk_ir::Ty<Interner> {
171 let arg = subst[0].clone().to_chalk(db); 285 let arg = subst[0].clone().to_chalk(db);
172 let lifetime = LifetimeData::Static.intern(&Interner); 286 let lifetime = LifetimeData::Static.intern(&Interner);
173 chalk_ir::ApplicationTy { 287 chalk_ir::TyKind::Ref(mutability.to_chalk(db), lifetime, arg).intern(&Interner)
174 name: TypeName::Ref(mutability.to_chalk(db)),
175 substitution: chalk_ir::Substitution::from_iter(
176 &Interner,
177 vec![lifetime.cast(&Interner), arg.cast(&Interner)],
178 ),
179 }
180 .intern(&Interner)
181}
182
183/// Here we remove the lifetime from the type we got from Chalk.
184fn ref_from_chalk(
185 db: &dyn HirDatabase,
186 mutability: chalk_ir::Mutability,
187 subst: chalk_ir::Substitution<Interner>,
188) -> Ty {
189 let tys = subst
190 .iter(&Interner)
191 .filter_map(|p| Some(from_chalk(db, p.ty(&Interner)?.clone())))
192 .collect();
193 Ty::apply(TypeCtor::Ref(from_chalk(db, mutability)), Substs(tys))
194} 288}
195 289
196/// We currently don't model constants, but Chalk does. So, we have to insert a 290/// We currently don't model constants, but Chalk does. So, we have to insert a
197/// fake constant here, because Chalks built-in logic may expect it to be there. 291/// fake constant here, because Chalks built-in logic may expect it to be there.
198fn array_to_chalk(db: &dyn HirDatabase, subst: Substs) -> chalk_ir::Ty<Interner> { 292fn array_to_chalk(db: &dyn HirDatabase, subst: Substs) -> chalk_ir::Ty<Interner> {
199 let arg = subst[0].clone().to_chalk(db); 293 let arg = subst[0].clone().to_chalk(db);
200 let usize_ty = chalk_ir::ApplicationTy { 294 let usize_ty =
201 name: TypeName::Scalar(Scalar::Uint(chalk_ir::UintTy::Usize)), 295 chalk_ir::TyKind::Scalar(Scalar::Uint(chalk_ir::UintTy::Usize)).intern(&Interner);
202 substitution: chalk_ir::Substitution::empty(&Interner),
203 }
204 .intern(&Interner);
205 let const_ = chalk_ir::ConstData { 296 let const_ = chalk_ir::ConstData {
206 ty: usize_ty, 297 ty: usize_ty,
207 value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: () }), 298 value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: () }),
208 } 299 }
209 .intern(&Interner); 300 .intern(&Interner);
210 chalk_ir::ApplicationTy { 301 chalk_ir::TyKind::Array(arg, const_).intern(&Interner)
211 name: TypeName::Array,
212 substitution: chalk_ir::Substitution::from_iter(
213 &Interner,
214 vec![arg.cast(&Interner), const_.cast(&Interner)],
215 ),
216 }
217 .intern(&Interner)
218}
219
220/// Here we remove the const from the type we got from Chalk.
221fn array_from_chalk(db: &dyn HirDatabase, subst: chalk_ir::Substitution<Interner>) -> Ty {
222 let tys = subst
223 .iter(&Interner)
224 .filter_map(|p| Some(from_chalk(db, p.ty(&Interner)?.clone())))
225 .collect();
226 Ty::apply(TypeCtor::Array, Substs(tys))
227} 302}
228 303
229impl ToChalk for Substs { 304impl ToChalk for Substs {
@@ -288,124 +363,6 @@ impl ToChalk for OpaqueTyId {
288 } 363 }
289} 364}
290 365
291impl ToChalk for TypeCtor {
292 type Chalk = TypeName<Interner>;
293
294 fn to_chalk(self, db: &dyn HirDatabase) -> TypeName<Interner> {
295 match self {
296 TypeCtor::AssociatedType(type_alias) => {
297 let assoc_type = TypeAliasAsAssocType(type_alias);
298 let assoc_type_id = assoc_type.to_chalk(db);
299 TypeName::AssociatedType(assoc_type_id)
300 }
301
302 TypeCtor::OpaqueType(impl_trait_id) => {
303 let id = impl_trait_id.to_chalk(db);
304 TypeName::OpaqueType(id)
305 }
306
307 TypeCtor::ForeignType(type_alias) => {
308 let foreign_type = TypeAliasAsForeignType(type_alias);
309 let foreign_type_id = foreign_type.to_chalk(db);
310 TypeName::Foreign(foreign_type_id)
311 }
312
313 TypeCtor::Bool => TypeName::Scalar(Scalar::Bool),
314 TypeCtor::Char => TypeName::Scalar(Scalar::Char),
315 TypeCtor::Int(int_ty) => TypeName::Scalar(int_ty_to_chalk(int_ty)),
316 TypeCtor::Float(FloatTy { bitness: FloatBitness::X32 }) => {
317 TypeName::Scalar(Scalar::Float(chalk_ir::FloatTy::F32))
318 }
319 TypeCtor::Float(FloatTy { bitness: FloatBitness::X64 }) => {
320 TypeName::Scalar(Scalar::Float(chalk_ir::FloatTy::F64))
321 }
322
323 TypeCtor::Tuple { cardinality } => TypeName::Tuple(cardinality.into()),
324 TypeCtor::RawPtr(mutability) => TypeName::Raw(mutability.to_chalk(db)),
325 TypeCtor::Slice => TypeName::Slice,
326 TypeCtor::Array => TypeName::Array,
327 TypeCtor::Ref(mutability) => TypeName::Ref(mutability.to_chalk(db)),
328 TypeCtor::Str => TypeName::Str,
329 TypeCtor::FnDef(callable_def) => {
330 let id = callable_def.to_chalk(db);
331 TypeName::FnDef(id)
332 }
333 TypeCtor::Never => TypeName::Never,
334
335 TypeCtor::Closure { def, expr } => {
336 let closure_id = db.intern_closure((def, expr));
337 TypeName::Closure(closure_id.into())
338 }
339
340 TypeCtor::Adt(adt_id) => TypeName::Adt(chalk_ir::AdtId(adt_id)),
341
342 TypeCtor::FnPtr { .. } => {
343 // This should not be reached, since Chalk doesn't represent
344 // function pointers with TypeName
345 unreachable!()
346 }
347 }
348 }
349
350 fn from_chalk(db: &dyn HirDatabase, type_name: TypeName<Interner>) -> TypeCtor {
351 match type_name {
352 TypeName::Adt(struct_id) => TypeCtor::Adt(struct_id.0),
353 TypeName::AssociatedType(type_id) => {
354 TypeCtor::AssociatedType(from_chalk::<TypeAliasAsAssocType, _>(db, type_id).0)
355 }
356 TypeName::OpaqueType(opaque_type_id) => {
357 TypeCtor::OpaqueType(from_chalk(db, opaque_type_id))
358 }
359
360 TypeName::Scalar(Scalar::Bool) => TypeCtor::Bool,
361 TypeName::Scalar(Scalar::Char) => TypeCtor::Char,
362 TypeName::Scalar(Scalar::Int(int_ty)) => TypeCtor::Int(IntTy {
363 signedness: Signedness::Signed,
364 bitness: bitness_from_chalk_int(int_ty),
365 }),
366 TypeName::Scalar(Scalar::Uint(uint_ty)) => TypeCtor::Int(IntTy {
367 signedness: Signedness::Unsigned,
368 bitness: bitness_from_chalk_uint(uint_ty),
369 }),
370 TypeName::Scalar(Scalar::Float(chalk_ir::FloatTy::F32)) => {
371 TypeCtor::Float(FloatTy { bitness: FloatBitness::X32 })
372 }
373 TypeName::Scalar(Scalar::Float(chalk_ir::FloatTy::F64)) => {
374 TypeCtor::Float(FloatTy { bitness: FloatBitness::X64 })
375 }
376 TypeName::Tuple(cardinality) => TypeCtor::Tuple { cardinality: cardinality as u16 },
377 TypeName::Raw(mutability) => TypeCtor::RawPtr(from_chalk(db, mutability)),
378 TypeName::Slice => TypeCtor::Slice,
379 TypeName::Ref(mutability) => TypeCtor::Ref(from_chalk(db, mutability)),
380 TypeName::Str => TypeCtor::Str,
381 TypeName::Never => TypeCtor::Never,
382
383 TypeName::FnDef(fn_def_id) => {
384 let callable_def = from_chalk(db, fn_def_id);
385 TypeCtor::FnDef(callable_def)
386 }
387 TypeName::Array => TypeCtor::Array,
388
389 TypeName::Closure(id) => {
390 let id: crate::db::ClosureId = id.into();
391 let (def, expr) = db.lookup_intern_closure(id);
392 TypeCtor::Closure { def, expr }
393 }
394
395 TypeName::Foreign(foreign_def_id) => {
396 TypeCtor::ForeignType(from_chalk::<TypeAliasAsForeignType, _>(db, foreign_def_id).0)
397 }
398
399 TypeName::Error => {
400 // this should not be reached, since we don't represent TypeName::Error with TypeCtor
401 unreachable!()
402 }
403 TypeName::Generator(_) => unimplemented!(), // FIXME
404 TypeName::GeneratorWitness(_) => unimplemented!(), // FIXME
405 }
406 }
407}
408
409fn bitness_from_chalk_uint(uint_ty: chalk_ir::UintTy) -> IntBitness { 366fn bitness_from_chalk_uint(uint_ty: chalk_ir::UintTy) -> IntBitness {
410 use chalk_ir::UintTy; 367 use chalk_ir::UintTy;
411 368
@@ -507,7 +464,7 @@ impl ToChalk for CallableDefId {
507 } 464 }
508} 465}
509 466
510pub struct TypeAliasAsAssocType(pub TypeAliasId); 467pub(crate) struct TypeAliasAsAssocType(pub(crate) TypeAliasId);
511 468
512impl ToChalk for TypeAliasAsAssocType { 469impl ToChalk for TypeAliasAsAssocType {
513 type Chalk = AssocTypeId; 470 type Chalk = AssocTypeId;
@@ -521,7 +478,7 @@ impl ToChalk for TypeAliasAsAssocType {
521 } 478 }
522} 479}
523 480
524pub struct TypeAliasAsForeignType(pub TypeAliasId); 481pub(crate) struct TypeAliasAsForeignType(pub(crate) TypeAliasId);
525 482
526impl ToChalk for TypeAliasAsForeignType { 483impl ToChalk for TypeAliasAsForeignType {
527 type Chalk = ForeignDefId; 484 type Chalk = ForeignDefId;
@@ -535,7 +492,7 @@ impl ToChalk for TypeAliasAsForeignType {
535 } 492 }
536} 493}
537 494
538pub struct TypeAliasAsValue(pub TypeAliasId); 495pub(crate) struct TypeAliasAsValue(pub(crate) TypeAliasId);
539 496
540impl ToChalk for TypeAliasAsValue { 497impl ToChalk for TypeAliasAsValue {
541 type Chalk = AssociatedTyValueId; 498 type Chalk = AssociatedTyValueId;
@@ -677,9 +634,9 @@ where
677 .kinds 634 .kinds
678 .iter() 635 .iter()
679 .map(|k| match k { 636 .map(|k| match k {
680 TyKind::General => chalk_ir::TyKind::General, 637 TyKind::General => chalk_ir::TyVariableKind::General,
681 TyKind::Integer => chalk_ir::TyKind::Integer, 638 TyKind::Integer => chalk_ir::TyVariableKind::Integer,
682 TyKind::Float => chalk_ir::TyKind::Float, 639 TyKind::Float => chalk_ir::TyVariableKind::Float,
683 }) 640 })
684 .map(|tk| { 641 .map(|tk| {
685 chalk_ir::CanonicalVarKind::new( 642 chalk_ir::CanonicalVarKind::new(
@@ -700,9 +657,9 @@ where
700 .iter(&Interner) 657 .iter(&Interner)
701 .map(|k| match k.kind { 658 .map(|k| match k.kind {
702 chalk_ir::VariableKind::Ty(tk) => match tk { 659 chalk_ir::VariableKind::Ty(tk) => match tk {
703 chalk_ir::TyKind::General => TyKind::General, 660 chalk_ir::TyVariableKind::General => TyKind::General,
704 chalk_ir::TyKind::Integer => TyKind::Integer, 661 chalk_ir::TyVariableKind::Integer => TyKind::Integer,
705 chalk_ir::TyKind::Float => TyKind::Float, 662 chalk_ir::TyVariableKind::Float => TyKind::Float,
706 }, 663 },
707 chalk_ir::VariableKind::Lifetime => panic!("unexpected lifetime from Chalk"), 664 chalk_ir::VariableKind::Lifetime => panic!("unexpected lifetime from Chalk"),
708 chalk_ir::VariableKind::Const(_) => panic!("unexpected const from Chalk"), 665 chalk_ir::VariableKind::Const(_) => panic!("unexpected const from Chalk"),
@@ -768,7 +725,8 @@ where
768 chalk_ir::Binders::new( 725 chalk_ir::Binders::new(
769 chalk_ir::VariableKinds::from_iter( 726 chalk_ir::VariableKinds::from_iter(
770 &Interner, 727 &Interner,
771 std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyKind::General)).take(num_vars), 728 std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
729 .take(num_vars),
772 ), 730 ),
773 value, 731 value,
774 ) 732 )
diff --git a/crates/hir_ty/src/traits/chalk/tls.rs b/crates/hir_ty/src/traits/chalk/tls.rs
index b4568cff6..75b16172e 100644
--- a/crates/hir_ty/src/traits/chalk/tls.rs
+++ b/crates/hir_ty/src/traits/chalk/tls.rs
@@ -1,114 +1,32 @@
1//! Implementation of Chalk debug helper functions using TLS. 1//! Implementation of Chalk debug helper functions using TLS.
2use std::fmt; 2use std::fmt;
3 3
4use chalk_ir::{AliasTy, GenericArg, Goal, Goals, Lifetime, ProgramClauseImplication, TypeName}; 4use chalk_ir::{AliasTy, GenericArg, Goal, Goals, Lifetime, ProgramClauseImplication};
5use itertools::Itertools; 5use itertools::Itertools;
6 6
7use super::{from_chalk, Interner, TypeAliasAsAssocType}; 7use super::{from_chalk, Interner, TypeAliasAsAssocType};
8use crate::{db::HirDatabase, CallableDefId, TypeCtor}; 8use crate::{db::HirDatabase, CallableDefId};
9use hir_def::{AdtId, AssocContainerId, DefWithBodyId, Lookup, TypeAliasId}; 9use hir_def::{AdtId, AssocContainerId, Lookup, TypeAliasId};
10 10
11pub use unsafe_tls::{set_current_program, with_current_program}; 11pub(crate) use unsafe_tls::{set_current_program, with_current_program};
12 12
13pub struct DebugContext<'a>(&'a dyn HirDatabase); 13pub(crate) struct DebugContext<'a>(&'a dyn HirDatabase);
14 14
15impl DebugContext<'_> { 15impl DebugContext<'_> {
16 pub fn debug_struct_id( 16 pub(crate) fn debug_struct_id(
17 &self, 17 &self,
18 id: super::AdtId, 18 id: super::AdtId,
19 f: &mut fmt::Formatter<'_>, 19 f: &mut fmt::Formatter<'_>,
20 ) -> Result<(), fmt::Error> { 20 ) -> Result<(), fmt::Error> {
21 let type_ctor: TypeCtor = from_chalk(self.0, TypeName::Adt(id)); 21 let name = match id.0 {
22 match type_ctor { 22 AdtId::StructId(it) => self.0.struct_data(it).name.clone(),
23 TypeCtor::Bool => write!(f, "bool")?, 23 AdtId::UnionId(it) => self.0.union_data(it).name.clone(),
24 TypeCtor::Char => write!(f, "char")?, 24 AdtId::EnumId(it) => self.0.enum_data(it).name.clone(),
25 TypeCtor::Int(t) => write!(f, "{}", t)?, 25 };
26 TypeCtor::Float(t) => write!(f, "{}", t)?, 26 write!(f, "{}", name)
27 TypeCtor::Str => write!(f, "str")?,
28 TypeCtor::Slice => write!(f, "slice")?,
29 TypeCtor::Array => write!(f, "array")?,
30 TypeCtor::RawPtr(m) => write!(f, "*{}", m.as_keyword_for_ptr())?,
31 TypeCtor::Ref(m) => write!(f, "&{}", m.as_keyword_for_ref())?,
32 TypeCtor::Never => write!(f, "!")?,
33 TypeCtor::Tuple { .. } => {
34 write!(f, "()")?;
35 }
36 TypeCtor::FnPtr { .. } => {
37 write!(f, "fn")?;
38 }
39 TypeCtor::FnDef(def) => {
40 let name = match def {
41 CallableDefId::FunctionId(ff) => self.0.function_data(ff).name.clone(),
42 CallableDefId::StructId(s) => self.0.struct_data(s).name.clone(),
43 CallableDefId::EnumVariantId(e) => {
44 let enum_data = self.0.enum_data(e.parent);
45 enum_data.variants[e.local_id].name.clone()
46 }
47 };
48 match def {
49 CallableDefId::FunctionId(_) => write!(f, "{{fn {}}}", name)?,
50 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {
51 write!(f, "{{ctor {}}}", name)?
52 }
53 }
54 }
55 TypeCtor::Adt(def_id) => {
56 let name = match def_id {
57 AdtId::StructId(it) => self.0.struct_data(it).name.clone(),
58 AdtId::UnionId(it) => self.0.union_data(it).name.clone(),
59 AdtId::EnumId(it) => self.0.enum_data(it).name.clone(),
60 };
61 write!(f, "{}", name)?;
62 }
63 TypeCtor::AssociatedType(type_alias) => {
64 let trait_ = match type_alias.lookup(self.0.upcast()).container {
65 AssocContainerId::TraitId(it) => it,
66 _ => panic!("not an associated type"),
67 };
68 let trait_name = self.0.trait_data(trait_).name.clone();
69 let name = self.0.type_alias_data(type_alias).name.clone();
70 write!(f, "{}::{}", trait_name, name)?;
71 }
72 TypeCtor::OpaqueType(opaque_ty_id) => match opaque_ty_id {
73 crate::OpaqueTyId::ReturnTypeImplTrait(func, idx) => {
74 write!(f, "{{impl trait {} of {:?}}}", idx, func)?;
75 }
76 crate::OpaqueTyId::AsyncBlockTypeImplTrait(def, idx) => {
77 write!(f, "{{impl trait of async block {} of {:?}}}", idx.into_raw(), def)?;
78 }
79 },
80 TypeCtor::ForeignType(type_alias) => {
81 let name = self.0.type_alias_data(type_alias).name.clone();
82 write!(f, "{}", name)?;
83 }
84 TypeCtor::Closure { def, expr } => {
85 write!(f, "{{closure {:?} in ", expr.into_raw())?;
86 match def {
87 DefWithBodyId::FunctionId(func) => {
88 write!(f, "fn {}", self.0.function_data(func).name)?
89 }
90 DefWithBodyId::StaticId(s) => {
91 if let Some(name) = self.0.static_data(s).name.as_ref() {
92 write!(f, "body of static {}", name)?;
93 } else {
94 write!(f, "body of unnamed static {:?}", s)?;
95 }
96 }
97 DefWithBodyId::ConstId(c) => {
98 if let Some(name) = self.0.const_data(c).name.as_ref() {
99 write!(f, "body of const {}", name)?;
100 } else {
101 write!(f, "body of unnamed const {:?}", c)?;
102 }
103 }
104 };
105 write!(f, "}}")?;
106 }
107 }
108 Ok(())
109 } 27 }
110 28
111 pub fn debug_trait_id( 29 pub(crate) fn debug_trait_id(
112 &self, 30 &self,
113 id: super::TraitId, 31 id: super::TraitId,
114 fmt: &mut fmt::Formatter<'_>, 32 fmt: &mut fmt::Formatter<'_>,
@@ -118,7 +36,7 @@ impl DebugContext<'_> {
118 write!(fmt, "{}", trait_data.name) 36 write!(fmt, "{}", trait_data.name)
119 } 37 }
120 38
121 pub fn debug_assoc_type_id( 39 pub(crate) fn debug_assoc_type_id(
122 &self, 40 &self,
123 id: super::AssocTypeId, 41 id: super::AssocTypeId,
124 fmt: &mut fmt::Formatter<'_>, 42 fmt: &mut fmt::Formatter<'_>,
@@ -133,7 +51,7 @@ impl DebugContext<'_> {
133 write!(fmt, "{}::{}", trait_data.name, type_alias_data.name) 51 write!(fmt, "{}::{}", trait_data.name, type_alias_data.name)
134 } 52 }
135 53
136 pub fn debug_opaque_ty_id( 54 pub(crate) fn debug_opaque_ty_id(
137 &self, 55 &self,
138 opaque_ty_id: chalk_ir::OpaqueTyId<Interner>, 56 opaque_ty_id: chalk_ir::OpaqueTyId<Interner>,
139 fmt: &mut fmt::Formatter<'_>, 57 fmt: &mut fmt::Formatter<'_>,
@@ -141,7 +59,7 @@ impl DebugContext<'_> {
141 fmt.debug_struct("OpaqueTyId").field("index", &opaque_ty_id.0).finish() 59 fmt.debug_struct("OpaqueTyId").field("index", &opaque_ty_id.0).finish()
142 } 60 }
143 61
144 pub fn debug_alias( 62 pub(crate) fn debug_alias(
145 &self, 63 &self,
146 alias_ty: &AliasTy<Interner>, 64 alias_ty: &AliasTy<Interner>,
147 fmt: &mut fmt::Formatter<'_>, 65 fmt: &mut fmt::Formatter<'_>,
@@ -152,7 +70,7 @@ impl DebugContext<'_> {
152 } 70 }
153 } 71 }
154 72
155 pub fn debug_projection_ty( 73 pub(crate) fn debug_projection_ty(
156 &self, 74 &self,
157 projection_ty: &chalk_ir::ProjectionTy<Interner>, 75 projection_ty: &chalk_ir::ProjectionTy<Interner>,
158 fmt: &mut fmt::Formatter<'_>, 76 fmt: &mut fmt::Formatter<'_>,
@@ -177,7 +95,7 @@ impl DebugContext<'_> {
177 write!(fmt, ">::{}", type_alias_data.name) 95 write!(fmt, ">::{}", type_alias_data.name)
178 } 96 }
179 97
180 pub fn debug_opaque_ty( 98 pub(crate) fn debug_opaque_ty(
181 &self, 99 &self,
182 opaque_ty: &chalk_ir::OpaqueTy<Interner>, 100 opaque_ty: &chalk_ir::OpaqueTy<Interner>,
183 fmt: &mut fmt::Formatter<'_>, 101 fmt: &mut fmt::Formatter<'_>,
@@ -185,7 +103,7 @@ impl DebugContext<'_> {
185 write!(fmt, "{:?}", opaque_ty.opaque_ty_id) 103 write!(fmt, "{:?}", opaque_ty.opaque_ty_id)
186 } 104 }
187 105
188 pub fn debug_ty( 106 pub(crate) fn debug_ty(
189 &self, 107 &self,
190 ty: &chalk_ir::Ty<Interner>, 108 ty: &chalk_ir::Ty<Interner>,
191 fmt: &mut fmt::Formatter<'_>, 109 fmt: &mut fmt::Formatter<'_>,
@@ -193,7 +111,7 @@ impl DebugContext<'_> {
193 write!(fmt, "{:?}", ty.data(&Interner)) 111 write!(fmt, "{:?}", ty.data(&Interner))
194 } 112 }
195 113
196 pub fn debug_lifetime( 114 pub(crate) fn debug_lifetime(
197 &self, 115 &self,
198 lifetime: &Lifetime<Interner>, 116 lifetime: &Lifetime<Interner>,
199 fmt: &mut fmt::Formatter<'_>, 117 fmt: &mut fmt::Formatter<'_>,
@@ -201,7 +119,7 @@ impl DebugContext<'_> {
201 write!(fmt, "{:?}", lifetime.data(&Interner)) 119 write!(fmt, "{:?}", lifetime.data(&Interner))
202 } 120 }
203 121
204 pub fn debug_generic_arg( 122 pub(crate) fn debug_generic_arg(
205 &self, 123 &self,
206 parameter: &GenericArg<Interner>, 124 parameter: &GenericArg<Interner>,
207 fmt: &mut fmt::Formatter<'_>, 125 fmt: &mut fmt::Formatter<'_>,
@@ -209,7 +127,7 @@ impl DebugContext<'_> {
209 write!(fmt, "{:?}", parameter.data(&Interner).inner_debug()) 127 write!(fmt, "{:?}", parameter.data(&Interner).inner_debug())
210 } 128 }
211 129
212 pub fn debug_goal( 130 pub(crate) fn debug_goal(
213 &self, 131 &self,
214 goal: &Goal<Interner>, 132 goal: &Goal<Interner>,
215 fmt: &mut fmt::Formatter<'_>, 133 fmt: &mut fmt::Formatter<'_>,
@@ -218,7 +136,7 @@ impl DebugContext<'_> {
218 write!(fmt, "{:?}", goal_data) 136 write!(fmt, "{:?}", goal_data)
219 } 137 }
220 138
221 pub fn debug_goals( 139 pub(crate) fn debug_goals(
222 &self, 140 &self,
223 goals: &Goals<Interner>, 141 goals: &Goals<Interner>,
224 fmt: &mut fmt::Formatter<'_>, 142 fmt: &mut fmt::Formatter<'_>,
@@ -226,7 +144,7 @@ impl DebugContext<'_> {
226 write!(fmt, "{:?}", goals.debug(&Interner)) 144 write!(fmt, "{:?}", goals.debug(&Interner))
227 } 145 }
228 146
229 pub fn debug_program_clause_implication( 147 pub(crate) fn debug_program_clause_implication(
230 &self, 148 &self,
231 pci: &ProgramClauseImplication<Interner>, 149 pci: &ProgramClauseImplication<Interner>,
232 fmt: &mut fmt::Formatter<'_>, 150 fmt: &mut fmt::Formatter<'_>,
@@ -234,15 +152,7 @@ impl DebugContext<'_> {
234 write!(fmt, "{:?}", pci.debug(&Interner)) 152 write!(fmt, "{:?}", pci.debug(&Interner))
235 } 153 }
236 154
237 pub fn debug_application_ty( 155 pub(crate) fn debug_substitution(
238 &self,
239 application_ty: &chalk_ir::ApplicationTy<Interner>,
240 fmt: &mut fmt::Formatter<'_>,
241 ) -> Result<(), fmt::Error> {
242 write!(fmt, "{:?}", application_ty.debug(&Interner))
243 }
244
245 pub fn debug_substitution(
246 &self, 156 &self,
247 substitution: &chalk_ir::Substitution<Interner>, 157 substitution: &chalk_ir::Substitution<Interner>,
248 fmt: &mut fmt::Formatter<'_>, 158 fmt: &mut fmt::Formatter<'_>,
@@ -250,7 +160,7 @@ impl DebugContext<'_> {
250 write!(fmt, "{:?}", substitution.debug(&Interner)) 160 write!(fmt, "{:?}", substitution.debug(&Interner))
251 } 161 }
252 162
253 pub fn debug_separator_trait_ref( 163 pub(crate) fn debug_separator_trait_ref(
254 &self, 164 &self,
255 separator_trait_ref: &chalk_ir::SeparatorTraitRef<Interner>, 165 separator_trait_ref: &chalk_ir::SeparatorTraitRef<Interner>,
256 fmt: &mut fmt::Formatter<'_>, 166 fmt: &mut fmt::Formatter<'_>,
@@ -258,7 +168,7 @@ impl DebugContext<'_> {
258 write!(fmt, "{:?}", separator_trait_ref.debug(&Interner)) 168 write!(fmt, "{:?}", separator_trait_ref.debug(&Interner))
259 } 169 }
260 170
261 pub fn debug_fn_def_id( 171 pub(crate) fn debug_fn_def_id(
262 &self, 172 &self,
263 fn_def_id: chalk_ir::FnDefId<Interner>, 173 fn_def_id: chalk_ir::FnDefId<Interner>,
264 fmt: &mut fmt::Formatter<'_>, 174 fmt: &mut fmt::Formatter<'_>,
@@ -280,7 +190,7 @@ impl DebugContext<'_> {
280 } 190 }
281 } 191 }
282 192
283 pub fn debug_const( 193 pub(crate) fn debug_const(
284 &self, 194 &self,
285 _constant: &chalk_ir::Const<Interner>, 195 _constant: &chalk_ir::Const<Interner>,
286 fmt: &mut fmt::Formatter<'_>, 196 fmt: &mut fmt::Formatter<'_>,
@@ -288,42 +198,42 @@ impl DebugContext<'_> {
288 write!(fmt, "const") 198 write!(fmt, "const")
289 } 199 }
290 200
291 pub fn debug_variable_kinds( 201 pub(crate) fn debug_variable_kinds(
292 &self, 202 &self,
293 variable_kinds: &chalk_ir::VariableKinds<Interner>, 203 variable_kinds: &chalk_ir::VariableKinds<Interner>,
294 fmt: &mut fmt::Formatter<'_>, 204 fmt: &mut fmt::Formatter<'_>,
295 ) -> fmt::Result { 205 ) -> fmt::Result {
296 write!(fmt, "{:?}", variable_kinds.as_slice(&Interner)) 206 write!(fmt, "{:?}", variable_kinds.as_slice(&Interner))
297 } 207 }
298 pub fn debug_variable_kinds_with_angles( 208 pub(crate) fn debug_variable_kinds_with_angles(
299 &self, 209 &self,
300 variable_kinds: &chalk_ir::VariableKinds<Interner>, 210 variable_kinds: &chalk_ir::VariableKinds<Interner>,
301 fmt: &mut fmt::Formatter<'_>, 211 fmt: &mut fmt::Formatter<'_>,
302 ) -> fmt::Result { 212 ) -> fmt::Result {
303 write!(fmt, "{:?}", variable_kinds.inner_debug(&Interner)) 213 write!(fmt, "{:?}", variable_kinds.inner_debug(&Interner))
304 } 214 }
305 pub fn debug_canonical_var_kinds( 215 pub(crate) fn debug_canonical_var_kinds(
306 &self, 216 &self,
307 canonical_var_kinds: &chalk_ir::CanonicalVarKinds<Interner>, 217 canonical_var_kinds: &chalk_ir::CanonicalVarKinds<Interner>,
308 fmt: &mut fmt::Formatter<'_>, 218 fmt: &mut fmt::Formatter<'_>,
309 ) -> fmt::Result { 219 ) -> fmt::Result {
310 write!(fmt, "{:?}", canonical_var_kinds.as_slice(&Interner)) 220 write!(fmt, "{:?}", canonical_var_kinds.as_slice(&Interner))
311 } 221 }
312 pub fn debug_program_clause( 222 pub(crate) fn debug_program_clause(
313 &self, 223 &self,
314 clause: &chalk_ir::ProgramClause<Interner>, 224 clause: &chalk_ir::ProgramClause<Interner>,
315 fmt: &mut fmt::Formatter<'_>, 225 fmt: &mut fmt::Formatter<'_>,
316 ) -> fmt::Result { 226 ) -> fmt::Result {
317 write!(fmt, "{:?}", clause.data(&Interner)) 227 write!(fmt, "{:?}", clause.data(&Interner))
318 } 228 }
319 pub fn debug_program_clauses( 229 pub(crate) fn debug_program_clauses(
320 &self, 230 &self,
321 clauses: &chalk_ir::ProgramClauses<Interner>, 231 clauses: &chalk_ir::ProgramClauses<Interner>,
322 fmt: &mut fmt::Formatter<'_>, 232 fmt: &mut fmt::Formatter<'_>,
323 ) -> fmt::Result { 233 ) -> fmt::Result {
324 write!(fmt, "{:?}", clauses.as_slice(&Interner)) 234 write!(fmt, "{:?}", clauses.as_slice(&Interner))
325 } 235 }
326 pub fn debug_quantified_where_clauses( 236 pub(crate) fn debug_quantified_where_clauses(
327 &self, 237 &self,
328 clauses: &chalk_ir::QuantifiedWhereClauses<Interner>, 238 clauses: &chalk_ir::QuantifiedWhereClauses<Interner>,
329 fmt: &mut fmt::Formatter<'_>, 239 fmt: &mut fmt::Formatter<'_>,
@@ -339,7 +249,7 @@ mod unsafe_tls {
339 249
340 scoped_thread_local!(static PROGRAM: DebugContext); 250 scoped_thread_local!(static PROGRAM: DebugContext);
341 251
342 pub fn with_current_program<R>( 252 pub(crate) fn with_current_program<R>(
343 op: impl for<'a> FnOnce(Option<&'a DebugContext<'a>>) -> R, 253 op: impl for<'a> FnOnce(Option<&'a DebugContext<'a>>) -> R,
344 ) -> R { 254 ) -> R {
345 if PROGRAM.is_set() { 255 if PROGRAM.is_set() {
@@ -349,7 +259,7 @@ mod unsafe_tls {
349 } 259 }
350 } 260 }
351 261
352 pub fn set_current_program<OP, R>(p: &dyn HirDatabase, op: OP) -> R 262 pub(crate) fn set_current_program<OP, R>(p: &dyn HirDatabase, op: OP) -> R
353 where 263 where
354 OP: FnOnce() -> R, 264 OP: FnOnce() -> R,
355 { 265 {
diff --git a/crates/ide/src/diagnostics/fixes.rs b/crates/ide/src/diagnostics/fixes.rs
index 0c950003e..02e17ba43 100644
--- a/crates/ide/src/diagnostics/fixes.rs
+++ b/crates/ide/src/diagnostics/fixes.rs
@@ -25,7 +25,7 @@ use crate::{diagnostics::Fix, references::rename::rename_with_semantics, FilePos
25/// A [Diagnostic] that potentially has a fix available. 25/// A [Diagnostic] that potentially has a fix available.
26/// 26///
27/// [Diagnostic]: hir::diagnostics::Diagnostic 27/// [Diagnostic]: hir::diagnostics::Diagnostic
28pub trait DiagnosticWithFix: Diagnostic { 28pub(crate) trait DiagnosticWithFix: Diagnostic {
29 fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Fix>; 29 fn fix(&self, sema: &Semantics<RootDatabase>) -> Option<Fix>;
30} 30}
31 31
diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs
index 250f10f9f..10263537a 100644
--- a/crates/ide/src/doc_links.rs
+++ b/crates/ide/src/doc_links.rs
@@ -1,7 +1,6 @@
1//! Resolves and rewrites links in markdown documentation. 1//! Resolves and rewrites links in markdown documentation.
2 2
3use std::convert::TryFrom; 3use std::{convert::TryFrom, iter::once};
4use std::iter::once;
5 4
6use itertools::Itertools; 5use itertools::Itertools;
7use pulldown_cmark::{BrokenLink, CowStr, Event, InlineStr, LinkType, Options, Parser, Tag}; 6use pulldown_cmark::{BrokenLink, CowStr, Event, InlineStr, LinkType, Options, Parser, Tag};
@@ -21,10 +20,10 @@ use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset,
21 20
22use crate::{FilePosition, Semantics}; 21use crate::{FilePosition, Semantics};
23 22
24pub type DocumentationLink = String; 23pub(crate) type DocumentationLink = String;
25 24
26/// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs) 25/// Rewrite documentation links in markdown to point to an online host (e.g. docs.rs)
27pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String { 26pub(crate) fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition) -> String {
28 let mut cb = |link: BrokenLink| { 27 let mut cb = |link: BrokenLink| {
29 Some(( 28 Some((
30 /*url*/ link.reference.to_owned().into(), 29 /*url*/ link.reference.to_owned().into(),
@@ -63,7 +62,7 @@ pub fn rewrite_links(db: &RootDatabase, markdown: &str, definition: &Definition)
63} 62}
64 63
65/// Remove all links in markdown documentation. 64/// Remove all links in markdown documentation.
66pub fn remove_links(markdown: &str) -> String { 65pub(crate) fn remove_links(markdown: &str) -> String {
67 let mut drop_link = false; 66 let mut drop_link = false;
68 67
69 let mut opts = Options::empty(); 68 let mut opts = Options::empty();
diff --git a/crates/ide/src/file_structure.rs b/crates/ide/src/file_structure.rs
index 6168fb837..415795e8c 100644
--- a/crates/ide/src/file_structure.rs
+++ b/crates/ide/src/file_structure.rs
@@ -27,7 +27,7 @@ pub struct StructureNode {
27// 27//
28// | VS Code | kbd:[Ctrl+Shift+O] 28// | VS Code | kbd:[Ctrl+Shift+O]
29// |=== 29// |===
30pub fn file_structure(file: &SourceFile) -> Vec<StructureNode> { 30pub(crate) fn file_structure(file: &SourceFile) -> Vec<StructureNode> {
31 let mut res = Vec::new(); 31 let mut res = Vec::new();
32 let mut stack = Vec::new(); 32 let mut stack = Vec::new();
33 33
diff --git a/crates/ide/src/inlay_hints.rs b/crates/ide/src/inlay_hints.rs
index 49d8e4ae1..ac704ae21 100644
--- a/crates/ide/src/inlay_hints.rs
+++ b/crates/ide/src/inlay_hints.rs
@@ -1,6 +1,6 @@
1use assists::utils::FamousDefs; 1use assists::utils::FamousDefs;
2use either::Either; 2use either::Either;
3use hir::{known, HirDisplay, Semantics}; 3use hir::{known, Callable, HirDisplay, Semantics};
4use ide_db::RootDatabase; 4use ide_db::RootDatabase;
5use stdx::to_lower_snake_case; 5use stdx::to_lower_snake_case;
6use syntax::{ 6use syntax::{
@@ -170,7 +170,7 @@ fn get_param_name_hints(
170 }; 170 };
171 Some((param_name, arg)) 171 Some((param_name, arg))
172 }) 172 })
173 .filter(|(param_name, arg)| should_show_param_name_hint(sema, &callable, &param_name, &arg)) 173 .filter(|(param_name, arg)| should_show_param_name_hint(sema, &callable, param_name, &arg))
174 .map(|(param_name, arg)| InlayHint { 174 .map(|(param_name, arg)| InlayHint {
175 range: arg.syntax().text_range(), 175 range: arg.syntax().text_range(),
176 kind: InlayKind::ParameterHint, 176 kind: InlayKind::ParameterHint,
@@ -334,9 +334,11 @@ fn should_show_param_name_hint(
334 | hir::CallableKind::TupleEnumVariant(_) 334 | hir::CallableKind::TupleEnumVariant(_)
335 | hir::CallableKind::Closure => None, 335 | hir::CallableKind::Closure => None,
336 }; 336 };
337
337 if param_name.is_empty() 338 if param_name.is_empty()
338 || Some(param_name) == fn_name.as_ref().map(|s| s.trim_start_matches('_')) 339 || Some(param_name) == fn_name.as_ref().map(|s| s.trim_start_matches('_'))
339 || is_argument_similar_to_param_name(sema, argument, param_name) 340 || is_argument_similar_to_param_name(sema, argument, param_name)
341 || is_param_name_similar_to_fn_name(param_name, callable, fn_name.as_ref())
340 || param_name.starts_with("ra_fixture") 342 || param_name.starts_with("ra_fixture")
341 { 343 {
342 return false; 344 return false;
@@ -364,6 +366,26 @@ fn is_argument_similar_to_param_name(
364 } 366 }
365} 367}
366 368
369fn is_param_name_similar_to_fn_name(
370 param_name: &str,
371 callable: &Callable,
372 fn_name: Option<&String>,
373) -> bool {
374 // if it's the only parameter, don't show it if:
375 // - is the same as the function name, or
376 // - the function ends with '_' + param_name
377
378 match (callable.n_params(), fn_name) {
379 (1, Some(function)) => {
380 function == param_name
381 || (function.len() > param_name.len()
382 && function.ends_with(param_name)
383 && function[..function.len() - param_name.len()].ends_with('_'))
384 }
385 _ => false,
386 }
387}
388
367fn is_enum_name_similar_to_param_name( 389fn is_enum_name_similar_to_param_name(
368 sema: &Semantics<RootDatabase>, 390 sema: &Semantics<RootDatabase>,
369 argument: &ast::Expr, 391 argument: &ast::Expr,
@@ -457,6 +479,88 @@ fn main() {
457 } 479 }
458 480
459 #[test] 481 #[test]
482 fn param_name_similar_to_fn_name_still_hints() {
483 check_with_config(
484 InlayHintsConfig {
485 parameter_hints: true,
486 type_hints: false,
487 chaining_hints: false,
488 max_length: None,
489 },
490 r#"
491fn max(x: i32, y: i32) -> i32 { x + y }
492fn main() {
493 let _x = max(
494 4,
495 //^ x
496 4,
497 //^ y
498 );
499}"#,
500 );
501 }
502
503 #[test]
504 fn param_name_similar_to_fn_name() {
505 check_with_config(
506 InlayHintsConfig {
507 parameter_hints: true,
508 type_hints: false,
509 chaining_hints: false,
510 max_length: None,
511 },
512 r#"
513fn param_with_underscore(with_underscore: i32) -> i32 { with_underscore }
514fn main() {
515 let _x = param_with_underscore(
516 4,
517 );
518}"#,
519 );
520 }
521
522 #[test]
523 fn param_name_same_as_fn_name() {
524 check_with_config(
525 InlayHintsConfig {
526 parameter_hints: true,
527 type_hints: false,
528 chaining_hints: false,
529 max_length: None,
530 },
531 r#"
532fn foo(foo: i32) -> i32 { foo }
533fn main() {
534 let _x = foo(
535 4,
536 );
537}"#,
538 );
539 }
540
541 #[test]
542 fn never_hide_param_when_multiple_params() {
543 check_with_config(
544 InlayHintsConfig {
545 parameter_hints: true,
546 type_hints: false,
547 chaining_hints: false,
548 max_length: None,
549 },
550 r#"
551fn foo(bar: i32, baz: i32) -> i32 { bar + baz }
552fn main() {
553 let _x = foo(
554 4,
555 //^ bar
556 8,
557 //^ baz
558 );
559}"#,
560 );
561 }
562
563 #[test]
460 fn hints_disabled() { 564 fn hints_disabled() {
461 check_with_config( 565 check_with_config(
462 InlayHintsConfig { 566 InlayHintsConfig {
@@ -1235,4 +1339,25 @@ fn main() {
1235"#, 1339"#,
1236 ); 1340 );
1237 } 1341 }
1342
1343 #[test]
1344 fn infer_call_method_return_associated_types_with_generic() {
1345 check(
1346 r#"
1347 pub trait Default {
1348 fn default() -> Self;
1349 }
1350 pub trait Foo {
1351 type Bar: Default;
1352 }
1353
1354 pub fn quux<T: Foo>() -> T::Bar {
1355 let y = Default::default();
1356 //^ <T as Foo>::Bar
1357
1358 y
1359 }
1360 "#,
1361 );
1362 }
1238} 1363}
diff --git a/crates/ide/src/join_lines.rs b/crates/ide/src/join_lines.rs
index e37702acd..b5a6f66fd 100644
--- a/crates/ide/src/join_lines.rs
+++ b/crates/ide/src/join_lines.rs
@@ -18,7 +18,7 @@ use text_edit::{TextEdit, TextEditBuilder};
18// 18//
19// | VS Code | **Rust Analyzer: Join lines** 19// | VS Code | **Rust Analyzer: Join lines**
20// |=== 20// |===
21pub fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit { 21pub(crate) fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
22 let range = if range.is_empty() { 22 let range = if range.is_empty() {
23 let syntax = file.syntax(); 23 let syntax = file.syntax();
24 let text = syntax.text().slice(range.start()..); 24 let text = syntax.text().slice(range.start()..);
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs
index 4bc733b70..6288f7ea7 100644
--- a/crates/ide/src/lib.rs
+++ b/crates/ide/src/lib.rs
@@ -72,18 +72,20 @@ pub use crate::{
72 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind}, 72 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
73 markup::Markup, 73 markup::Markup,
74 prime_caches::PrimeCachesProgress, 74 prime_caches::PrimeCachesProgress,
75 references::{ 75 references::{rename::RenameError, Declaration, ReferenceSearchResult},
76 Declaration, Reference, ReferenceAccess, ReferenceKind, ReferenceSearchResult, RenameError,
77 },
78 runnables::{Runnable, RunnableKind, TestId}, 76 runnables::{Runnable, RunnableKind, TestId},
79 syntax_highlighting::{ 77 syntax_highlighting::{
80 Highlight, HighlightModifier, HighlightModifiers, HighlightTag, HighlightedRange, 78 tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag},
79 HighlightedRange,
81 }, 80 },
82}; 81};
83pub use completion::{ 82pub use completion::{
84 CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat, 83 CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat,
85}; 84};
86pub use ide_db::call_info::CallInfo; 85pub use ide_db::{
86 call_info::CallInfo,
87 search::{Reference, ReferenceAccess, ReferenceKind},
88};
87 89
88pub use assists::{ 90pub use assists::{
89 utils::MergeBehaviour, Assist, AssistConfig, AssistId, AssistKind, ResolvedAssist, 91 utils::MergeBehaviour, Assist, AssistConfig, AssistId, AssistKind, ResolvedAssist,
@@ -503,7 +505,7 @@ impl Analysis {
503 position: FilePosition, 505 position: FilePosition,
504 new_name: &str, 506 new_name: &str,
505 ) -> Cancelable<Result<RangeInfo<SourceChange>, RenameError>> { 507 ) -> Cancelable<Result<RangeInfo<SourceChange>, RenameError>> {
506 self.with_db(|db| references::rename(db, position, new_name)) 508 self.with_db(|db| references::rename::rename(db, position, new_name))
507 } 509 }
508 510
509 pub fn structural_search_replace( 511 pub fn structural_search_replace(
diff --git a/crates/ide/src/markdown_remove.rs b/crates/ide/src/markdown_remove.rs
index 02ad39dfb..3ec5c629e 100644
--- a/crates/ide/src/markdown_remove.rs
+++ b/crates/ide/src/markdown_remove.rs
@@ -1,11 +1,10 @@
1//! Removes markdown from strings. 1//! Removes markdown from strings.
2
3use pulldown_cmark::{Event, Parser, Tag}; 2use pulldown_cmark::{Event, Parser, Tag};
4 3
5/// Removes all markdown, keeping the text and code blocks 4/// Removes all markdown, keeping the text and code blocks
6/// 5///
7/// Currently limited in styling, i.e. no ascii tables or lists 6/// Currently limited in styling, i.e. no ascii tables or lists
8pub fn remove_markdown(markdown: &str) -> String { 7pub(crate) fn remove_markdown(markdown: &str) -> String {
9 let mut out = String::new(); 8 let mut out = String::new();
10 let parser = Parser::new(markdown); 9 let parser = Parser::new(markdown);
11 10
diff --git a/crates/ide/src/matching_brace.rs b/crates/ide/src/matching_brace.rs
index cb6abb0db..d70248afe 100644
--- a/crates/ide/src/matching_brace.rs
+++ b/crates/ide/src/matching_brace.rs
@@ -15,7 +15,7 @@ use test_utils::mark;
15// 15//
16// | VS Code | **Rust Analyzer: Find matching brace** 16// | VS Code | **Rust Analyzer: Find matching brace**
17// |=== 17// |===
18pub fn matching_brace(file: &SourceFile, offset: TextSize) -> Option<TextSize> { 18pub(crate) fn matching_brace(file: &SourceFile, offset: TextSize) -> Option<TextSize> {
19 const BRACES: &[SyntaxKind] = 19 const BRACES: &[SyntaxKind] =
20 &[T!['{'], T!['}'], T!['['], T![']'], T!['('], T![')'], T![<], T![>], T![|], T![|]]; 20 &[T!['{'], T!['}'], T!['['], T![']'], T!['('], T![')'], T![<], T![>], T![|], T![|]];
21 let (brace_token, brace_idx) = file 21 let (brace_token, brace_idx) = file
diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs
index a517081d5..e05465b32 100644
--- a/crates/ide/src/references.rs
+++ b/crates/ide/src/references.rs
@@ -14,7 +14,8 @@ pub(crate) mod rename;
14use hir::Semantics; 14use hir::Semantics;
15use ide_db::{ 15use ide_db::{
16 defs::{Definition, NameClass, NameRefClass}, 16 defs::{Definition, NameClass, NameRefClass},
17 search::SearchScope, 17 search::Reference,
18 search::{ReferenceAccess, ReferenceKind, SearchScope},
18 RootDatabase, 19 RootDatabase,
19}; 20};
20use syntax::{ 21use syntax::{
@@ -25,11 +26,6 @@ use syntax::{
25 26
26use crate::{display::TryToNav, FilePosition, FileRange, NavigationTarget, RangeInfo}; 27use crate::{display::TryToNav, FilePosition, FileRange, NavigationTarget, RangeInfo};
27 28
28pub(crate) use self::rename::rename;
29pub use self::rename::RenameError;
30
31pub use ide_db::search::{Reference, ReferenceAccess, ReferenceKind};
32
33#[derive(Debug, Clone)] 29#[derive(Debug, Clone)]
34pub struct ReferenceSearchResult { 30pub struct ReferenceSearchResult {
35 declaration: Declaration, 31 declaration: Declaration,
diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs
index eb82456ad..2bd0e86e5 100644
--- a/crates/ide/src/runnables.rs
+++ b/crates/ide/src/runnables.rs
@@ -102,6 +102,7 @@ pub(crate) fn runnable(
102) -> Option<Runnable> { 102) -> Option<Runnable> {
103 match_ast! { 103 match_ast! {
104 match item { 104 match item {
105 ast::Struct(it) => runnable_struct(sema, it, file_id),
105 ast::Fn(it) => runnable_fn(sema, it, file_id), 106 ast::Fn(it) => runnable_fn(sema, it, file_id),
106 ast::Module(it) => runnable_mod(sema, it, file_id), 107 ast::Module(it) => runnable_mod(sema, it, file_id),
107 _ => None, 108 _ => None,
@@ -182,6 +183,43 @@ fn runnable_fn(
182 Some(Runnable { nav, kind, cfg }) 183 Some(Runnable { nav, kind, cfg })
183} 184}
184 185
186fn runnable_struct(
187 sema: &Semantics<RootDatabase>,
188 struct_def: ast::Struct,
189 file_id: FileId,
190) -> Option<Runnable> {
191 if !has_runnable_doc_test(&struct_def) {
192 return None;
193 }
194 let name_string = struct_def.name()?.text().to_string();
195
196 let attrs =
197 Attrs::from_attrs_owner(sema.db, InFile::new(HirFileId::from(file_id), &struct_def));
198 let cfg = attrs.cfg();
199
200 let test_id = match sema.to_def(&struct_def).map(|def| def.module(sema.db)) {
201 Some(module) => {
202 let path_iter = module
203 .path_to_root(sema.db)
204 .into_iter()
205 .rev()
206 .filter_map(|it| it.name(sema.db))
207 .map(|name| name.to_string());
208 let path = path_iter.chain(std::iter::once(name_string)).join("::");
209
210 TestId::Path(path)
211 }
212 None => TestId::Name(name_string),
213 };
214
215 let nav = NavigationTarget::from_doc_commented(
216 sema.db,
217 InFile::new(file_id.into(), &struct_def),
218 InFile::new(file_id.into(), &struct_def),
219 );
220 Some(Runnable { nav, kind: RunnableKind::DocTest { test_id }, cfg })
221}
222
185#[derive(Debug, Copy, Clone)] 223#[derive(Debug, Copy, Clone)]
186pub struct TestAttr { 224pub struct TestAttr {
187 pub ignore: bool, 225 pub ignore: bool,
@@ -215,8 +253,8 @@ const RUSTDOC_FENCE: &str = "```";
215const RUSTDOC_CODE_BLOCK_ATTRIBUTES_RUNNABLE: &[&str] = 253const RUSTDOC_CODE_BLOCK_ATTRIBUTES_RUNNABLE: &[&str] =
216 &["", "rust", "should_panic", "edition2015", "edition2018"]; 254 &["", "rust", "should_panic", "edition2015", "edition2018"];
217 255
218fn has_runnable_doc_test(fn_def: &ast::Fn) -> bool { 256fn has_runnable_doc_test(def: &dyn DocCommentsOwner) -> bool {
219 fn_def.doc_comment_text().map_or(false, |comments_text| { 257 def.doc_comment_text().map_or(false, |comments_text| {
220 let mut in_code_block = false; 258 let mut in_code_block = false;
221 259
222 for line in comments_text.lines() { 260 for line in comments_text.lines() {
@@ -487,8 +525,14 @@ fn should_have_no_runnable_5() {}
487/// let z = 55; 525/// let z = 55;
488/// ``` 526/// ```
489fn should_have_no_runnable_6() {} 527fn should_have_no_runnable_6() {}
528
529/// ```
530/// let x = 5;
531/// ```
532struct StructWithRunnable(String);
533
490"#, 534"#,
491 &[&BIN, &DOCTEST, &DOCTEST, &DOCTEST], 535 &[&BIN, &DOCTEST, &DOCTEST, &DOCTEST, &DOCTEST],
492 expect![[r#" 536 expect![[r#"
493 [ 537 [
494 Runnable { 538 Runnable {
@@ -569,6 +613,26 @@ fn should_have_no_runnable_6() {}
569 }, 613 },
570 cfg: None, 614 cfg: None,
571 }, 615 },
616 Runnable {
617 nav: NavigationTarget {
618 file_id: FileId(
619 0,
620 ),
621 full_range: 756..821,
622 focus_range: None,
623 name: "StructWithRunnable",
624 kind: STRUCT,
625 container_name: None,
626 description: None,
627 docs: None,
628 },
629 kind: DocTest {
630 test_id: Path(
631 "StructWithRunnable",
632 ),
633 },
634 cfg: None,
635 },
572 ] 636 ]
573 "#]], 637 "#]],
574 ); 638 );
diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs
index 9f864179e..efcc8ecfe 100644
--- a/crates/ide/src/syntax_highlighting.rs
+++ b/crates/ide/src/syntax_highlighting.rs
@@ -2,7 +2,7 @@ mod format;
2mod html; 2mod html;
3mod injection; 3mod injection;
4mod macro_rules; 4mod macro_rules;
5mod tags; 5pub(crate) mod tags;
6#[cfg(test)] 6#[cfg(test)]
7mod tests; 7mod tests;
8 8
@@ -20,12 +20,13 @@ use syntax::{
20}; 20};
21 21
22use crate::{ 22use crate::{
23 syntax_highlighting::{format::FormatStringHighlighter, macro_rules::MacroRulesHighlighter}, 23 syntax_highlighting::{
24 FileId, 24 format::FormatStringHighlighter, macro_rules::MacroRulesHighlighter, tags::Highlight,
25 },
26 FileId, HighlightModifier, HighlightTag,
25}; 27};
26 28
27pub(crate) use html::highlight_as_html; 29pub(crate) use html::highlight_as_html;
28pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
29 30
30#[derive(Debug, Clone)] 31#[derive(Debug, Clone)]
31pub struct HighlightedRange { 32pub struct HighlightedRange {
@@ -562,6 +563,9 @@ fn highlight_element(
562 T![!] if element.parent().and_then(ast::MacroCall::cast).is_some() => { 563 T![!] if element.parent().and_then(ast::MacroCall::cast).is_some() => {
563 HighlightTag::Macro.into() 564 HighlightTag::Macro.into()
564 } 565 }
566 T![!] if element.parent().and_then(ast::NeverType::cast).is_some() => {
567 HighlightTag::BuiltinType.into()
568 }
565 T![*] if element.parent().and_then(ast::PtrType::cast).is_some() => { 569 T![*] if element.parent().and_then(ast::PtrType::cast).is_some() => {
566 HighlightTag::Keyword.into() 570 HighlightTag::Keyword.into()
567 } 571 }
diff --git a/crates/ide/src/syntax_highlighting/test_data/highlighting.html b/crates/ide/src/syntax_highlighting/test_data/highlighting.html
index c6b4f5a00..5eb222ee2 100644
--- a/crates/ide/src/syntax_highlighting/test_data/highlighting.html
+++ b/crates/ide/src/syntax_highlighting/test_data/highlighting.html
@@ -110,11 +110,21 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
110 <span class="function">foo</span><span class="operator">::</span><span class="punctuation">&lt;</span><span class="lifetime">'a</span><span class="punctuation">,</span> <span class="builtin_type">i32</span><span class="punctuation">&gt;</span><span class="punctuation">(</span><span class="punctuation">)</span> 110 <span class="function">foo</span><span class="operator">::</span><span class="punctuation">&lt;</span><span class="lifetime">'a</span><span class="punctuation">,</span> <span class="builtin_type">i32</span><span class="punctuation">&gt;</span><span class="punctuation">(</span><span class="punctuation">)</span>
111<span class="punctuation">}</span> 111<span class="punctuation">}</span>
112 112
113<span class="keyword">fn</span> <span class="function declaration">never</span><span class="punctuation">(</span><span class="punctuation">)</span> <span class="operator">-&gt;</span> <span class="builtin_type">!</span> <span class="punctuation">{</span>
114 <span class="keyword control">loop</span> <span class="punctuation">{</span><span class="punctuation">}</span>
115<span class="punctuation">}</span>
116
113<span class="keyword">use</span> <span class="module">ops</span><span class="operator">::</span><span class="trait">Fn</span><span class="punctuation">;</span> 117<span class="keyword">use</span> <span class="module">ops</span><span class="operator">::</span><span class="trait">Fn</span><span class="punctuation">;</span>
114<span class="keyword">fn</span> <span class="function declaration">baz</span><span class="punctuation">&lt;</span><span class="type_param declaration">F</span><span class="punctuation">:</span> <span class="trait">Fn</span><span class="punctuation">(</span><span class="punctuation">)</span> <span class="operator">-&gt;</span> <span class="punctuation">(</span><span class="punctuation">)</span><span class="punctuation">&gt;</span><span class="punctuation">(</span><span class="value_param declaration callable">f</span><span class="punctuation">:</span> <span class="type_param">F</span><span class="punctuation">)</span> <span class="punctuation">{</span> 118<span class="keyword">fn</span> <span class="function declaration">baz</span><span class="punctuation">&lt;</span><span class="type_param declaration">F</span><span class="punctuation">:</span> <span class="trait">Fn</span><span class="punctuation">(</span><span class="punctuation">)</span> <span class="operator">-&gt;</span> <span class="punctuation">(</span><span class="punctuation">)</span><span class="punctuation">&gt;</span><span class="punctuation">(</span><span class="value_param declaration callable">f</span><span class="punctuation">:</span> <span class="type_param">F</span><span class="punctuation">)</span> <span class="punctuation">{</span>
115 <span class="value_param callable">f</span><span class="punctuation">(</span><span class="punctuation">)</span> 119 <span class="value_param callable">f</span><span class="punctuation">(</span><span class="punctuation">)</span>
116<span class="punctuation">}</span> 120<span class="punctuation">}</span>
117 121
122<span class="keyword">fn</span> <span class="function declaration">foobar</span><span class="punctuation">(</span><span class="punctuation">)</span> <span class="operator">-&gt;</span> <span class="keyword">impl</span> <span class="unresolved_reference">Copy</span> <span class="punctuation">{</span><span class="punctuation">}</span>
123
124<span class="keyword">fn</span> <span class="function declaration">foo</span><span class="punctuation">(</span><span class="punctuation">)</span> <span class="punctuation">{</span>
125 <span class="keyword">let</span> <span class="variable declaration">bar</span> <span class="operator">=</span> <span class="function">foobar</span><span class="punctuation">(</span><span class="punctuation">)</span><span class="punctuation">;</span>
126<span class="punctuation">}</span>
127
118<span class="macro">macro_rules!</span> <span class="macro declaration">def_fn</span> <span class="punctuation">{</span> 128<span class="macro">macro_rules!</span> <span class="macro declaration">def_fn</span> <span class="punctuation">{</span>
119 <span class="punctuation">(</span><span class="punctuation">$</span><span class="punctuation">(</span><span class="punctuation">$</span>tt<span class="punctuation">:</span>tt<span class="punctuation">)</span><span class="punctuation">*</span><span class="punctuation">)</span> <span class="operator">=</span><span class="punctuation">&gt;</span> <span class="punctuation">{</span><span class="punctuation">$</span><span class="punctuation">(</span><span class="punctuation">$</span>tt<span class="punctuation">)</span><span class="punctuation">*</span><span class="punctuation">}</span> 129 <span class="punctuation">(</span><span class="punctuation">$</span><span class="punctuation">(</span><span class="punctuation">$</span>tt<span class="punctuation">:</span>tt<span class="punctuation">)</span><span class="punctuation">*</span><span class="punctuation">)</span> <span class="operator">=</span><span class="punctuation">&gt;</span> <span class="punctuation">{</span><span class="punctuation">$</span><span class="punctuation">(</span><span class="punctuation">$</span>tt<span class="punctuation">)</span><span class="punctuation">*</span><span class="punctuation">}</span>
120<span class="punctuation">}</span> 130<span class="punctuation">}</span>
@@ -179,6 +189,8 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
179 189
180 <span class="keyword">let</span> <span class="variable declaration">baz</span> <span class="operator">=</span> <span class="numeric_literal">-</span><span class="numeric_literal">42</span><span class="punctuation">;</span> 190 <span class="keyword">let</span> <span class="variable declaration">baz</span> <span class="operator">=</span> <span class="numeric_literal">-</span><span class="numeric_literal">42</span><span class="punctuation">;</span>
181 <span class="keyword">let</span> <span class="variable declaration">baz</span> <span class="operator">=</span> <span class="operator">-</span><span class="variable">baz</span><span class="punctuation">;</span> 191 <span class="keyword">let</span> <span class="variable declaration">baz</span> <span class="operator">=</span> <span class="operator">-</span><span class="variable">baz</span><span class="punctuation">;</span>
192
193 <span class="keyword">let</span> <span class="punctuation">_</span> <span class="operator">=</span> <span class="operator">!</span><span class="bool_literal">true</span><span class="punctuation">;</span>
182<span class="punctuation">}</span> 194<span class="punctuation">}</span>
183 195
184<span class="keyword">enum</span> <span class="enum declaration">Option</span><span class="punctuation">&lt;</span><span class="type_param declaration">T</span><span class="punctuation">&gt;</span> <span class="punctuation">{</span> 196<span class="keyword">enum</span> <span class="enum declaration">Option</span><span class="punctuation">&lt;</span><span class="type_param declaration">T</span><span class="punctuation">&gt;</span> <span class="punctuation">{</span>
diff --git a/crates/ide/src/syntax_highlighting/tests.rs b/crates/ide/src/syntax_highlighting/tests.rs
index dd43f9dd9..2b667b0d4 100644
--- a/crates/ide/src/syntax_highlighting/tests.rs
+++ b/crates/ide/src/syntax_highlighting/tests.rs
@@ -84,11 +84,21 @@ fn foo<'a, T>() -> T {
84 foo::<'a, i32>() 84 foo::<'a, i32>()
85} 85}
86 86
87fn never() -> ! {
88 loop {}
89}
90
87use ops::Fn; 91use ops::Fn;
88fn baz<F: Fn() -> ()>(f: F) { 92fn baz<F: Fn() -> ()>(f: F) {
89 f() 93 f()
90} 94}
91 95
96fn foobar() -> impl Copy {}
97
98fn foo() {
99 let bar = foobar();
100}
101
92macro_rules! def_fn { 102macro_rules! def_fn {
93 ($($tt:tt)*) => {$($tt)*} 103 ($($tt:tt)*) => {$($tt)*}
94} 104}
@@ -153,6 +163,8 @@ fn main() {
153 163
154 let baz = -42; 164 let baz = -42;
155 let baz = -baz; 165 let baz = -baz;
166
167 let _ = !true;
156} 168}
157 169
158enum Option<T> { 170enum Option<T> {
diff --git a/crates/mbe/src/mbe_expander/matcher.rs b/crates/mbe/src/mbe_expander/matcher.rs
index b698b9832..39a8eefbd 100644
--- a/crates/mbe/src/mbe_expander/matcher.rs
+++ b/crates/mbe/src/mbe_expander/matcher.rs
@@ -61,16 +61,16 @@ macro_rules! err {
61 61
62#[derive(Debug, Default)] 62#[derive(Debug, Default)]
63pub(super) struct Match { 63pub(super) struct Match {
64 pub bindings: Bindings, 64 pub(super) bindings: Bindings,
65 /// We currently just keep the first error and count the rest to compare matches. 65 /// We currently just keep the first error and count the rest to compare matches.
66 pub err: Option<ExpandError>, 66 pub(super) err: Option<ExpandError>,
67 pub err_count: usize, 67 pub(super) err_count: usize,
68 /// How many top-level token trees were left to match. 68 /// How many top-level token trees were left to match.
69 pub unmatched_tts: usize, 69 pub(super) unmatched_tts: usize,
70} 70}
71 71
72impl Match { 72impl Match {
73 pub fn add_err(&mut self, err: ExpandError) { 73 pub(super) fn add_err(&mut self, err: ExpandError) {
74 let prev_err = self.err.take(); 74 let prev_err = self.err.take();
75 self.err = prev_err.or(Some(err)); 75 self.err = prev_err.or(Some(err));
76 self.err_count += 1; 76 self.err_count += 1;
diff --git a/crates/mbe/src/subtree_source.rs b/crates/mbe/src/subtree_source.rs
index 396ce8b16..ccc56c479 100644
--- a/crates/mbe/src/subtree_source.rs
+++ b/crates/mbe/src/subtree_source.rs
@@ -7,9 +7,9 @@ use tt::buffer::{Cursor, TokenBuffer};
7 7
8#[derive(Debug, Clone, Eq, PartialEq)] 8#[derive(Debug, Clone, Eq, PartialEq)]
9struct TtToken { 9struct TtToken {
10 pub kind: SyntaxKind, 10 kind: SyntaxKind,
11 pub is_joint_to_next: bool, 11 is_joint_to_next: bool,
12 pub text: SmolStr, 12 text: SmolStr,
13} 13}
14 14
15pub(crate) struct SubtreeTokenSource<'a> { 15pub(crate) struct SubtreeTokenSource<'a> {
@@ -21,7 +21,7 @@ pub(crate) struct SubtreeTokenSource<'a> {
21impl<'a> SubtreeTokenSource<'a> { 21impl<'a> SubtreeTokenSource<'a> {
22 // Helper function used in test 22 // Helper function used in test
23 #[cfg(test)] 23 #[cfg(test)]
24 pub fn text(&self) -> SmolStr { 24 pub(crate) fn text(&self) -> SmolStr {
25 match *self.get(self.curr.1) { 25 match *self.get(self.curr.1) {
26 Some(ref tt) => tt.text.clone(), 26 Some(ref tt) => tt.text.clone(),
27 _ => SmolStr::new(""), 27 _ => SmolStr::new(""),
@@ -30,7 +30,7 @@ impl<'a> SubtreeTokenSource<'a> {
30} 30}
31 31
32impl<'a> SubtreeTokenSource<'a> { 32impl<'a> SubtreeTokenSource<'a> {
33 pub fn new(buffer: &'a TokenBuffer) -> SubtreeTokenSource<'a> { 33 pub(crate) fn new(buffer: &'a TokenBuffer) -> SubtreeTokenSource<'a> {
34 let cursor = buffer.begin(); 34 let cursor = buffer.begin();
35 35
36 let mut res = SubtreeTokenSource { 36 let mut res = SubtreeTokenSource {
diff --git a/crates/parser/src/grammar.rs b/crates/parser/src/grammar.rs
index 562e92252..4ab206a83 100644
--- a/crates/parser/src/grammar.rs
+++ b/crates/parser/src/grammar.rs
@@ -184,7 +184,11 @@ fn opt_visibility(p: &mut Parser) -> bool {
184 // pub(self) struct S; 184 // pub(self) struct S;
185 // pub(self) struct S; 185 // pub(self) struct S;
186 // pub(self) struct S; 186 // pub(self) struct S;
187 T![crate] | T![self] | T![super] => { 187
188 // test pub_parens_typepath
189 // struct B(pub (super::A));
190 // struct B(pub (crate::A,));
191 T![crate] | T![self] | T![super] if p.nth(2) != T![:] => {
188 p.bump_any(); 192 p.bump_any();
189 p.bump_any(); 193 p.bump_any();
190 p.expect(T![')']); 194 p.expect(T![')']);
diff --git a/crates/proc_macro_api/src/process.rs b/crates/proc_macro_api/src/process.rs
index 51ffcaa78..907cb3db7 100644
--- a/crates/proc_macro_api/src/process.rs
+++ b/crates/proc_macro_api/src/process.rs
@@ -30,7 +30,7 @@ pub(crate) struct ProcMacroProcessThread {
30} 30}
31 31
32impl ProcMacroProcessSrv { 32impl ProcMacroProcessSrv {
33 pub fn run( 33 pub(crate) fn run(
34 process_path: PathBuf, 34 process_path: PathBuf,
35 args: impl IntoIterator<Item = impl AsRef<OsStr>>, 35 args: impl IntoIterator<Item = impl AsRef<OsStr>>,
36 ) -> io::Result<(ProcMacroProcessThread, ProcMacroProcessSrv)> { 36 ) -> io::Result<(ProcMacroProcessThread, ProcMacroProcessSrv)> {
@@ -48,7 +48,7 @@ impl ProcMacroProcessSrv {
48 Ok((thread, srv)) 48 Ok((thread, srv))
49 } 49 }
50 50
51 pub fn find_proc_macros( 51 pub(crate) fn find_proc_macros(
52 &self, 52 &self,
53 dylib_path: &Path, 53 dylib_path: &Path,
54 ) -> Result<Vec<(String, ProcMacroKind)>, tt::ExpansionError> { 54 ) -> Result<Vec<(String, ProcMacroKind)>, tt::ExpansionError> {
@@ -58,7 +58,7 @@ impl ProcMacroProcessSrv {
58 Ok(result.macros) 58 Ok(result.macros)
59 } 59 }
60 60
61 pub fn custom_derive( 61 pub(crate) fn custom_derive(
62 &self, 62 &self,
63 dylib_path: &Path, 63 dylib_path: &Path,
64 subtree: &Subtree, 64 subtree: &Subtree,
@@ -75,7 +75,7 @@ impl ProcMacroProcessSrv {
75 Ok(result.expansion) 75 Ok(result.expansion)
76 } 76 }
77 77
78 pub fn send_task<R>(&self, req: Request) -> Result<R, tt::ExpansionError> 78 pub(crate) fn send_task<R>(&self, req: Request) -> Result<R, tt::ExpansionError>
79 where 79 where
80 R: TryFrom<Response, Error = &'static str>, 80 R: TryFrom<Response, Error = &'static str>,
81 { 81 {
diff --git a/crates/proc_macro_api/src/rpc.rs b/crates/proc_macro_api/src/rpc.rs
index 47624163e..203109ca4 100644
--- a/crates/proc_macro_api/src/rpc.rs
+++ b/crates/proc_macro_api/src/rpc.rs
@@ -75,18 +75,18 @@ struct TokenIdDef(u32);
75#[serde(remote = "Delimiter")] 75#[serde(remote = "Delimiter")]
76struct DelimiterDef { 76struct DelimiterDef {
77 #[serde(with = "TokenIdDef")] 77 #[serde(with = "TokenIdDef")]
78 pub id: TokenId, 78 id: TokenId,
79 #[serde(with = "DelimiterKindDef")] 79 #[serde(with = "DelimiterKindDef")]
80 pub kind: DelimiterKind, 80 kind: DelimiterKind,
81} 81}
82 82
83#[derive(Serialize, Deserialize)] 83#[derive(Serialize, Deserialize)]
84#[serde(remote = "Subtree")] 84#[serde(remote = "Subtree")]
85struct SubtreeDef { 85struct SubtreeDef {
86 #[serde(default, with = "opt_delimiter_def")] 86 #[serde(default, with = "opt_delimiter_def")]
87 pub delimiter: Option<Delimiter>, 87 delimiter: Option<Delimiter>,
88 #[serde(with = "vec_token_tree")] 88 #[serde(with = "vec_token_tree")]
89 pub token_trees: Vec<TokenTree>, 89 token_trees: Vec<TokenTree>,
90} 90}
91 91
92#[derive(Serialize, Deserialize)] 92#[derive(Serialize, Deserialize)]
@@ -112,19 +112,19 @@ enum LeafDef {
112#[derive(Serialize, Deserialize)] 112#[derive(Serialize, Deserialize)]
113#[serde(remote = "Literal")] 113#[serde(remote = "Literal")]
114struct LiteralDef { 114struct LiteralDef {
115 pub text: SmolStr, 115 text: SmolStr,
116 #[serde(with = "TokenIdDef")] 116 #[serde(with = "TokenIdDef")]
117 pub id: TokenId, 117 id: TokenId,
118} 118}
119 119
120#[derive(Serialize, Deserialize)] 120#[derive(Serialize, Deserialize)]
121#[serde(remote = "Punct")] 121#[serde(remote = "Punct")]
122struct PunctDef { 122struct PunctDef {
123 pub char: char, 123 char: char,
124 #[serde(with = "SpacingDef")] 124 #[serde(with = "SpacingDef")]
125 pub spacing: Spacing, 125 spacing: Spacing,
126 #[serde(with = "TokenIdDef")] 126 #[serde(with = "TokenIdDef")]
127 pub id: TokenId, 127 id: TokenId,
128} 128}
129 129
130#[derive(Serialize, Deserialize)] 130#[derive(Serialize, Deserialize)]
@@ -137,16 +137,16 @@ enum SpacingDef {
137#[derive(Serialize, Deserialize)] 137#[derive(Serialize, Deserialize)]
138#[serde(remote = "Ident")] 138#[serde(remote = "Ident")]
139struct IdentDef { 139struct IdentDef {
140 pub text: SmolStr, 140 text: SmolStr,
141 #[serde(with = "TokenIdDef")] 141 #[serde(with = "TokenIdDef")]
142 pub id: TokenId, 142 id: TokenId,
143} 143}
144 144
145mod opt_delimiter_def { 145mod opt_delimiter_def {
146 use super::{Delimiter, DelimiterDef}; 146 use super::{Delimiter, DelimiterDef};
147 use serde::{Deserialize, Deserializer, Serialize, Serializer}; 147 use serde::{Deserialize, Deserializer, Serialize, Serializer};
148 148
149 pub fn serialize<S>(value: &Option<Delimiter>, serializer: S) -> Result<S::Ok, S::Error> 149 pub(super) fn serialize<S>(value: &Option<Delimiter>, serializer: S) -> Result<S::Ok, S::Error>
150 where 150 where
151 S: Serializer, 151 S: Serializer,
152 { 152 {
@@ -155,7 +155,7 @@ mod opt_delimiter_def {
155 value.as_ref().map(Helper).serialize(serializer) 155 value.as_ref().map(Helper).serialize(serializer)
156 } 156 }
157 157
158 pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Delimiter>, D::Error> 158 pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<Option<Delimiter>, D::Error>
159 where 159 where
160 D: Deserializer<'de>, 160 D: Deserializer<'de>,
161 { 161 {
@@ -170,7 +170,7 @@ mod opt_subtree_def {
170 use super::{Subtree, SubtreeDef}; 170 use super::{Subtree, SubtreeDef};
171 use serde::{Deserialize, Deserializer, Serialize, Serializer}; 171 use serde::{Deserialize, Deserializer, Serialize, Serializer};
172 172
173 pub fn serialize<S>(value: &Option<Subtree>, serializer: S) -> Result<S::Ok, S::Error> 173 pub(super) fn serialize<S>(value: &Option<Subtree>, serializer: S) -> Result<S::Ok, S::Error>
174 where 174 where
175 S: Serializer, 175 S: Serializer,
176 { 176 {
@@ -179,7 +179,7 @@ mod opt_subtree_def {
179 value.as_ref().map(Helper).serialize(serializer) 179 value.as_ref().map(Helper).serialize(serializer)
180 } 180 }
181 181
182 pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Subtree>, D::Error> 182 pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<Option<Subtree>, D::Error>
183 where 183 where
184 D: Deserializer<'de>, 184 D: Deserializer<'de>,
185 { 185 {
@@ -194,7 +194,7 @@ mod vec_token_tree {
194 use super::{TokenTree, TokenTreeDef}; 194 use super::{TokenTree, TokenTreeDef};
195 use serde::{ser::SerializeSeq, Deserialize, Deserializer, Serialize, Serializer}; 195 use serde::{ser::SerializeSeq, Deserialize, Deserializer, Serialize, Serializer};
196 196
197 pub fn serialize<S>(value: &Vec<TokenTree>, serializer: S) -> Result<S::Ok, S::Error> 197 pub(super) fn serialize<S>(value: &Vec<TokenTree>, serializer: S) -> Result<S::Ok, S::Error>
198 where 198 where
199 S: Serializer, 199 S: Serializer,
200 { 200 {
@@ -209,7 +209,7 @@ mod vec_token_tree {
209 seq.end() 209 seq.end()
210 } 210 }
211 211
212 pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<TokenTree>, D::Error> 212 pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<TokenTree>, D::Error>
213 where 213 where
214 D: Deserializer<'de>, 214 D: Deserializer<'de>,
215 { 215 {
diff --git a/crates/proc_macro_srv/src/lib.rs b/crates/proc_macro_srv/src/lib.rs
index 7e4e4ad50..6e890f8e2 100644
--- a/crates/proc_macro_srv/src/lib.rs
+++ b/crates/proc_macro_srv/src/lib.rs
@@ -9,6 +9,7 @@
9//! RA than `proc-macro2` token stream. 9//! RA than `proc-macro2` token stream.
10//! * By **copying** the whole rustc `lib_proc_macro` code, we are able to build this with `stable` 10//! * By **copying** the whole rustc `lib_proc_macro` code, we are able to build this with `stable`
11//! rustc rather than `unstable`. (Although in general ABI compatibility is still an issue)… 11//! rustc rather than `unstable`. (Although in general ABI compatibility is still an issue)…
12#![allow(unreachable_pub)]
12 13
13#[allow(dead_code)] 14#[allow(dead_code)]
14#[doc(hidden)] 15#[doc(hidden)]
diff --git a/crates/profile/src/hprof.rs b/crates/profile/src/hprof.rs
index 934cc8e37..8957ea016 100644
--- a/crates/profile/src/hprof.rs
+++ b/crates/profile/src/hprof.rs
@@ -27,7 +27,7 @@ pub fn init_from(spec: &str) {
27 filter.install(); 27 filter.install();
28} 28}
29 29
30pub type Label = &'static str; 30type Label = &'static str;
31 31
32/// This function starts a profiling scope in the current execution stack with a given description. 32/// This function starts a profiling scope in the current execution stack with a given description.
33/// It returns a `Profile` struct that measures elapsed time between this method invocation and `Profile` struct drop. 33/// It returns a `Profile` struct that measures elapsed time between this method invocation and `Profile` struct drop.
@@ -173,7 +173,7 @@ impl ProfileStack {
173 true 173 true
174 } 174 }
175 175
176 pub fn pop(&mut self, label: Label, detail: Option<String>) { 176 fn pop(&mut self, label: Label, detail: Option<String>) {
177 let start = self.starts.pop().unwrap(); 177 let start = self.starts.pop().unwrap();
178 let duration = start.elapsed(); 178 let duration = start.elapsed();
179 self.messages.finish(Message { duration, label, detail }); 179 self.messages.finish(Message { duration, label, detail });
diff --git a/crates/profile/src/tree.rs b/crates/profile/src/tree.rs
index 096f58511..3fac1f36c 100644
--- a/crates/profile/src/tree.rs
+++ b/crates/profile/src/tree.rs
@@ -4,15 +4,15 @@ use std::ops;
4use arena::Arena; 4use arena::Arena;
5 5
6#[derive(Default)] 6#[derive(Default)]
7pub struct Tree<T> { 7pub(crate) struct Tree<T> {
8 nodes: Arena<Node<T>>, 8 nodes: Arena<Node<T>>,
9 current_path: Vec<(Idx<T>, Option<Idx<T>>)>, 9 current_path: Vec<(Idx<T>, Option<Idx<T>>)>,
10} 10}
11 11
12pub type Idx<T> = arena::Idx<Node<T>>; 12pub(crate) type Idx<T> = arena::Idx<Node<T>>;
13 13
14impl<T> Tree<T> { 14impl<T> Tree<T> {
15 pub fn start(&mut self) 15 pub(crate) fn start(&mut self)
16 where 16 where
17 T: Default, 17 T: Default,
18 { 18 {
@@ -30,19 +30,19 @@ impl<T> Tree<T> {
30 self.current_path.push((me, None)); 30 self.current_path.push((me, None));
31 } 31 }
32 32
33 pub fn finish(&mut self, data: T) { 33 pub(crate) fn finish(&mut self, data: T) {
34 let (me, _last_child) = self.current_path.pop().unwrap(); 34 let (me, _last_child) = self.current_path.pop().unwrap();
35 self.nodes[me].data = data; 35 self.nodes[me].data = data;
36 } 36 }
37 37
38 pub fn root(&self) -> Option<Idx<T>> { 38 pub(crate) fn root(&self) -> Option<Idx<T>> {
39 self.nodes.iter().next().map(|(idx, _)| idx) 39 self.nodes.iter().next().map(|(idx, _)| idx)
40 } 40 }
41 41
42 pub fn children(&self, idx: Idx<T>) -> impl Iterator<Item = Idx<T>> + '_ { 42 pub(crate) fn children(&self, idx: Idx<T>) -> impl Iterator<Item = Idx<T>> + '_ {
43 NodeIter { nodes: &self.nodes, next: self.nodes[idx].first_child } 43 NodeIter { nodes: &self.nodes, next: self.nodes[idx].first_child }
44 } 44 }
45 pub fn clear(&mut self) { 45 pub(crate) fn clear(&mut self) {
46 self.nodes.clear(); 46 self.nodes.clear();
47 self.current_path.clear(); 47 self.current_path.clear();
48 } 48 }
@@ -55,7 +55,7 @@ impl<T> ops::Index<Idx<T>> for Tree<T> {
55 } 55 }
56} 56}
57 57
58pub struct Node<T> { 58pub(crate) struct Node<T> {
59 data: T, 59 data: T,
60 first_child: Option<Idx<T>>, 60 first_child: Option<Idx<T>>,
61 next_sibling: Option<Idx<T>>, 61 next_sibling: Option<Idx<T>>,
diff --git a/crates/project_model/src/cargo_workspace.rs b/crates/project_model/src/cargo_workspace.rs
index e5c2d2b25..d5f6a4025 100644
--- a/crates/project_model/src/cargo_workspace.rs
+++ b/crates/project_model/src/cargo_workspace.rs
@@ -278,13 +278,13 @@ impl CargoWorkspace {
278} 278}
279 279
280#[derive(Debug, Clone, Default)] 280#[derive(Debug, Clone, Default)]
281pub struct ExternResources { 281pub(crate) struct ExternResources {
282 out_dirs: FxHashMap<PackageId, AbsPathBuf>, 282 out_dirs: FxHashMap<PackageId, AbsPathBuf>,
283 proc_dylib_paths: FxHashMap<PackageId, AbsPathBuf>, 283 proc_dylib_paths: FxHashMap<PackageId, AbsPathBuf>,
284 cfgs: FxHashMap<PackageId, Vec<CfgFlag>>, 284 cfgs: FxHashMap<PackageId, Vec<CfgFlag>>,
285} 285}
286 286
287pub fn load_extern_resources( 287pub(crate) fn load_extern_resources(
288 cargo_toml: &Path, 288 cargo_toml: &Path,
289 cargo_features: &CargoConfig, 289 cargo_features: &CargoConfig,
290) -> Result<ExternResources> { 290) -> Result<ExternResources> {
diff --git a/crates/project_model/src/sysroot.rs b/crates/project_model/src/sysroot.rs
index b2ff98a15..3fe494729 100644
--- a/crates/project_model/src/sysroot.rs
+++ b/crates/project_model/src/sysroot.rs
@@ -17,7 +17,7 @@ pub struct Sysroot {
17 crates: Arena<SysrootCrateData>, 17 crates: Arena<SysrootCrateData>,
18} 18}
19 19
20pub type SysrootCrate = Idx<SysrootCrateData>; 20pub(crate) type SysrootCrate = Idx<SysrootCrateData>;
21 21
22#[derive(Debug, Clone, Eq, PartialEq)] 22#[derive(Debug, Clone, Eq, PartialEq)]
23pub struct SysrootCrateData { 23pub struct SysrootCrateData {
@@ -60,9 +60,7 @@ impl Sysroot {
60 let mut sysroot = Sysroot { crates: Arena::default() }; 60 let mut sysroot = Sysroot { crates: Arena::default() };
61 61
62 for name in SYSROOT_CRATES.trim().lines() { 62 for name in SYSROOT_CRATES.trim().lines() {
63 // FIXME: first path when 1.47 comes out 63 let root = [format!("{}/src/lib.rs", name), format!("lib{}/lib.rs", name)]
64 // https://github.com/rust-lang/rust/pull/73265
65 let root = [format!("lib{}/lib.rs", name), format!("{}/src/lib.rs", name)]
66 .iter() 64 .iter()
67 .map(|it| sysroot_src_dir.join(it)) 65 .map(|it| sysroot_src_dir.join(it))
68 .find(|it| it.exists()); 66 .find(|it| it.exists());
@@ -149,9 +147,6 @@ try running `rustup component add rust-src` or set `RUST_SRC_PATH`",
149 147
150fn get_rust_src(sysroot_path: &AbsPath) -> Option<AbsPathBuf> { 148fn get_rust_src(sysroot_path: &AbsPath) -> Option<AbsPathBuf> {
151 // Try the new path first since the old one still exists. 149 // Try the new path first since the old one still exists.
152 //
153 // FIXME: remove `src` when 1.47 comes out
154 // https://github.com/rust-lang/rust/pull/73265
155 let rust_src = sysroot_path.join("lib/rustlib/src/rust"); 150 let rust_src = sysroot_path.join("lib/rustlib/src/rust");
156 log::debug!("Checking sysroot (looking for `library` and `src` dirs): {}", rust_src.display()); 151 log::debug!("Checking sysroot (looking for `library` and `src` dirs): {}", rust_src.display());
157 ["library", "src"].iter().map(|it| rust_src.join(it)).find(|it| it.exists()) 152 ["library", "src"].iter().map(|it| rust_src.join(it)).find(|it| it.exists())
diff --git a/crates/rust-analyzer/Cargo.toml b/crates/rust-analyzer/Cargo.toml
index 975b24aaf..d25c4bf83 100644
--- a/crates/rust-analyzer/Cargo.toml
+++ b/crates/rust-analyzer/Cargo.toml
@@ -21,7 +21,7 @@ env_logger = { version = "0.8.1", default-features = false }
21itertools = "0.9.0" 21itertools = "0.9.0"
22jod-thread = "0.1.0" 22jod-thread = "0.1.0"
23log = "0.4.8" 23log = "0.4.8"
24lsp-types = { version = "0.82.0", features = ["proposed"] } 24lsp-types = { version = "0.83.0", features = ["proposed"] }
25parking_lot = "0.11.0" 25parking_lot = "0.11.0"
26pico-args = "0.3.1" 26pico-args = "0.3.1"
27oorandom = "11.1.2" 27oorandom = "11.1.2"
diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs
index 4175e569e..21fba8302 100644
--- a/crates/rust-analyzer/src/bin/main.rs
+++ b/crates/rust-analyzer/src/bin/main.rs
@@ -81,7 +81,7 @@ mod tracing_setup {
81 use tracing_subscriber::Registry; 81 use tracing_subscriber::Registry;
82 use tracing_tree::HierarchicalLayer; 82 use tracing_tree::HierarchicalLayer;
83 83
84 pub fn setup_tracing() -> super::Result<()> { 84 pub(crate) fn setup_tracing() -> super::Result<()> {
85 let filter = EnvFilter::from_env("CHALK_DEBUG"); 85 let filter = EnvFilter::from_env("CHALK_DEBUG");
86 let layer = HierarchicalLayer::default() 86 let layer = HierarchicalLayer::default()
87 .with_indent_lines(true) 87 .with_indent_lines(true)
diff --git a/crates/rust-analyzer/src/caps.rs b/crates/rust-analyzer/src/caps.rs
index c589afeaf..ff1ae9575 100644
--- a/crates/rust-analyzer/src/caps.rs
+++ b/crates/rust-analyzer/src/caps.rs
@@ -48,7 +48,7 @@ pub fn server_capabilities(client_caps: &ClientCapabilities) -> ServerCapabiliti
48 references_provider: Some(OneOf::Left(true)), 48 references_provider: Some(OneOf::Left(true)),
49 document_highlight_provider: Some(OneOf::Left(true)), 49 document_highlight_provider: Some(OneOf::Left(true)),
50 document_symbol_provider: Some(OneOf::Left(true)), 50 document_symbol_provider: Some(OneOf::Left(true)),
51 workspace_symbol_provider: Some(true), 51 workspace_symbol_provider: Some(OneOf::Left(true)),
52 code_action_provider: Some(code_action_provider), 52 code_action_provider: Some(code_action_provider),
53 code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(true) }), 53 code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(true) }),
54 document_formatting_provider: Some(OneOf::Left(true)), 54 document_formatting_provider: Some(OneOf::Left(true)),
@@ -113,6 +113,7 @@ fn code_action_capabilities(client_caps: &ClientCapabilities) -> CodeActionProvi
113 CodeActionKind::REFACTOR_INLINE, 113 CodeActionKind::REFACTOR_INLINE,
114 CodeActionKind::REFACTOR_REWRITE, 114 CodeActionKind::REFACTOR_REWRITE,
115 ]), 115 ]),
116 resolve_provider: None,
116 work_done_progress_options: Default::default(), 117 work_done_progress_options: Default::default(),
117 }) 118 })
118 }) 119 })
diff --git a/crates/rust-analyzer/src/cli/progress_report.rs b/crates/rust-analyzer/src/cli/progress_report.rs
index 31867a1e9..bdbe565e6 100644
--- a/crates/rust-analyzer/src/cli/progress_report.rs
+++ b/crates/rust-analyzer/src/cli/progress_report.rs
@@ -4,7 +4,7 @@
4use std::io::Write; 4use std::io::Write;
5 5
6/// A Simple ASCII Progress Bar 6/// A Simple ASCII Progress Bar
7pub struct ProgressReport { 7pub(crate) struct ProgressReport {
8 curr: f32, 8 curr: f32,
9 text: String, 9 text: String,
10 hidden: bool, 10 hidden: bool,
@@ -15,7 +15,7 @@ pub struct ProgressReport {
15} 15}
16 16
17impl ProgressReport { 17impl ProgressReport {
18 pub fn new(len: u64) -> ProgressReport { 18 pub(crate) fn new(len: u64) -> ProgressReport {
19 ProgressReport { 19 ProgressReport {
20 curr: 0.0, 20 curr: 0.0,
21 text: String::new(), 21 text: String::new(),
@@ -26,7 +26,7 @@ impl ProgressReport {
26 } 26 }
27 } 27 }
28 28
29 pub fn hidden() -> ProgressReport { 29 pub(crate) fn hidden() -> ProgressReport {
30 ProgressReport { 30 ProgressReport {
31 curr: 0.0, 31 curr: 0.0,
32 text: String::new(), 32 text: String::new(),
@@ -37,18 +37,18 @@ impl ProgressReport {
37 } 37 }
38 } 38 }
39 39
40 pub fn set_message(&mut self, msg: &str) { 40 pub(crate) fn set_message(&mut self, msg: &str) {
41 self.msg = msg.to_string(); 41 self.msg = msg.to_string();
42 self.tick(); 42 self.tick();
43 } 43 }
44 44
45 pub fn println<I: Into<String>>(&mut self, msg: I) { 45 pub(crate) fn println<I: Into<String>>(&mut self, msg: I) {
46 self.clear(); 46 self.clear();
47 println!("{}", msg.into()); 47 println!("{}", msg.into());
48 self.tick(); 48 self.tick();
49 } 49 }
50 50
51 pub fn inc(&mut self, delta: u64) { 51 pub(crate) fn inc(&mut self, delta: u64) {
52 self.pos += delta; 52 self.pos += delta;
53 if self.len == 0 { 53 if self.len == 0 {
54 self.set_value(0.0) 54 self.set_value(0.0)
@@ -58,11 +58,11 @@ impl ProgressReport {
58 self.tick(); 58 self.tick();
59 } 59 }
60 60
61 pub fn finish_and_clear(&mut self) { 61 pub(crate) fn finish_and_clear(&mut self) {
62 self.clear(); 62 self.clear();
63 } 63 }
64 64
65 pub fn tick(&mut self) { 65 pub(crate) fn tick(&mut self) {
66 if self.hidden { 66 if self.hidden {
67 return; 67 return;
68 } 68 }
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs
index 1b9b24698..2ed6a0d82 100644
--- a/crates/rust-analyzer/src/config.rs
+++ b/crates/rust-analyzer/src/config.rs
@@ -47,6 +47,7 @@ pub struct Config {
47 pub call_info_full: bool, 47 pub call_info_full: bool,
48 pub lens: LensConfig, 48 pub lens: LensConfig,
49 pub hover: HoverConfig, 49 pub hover: HoverConfig,
50 pub semantic_tokens_refresh: bool,
50 51
51 pub with_sysroot: bool, 52 pub with_sysroot: bool,
52 pub linked_projects: Vec<LinkedProject>, 53 pub linked_projects: Vec<LinkedProject>,
@@ -193,6 +194,7 @@ impl Config {
193 call_info_full: true, 194 call_info_full: true,
194 lens: LensConfig::default(), 195 lens: LensConfig::default(),
195 hover: HoverConfig::default(), 196 hover: HoverConfig::default(),
197 semantic_tokens_refresh: false,
196 linked_projects: Vec::new(), 198 linked_projects: Vec::new(),
197 root_path, 199 root_path,
198 } 200 }
@@ -402,6 +404,14 @@ impl Config {
402 self.client_caps.hover_actions = get_bool("hoverActions"); 404 self.client_caps.hover_actions = get_bool("hoverActions");
403 self.client_caps.status_notification = get_bool("statusNotification"); 405 self.client_caps.status_notification = get_bool("statusNotification");
404 } 406 }
407
408 if let Some(workspace_caps) = caps.workspace.as_ref() {
409 if let Some(refresh_support) =
410 workspace_caps.semantic_tokens.as_ref().and_then(|it| it.refresh_support)
411 {
412 self.semantic_tokens_refresh = refresh_support;
413 }
414 }
405 } 415 }
406} 416}
407 417
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt b/crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt
index d06517126..58d47d32a 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/clippy_pass_by_ref.txt
@@ -20,6 +20,7 @@
20 "trivially_copy_pass_by_ref", 20 "trivially_copy_pass_by_ref",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "clippy", 25 "clippy",
25 ), 26 ),
@@ -61,6 +62,7 @@
61 ], 62 ],
62 ), 63 ),
63 tags: None, 64 tags: None,
65 data: None,
64 }, 66 },
65 fixes: [], 67 fixes: [],
66 }, 68 },
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt b/crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt
index f5de2f07f..6aa26bf63 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/handles_macro_location.txt
@@ -20,12 +20,14 @@
20 "E0277", 20 "E0277",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "rustc", 25 "rustc",
25 ), 26 ),
26 message: "can\'t compare `{integer}` with `&str`\nthe trait `std::cmp::PartialEq<&str>` is not implemented for `{integer}`", 27 message: "can\'t compare `{integer}` with `&str`\nthe trait `std::cmp::PartialEq<&str>` is not implemented for `{integer}`",
27 related_information: None, 28 related_information: None,
28 tags: None, 29 tags: None,
30 data: None,
29 }, 31 },
30 fixes: [], 32 fixes: [],
31 }, 33 },
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt b/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt
index 00e8da8a7..7aaffaba2 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/macro_compiler_error.txt
@@ -16,6 +16,7 @@
16 Error, 16 Error,
17 ), 17 ),
18 code: None, 18 code: None,
19 code_description: None,
19 source: Some( 20 source: Some(
20 "rustc", 21 "rustc",
21 ), 22 ),
@@ -41,6 +42,7 @@
41 ], 42 ],
42 ), 43 ),
43 tags: None, 44 tags: None,
45 data: None,
44 }, 46 },
45 fixes: [], 47 fixes: [],
46 }, 48 },
@@ -61,6 +63,7 @@
61 Error, 63 Error,
62 ), 64 ),
63 code: None, 65 code: None,
66 code_description: None,
64 source: Some( 67 source: Some(
65 "rustc", 68 "rustc",
66 ), 69 ),
@@ -86,6 +89,7 @@
86 ], 89 ],
87 ), 90 ),
88 tags: None, 91 tags: None,
92 data: None,
89 }, 93 },
90 fixes: [], 94 fixes: [],
91 }, 95 },
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt
index fc54440be..584213420 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_incompatible_type_for_trait.txt
@@ -20,12 +20,14 @@
20 "E0053", 20 "E0053",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "rustc", 25 "rustc",
25 ), 26 ),
26 message: "method `next` has an incompatible type for trait\nexpected type `fn(&mut ty::list_iter::ListIterator<\'list, M>) -> std::option::Option<&ty::Ref<M>>`\n found type `fn(&ty::list_iter::ListIterator<\'list, M>) -> std::option::Option<&\'list ty::Ref<M>>`", 27 message: "method `next` has an incompatible type for trait\nexpected type `fn(&mut ty::list_iter::ListIterator<\'list, M>) -> std::option::Option<&ty::Ref<M>>`\n found type `fn(&ty::list_iter::ListIterator<\'list, M>) -> std::option::Option<&\'list ty::Ref<M>>`",
27 related_information: None, 28 related_information: None,
28 tags: None, 29 tags: None,
30 data: None,
29 }, 31 },
30 fixes: [], 32 fixes: [],
31 }, 33 },
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt
index c269af218..2610e4e20 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_mismatched_type.txt
@@ -20,12 +20,14 @@
20 "E0308", 20 "E0308",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "rustc", 25 "rustc",
25 ), 26 ),
26 message: "mismatched types\nexpected usize, found u32", 27 message: "mismatched types\nexpected usize, found u32",
27 related_information: None, 28 related_information: None,
28 tags: None, 29 tags: None,
30 data: None,
29 }, 31 },
30 fixes: [], 32 fixes: [],
31 }, 33 },
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt
index 74d91bc77..8dc53391e 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable.txt
@@ -20,6 +20,7 @@
20 "unused_variables", 20 "unused_variables",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "rustc", 25 "rustc",
25 ), 26 ),
@@ -30,6 +31,7 @@
30 Unnecessary, 31 Unnecessary,
31 ], 32 ],
32 ), 33 ),
34 data: None,
33 }, 35 },
34 fixes: [ 36 fixes: [
35 CodeAction { 37 CodeAction {
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt
index 8a420c949..c8703194c 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_hint.txt
@@ -20,6 +20,7 @@
20 "unused_variables", 20 "unused_variables",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "rustc", 25 "rustc",
25 ), 26 ),
@@ -30,6 +31,7 @@
30 Unnecessary, 31 Unnecessary,
31 ], 32 ],
32 ), 33 ),
34 data: None,
33 }, 35 },
34 fixes: [ 36 fixes: [
35 CodeAction { 37 CodeAction {
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt
index 79910660b..dc93227ad 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_unused_variable_as_info.txt
@@ -20,6 +20,7 @@
20 "unused_variables", 20 "unused_variables",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "rustc", 25 "rustc",
25 ), 26 ),
@@ -30,6 +31,7 @@
30 Unnecessary, 31 Unnecessary,
31 ], 32 ],
32 ), 33 ),
34 data: None,
33 }, 35 },
34 fixes: [ 36 fixes: [
35 CodeAction { 37 CodeAction {
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt b/crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt
index efe37261d..ba1b98b33 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/rustc_wrong_number_of_parameters.txt
@@ -20,6 +20,7 @@
20 "E0061", 20 "E0061",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "rustc", 25 "rustc",
25 ), 26 ),
@@ -45,6 +46,7 @@
45 ], 46 ],
46 ), 47 ),
47 tags: None, 48 tags: None,
49 data: None,
48 }, 50 },
49 fixes: [], 51 fixes: [],
50 }, 52 },
diff --git a/crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt b/crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt
index 4f811ab64..81f752672 100644
--- a/crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt
+++ b/crates/rust-analyzer/src/diagnostics/test_data/snap_multi_line_fix.txt
@@ -20,6 +20,7 @@
20 "let_and_return", 20 "let_and_return",
21 ), 21 ),
22 ), 22 ),
23 code_description: None,
23 source: Some( 24 source: Some(
24 "clippy", 25 "clippy",
25 ), 26 ),
@@ -45,6 +46,7 @@
45 ], 46 ],
46 ), 47 ),
47 tags: None, 48 tags: None,
49 data: None,
48 }, 50 },
49 fixes: [ 51 fixes: [
50 CodeAction { 52 CodeAction {
diff --git a/crates/rust-analyzer/src/diagnostics/to_proto.rs b/crates/rust-analyzer/src/diagnostics/to_proto.rs
index 33606edda..b949577c1 100644
--- a/crates/rust-analyzer/src/diagnostics/to_proto.rs
+++ b/crates/rust-analyzer/src/diagnostics/to_proto.rs
@@ -248,10 +248,12 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
248 range: in_macro_location.range, 248 range: in_macro_location.range,
249 severity, 249 severity,
250 code: code.clone().map(lsp_types::NumberOrString::String), 250 code: code.clone().map(lsp_types::NumberOrString::String),
251 code_description: None,
251 source: Some(source.clone()), 252 source: Some(source.clone()),
252 message: message.clone(), 253 message: message.clone(),
253 related_information: Some(information_for_additional_diagnostic), 254 related_information: Some(information_for_additional_diagnostic),
254 tags: if tags.is_empty() { None } else { Some(tags.clone()) }, 255 tags: if tags.is_empty() { None } else { Some(tags.clone()) },
256 data: None,
255 }; 257 };
256 258
257 Some(MappedRustDiagnostic { 259 Some(MappedRustDiagnostic {
@@ -267,6 +269,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
267 range: location.range, 269 range: location.range,
268 severity, 270 severity,
269 code: code.clone().map(lsp_types::NumberOrString::String), 271 code: code.clone().map(lsp_types::NumberOrString::String),
272 code_description: None,
270 source: Some(source.clone()), 273 source: Some(source.clone()),
271 message, 274 message,
272 related_information: if related_information.is_empty() { 275 related_information: if related_information.is_empty() {
@@ -275,6 +278,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
275 Some(related_information.clone()) 278 Some(related_information.clone())
276 }, 279 },
277 tags: if tags.is_empty() { None } else { Some(tags.clone()) }, 280 tags: if tags.is_empty() { None } else { Some(tags.clone()) },
281 data: None,
278 }; 282 };
279 283
280 let main_diagnostic = 284 let main_diagnostic =
diff --git a/crates/rust-analyzer/src/dispatch.rs b/crates/rust-analyzer/src/dispatch.rs
index 7a87515e9..81b85a269 100644
--- a/crates/rust-analyzer/src/dispatch.rs
+++ b/crates/rust-analyzer/src/dispatch.rs
@@ -28,17 +28,16 @@ impl<'a> RequestDispatcher<'a> {
28 { 28 {
29 let (id, params) = match self.parse::<R>() { 29 let (id, params) = match self.parse::<R>() {
30 Some(it) => it, 30 Some(it) => it,
31 None => { 31 None => return Ok(self),
32 return Ok(self);
33 }
34 }; 32 };
35 let world = panic::AssertUnwindSafe(&mut *self.global_state); 33 let world = panic::AssertUnwindSafe(&mut *self.global_state);
34
36 let response = panic::catch_unwind(move || { 35 let response = panic::catch_unwind(move || {
37 let _pctx = stdx::panic_context::enter(format!("request: {} {:#?}", R::METHOD, params)); 36 let _pctx = stdx::panic_context::enter(format!("request: {} {:#?}", R::METHOD, params));
38 let result = f(world.0, params); 37 let result = f(world.0, params);
39 result_to_response::<R>(id, result) 38 result_to_response::<R>(id, result)
40 }) 39 })
41 .map_err(|_| format!("sync task {:?} panicked", R::METHOD))?; 40 .map_err(|_err| format!("sync task {:?} panicked", R::METHOD))?;
42 self.global_state.respond(response); 41 self.global_state.respond(response);
43 Ok(self) 42 Ok(self)
44 } 43 }
@@ -47,7 +46,7 @@ impl<'a> RequestDispatcher<'a> {
47 pub(crate) fn on<R>( 46 pub(crate) fn on<R>(
48 &mut self, 47 &mut self,
49 f: fn(GlobalStateSnapshot, R::Params) -> Result<R::Result>, 48 f: fn(GlobalStateSnapshot, R::Params) -> Result<R::Result>,
50 ) -> Result<&mut Self> 49 ) -> &mut Self
51 where 50 where
52 R: lsp_types::request::Request + 'static, 51 R: lsp_types::request::Request + 'static,
53 R::Params: DeserializeOwned + Send + fmt::Debug + 'static, 52 R::Params: DeserializeOwned + Send + fmt::Debug + 'static,
@@ -55,9 +54,7 @@ impl<'a> RequestDispatcher<'a> {
55 { 54 {
56 let (id, params) = match self.parse::<R>() { 55 let (id, params) = match self.parse::<R>() {
57 Some(it) => it, 56 Some(it) => it,
58 None => { 57 None => return self,
59 return Ok(self);
60 }
61 }; 58 };
62 59
63 self.global_state.task_pool.handle.spawn({ 60 self.global_state.task_pool.handle.spawn({
@@ -71,7 +68,7 @@ impl<'a> RequestDispatcher<'a> {
71 } 68 }
72 }); 69 });
73 70
74 Ok(self) 71 self
75 } 72 }
76 73
77 pub(crate) fn finish(&mut self) { 74 pub(crate) fn finish(&mut self) {
@@ -82,7 +79,7 @@ impl<'a> RequestDispatcher<'a> {
82 lsp_server::ErrorCode::MethodNotFound as i32, 79 lsp_server::ErrorCode::MethodNotFound as i32,
83 "unknown request".to_string(), 80 "unknown request".to_string(),
84 ); 81 );
85 self.global_state.respond(response) 82 self.global_state.respond(response);
86 } 83 }
87 } 84 }
88 85
@@ -91,15 +88,24 @@ impl<'a> RequestDispatcher<'a> {
91 R: lsp_types::request::Request + 'static, 88 R: lsp_types::request::Request + 'static,
92 R::Params: DeserializeOwned + 'static, 89 R::Params: DeserializeOwned + 'static,
93 { 90 {
94 let req = self.req.take()?; 91 let req = match &self.req {
95 let (id, params) = match req.extract::<R::Params>(R::METHOD) { 92 Some(req) if req.method == R::METHOD => self.req.take().unwrap(),
96 Ok(it) => it, 93 _ => return None,
97 Err(req) => { 94 };
98 self.req = Some(req); 95
96 let res = crate::from_json(R::METHOD, req.params);
97 match res {
98 Ok(params) => return Some((req.id, params)),
99 Err(err) => {
100 let response = lsp_server::Response::new_err(
101 req.id,
102 lsp_server::ErrorCode::InvalidParams as i32,
103 err.to_string(),
104 );
105 self.global_state.respond(response);
99 return None; 106 return None;
100 } 107 }
101 }; 108 }
102 Some((id, params))
103 } 109 }
104} 110}
105 111
diff --git a/crates/rust-analyzer/src/document.rs b/crates/rust-analyzer/src/document.rs
index e882c9865..04c7ee150 100644
--- a/crates/rust-analyzer/src/document.rs
+++ b/crates/rust-analyzer/src/document.rs
@@ -6,11 +6,11 @@
6/// client notifications. 6/// client notifications.
7#[derive(Debug, Clone)] 7#[derive(Debug, Clone)]
8pub(crate) struct DocumentData { 8pub(crate) struct DocumentData {
9 pub version: Option<i64>, 9 pub(crate) version: Option<i64>,
10} 10}
11 11
12impl DocumentData { 12impl DocumentData {
13 pub fn new(version: i64) -> Self { 13 pub(crate) fn new(version: i64) -> Self {
14 DocumentData { version: Some(version) } 14 DocumentData { version: Some(version) }
15 } 15 }
16} 16}
diff --git a/crates/rust-analyzer/src/global_state.rs b/crates/rust-analyzer/src/global_state.rs
index 673a2eebc..63c70a09d 100644
--- a/crates/rust-analyzer/src/global_state.rs
+++ b/crates/rust-analyzer/src/global_state.rs
@@ -87,7 +87,7 @@ pub(crate) struct GlobalStateSnapshot {
87 pub(crate) check_fixes: CheckFixes, 87 pub(crate) check_fixes: CheckFixes,
88 pub(crate) latest_requests: Arc<RwLock<LatestRequests>>, 88 pub(crate) latest_requests: Arc<RwLock<LatestRequests>>,
89 mem_docs: FxHashMap<VfsPath, DocumentData>, 89 mem_docs: FxHashMap<VfsPath, DocumentData>,
90 pub semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>, 90 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
91 vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>, 91 vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
92 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>, 92 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
93} 93}
diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs
index 2680e5f08..049c583a4 100644
--- a/crates/rust-analyzer/src/handlers.rs
+++ b/crates/rust-analyzer/src/handlers.rs
@@ -1121,10 +1121,12 @@ pub(crate) fn publish_diagnostics(
1121 range: to_proto::range(&line_index, d.range), 1121 range: to_proto::range(&line_index, d.range),
1122 severity: Some(to_proto::diagnostic_severity(d.severity)), 1122 severity: Some(to_proto::diagnostic_severity(d.severity)),
1123 code: None, 1123 code: None,
1124 code_description: None,
1124 source: Some("rust-analyzer".to_string()), 1125 source: Some("rust-analyzer".to_string()),
1125 message: d.message, 1126 message: d.message,
1126 related_information: None, 1127 related_information: None,
1127 tags: if d.unused { Some(vec![DiagnosticTag::Unnecessary]) } else { None }, 1128 tags: if d.unused { Some(vec![DiagnosticTag::Unnecessary]) } else { None },
1129 data: None,
1128 }) 1130 })
1129 .collect(); 1131 .collect();
1130 Ok(diagnostics) 1132 Ok(diagnostics)
diff --git a/crates/rust-analyzer/src/lib.rs b/crates/rust-analyzer/src/lib.rs
index 87f72b497..ad08f1afb 100644
--- a/crates/rust-analyzer/src/lib.rs
+++ b/crates/rust-analyzer/src/lib.rs
@@ -37,14 +37,16 @@ mod document;
37pub mod lsp_ext; 37pub mod lsp_ext;
38pub mod config; 38pub mod config;
39 39
40use serde::de::DeserializeOwned;
41
42pub type Result<T, E = Box<dyn std::error::Error + Send + Sync>> = std::result::Result<T, E>;
43pub use crate::{caps::server_capabilities, main_loop::main_loop};
44use ide::AnalysisHost; 40use ide::AnalysisHost;
41use serde::de::DeserializeOwned;
45use std::fmt; 42use std::fmt;
46use vfs::Vfs; 43use vfs::Vfs;
47 44
45pub use crate::{caps::server_capabilities, main_loop::main_loop};
46
47pub type Error = Box<dyn std::error::Error + Send + Sync>;
48pub type Result<T, E = Error> = std::result::Result<T, E>;
49
48pub fn from_json<T: DeserializeOwned>(what: &'static str, json: serde_json::Value) -> Result<T> { 50pub fn from_json<T: DeserializeOwned>(what: &'static str, json: serde_json::Value) -> Result<T> {
49 let res = T::deserialize(&json) 51 let res = T::deserialize(&json)
50 .map_err(|e| format!("Failed to deserialize {}: {}; {}", what, e, json))?; 52 .map_err(|e| format!("Failed to deserialize {}: {}; {}", what, e, json))?;
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs
index ed5292733..e9d08ff15 100644
--- a/crates/rust-analyzer/src/main_loop.rs
+++ b/crates/rust-analyzer/src/main_loop.rs
@@ -190,15 +190,35 @@ impl GlobalState {
190 } 190 }
191 lsp_server::Message::Response(resp) => self.complete_request(resp), 191 lsp_server::Message::Response(resp) => self.complete_request(resp),
192 }, 192 },
193 Event::Task(task) => match task { 193 Event::Task(mut task) => {
194 Task::Response(response) => self.respond(response), 194 let _p = profile::span("GlobalState::handle_event/task");
195 Task::Diagnostics(diagnostics_per_file) => { 195 let mut prime_caches_started = false;
196 for (file_id, diagnostics) in diagnostics_per_file { 196 let mut prime_caches_progress = None;
197 self.diagnostics.set_native_diagnostics(file_id, diagnostics) 197 loop {
198 match task {
199 Task::Response(response) => self.respond(response),
200 Task::Diagnostics(diagnostics_per_file) => {
201 for (file_id, diagnostics) in diagnostics_per_file {
202 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
203 }
204 }
205 Task::Workspaces(workspaces) => self.switch_workspaces(workspaces),
206 Task::PrimeCaches(progress) => {
207 if let PrimeCachesProgress::Started = progress {
208 prime_caches_started = true;
209 }
210
211 prime_caches_progress = Some(progress);
212 }
198 } 213 }
214 // Coalesce multiple task events into one loop turn
215 task = match self.task_pool.receiver.try_recv() {
216 Ok(task) => task,
217 Err(_) => break,
218 };
199 } 219 }
200 Task::Workspaces(workspaces) => self.switch_workspaces(workspaces), 220
201 Task::PrimeCaches(progress) => { 221 if let Some(progress) = prime_caches_progress {
202 let (state, message, fraction); 222 let (state, message, fraction);
203 match progress { 223 match progress {
204 PrimeCachesProgress::Started => { 224 PrimeCachesProgress::Started => {
@@ -218,9 +238,14 @@ impl GlobalState {
218 } 238 }
219 }; 239 };
220 240
241 if state != Progress::Begin && prime_caches_started {
242 // Progress indicator needs to be created first.
243 self.report_progress("indexing", Progress::Begin, None, Some(0.0));
244 }
245
221 self.report_progress("indexing", state, message, Some(fraction)); 246 self.report_progress("indexing", state, message, Some(fraction));
222 } 247 }
223 }, 248 }
224 Event::Vfs(mut task) => { 249 Event::Vfs(mut task) => {
225 let _p = profile::span("GlobalState::handle_event/vfs"); 250 let _p = profile::span("GlobalState::handle_event/vfs");
226 loop { 251 loop {
@@ -330,6 +355,12 @@ impl GlobalState {
330 .collect::<Vec<_>>(); 355 .collect::<Vec<_>>();
331 356
332 self.update_file_notifications_on_threadpool(subscriptions); 357 self.update_file_notifications_on_threadpool(subscriptions);
358
359 // Refresh semantic tokens if the client supports it.
360 if self.config.semantic_tokens_refresh {
361 self.semantic_tokens_cache.lock().clear();
362 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
363 }
333 } 364 }
334 365
335 if let Some(diagnostic_changes) = self.diagnostics.take_changes() { 366 if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
@@ -397,53 +428,49 @@ impl GlobalState {
397 handlers::handle_matching_brace(s.snapshot(), p) 428 handlers::handle_matching_brace(s.snapshot(), p)
398 })? 429 })?
399 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))? 430 .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
400 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)? 431 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
401 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)? 432 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
402 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)? 433 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
403 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)? 434 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
404 .on::<lsp_ext::Runnables>(handlers::handle_runnables)? 435 .on::<lsp_ext::Runnables>(handlers::handle_runnables)
405 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)? 436 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
406 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)? 437 .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
407 .on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)? 438 .on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)
408 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)? 439 .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
409 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)? 440 .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
410 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)? 441 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
411 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)? 442 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
412 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)? 443 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
413 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)? 444 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
414 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)? 445 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
415 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)? 446 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
416 .on::<lsp_types::request::Completion>(handlers::handle_completion)? 447 .on::<lsp_types::request::Completion>(handlers::handle_completion)
417 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)? 448 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
418 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)? 449 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
419 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)? 450 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
420 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)? 451 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
421 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)? 452 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
422 .on::<lsp_types::request::Rename>(handlers::handle_rename)? 453 .on::<lsp_types::request::Rename>(handlers::handle_rename)
423 .on::<lsp_types::request::References>(handlers::handle_references)? 454 .on::<lsp_types::request::References>(handlers::handle_references)
424 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)? 455 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
425 .on::<lsp_types::request::DocumentHighlightRequest>( 456 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
426 handlers::handle_document_highlight, 457 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
427 )?
428 .on::<lsp_types::request::CallHierarchyPrepare>(
429 handlers::handle_call_hierarchy_prepare,
430 )?
431 .on::<lsp_types::request::CallHierarchyIncomingCalls>( 458 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
432 handlers::handle_call_hierarchy_incoming, 459 handlers::handle_call_hierarchy_incoming,
433 )? 460 )
434 .on::<lsp_types::request::CallHierarchyOutgoingCalls>( 461 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
435 handlers::handle_call_hierarchy_outgoing, 462 handlers::handle_call_hierarchy_outgoing,
436 )? 463 )
437 .on::<lsp_types::request::SemanticTokensFullRequest>( 464 .on::<lsp_types::request::SemanticTokensFullRequest>(
438 handlers::handle_semantic_tokens_full, 465 handlers::handle_semantic_tokens_full,
439 )? 466 )
440 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>( 467 .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
441 handlers::handle_semantic_tokens_full_delta, 468 handlers::handle_semantic_tokens_full_delta,
442 )? 469 )
443 .on::<lsp_types::request::SemanticTokensRangeRequest>( 470 .on::<lsp_types::request::SemanticTokensRangeRequest>(
444 handlers::handle_semantic_tokens_range, 471 handlers::handle_semantic_tokens_range,
445 )? 472 )
446 .on::<lsp_ext::Ssr>(handlers::handle_ssr)? 473 .on::<lsp_ext::Ssr>(handlers::handle_ssr)
447 .finish(); 474 .finish();
448 Ok(()) 475 Ok(())
449 } 476 }
diff --git a/crates/rust-analyzer/src/semantic_tokens.rs b/crates/rust-analyzer/src/semantic_tokens.rs
index 7df28c9dd..e7991fd28 100644
--- a/crates/rust-analyzer/src/semantic_tokens.rs
+++ b/crates/rust-analyzer/src/semantic_tokens.rs
@@ -101,12 +101,12 @@ pub(crate) struct SemanticTokensBuilder {
101} 101}
102 102
103impl SemanticTokensBuilder { 103impl SemanticTokensBuilder {
104 pub fn new(id: String) -> Self { 104 pub(crate) fn new(id: String) -> Self {
105 SemanticTokensBuilder { id, prev_line: 0, prev_char: 0, data: Default::default() } 105 SemanticTokensBuilder { id, prev_line: 0, prev_char: 0, data: Default::default() }
106 } 106 }
107 107
108 /// Push a new token onto the builder 108 /// Push a new token onto the builder
109 pub fn push(&mut self, range: Range, token_index: u32, modifier_bitset: u32) { 109 pub(crate) fn push(&mut self, range: Range, token_index: u32, modifier_bitset: u32) {
110 let mut push_line = range.start.line as u32; 110 let mut push_line = range.start.line as u32;
111 let mut push_char = range.start.character as u32; 111 let mut push_char = range.start.character as u32;
112 112
@@ -134,12 +134,12 @@ impl SemanticTokensBuilder {
134 self.prev_char = range.start.character as u32; 134 self.prev_char = range.start.character as u32;
135 } 135 }
136 136
137 pub fn build(self) -> SemanticTokens { 137 pub(crate) fn build(self) -> SemanticTokens {
138 SemanticTokens { result_id: Some(self.id), data: self.data } 138 SemanticTokens { result_id: Some(self.id), data: self.data }
139 } 139 }
140} 140}
141 141
142pub fn diff_tokens(old: &[SemanticToken], new: &[SemanticToken]) -> Vec<SemanticTokensEdit> { 142pub(crate) fn diff_tokens(old: &[SemanticToken], new: &[SemanticToken]) -> Vec<SemanticTokensEdit> {
143 let offset = new.iter().zip(old.iter()).take_while(|&(n, p)| n == p).count(); 143 let offset = new.iter().zip(old.iter()).take_while(|&(n, p)| n == p).count();
144 144
145 let (_, old) = old.split_at(offset); 145 let (_, old) = old.split_at(offset);
@@ -165,7 +165,7 @@ pub fn diff_tokens(old: &[SemanticToken], new: &[SemanticToken]) -> Vec<Semantic
165 } 165 }
166} 166}
167 167
168pub fn type_index(type_: SemanticTokenType) -> u32 { 168pub(crate) fn type_index(type_: SemanticTokenType) -> u32 {
169 SUPPORTED_TYPES.iter().position(|it| *it == type_).unwrap() as u32 169 SUPPORTED_TYPES.iter().position(|it| *it == type_).unwrap() as u32
170} 170}
171 171
diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs
index 24a658fc6..92b7c7b68 100644
--- a/crates/rust-analyzer/src/to_proto.rs
+++ b/crates/rust-analyzer/src/to_proto.rs
@@ -709,7 +709,16 @@ pub(crate) fn call_hierarchy_item(
709 let detail = target.description.clone(); 709 let detail = target.description.clone();
710 let kind = symbol_kind(target.kind); 710 let kind = symbol_kind(target.kind);
711 let (uri, range, selection_range) = location_info(snap, target)?; 711 let (uri, range, selection_range) = location_info(snap, target)?;
712 Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range }) 712 Ok(lsp_types::CallHierarchyItem {
713 name,
714 kind,
715 tags: None,
716 detail,
717 uri,
718 range,
719 selection_range,
720 data: None,
721 })
713} 722}
714 723
715pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind { 724pub(crate) fn code_action_kind(kind: AssistKind) -> lsp_types::CodeActionKind {
diff --git a/crates/rust-analyzer/tests/rust-analyzer/support.rs b/crates/rust-analyzer/tests/rust-analyzer/support.rs
index 784cbda79..fe9362bc0 100644
--- a/crates/rust-analyzer/tests/rust-analyzer/support.rs
+++ b/crates/rust-analyzer/tests/rust-analyzer/support.rs
@@ -24,7 +24,7 @@ use vfs::AbsPathBuf;
24 24
25use crate::testdir::TestDir; 25use crate::testdir::TestDir;
26 26
27pub struct Project<'a> { 27pub(crate) struct Project<'a> {
28 fixture: &'a str, 28 fixture: &'a str,
29 with_sysroot: bool, 29 with_sysroot: bool,
30 tmp_dir: Option<TestDir>, 30 tmp_dir: Option<TestDir>,
@@ -33,11 +33,11 @@ pub struct Project<'a> {
33} 33}
34 34
35impl<'a> Project<'a> { 35impl<'a> Project<'a> {
36 pub fn with_fixture(fixture: &str) -> Project { 36 pub(crate) fn with_fixture(fixture: &str) -> Project {
37 Project { fixture, tmp_dir: None, roots: vec![], with_sysroot: false, config: None } 37 Project { fixture, tmp_dir: None, roots: vec![], with_sysroot: false, config: None }
38 } 38 }
39 39
40 pub fn tmp_dir(mut self, tmp_dir: TestDir) -> Project<'a> { 40 pub(crate) fn tmp_dir(mut self, tmp_dir: TestDir) -> Project<'a> {
41 self.tmp_dir = Some(tmp_dir); 41 self.tmp_dir = Some(tmp_dir);
42 self 42 self
43 } 43 }
@@ -47,17 +47,17 @@ impl<'a> Project<'a> {
47 self 47 self
48 } 48 }
49 49
50 pub fn with_sysroot(mut self, sysroot: bool) -> Project<'a> { 50 pub(crate) fn with_sysroot(mut self, sysroot: bool) -> Project<'a> {
51 self.with_sysroot = sysroot; 51 self.with_sysroot = sysroot;
52 self 52 self
53 } 53 }
54 54
55 pub fn with_config(mut self, config: impl Fn(&mut Config) + 'static) -> Project<'a> { 55 pub(crate) fn with_config(mut self, config: impl Fn(&mut Config) + 'static) -> Project<'a> {
56 self.config = Some(Box::new(config)); 56 self.config = Some(Box::new(config));
57 self 57 self
58 } 58 }
59 59
60 pub fn server(self) -> Server { 60 pub(crate) fn server(self) -> Server {
61 let tmp_dir = self.tmp_dir.unwrap_or_else(|| TestDir::new()); 61 let tmp_dir = self.tmp_dir.unwrap_or_else(|| TestDir::new());
62 static INIT: Once = Once::new(); 62 static INIT: Once = Once::new();
63 INIT.call_once(|| { 63 INIT.call_once(|| {
@@ -103,11 +103,11 @@ impl<'a> Project<'a> {
103 } 103 }
104} 104}
105 105
106pub fn project(fixture: &str) -> Server { 106pub(crate) fn project(fixture: &str) -> Server {
107 Project::with_fixture(fixture).server() 107 Project::with_fixture(fixture).server()
108} 108}
109 109
110pub struct Server { 110pub(crate) struct Server {
111 req_id: Cell<u64>, 111 req_id: Cell<u64>,
112 messages: RefCell<Vec<Message>>, 112 messages: RefCell<Vec<Message>>,
113 _thread: jod_thread::JoinHandle<()>, 113 _thread: jod_thread::JoinHandle<()>,
@@ -128,12 +128,12 @@ impl Server {
128 Server { req_id: Cell::new(1), dir, messages: Default::default(), client, _thread } 128 Server { req_id: Cell::new(1), dir, messages: Default::default(), client, _thread }
129 } 129 }
130 130
131 pub fn doc_id(&self, rel_path: &str) -> TextDocumentIdentifier { 131 pub(crate) fn doc_id(&self, rel_path: &str) -> TextDocumentIdentifier {
132 let path = self.dir.path().join(rel_path); 132 let path = self.dir.path().join(rel_path);
133 TextDocumentIdentifier { uri: Url::from_file_path(path).unwrap() } 133 TextDocumentIdentifier { uri: Url::from_file_path(path).unwrap() }
134 } 134 }
135 135
136 pub fn notification<N>(&self, params: N::Params) 136 pub(crate) fn notification<N>(&self, params: N::Params)
137 where 137 where
138 N: lsp_types::notification::Notification, 138 N: lsp_types::notification::Notification,
139 N::Params: Serialize, 139 N::Params: Serialize,
@@ -142,7 +142,7 @@ impl Server {
142 self.send_notification(r) 142 self.send_notification(r)
143 } 143 }
144 144
145 pub fn request<R>(&self, params: R::Params, expected_resp: Value) 145 pub(crate) fn request<R>(&self, params: R::Params, expected_resp: Value)
146 where 146 where
147 R: lsp_types::request::Request, 147 R: lsp_types::request::Request,
148 R::Params: Serialize, 148 R::Params: Serialize,
@@ -159,7 +159,7 @@ impl Server {
159 } 159 }
160 } 160 }
161 161
162 pub fn send_request<R>(&self, params: R::Params) -> Value 162 pub(crate) fn send_request<R>(&self, params: R::Params) -> Value
163 where 163 where
164 R: lsp_types::request::Request, 164 R: lsp_types::request::Request,
165 R::Params: Serialize, 165 R::Params: Serialize,
@@ -202,7 +202,7 @@ impl Server {
202 } 202 }
203 panic!("no response"); 203 panic!("no response");
204 } 204 }
205 pub fn wait_until_workspace_is_loaded(self) -> Server { 205 pub(crate) fn wait_until_workspace_is_loaded(self) -> Server {
206 self.wait_for_message_cond(1, &|msg: &Message| match msg { 206 self.wait_for_message_cond(1, &|msg: &Message| match msg {
207 Message::Notification(n) if n.method == "$/progress" => { 207 Message::Notification(n) if n.method == "$/progress" => {
208 match n.clone().extract::<ProgressParams>("$/progress").unwrap() { 208 match n.clone().extract::<ProgressParams>("$/progress").unwrap() {
@@ -241,7 +241,7 @@ impl Server {
241 self.client.sender.send(Message::Notification(not)).unwrap(); 241 self.client.sender.send(Message::Notification(not)).unwrap();
242 } 242 }
243 243
244 pub fn path(&self) -> &Path { 244 pub(crate) fn path(&self) -> &Path {
245 self.dir.path() 245 self.dir.path()
246 } 246 }
247} 247}
diff --git a/crates/rust-analyzer/tests/rust-analyzer/testdir.rs b/crates/rust-analyzer/tests/rust-analyzer/testdir.rs
index 7487e7429..36271344b 100644
--- a/crates/rust-analyzer/tests/rust-analyzer/testdir.rs
+++ b/crates/rust-analyzer/tests/rust-analyzer/testdir.rs
@@ -4,13 +4,13 @@ use std::{
4 sync::atomic::{AtomicUsize, Ordering}, 4 sync::atomic::{AtomicUsize, Ordering},
5}; 5};
6 6
7pub struct TestDir { 7pub(crate) struct TestDir {
8 path: PathBuf, 8 path: PathBuf,
9 keep: bool, 9 keep: bool,
10} 10}
11 11
12impl TestDir { 12impl TestDir {
13 pub fn new() -> TestDir { 13 pub(crate) fn new() -> TestDir {
14 let base = std::env::temp_dir().join("testdir"); 14 let base = std::env::temp_dir().join("testdir");
15 let pid = std::process::id(); 15 let pid = std::process::id();
16 16
@@ -27,11 +27,11 @@ impl TestDir {
27 panic!("Failed to create a temporary directory") 27 panic!("Failed to create a temporary directory")
28 } 28 }
29 #[allow(unused)] 29 #[allow(unused)]
30 pub fn keep(mut self) -> TestDir { 30 pub(crate) fn keep(mut self) -> TestDir {
31 self.keep = true; 31 self.keep = true;
32 self 32 self
33 } 33 }
34 pub fn path(&self) -> &Path { 34 pub(crate) fn path(&self) -> &Path {
35 &self.path 35 &self.path
36 } 36 }
37} 37}
diff --git a/crates/ssr/src/parsing.rs b/crates/ssr/src/parsing.rs
index 05b66dcd7..f3b084baf 100644
--- a/crates/ssr/src/parsing.rs
+++ b/crates/ssr/src/parsing.rs
@@ -42,7 +42,7 @@ pub(crate) struct Placeholder {
42 42
43/// Represents a `$var` in an SSR query. 43/// Represents a `$var` in an SSR query.
44#[derive(Debug, Clone, PartialEq, Eq, Hash)] 44#[derive(Debug, Clone, PartialEq, Eq, Hash)]
45pub(crate) struct Var(pub String); 45pub(crate) struct Var(pub(crate) String);
46 46
47#[derive(Clone, Debug, PartialEq, Eq)] 47#[derive(Clone, Debug, PartialEq, Eq)]
48pub(crate) enum Constraint { 48pub(crate) enum Constraint {
diff --git a/crates/syntax/Cargo.toml b/crates/syntax/Cargo.toml
index e8de61868..61d2acb49 100644
--- a/crates/syntax/Cargo.toml
+++ b/crates/syntax/Cargo.toml
@@ -13,7 +13,7 @@ doctest = false
13[dependencies] 13[dependencies]
14itertools = "0.9.0" 14itertools = "0.9.0"
15rowan = "0.10.0" 15rowan = "0.10.0"
16rustc_lexer = { version = "685.0.0", package = "rustc-ap-rustc_lexer" } 16rustc_lexer = { version = "686.0.0", package = "rustc-ap-rustc_lexer" }
17rustc-hash = "1.1.0" 17rustc-hash = "1.1.0"
18arrayvec = "0.5.1" 18arrayvec = "0.5.1"
19once_cell = "1.3.1" 19once_cell = "1.3.1"
@@ -27,7 +27,7 @@ serde = { version = "1.0.106", features = ["derive"] }
27stdx = { path = "../stdx", version = "0.0.0" } 27stdx = { path = "../stdx", version = "0.0.0" }
28text_edit = { path = "../text_edit", version = "0.0.0" } 28text_edit = { path = "../text_edit", version = "0.0.0" }
29parser = { path = "../parser", version = "0.0.0" } 29parser = { path = "../parser", version = "0.0.0" }
30test_utils = { path = "../test_utils" } 30test_utils = { path = "../test_utils", version = "0.0.0" }
31 31
32[dev-dependencies] 32[dev-dependencies]
33walkdir = "2.3.1" 33walkdir = "2.3.1"
diff --git a/crates/syntax/src/ast.rs b/crates/syntax/src/ast.rs
index d536bb1e7..8a0e3d27b 100644
--- a/crates/syntax/src/ast.rs
+++ b/crates/syntax/src/ast.rs
@@ -17,7 +17,7 @@ use crate::{
17 17
18pub use self::{ 18pub use self::{
19 expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind, PrefixOp, RangeOp}, 19 expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind, PrefixOp, RangeOp},
20 generated::*, 20 generated::{nodes::*, tokens::*},
21 node_ext::{ 21 node_ext::{
22 AttrKind, FieldKind, NameOrNameRef, PathSegmentKind, SelfParamKind, SlicePatComponents, 22 AttrKind, FieldKind, NameOrNameRef, PathSegmentKind, SelfParamKind, SlicePatComponents,
23 StructKind, TypeBoundKind, VisibilityKind, 23 StructKind, TypeBoundKind, VisibilityKind,
diff --git a/crates/syntax/src/ast/generated.rs b/crates/syntax/src/ast/generated.rs
index 4a6f41ee7..843b43cf0 100644
--- a/crates/syntax/src/ast/generated.rs
+++ b/crates/syntax/src/ast/generated.rs
@@ -1,8 +1,8 @@
1//! This file is actually hand-written, but the submodules are indeed generated. 1//! This file is actually hand-written, but the submodules are indeed generated.
2#[rustfmt::skip] 2#[rustfmt::skip]
3mod nodes; 3pub(crate) mod nodes;
4#[rustfmt::skip] 4#[rustfmt::skip]
5mod tokens; 5pub(crate) mod tokens;
6 6
7use crate::{ 7use crate::{
8 AstNode, 8 AstNode,
@@ -10,7 +10,7 @@ use crate::{
10 SyntaxNode, 10 SyntaxNode,
11}; 11};
12 12
13pub use {nodes::*, tokens::*}; 13pub(crate) use nodes::*;
14 14
15// Stmt is the only nested enum, so it's easier to just hand-write it 15// Stmt is the only nested enum, so it's easier to just hand-write it
16impl AstNode for Stmt { 16impl AstNode for Stmt {
diff --git a/crates/syntax/src/lib.rs b/crates/syntax/src/lib.rs
index 849a1cdd6..e753b11bb 100644
--- a/crates/syntax/src/lib.rs
+++ b/crates/syntax/src/lib.rs
@@ -46,16 +46,19 @@ use text_edit::Indel;
46pub use crate::{ 46pub use crate::{
47 algo::InsertPosition, 47 algo::InsertPosition,
48 ast::{AstNode, AstToken}, 48 ast::{AstNode, AstToken},
49 parsing::{lex_single_syntax_kind, lex_single_valid_syntax_kind, tokenize, Token}, 49 parsing::lexer::{lex_single_syntax_kind, lex_single_valid_syntax_kind, tokenize, Token},
50 ptr::{AstPtr, SyntaxNodePtr}, 50 ptr::{AstPtr, SyntaxNodePtr},
51 syntax_error::SyntaxError, 51 syntax_error::SyntaxError,
52 syntax_node::{ 52 syntax_node::{
53 Direction, GreenNode, NodeOrToken, SyntaxElement, SyntaxElementChildren, SyntaxNode, 53 SyntaxElement, SyntaxElementChildren, SyntaxNode, SyntaxNodeChildren, SyntaxToken,
54 SyntaxNodeChildren, SyntaxToken, SyntaxTreeBuilder, 54 SyntaxTreeBuilder,
55 }, 55 },
56}; 56};
57pub use parser::{SyntaxKind, T}; 57pub use parser::{SyntaxKind, T};
58pub use rowan::{SmolStr, SyntaxText, TextRange, TextSize, TokenAtOffset, WalkEvent}; 58pub use rowan::{
59 Direction, GreenNode, NodeOrToken, SmolStr, SyntaxText, TextRange, TextSize, TokenAtOffset,
60 WalkEvent,
61};
59 62
60/// `Parse` is the result of the parsing: a syntax tree and a collection of 63/// `Parse` is the result of the parsing: a syntax tree and a collection of
61/// errors. 64/// errors.
diff --git a/crates/syntax/src/parsing.rs b/crates/syntax/src/parsing.rs
index 68a39eb21..333bde54a 100644
--- a/crates/syntax/src/parsing.rs
+++ b/crates/syntax/src/parsing.rs
@@ -1,7 +1,7 @@
1//! Lexing, bridging to parser (which does the actual parsing) and 1//! Lexing, bridging to parser (which does the actual parsing) and
2//! incremental reparsing. 2//! incremental reparsing.
3 3
4mod lexer; 4pub(crate) mod lexer;
5mod text_token_source; 5mod text_token_source;
6mod text_tree_sink; 6mod text_tree_sink;
7mod reparsing; 7mod reparsing;
@@ -10,7 +10,7 @@ use crate::{syntax_node::GreenNode, AstNode, SyntaxError, SyntaxNode};
10use text_token_source::TextTokenSource; 10use text_token_source::TextTokenSource;
11use text_tree_sink::TextTreeSink; 11use text_tree_sink::TextTreeSink;
12 12
13pub use lexer::*; 13pub(crate) use lexer::*;
14 14
15pub(crate) use self::reparsing::incremental_reparse; 15pub(crate) use self::reparsing::incremental_reparse;
16use parser::SyntaxKind; 16use parser::SyntaxKind;
diff --git a/crates/syntax/src/parsing/text_token_source.rs b/crates/syntax/src/parsing/text_token_source.rs
index df866dc2b..0614194a5 100644
--- a/crates/syntax/src/parsing/text_token_source.rs
+++ b/crates/syntax/src/parsing/text_token_source.rs
@@ -65,7 +65,7 @@ fn mk_token(pos: usize, token_offset_pairs: &[(Token, TextSize)]) -> parser::Tok
65 65
66impl<'t> TextTokenSource<'t> { 66impl<'t> TextTokenSource<'t> {
67 /// Generate input from tokens(expect comment and whitespace). 67 /// Generate input from tokens(expect comment and whitespace).
68 pub fn new(text: &'t str, raw_tokens: &'t [Token]) -> TextTokenSource<'t> { 68 pub(crate) fn new(text: &'t str, raw_tokens: &'t [Token]) -> TextTokenSource<'t> {
69 let token_offset_pairs: Vec<_> = raw_tokens 69 let token_offset_pairs: Vec<_> = raw_tokens
70 .iter() 70 .iter()
71 .filter_map({ 71 .filter_map({
diff --git a/crates/syntax/src/syntax_node.rs b/crates/syntax/src/syntax_node.rs
index b2abcbfbb..cc30138fa 100644
--- a/crates/syntax/src/syntax_node.rs
+++ b/crates/syntax/src/syntax_node.rs
@@ -10,9 +10,7 @@ use rowan::{GreenNodeBuilder, Language};
10 10
11use crate::{Parse, SmolStr, SyntaxError, SyntaxKind, TextSize}; 11use crate::{Parse, SmolStr, SyntaxError, SyntaxKind, TextSize};
12 12
13pub use rowan::GreenNode; 13pub(crate) use rowan::{GreenNode, GreenToken, NodeOrToken};
14
15pub(crate) use rowan::GreenToken;
16 14
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub enum RustLanguage {} 16pub enum RustLanguage {}
@@ -34,8 +32,6 @@ pub type SyntaxElement = rowan::SyntaxElement<RustLanguage>;
34pub type SyntaxNodeChildren = rowan::SyntaxNodeChildren<RustLanguage>; 32pub type SyntaxNodeChildren = rowan::SyntaxNodeChildren<RustLanguage>;
35pub type SyntaxElementChildren = rowan::SyntaxElementChildren<RustLanguage>; 33pub type SyntaxElementChildren = rowan::SyntaxElementChildren<RustLanguage>;
36 34
37pub use rowan::{Direction, NodeOrToken};
38
39#[derive(Default)] 35#[derive(Default)]
40pub struct SyntaxTreeBuilder { 36pub struct SyntaxTreeBuilder {
41 errors: Vec<SyntaxError>, 37 errors: Vec<SyntaxError>,
diff --git a/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rast b/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rast
new file mode 100644
index 000000000..c204f0e2d
--- /dev/null
+++ b/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rast
@@ -0,0 +1,54 @@
1[email protected]
2 [email protected]
3 [email protected] "struct"
4 [email protected] " "
5 [email protected]
6 [email protected] "B"
7 [email protected]
8 [email protected] "("
9 [email protected]
10 [email protected]
11 [email protected] "pub"
12 [email protected] " "
13 [email protected]
14 [email protected] "("
15 [email protected]
16 [email protected]
17 [email protected]
18 [email protected]
19 [email protected] "super"
20 [email protected] "::"
21 [email protected]
22 [email protected]
23 [email protected] "A"
24 [email protected] ")"
25 [email protected] ")"
26 [email protected] ";"
27 [email protected] "\n"
28 [email protected]
29 [email protected] "struct"
30 [email protected] " "
31 [email protected]
32 [email protected] "B"
33 [email protected]
34 [email protected] "("
35 [email protected]
36 [email protected]
37 [email protected] "pub"
38 [email protected] " "
39 [email protected]
40 [email protected] "("
41 [email protected]
42 [email protected]
43 [email protected]
44 [email protected]
45 [email protected] "crate"
46 [email protected] "::"
47 [email protected]
48 [email protected]
49 [email protected] "A"
50 [email protected] ","
51 [email protected] ")"
52 [email protected] ")"
53 [email protected] ";"
54 [email protected] "\n"
diff --git a/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rs b/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rs
new file mode 100644
index 000000000..d4c163822
--- /dev/null
+++ b/crates/syntax/test_data/parser/inline/ok/0153_pub_parens_typepath.rs
@@ -0,0 +1,2 @@
1struct B(pub (super::A));
2struct B(pub (crate::A,));
diff --git a/crates/vfs/src/vfs_path.rs b/crates/vfs/src/vfs_path.rs
index 022a0be1e..815697597 100644
--- a/crates/vfs/src/vfs_path.rs
+++ b/crates/vfs/src/vfs_path.rs
@@ -120,7 +120,7 @@ impl VfsPath {
120 120
121#[cfg(windows)] 121#[cfg(windows)]
122mod windows_paths { 122mod windows_paths {
123 pub trait Encode { 123 pub(crate) trait Encode {
124 fn encode(&self, buf: &mut Vec<u8>); 124 fn encode(&self, buf: &mut Vec<u8>);
125 } 125 }
126 126
@@ -149,7 +149,7 @@ mod windows_paths {
149 } 149 }
150 } 150 }
151 151
152 pub const SEP: &str = "\\"; 152 pub(crate) const SEP: &str = "\\";
153 const VERBATIM: &str = "\\\\?\\"; 153 const VERBATIM: &str = "\\\\?\\";
154 const UNC: &str = "UNC"; 154 const UNC: &str = "UNC";
155 const DEVICE: &str = "\\\\.\\"; 155 const DEVICE: &str = "\\\\.\\";
@@ -287,7 +287,7 @@ impl VirtualPath {
287 Some(res) 287 Some(res)
288 } 288 }
289 289
290 pub fn name_and_extension(&self) -> Option<(&str, Option<&str>)> { 290 pub(crate) fn name_and_extension(&self) -> Option<(&str, Option<&str>)> {
291 let file_path = if self.0.ends_with('/') { &self.0[..&self.0.len() - 1] } else { &self.0 }; 291 let file_path = if self.0.ends_with('/') { &self.0[..&self.0.len() - 1] } else { &self.0 };
292 let file_name = match file_path.rfind('/') { 292 let file_name = match file_path.rfind('/') {
293 Some(position) => &file_path[position + 1..], 293 Some(position) => &file_path[position + 1..],