aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/assists/src/assist_context.rs16
-rw-r--r--crates/assists/src/handlers/add_missing_impl_members.rs63
-rw-r--r--crates/assists/src/lib.rs36
-rw-r--r--crates/assists/src/tests/generated.rs3
-rw-r--r--crates/hir/src/has_source.rs2
-rw-r--r--crates/hir_def/src/diagnostics.rs5
-rw-r--r--crates/hir_expand/src/diagnostics.rs10
-rw-r--r--crates/hir_ty/Cargo.toml6
-rw-r--r--crates/hir_ty/src/diagnostics.rs27
-rw-r--r--crates/hir_ty/src/diagnostics/expr.rs4
-rw-r--r--crates/hir_ty/src/diagnostics/match_check.rs17
-rw-r--r--crates/hir_ty/src/tests.rs17
-rw-r--r--crates/hir_ty/src/traits.rs4
-rw-r--r--crates/ide/src/completion.rs1
-rw-r--r--crates/ide/src/completion/complete_attribute.rs21
-rw-r--r--crates/ide/src/completion/generated_features.rs4
-rw-r--r--crates/ide/src/diagnostics.rs92
-rw-r--r--crates/ide/src/diagnostics/fixes.rs (renamed from crates/ide/src/diagnostics/diagnostics_with_fix.rs)10
-rw-r--r--crates/ide/src/lib.rs35
-rw-r--r--crates/ide_db/src/label.rs49
-rw-r--r--crates/ide_db/src/lib.rs1
-rw-r--r--crates/proc_macro_api/src/lib.rs6
-rw-r--r--crates/rust-analyzer/src/cli/analysis_bench.rs7
-rw-r--r--crates/rust-analyzer/src/cli/diagnostics.rs5
-rw-r--r--crates/rust-analyzer/src/config.rs15
-rw-r--r--crates/rust-analyzer/src/diagnostics.rs2
-rw-r--r--crates/rust-analyzer/src/diagnostics/to_proto.rs18
-rw-r--r--crates/rust-analyzer/src/handlers.rs39
-rw-r--r--crates/rust-analyzer/src/lsp_ext.rs7
-rw-r--r--crates/rust-analyzer/src/main_loop.rs2
-rw-r--r--crates/rust-analyzer/src/reload.rs5
-rw-r--r--crates/rust-analyzer/src/to_proto.rs8
-rw-r--r--crates/rust-analyzer/tests/rust-analyzer/main.rs (renamed from crates/rust-analyzer/tests/heavy_tests/main.rs)10
-rw-r--r--crates/rust-analyzer/tests/rust-analyzer/support.rs (renamed from crates/rust-analyzer/tests/heavy_tests/support.rs)0
-rw-r--r--crates/rust-analyzer/tests/rust-analyzer/testdir.rs (renamed from crates/rust-analyzer/tests/heavy_tests/testdir.rs)0
-rw-r--r--crates/ssr/Cargo.toml1
-rw-r--r--crates/ssr/src/lib.rs5
-rw-r--r--crates/ssr/src/matching.rs95
-rw-r--r--crates/ssr/src/parsing.rs24
-rw-r--r--crates/ssr/src/replacing.rs50
-rw-r--r--crates/ssr/src/tests.rs109
-rw-r--r--crates/stdx/src/lib.rs32
-rw-r--r--crates/syntax/Cargo.toml2
-rw-r--r--crates/syntax/src/ast/edit.rs29
44 files changed, 692 insertions, 202 deletions
diff --git a/crates/assists/src/assist_context.rs b/crates/assists/src/assist_context.rs
index 79574b9ac..11c171fc2 100644
--- a/crates/assists/src/assist_context.rs
+++ b/crates/assists/src/assist_context.rs
@@ -6,6 +6,7 @@ use algo::find_covering_element;
6use base_db::{FileId, FileRange}; 6use base_db::{FileId, FileRange};
7use hir::Semantics; 7use hir::Semantics;
8use ide_db::{ 8use ide_db::{
9 label::Label,
9 source_change::{SourceChange, SourceFileEdit}, 10 source_change::{SourceChange, SourceFileEdit},
10 RootDatabase, 11 RootDatabase,
11}; 12};
@@ -157,8 +158,9 @@ impl Assists {
157 if !self.is_allowed(&id) { 158 if !self.is_allowed(&id) {
158 return None; 159 return None;
159 } 160 }
160 let label = Assist::new(id, label.into(), None, target); 161 let label = Label::new(label.into());
161 self.add_impl(label, f) 162 let assist = Assist { id, label, group: None, target };
163 self.add_impl(assist, f)
162 } 164 }
163 165
164 pub(crate) fn add_group( 166 pub(crate) fn add_group(
@@ -172,12 +174,12 @@ impl Assists {
172 if !self.is_allowed(&id) { 174 if !self.is_allowed(&id) {
173 return None; 175 return None;
174 } 176 }
175 177 let label = Label::new(label.into());
176 let label = Assist::new(id, label.into(), Some(group.clone()), target); 178 let assist = Assist { id, label, group: Some(group.clone()), target };
177 self.add_impl(label, f) 179 self.add_impl(assist, f)
178 } 180 }
179 181
180 fn add_impl(&mut self, label: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> { 182 fn add_impl(&mut self, assist: Assist, f: impl FnOnce(&mut AssistBuilder)) -> Option<()> {
181 let source_change = if self.resolve { 183 let source_change = if self.resolve {
182 let mut builder = AssistBuilder::new(self.file); 184 let mut builder = AssistBuilder::new(self.file);
183 f(&mut builder); 185 f(&mut builder);
@@ -186,7 +188,7 @@ impl Assists {
186 None 188 None
187 }; 189 };
188 190
189 self.buf.push((label, source_change)); 191 self.buf.push((assist, source_change));
190 Some(()) 192 Some(())
191 } 193 }
192 194
diff --git a/crates/assists/src/handlers/add_missing_impl_members.rs b/crates/assists/src/handlers/add_missing_impl_members.rs
index 81b61ebf8..83a2ada9a 100644
--- a/crates/assists/src/handlers/add_missing_impl_members.rs
+++ b/crates/assists/src/handlers/add_missing_impl_members.rs
@@ -48,7 +48,6 @@ enum AddMissingImplMembersMode {
48// fn foo(&self) -> u32 { 48// fn foo(&self) -> u32 {
49// ${0:todo!()} 49// ${0:todo!()}
50// } 50// }
51//
52// } 51// }
53// ``` 52// ```
54pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 53pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
@@ -89,8 +88,8 @@ pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -
89// impl Trait for () { 88// impl Trait for () {
90// Type X = (); 89// Type X = ();
91// fn foo(&self) {} 90// fn foo(&self) {}
92// $0fn bar(&self) {}
93// 91//
92// $0fn bar(&self) {}
94// } 93// }
95// ``` 94// ```
96pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 95pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
@@ -240,15 +239,18 @@ struct S;
240 239
241impl Foo for S { 240impl Foo for S {
242 fn bar(&self) {} 241 fn bar(&self) {}
242
243 $0type Output; 243 $0type Output;
244
244 const CONST: usize = 42; 245 const CONST: usize = 42;
246
245 fn foo(&self) { 247 fn foo(&self) {
246 todo!() 248 todo!()
247 } 249 }
250
248 fn baz(&self) { 251 fn baz(&self) {
249 todo!() 252 todo!()
250 } 253 }
251
252}"#, 254}"#,
253 ); 255 );
254 } 256 }
@@ -281,10 +283,10 @@ struct S;
281 283
282impl Foo for S { 284impl Foo for S {
283 fn bar(&self) {} 285 fn bar(&self) {}
286
284 fn foo(&self) { 287 fn foo(&self) {
285 ${0:todo!()} 288 ${0:todo!()}
286 } 289 }
287
288}"#, 290}"#,
289 ); 291 );
290 } 292 }
@@ -599,6 +601,7 @@ trait Foo {
599struct S; 601struct S;
600impl Foo for S { 602impl Foo for S {
601 $0type Output; 603 $0type Output;
604
602 fn foo(&self) { 605 fn foo(&self) {
603 todo!() 606 todo!()
604 } 607 }
@@ -708,4 +711,56 @@ impl Tr for () {
708}"#, 711}"#,
709 ) 712 )
710 } 713 }
714
715 #[test]
716 fn test_whitespace_fixup_preserves_bad_tokens() {
717 check_assist(
718 add_missing_impl_members,
719 r#"
720trait Tr {
721 fn foo();
722}
723
724impl Tr for ()<|> {
725 +++
726}"#,
727 r#"
728trait Tr {
729 fn foo();
730}
731
732impl Tr for () {
733 fn foo() {
734 ${0:todo!()}
735 }
736 +++
737}"#,
738 )
739 }
740
741 #[test]
742 fn test_whitespace_fixup_preserves_comments() {
743 check_assist(
744 add_missing_impl_members,
745 r#"
746trait Tr {
747 fn foo();
748}
749
750impl Tr for ()<|> {
751 // very important
752}"#,
753 r#"
754trait Tr {
755 fn foo();
756}
757
758impl Tr for () {
759 fn foo() {
760 ${0:todo!()}
761 }
762 // very important
763}"#,
764 )
765 }
711} 766}
diff --git a/crates/assists/src/lib.rs b/crates/assists/src/lib.rs
index ae90d68a3..14834480a 100644
--- a/crates/assists/src/lib.rs
+++ b/crates/assists/src/lib.rs
@@ -19,7 +19,7 @@ pub mod ast_transform;
19 19
20use base_db::FileRange; 20use base_db::FileRange;
21use hir::Semantics; 21use hir::Semantics;
22use ide_db::{source_change::SourceChange, RootDatabase}; 22use ide_db::{label::Label, source_change::SourceChange, RootDatabase};
23use syntax::TextRange; 23use syntax::TextRange;
24 24
25pub(crate) use crate::assist_context::{AssistContext, Assists}; 25pub(crate) use crate::assist_context::{AssistContext, Assists};
@@ -66,13 +66,13 @@ pub struct GroupLabel(pub String);
66 66
67#[derive(Debug, Clone)] 67#[derive(Debug, Clone)]
68pub struct Assist { 68pub struct Assist {
69 id: AssistId, 69 pub id: AssistId,
70 /// Short description of the assist, as shown in the UI. 70 /// Short description of the assist, as shown in the UI.
71 label: String, 71 pub label: Label,
72 group: Option<GroupLabel>, 72 pub group: Option<GroupLabel>,
73 /// Target ranges are used to sort assists: the smaller the target range, 73 /// Target ranges are used to sort assists: the smaller the target range,
74 /// the more specific assist is, and so it should be sorted first. 74 /// the more specific assist is, and so it should be sorted first.
75 target: TextRange, 75 pub target: TextRange,
76} 76}
77 77
78#[derive(Debug, Clone)] 78#[derive(Debug, Clone)]
@@ -113,32 +113,6 @@ impl Assist {
113 }); 113 });
114 acc.finish_resolved() 114 acc.finish_resolved()
115 } 115 }
116
117 pub(crate) fn new(
118 id: AssistId,
119 label: String,
120 group: Option<GroupLabel>,
121 target: TextRange,
122 ) -> Assist {
123 assert!(label.starts_with(|c: char| c.is_uppercase()));
124 Assist { id, label, group, target }
125 }
126
127 pub fn id(&self) -> AssistId {
128 self.id
129 }
130
131 pub fn label(&self) -> String {
132 self.label.clone()
133 }
134
135 pub fn group(&self) -> Option<GroupLabel> {
136 self.group.clone()
137 }
138
139 pub fn target(&self) -> TextRange {
140 self.target
141 }
142} 116}
143 117
144mod handlers { 118mod handlers {
diff --git a/crates/assists/src/tests/generated.rs b/crates/assists/src/tests/generated.rs
index d16e6fb0a..173567003 100644
--- a/crates/assists/src/tests/generated.rs
+++ b/crates/assists/src/tests/generated.rs
@@ -82,8 +82,8 @@ trait Trait {
82impl Trait for () { 82impl Trait for () {
83 Type X = (); 83 Type X = ();
84 fn foo(&self) {} 84 fn foo(&self) {}
85 $0fn bar(&self) {}
86 85
86 $0fn bar(&self) {}
87} 87}
88"#####, 88"#####,
89 ) 89 )
@@ -115,7 +115,6 @@ impl Trait<u32> for () {
115 fn foo(&self) -> u32 { 115 fn foo(&self) -> u32 {
116 ${0:todo!()} 116 ${0:todo!()}
117 } 117 }
118
119} 118}
120"#####, 119"#####,
121 ) 120 )
diff --git a/crates/hir/src/has_source.rs b/crates/hir/src/has_source.rs
index a50d4ff02..3bad2338a 100644
--- a/crates/hir/src/has_source.rs
+++ b/crates/hir/src/has_source.rs
@@ -1,4 +1,4 @@
1//! FIXME: write short doc here 1//! Provides set of implementation for hir's objects that allows get back location in file.
2 2
3use either::Either; 3use either::Either;
4use hir_def::{ 4use hir_def::{
diff --git a/crates/hir_def/src/diagnostics.rs b/crates/hir_def/src/diagnostics.rs
index 2e38a978f..3e19d9117 100644
--- a/crates/hir_def/src/diagnostics.rs
+++ b/crates/hir_def/src/diagnostics.rs
@@ -2,7 +2,7 @@
2 2
3use std::any::Any; 3use std::any::Any;
4 4
5use hir_expand::diagnostics::Diagnostic; 5use hir_expand::diagnostics::{Diagnostic, DiagnosticCode};
6use syntax::{ast, AstPtr, SyntaxNodePtr}; 6use syntax::{ast, AstPtr, SyntaxNodePtr};
7 7
8use hir_expand::{HirFileId, InFile}; 8use hir_expand::{HirFileId, InFile};
@@ -15,6 +15,9 @@ pub struct UnresolvedModule {
15} 15}
16 16
17impl Diagnostic for UnresolvedModule { 17impl Diagnostic for UnresolvedModule {
18 fn code(&self) -> DiagnosticCode {
19 DiagnosticCode("unresolved-module")
20 }
18 fn message(&self) -> String { 21 fn message(&self) -> String {
19 "unresolved module".to_string() 22 "unresolved module".to_string()
20 } 23 }
diff --git a/crates/hir_expand/src/diagnostics.rs b/crates/hir_expand/src/diagnostics.rs
index 59d35debe..78ccc212c 100644
--- a/crates/hir_expand/src/diagnostics.rs
+++ b/crates/hir_expand/src/diagnostics.rs
@@ -20,7 +20,17 @@ use syntax::SyntaxNodePtr;
20 20
21use crate::InFile; 21use crate::InFile;
22 22
23#[derive(Copy, Clone, PartialEq)]
24pub struct DiagnosticCode(pub &'static str);
25
26impl DiagnosticCode {
27 pub fn as_str(&self) -> &str {
28 self.0
29 }
30}
31
23pub trait Diagnostic: Any + Send + Sync + fmt::Debug + 'static { 32pub trait Diagnostic: Any + Send + Sync + fmt::Debug + 'static {
33 fn code(&self) -> DiagnosticCode;
24 fn message(&self) -> String; 34 fn message(&self) -> String;
25 /// Used in highlighting and related purposes 35 /// Used in highlighting and related purposes
26 fn display_source(&self) -> InFile<SyntaxNodePtr>; 36 fn display_source(&self) -> InFile<SyntaxNodePtr>;
diff --git a/crates/hir_ty/Cargo.toml b/crates/hir_ty/Cargo.toml
index 83b5013a9..a319b0ce8 100644
--- a/crates/hir_ty/Cargo.toml
+++ b/crates/hir_ty/Cargo.toml
@@ -16,9 +16,9 @@ ena = "0.14.0"
16log = "0.4.8" 16log = "0.4.8"
17rustc-hash = "1.1.0" 17rustc-hash = "1.1.0"
18scoped-tls = "1" 18scoped-tls = "1"
19chalk-solve = { version = "0.21.0" } 19chalk-solve = { version = "0.23.0" }
20chalk-ir = { version = "0.21.0" } 20chalk-ir = { version = "0.23.0" }
21chalk-recursive = { version = "0.21.0" } 21chalk-recursive = { version = "0.23.0" }
22 22
23stdx = { path = "../stdx" } 23stdx = { path = "../stdx" }
24hir_def = { path = "../hir_def" } 24hir_def = { path = "../hir_def" }
diff --git a/crates/hir_ty/src/diagnostics.rs b/crates/hir_ty/src/diagnostics.rs
index ae0cf8d09..9ba005fab 100644
--- a/crates/hir_ty/src/diagnostics.rs
+++ b/crates/hir_ty/src/diagnostics.rs
@@ -6,7 +6,7 @@ mod unsafe_check;
6use std::any::Any; 6use std::any::Any;
7 7
8use hir_def::DefWithBodyId; 8use hir_def::DefWithBodyId;
9use hir_expand::diagnostics::{Diagnostic, DiagnosticSink}; 9use hir_expand::diagnostics::{Diagnostic, DiagnosticCode, DiagnosticSink};
10use hir_expand::{name::Name, HirFileId, InFile}; 10use hir_expand::{name::Name, HirFileId, InFile};
11use stdx::format_to; 11use stdx::format_to;
12use syntax::{ast, AstPtr, SyntaxNodePtr}; 12use syntax::{ast, AstPtr, SyntaxNodePtr};
@@ -32,6 +32,10 @@ pub struct NoSuchField {
32} 32}
33 33
34impl Diagnostic for NoSuchField { 34impl Diagnostic for NoSuchField {
35 fn code(&self) -> DiagnosticCode {
36 DiagnosticCode("no-such-field")
37 }
38
35 fn message(&self) -> String { 39 fn message(&self) -> String {
36 "no such field".to_string() 40 "no such field".to_string()
37 } 41 }
@@ -54,6 +58,9 @@ pub struct MissingFields {
54} 58}
55 59
56impl Diagnostic for MissingFields { 60impl Diagnostic for MissingFields {
61 fn code(&self) -> DiagnosticCode {
62 DiagnosticCode("missing-structure-fields")
63 }
57 fn message(&self) -> String { 64 fn message(&self) -> String {
58 let mut buf = String::from("Missing structure fields:\n"); 65 let mut buf = String::from("Missing structure fields:\n");
59 for field in &self.missed_fields { 66 for field in &self.missed_fields {
@@ -87,6 +94,9 @@ pub struct MissingPatFields {
87} 94}
88 95
89impl Diagnostic for MissingPatFields { 96impl Diagnostic for MissingPatFields {
97 fn code(&self) -> DiagnosticCode {
98 DiagnosticCode("missing-pat-fields")
99 }
90 fn message(&self) -> String { 100 fn message(&self) -> String {
91 let mut buf = String::from("Missing structure fields:\n"); 101 let mut buf = String::from("Missing structure fields:\n");
92 for field in &self.missed_fields { 102 for field in &self.missed_fields {
@@ -117,6 +127,9 @@ pub struct MissingMatchArms {
117} 127}
118 128
119impl Diagnostic for MissingMatchArms { 129impl Diagnostic for MissingMatchArms {
130 fn code(&self) -> DiagnosticCode {
131 DiagnosticCode("missing-match-arm")
132 }
120 fn message(&self) -> String { 133 fn message(&self) -> String {
121 String::from("Missing match arm") 134 String::from("Missing match arm")
122 } 135 }
@@ -135,6 +148,9 @@ pub struct MissingOkInTailExpr {
135} 148}
136 149
137impl Diagnostic for MissingOkInTailExpr { 150impl Diagnostic for MissingOkInTailExpr {
151 fn code(&self) -> DiagnosticCode {
152 DiagnosticCode("missing-ok-in-tail-expr")
153 }
138 fn message(&self) -> String { 154 fn message(&self) -> String {
139 "wrap return expression in Ok".to_string() 155 "wrap return expression in Ok".to_string()
140 } 156 }
@@ -153,6 +169,9 @@ pub struct BreakOutsideOfLoop {
153} 169}
154 170
155impl Diagnostic for BreakOutsideOfLoop { 171impl Diagnostic for BreakOutsideOfLoop {
172 fn code(&self) -> DiagnosticCode {
173 DiagnosticCode("break-outside-of-loop")
174 }
156 fn message(&self) -> String { 175 fn message(&self) -> String {
157 "break outside of loop".to_string() 176 "break outside of loop".to_string()
158 } 177 }
@@ -171,6 +190,9 @@ pub struct MissingUnsafe {
171} 190}
172 191
173impl Diagnostic for MissingUnsafe { 192impl Diagnostic for MissingUnsafe {
193 fn code(&self) -> DiagnosticCode {
194 DiagnosticCode("missing-unsafe")
195 }
174 fn message(&self) -> String { 196 fn message(&self) -> String {
175 format!("This operation is unsafe and requires an unsafe function or block") 197 format!("This operation is unsafe and requires an unsafe function or block")
176 } 198 }
@@ -191,6 +213,9 @@ pub struct MismatchedArgCount {
191} 213}
192 214
193impl Diagnostic for MismatchedArgCount { 215impl Diagnostic for MismatchedArgCount {
216 fn code(&self) -> DiagnosticCode {
217 DiagnosticCode("mismatched-arg-count")
218 }
194 fn message(&self) -> String { 219 fn message(&self) -> String {
195 let s = if self.expected == 1 { "" } else { "s" }; 220 let s = if self.expected == 1 { "" } else { "s" };
196 format!("Expected {} argument{}, found {}", self.expected, s, self.found) 221 format!("Expected {} argument{}, found {}", self.expected, s, self.found)
diff --git a/crates/hir_ty/src/diagnostics/expr.rs b/crates/hir_ty/src/diagnostics/expr.rs
index fb76e2e4e..278a4b947 100644
--- a/crates/hir_ty/src/diagnostics/expr.rs
+++ b/crates/hir_ty/src/diagnostics/expr.rs
@@ -223,10 +223,10 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
223 db.body_with_source_map(self.owner.into()); 223 db.body_with_source_map(self.owner.into());
224 224
225 let match_expr_ty = match infer.type_of_expr.get(match_expr) { 225 let match_expr_ty = match infer.type_of_expr.get(match_expr) {
226 Some(ty) => ty,
227 // If we can't resolve the type of the match expression 226 // If we can't resolve the type of the match expression
228 // we cannot perform exhaustiveness checks. 227 // we cannot perform exhaustiveness checks.
229 None => return, 228 None | Some(Ty::Unknown) => return,
229 Some(ty) => ty,
230 }; 230 };
231 231
232 let cx = MatchCheckCtx { match_expr, body, infer: infer.clone(), db }; 232 let cx = MatchCheckCtx { match_expr, body, infer: infer.clone(), db };
diff --git a/crates/hir_ty/src/diagnostics/match_check.rs b/crates/hir_ty/src/diagnostics/match_check.rs
index 7f007f1d6..5bd03f2ac 100644
--- a/crates/hir_ty/src/diagnostics/match_check.rs
+++ b/crates/hir_ty/src/diagnostics/match_check.rs
@@ -1335,6 +1335,23 @@ fn panic(a: Category, b: Category) {
1335 ); 1335 );
1336 } 1336 }
1337 1337
1338 #[test]
1339 fn unknown_type() {
1340 check_diagnostics(
1341 r#"
1342enum Option<T> { Some(T), None }
1343
1344fn main() {
1345 // `Never` is deliberately not defined so that it's an uninferred type.
1346 match Option::<Never>::None {
1347 None => (),
1348 Some(never) => match never {},
1349 }
1350}
1351"#,
1352 );
1353 }
1354
1338 mod false_negatives { 1355 mod false_negatives {
1339 //! The implementation of match checking here is a work in progress. As we roll this out, we 1356 //! The implementation of match checking here is a work in progress. As we roll this out, we
1340 //! prefer false negatives to false positives (ideally there would be no false positives). This 1357 //! prefer false negatives to false positives (ideally there would be no false positives). This
diff --git a/crates/hir_ty/src/tests.rs b/crates/hir_ty/src/tests.rs
index c953925ec..91c9d38c5 100644
--- a/crates/hir_ty/src/tests.rs
+++ b/crates/hir_ty/src/tests.rs
@@ -8,7 +8,7 @@ mod method_resolution;
8mod macros; 8mod macros;
9mod display_source_code; 9mod display_source_code;
10 10
11use std::sync::Arc; 11use std::{env, sync::Arc};
12 12
13use base_db::{fixture::WithFixture, FileRange, SourceDatabase, SourceDatabaseExt}; 13use base_db::{fixture::WithFixture, FileRange, SourceDatabase, SourceDatabaseExt};
14use expect::Expect; 14use expect::Expect;
@@ -22,12 +22,14 @@ use hir_def::{
22 AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId, 22 AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId,
23}; 23};
24use hir_expand::{db::AstDatabase, InFile}; 24use hir_expand::{db::AstDatabase, InFile};
25use stdx::format_to; 25use stdx::{format_to, RacyFlag};
26use syntax::{ 26use syntax::{
27 algo, 27 algo,
28 ast::{self, AstNode}, 28 ast::{self, AstNode},
29 SyntaxNode, 29 SyntaxNode,
30}; 30};
31use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
32use tracing_tree::HierarchicalLayer;
31 33
32use crate::{ 34use crate::{
33 db::HirDatabase, display::HirDisplay, infer::TypeMismatch, test_db::TestDB, InferenceResult, Ty, 35 db::HirDatabase, display::HirDisplay, infer::TypeMismatch, test_db::TestDB, InferenceResult, Ty,
@@ -37,9 +39,12 @@ use crate::{
37// against snapshots of the expected results using expect. Use 39// against snapshots of the expected results using expect. Use
38// `env UPDATE_EXPECT=1 cargo test -p hir_ty` to update the snapshots. 40// `env UPDATE_EXPECT=1 cargo test -p hir_ty` to update the snapshots.
39 41
40fn setup_tracing() -> tracing::subscriber::DefaultGuard { 42fn setup_tracing() -> Option<tracing::subscriber::DefaultGuard> {
41 use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry}; 43 static ENABLE: RacyFlag = RacyFlag::new();
42 use tracing_tree::HierarchicalLayer; 44 if !ENABLE.get(|| env::var("CHALK_DEBUG").is_ok()) {
45 return None;
46 }
47
43 let filter = EnvFilter::from_env("CHALK_DEBUG"); 48 let filter = EnvFilter::from_env("CHALK_DEBUG");
44 let layer = HierarchicalLayer::default() 49 let layer = HierarchicalLayer::default()
45 .with_indent_lines(true) 50 .with_indent_lines(true)
@@ -47,7 +52,7 @@ fn setup_tracing() -> tracing::subscriber::DefaultGuard {
47 .with_indent_amount(2) 52 .with_indent_amount(2)
48 .with_writer(std::io::stderr); 53 .with_writer(std::io::stderr);
49 let subscriber = Registry::default().with(filter).with(layer); 54 let subscriber = Registry::default().with(filter).with(layer);
50 tracing::subscriber::set_default(subscriber) 55 Some(tracing::subscriber::set_default(subscriber))
51} 56}
52 57
53fn check_types(ra_fixture: &str) { 58fn check_types(ra_fixture: &str) {
diff --git a/crates/hir_ty/src/traits.rs b/crates/hir_ty/src/traits.rs
index 1c3abb18f..14cd3a2b4 100644
--- a/crates/hir_ty/src/traits.rs
+++ b/crates/hir_ty/src/traits.rs
@@ -170,11 +170,11 @@ fn solve(
170 let mut solve = || { 170 let mut solve = || {
171 if is_chalk_print() { 171 if is_chalk_print() {
172 let logging_db = LoggingRustIrDatabase::new(context); 172 let logging_db = LoggingRustIrDatabase::new(context);
173 let solution = solver.solve_limited(&logging_db, goal, should_continue); 173 let solution = solver.solve_limited(&logging_db, goal, &should_continue);
174 log::debug!("chalk program:\n{}", logging_db); 174 log::debug!("chalk program:\n{}", logging_db);
175 solution 175 solution
176 } else { 176 } else {
177 solver.solve_limited(&context, goal, should_continue) 177 solver.solve_limited(&context, goal, &should_continue)
178 } 178 }
179 }; 179 };
180 180
diff --git a/crates/ide/src/completion.rs b/crates/ide/src/completion.rs
index 7fb4d687e..25e580d80 100644
--- a/crates/ide/src/completion.rs
+++ b/crates/ide/src/completion.rs
@@ -3,6 +3,7 @@ mod completion_item;
3mod completion_context; 3mod completion_context;
4mod presentation; 4mod presentation;
5mod patterns; 5mod patterns;
6mod generated_features;
6#[cfg(test)] 7#[cfg(test)]
7mod test_utils; 8mod test_utils;
8 9
diff --git a/crates/ide/src/completion/complete_attribute.rs b/crates/ide/src/completion/complete_attribute.rs
index 603d935de..042c3ecef 100644
--- a/crates/ide/src/completion/complete_attribute.rs
+++ b/crates/ide/src/completion/complete_attribute.rs
@@ -9,6 +9,7 @@ use syntax::{ast, AstNode, SyntaxKind};
9use crate::completion::{ 9use crate::completion::{
10 completion_context::CompletionContext, 10 completion_context::CompletionContext,
11 completion_item::{CompletionItem, CompletionItemKind, CompletionKind, Completions}, 11 completion_item::{CompletionItem, CompletionItemKind, CompletionKind, Completions},
12 generated_features::FEATURES,
12}; 13};
13 14
14pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { 15pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
@@ -17,12 +18,15 @@ pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext)
17 (Some(path), Some(token_tree)) if path.to_string() == "derive" => { 18 (Some(path), Some(token_tree)) if path.to_string() == "derive" => {
18 complete_derive(acc, ctx, token_tree) 19 complete_derive(acc, ctx, token_tree)
19 } 20 }
21 (Some(path), Some(token_tree)) if path.to_string() == "feature" => {
22 complete_lint(acc, ctx, token_tree, FEATURES)
23 }
20 (Some(path), Some(token_tree)) 24 (Some(path), Some(token_tree))
21 if ["allow", "warn", "deny", "forbid"] 25 if ["allow", "warn", "deny", "forbid"]
22 .iter() 26 .iter()
23 .any(|lint_level| lint_level == &path.to_string()) => 27 .any(|lint_level| lint_level == &path.to_string()) =>
24 { 28 {
25 complete_lint(acc, ctx, token_tree) 29 complete_lint(acc, ctx, token_tree, DEFAULT_LINT_COMPLETIONS)
26 } 30 }
27 (_, Some(_token_tree)) => {} 31 (_, Some(_token_tree)) => {}
28 _ => complete_attribute_start(acc, ctx, attribute), 32 _ => complete_attribute_start(acc, ctx, attribute),
@@ -162,9 +166,14 @@ fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input:
162 } 166 }
163} 167}
164 168
165fn complete_lint(acc: &mut Completions, ctx: &CompletionContext, derive_input: ast::TokenTree) { 169fn complete_lint(
170 acc: &mut Completions,
171 ctx: &CompletionContext,
172 derive_input: ast::TokenTree,
173 lints_completions: &[LintCompletion],
174) {
166 if let Ok(existing_lints) = parse_comma_sep_input(derive_input) { 175 if let Ok(existing_lints) = parse_comma_sep_input(derive_input) {
167 for lint_completion in DEFAULT_LINT_COMPLETIONS 176 for lint_completion in lints_completions
168 .into_iter() 177 .into_iter()
169 .filter(|completion| !existing_lints.contains(completion.label)) 178 .filter(|completion| !existing_lints.contains(completion.label))
170 { 179 {
@@ -248,9 +257,9 @@ const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[
248 DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] }, 257 DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] },
249]; 258];
250 259
251struct LintCompletion { 260pub(super) struct LintCompletion {
252 label: &'static str, 261 pub(super) label: &'static str,
253 description: &'static str, 262 pub(super) description: &'static str,
254} 263}
255 264
256#[rustfmt::skip] 265#[rustfmt::skip]
diff --git a/crates/ide/src/completion/generated_features.rs b/crates/ide/src/completion/generated_features.rs
new file mode 100644
index 000000000..24754a8cf
--- /dev/null
+++ b/crates/ide/src/completion/generated_features.rs
@@ -0,0 +1,4 @@
1//! Generated file, do not edit by hand, see `xtask/src/codegen`
2
3use crate::completion::complete_attribute::LintCompletion;
4pub ( super ) const FEATURES : & [ LintCompletion ] = & [ 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 : "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 : "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 : "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 : "doc_alias" , description : "# `doc_alias`\n\nThe tracking issue for this feature is: [#50146]\n\n[#50146]: https://github.com/rust-lang/rust/issues/50146\n\n------------------------\n\nYou can add alias(es) to an item when using the `rustdoc` search through the\n`doc(alias)` attribute. Example:\n\n```rust,no_run\n#![feature(doc_alias)]\n\n#[doc(alias = \"x\")]\n#[doc(alias = \"big\")]\npub struct BigX;\n```\n\nThen, when looking for it through the `rustdoc` search, if you enter \"x\" or\n\"big\", search will show the `BigX` struct first.\n\nNote that this feature is currently hidden behind the `feature(doc_alias)` gate.\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 : "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 : "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 : "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 : "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 : "ffi_const" , description : "# `ffi_const`\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[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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "ffi_pure" , description : "# `ffi_pure`\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[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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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`, `abi`.\nNote that it only work best with sized type 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 : "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 : "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 : "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 : "dec2flt" , description : "# `dec2flt`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "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 : "rt" , description : "# `rt`\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 : "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 : "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 : "fd" , description : "# `fd`\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 : "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 : "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 : "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 : "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 : "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 : "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 : "flt2dec" , description : "# `flt2dec`\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 : "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\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## 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\" / \"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| 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| 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) | 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| 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| 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 : "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 : "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 : "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 : "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_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 : "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 : "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 : "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 : "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 : "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 : "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 : "set_stdio" , description : "# `set_stdio`\n\nThis feature is internal to the Rust compiler and is not intended for general use.\n\n------------------------\n" } ] ;
diff --git a/crates/ide/src/diagnostics.rs b/crates/ide/src/diagnostics.rs
index a3ec98178..92b5adaa2 100644
--- a/crates/ide/src/diagnostics.rs
+++ b/crates/ide/src/diagnostics.rs
@@ -4,22 +4,48 @@
4//! macro-expanded files, but we need to present them to the users in terms of 4//! macro-expanded files, but we need to present them to the users in terms of
5//! original files. So we need to map the ranges. 5//! original files. So we need to map the ranges.
6 6
7mod fixes;
8
7use std::cell::RefCell; 9use std::cell::RefCell;
8 10
9use base_db::SourceDatabase; 11use base_db::SourceDatabase;
10use hir::{diagnostics::DiagnosticSinkBuilder, Semantics}; 12use hir::{diagnostics::DiagnosticSinkBuilder, Semantics};
11use ide_db::RootDatabase; 13use ide_db::RootDatabase;
12use itertools::Itertools; 14use itertools::Itertools;
15use rustc_hash::FxHashSet;
13use syntax::{ 16use syntax::{
14 ast::{self, AstNode}, 17 ast::{self, AstNode},
15 SyntaxNode, TextRange, T, 18 SyntaxNode, TextRange, T,
16}; 19};
17use text_edit::TextEdit; 20use text_edit::TextEdit;
18 21
19use crate::{Diagnostic, FileId, Fix, SourceFileEdit}; 22use crate::{FileId, Label, SourceChange, SourceFileEdit};
23
24use self::fixes::DiagnosticWithFix;
25
26#[derive(Debug)]
27pub struct Diagnostic {
28 // pub name: Option<String>,
29 pub message: String,
30 pub range: TextRange,
31 pub severity: Severity,
32 pub fix: Option<Fix>,
33}
20 34
21mod diagnostics_with_fix; 35#[derive(Debug)]
22use diagnostics_with_fix::DiagnosticWithFix; 36pub struct Fix {
37 pub label: Label,
38 pub source_change: SourceChange,
39 /// Allows to trigger the fix only when the caret is in the range given
40 pub fix_trigger_range: TextRange,
41}
42
43impl Fix {
44 fn new(label: &str, source_change: SourceChange, fix_trigger_range: TextRange) -> Self {
45 let label = Label::new(label);
46 Self { label, source_change, fix_trigger_range }
47 }
48}
23 49
24#[derive(Debug, Copy, Clone)] 50#[derive(Debug, Copy, Clone)]
25pub enum Severity { 51pub enum Severity {
@@ -27,10 +53,16 @@ pub enum Severity {
27 WeakWarning, 53 WeakWarning,
28} 54}
29 55
56#[derive(Default, Debug, Clone)]
57pub struct DiagnosticsConfig {
58 pub disable_experimental: bool,
59 pub disabled: FxHashSet<String>,
60}
61
30pub(crate) fn diagnostics( 62pub(crate) fn diagnostics(
31 db: &RootDatabase, 63 db: &RootDatabase,
64 config: &DiagnosticsConfig,
32 file_id: FileId, 65 file_id: FileId,
33 enable_experimental: bool,
34) -> Vec<Diagnostic> { 66) -> Vec<Diagnostic> {
35 let _p = profile::span("diagnostics"); 67 let _p = profile::span("diagnostics");
36 let sema = Semantics::new(db); 68 let sema = Semantics::new(db);
@@ -39,6 +71,7 @@ pub(crate) fn diagnostics(
39 71
40 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily. 72 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
41 res.extend(parse.errors().iter().take(128).map(|err| Diagnostic { 73 res.extend(parse.errors().iter().take(128).map(|err| Diagnostic {
74 // name: None,
42 range: err.range(), 75 range: err.range(),
43 message: format!("Syntax Error: {}", err), 76 message: format!("Syntax Error: {}", err),
44 severity: Severity::Error, 77 severity: Severity::Error,
@@ -50,7 +83,7 @@ pub(crate) fn diagnostics(
50 check_struct_shorthand_initialization(&mut res, file_id, &node); 83 check_struct_shorthand_initialization(&mut res, file_id, &node);
51 } 84 }
52 let res = RefCell::new(res); 85 let res = RefCell::new(res);
53 let mut sink = DiagnosticSinkBuilder::new() 86 let sink_builder = DiagnosticSinkBuilder::new()
54 .on::<hir::diagnostics::UnresolvedModule, _>(|d| { 87 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
55 res.borrow_mut().push(diagnostic_with_fix(d, &sema)); 88 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
56 }) 89 })
@@ -64,10 +97,15 @@ pub(crate) fn diagnostics(
64 res.borrow_mut().push(diagnostic_with_fix(d, &sema)); 97 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
65 }) 98 })
66 // Only collect experimental diagnostics when they're enabled. 99 // Only collect experimental diagnostics when they're enabled.
67 .filter(|diag| !diag.is_experimental() || enable_experimental) 100 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
101 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
102
103 // Finalize the `DiagnosticSink` building process.
104 let mut sink = sink_builder
68 // Diagnostics not handled above get no fix and default treatment. 105 // Diagnostics not handled above get no fix and default treatment.
69 .build(|d| { 106 .build(|d| {
70 res.borrow_mut().push(Diagnostic { 107 res.borrow_mut().push(Diagnostic {
108 // name: Some(d.name().into()),
71 message: d.message(), 109 message: d.message(),
72 range: sema.diagnostics_display_range(d).range, 110 range: sema.diagnostics_display_range(d).range,
73 severity: Severity::Error, 111 severity: Severity::Error,
@@ -84,6 +122,7 @@ pub(crate) fn diagnostics(
84 122
85fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic { 123fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
86 Diagnostic { 124 Diagnostic {
125 // name: Some(d.name().into()),
87 range: sema.diagnostics_display_range(d).range, 126 range: sema.diagnostics_display_range(d).range,
88 message: d.message(), 127 message: d.message(),
89 severity: Severity::Error, 128 severity: Severity::Error,
@@ -110,6 +149,7 @@ fn check_unnecessary_braces_in_use_statement(
110 }); 149 });
111 150
112 acc.push(Diagnostic { 151 acc.push(Diagnostic {
152 // name: None,
113 range: use_range, 153 range: use_range,
114 message: "Unnecessary braces in use statement".to_string(), 154 message: "Unnecessary braces in use statement".to_string(),
115 severity: Severity::WeakWarning, 155 severity: Severity::WeakWarning,
@@ -156,6 +196,7 @@ fn check_struct_shorthand_initialization(
156 196
157 let field_range = record_field.syntax().text_range(); 197 let field_range = record_field.syntax().text_range();
158 acc.push(Diagnostic { 198 acc.push(Diagnostic {
199 // name: None,
159 range: field_range, 200 range: field_range,
160 message: "Shorthand struct initialization".to_string(), 201 message: "Shorthand struct initialization".to_string(),
161 severity: Severity::WeakWarning, 202 severity: Severity::WeakWarning,
@@ -173,11 +214,14 @@ fn check_struct_shorthand_initialization(
173 214
174#[cfg(test)] 215#[cfg(test)]
175mod tests { 216mod tests {
217 use expect::{expect, Expect};
176 use stdx::trim_indent; 218 use stdx::trim_indent;
177 use test_utils::assert_eq_text; 219 use test_utils::assert_eq_text;
178 220
179 use crate::mock_analysis::{analysis_and_position, single_file, MockAnalysis}; 221 use crate::{
180 use expect::{expect, Expect}; 222 mock_analysis::{analysis_and_position, single_file, MockAnalysis},
223 DiagnosticsConfig,
224 };
181 225
182 /// Takes a multi-file input fixture with annotated cursor positions, 226 /// Takes a multi-file input fixture with annotated cursor positions,
183 /// and checks that: 227 /// and checks that:
@@ -188,7 +232,11 @@ mod tests {
188 let after = trim_indent(ra_fixture_after); 232 let after = trim_indent(ra_fixture_after);
189 233
190 let (analysis, file_position) = analysis_and_position(ra_fixture_before); 234 let (analysis, file_position) = analysis_and_position(ra_fixture_before);
191 let diagnostic = analysis.diagnostics(file_position.file_id, true).unwrap().pop().unwrap(); 235 let diagnostic = analysis
236 .diagnostics(&DiagnosticsConfig::default(), file_position.file_id)
237 .unwrap()
238 .pop()
239 .unwrap();
192 let mut fix = diagnostic.fix.unwrap(); 240 let mut fix = diagnostic.fix.unwrap();
193 let edit = fix.source_change.source_file_edits.pop().unwrap().edit; 241 let edit = fix.source_change.source_file_edits.pop().unwrap().edit;
194 let target_file_contents = analysis.file_text(file_position.file_id).unwrap(); 242 let target_file_contents = analysis.file_text(file_position.file_id).unwrap();
@@ -214,7 +262,11 @@ mod tests {
214 let ra_fixture_after = &trim_indent(ra_fixture_after); 262 let ra_fixture_after = &trim_indent(ra_fixture_after);
215 let (analysis, file_pos) = analysis_and_position(ra_fixture_before); 263 let (analysis, file_pos) = analysis_and_position(ra_fixture_before);
216 let current_file_id = file_pos.file_id; 264 let current_file_id = file_pos.file_id;
217 let diagnostic = analysis.diagnostics(current_file_id, true).unwrap().pop().unwrap(); 265 let diagnostic = analysis
266 .diagnostics(&DiagnosticsConfig::default(), current_file_id)
267 .unwrap()
268 .pop()
269 .unwrap();
218 let mut fix = diagnostic.fix.unwrap(); 270 let mut fix = diagnostic.fix.unwrap();
219 let edit = fix.source_change.source_file_edits.pop().unwrap(); 271 let edit = fix.source_change.source_file_edits.pop().unwrap();
220 let changed_file_id = edit.file_id; 272 let changed_file_id = edit.file_id;
@@ -235,14 +287,16 @@ mod tests {
235 let analysis = mock.analysis(); 287 let analysis = mock.analysis();
236 let diagnostics = files 288 let diagnostics = files
237 .into_iter() 289 .into_iter()
238 .flat_map(|file_id| analysis.diagnostics(file_id, true).unwrap()) 290 .flat_map(|file_id| {
291 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
292 })
239 .collect::<Vec<_>>(); 293 .collect::<Vec<_>>();
240 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics); 294 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
241 } 295 }
242 296
243 fn check_expect(ra_fixture: &str, expect: Expect) { 297 fn check_expect(ra_fixture: &str, expect: Expect) {
244 let (analysis, file_id) = single_file(ra_fixture); 298 let (analysis, file_id) = single_file(ra_fixture);
245 let diagnostics = analysis.diagnostics(file_id, true).unwrap(); 299 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
246 expect.assert_debug_eq(&diagnostics) 300 expect.assert_debug_eq(&diagnostics)
247 } 301 }
248 302
@@ -675,4 +729,18 @@ struct Foo {
675 ", 729 ",
676 ) 730 )
677 } 731 }
732
733 #[test]
734 fn test_disabled_diagnostics() {
735 let mut config = DiagnosticsConfig::default();
736 config.disabled.insert("unresolved-module".into());
737
738 let (analysis, file_id) = single_file(r#"mod foo;"#);
739
740 let diagnostics = analysis.diagnostics(&config, file_id).unwrap();
741 assert!(diagnostics.is_empty());
742
743 let diagnostics = analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
744 assert!(!diagnostics.is_empty());
745 }
678} 746}
diff --git a/crates/ide/src/diagnostics/diagnostics_with_fix.rs b/crates/ide/src/diagnostics/fixes.rs
index 85b46c995..68ae1c239 100644
--- a/crates/ide/src/diagnostics/diagnostics_with_fix.rs
+++ b/crates/ide/src/diagnostics/fixes.rs
@@ -1,7 +1,5 @@
1//! Provides a way to attach fixes to the diagnostics. 1//! Provides a way to attach fixes to the diagnostics.
2//! The same module also has all curret custom fixes for the diagnostics implemented. 2//! The same module also has all curret custom fixes for the diagnostics implemented.
3use crate::Fix;
4use ast::{edit::IndentLevel, make};
5use base_db::FileId; 3use base_db::FileId;
6use hir::{ 4use hir::{
7 db::AstDatabase, 5 db::AstDatabase,
@@ -12,9 +10,15 @@ use ide_db::{
12 source_change::{FileSystemEdit, SourceFileEdit}, 10 source_change::{FileSystemEdit, SourceFileEdit},
13 RootDatabase, 11 RootDatabase,
14}; 12};
15use syntax::{algo, ast, AstNode}; 13use syntax::{
14 algo,
15 ast::{self, edit::IndentLevel, make},
16 AstNode,
17};
16use text_edit::TextEdit; 18use text_edit::TextEdit;
17 19
20use crate::diagnostics::Fix;
21
18/// A [Diagnostic] that potentially has a fix available. 22/// A [Diagnostic] that potentially has a fix available.
19/// 23///
20/// [Diagnostic]: hir::diagnostics::Diagnostic 24/// [Diagnostic]: hir::diagnostics::Diagnostic
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs
index eb6389529..e3af6d5bc 100644
--- a/crates/ide/src/lib.rs
+++ b/crates/ide/src/lib.rs
@@ -65,7 +65,7 @@ pub use crate::{
65 completion::{ 65 completion::{
66 CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat, 66 CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat,
67 }, 67 },
68 diagnostics::Severity, 68 diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
69 display::NavigationTarget, 69 display::NavigationTarget,
70 expand_macro::ExpandedMacro, 70 expand_macro::ExpandedMacro,
71 file_structure::StructureNode, 71 file_structure::StructureNode,
@@ -88,6 +88,7 @@ pub use base_db::{
88pub use hir::{Documentation, Semantics}; 88pub use hir::{Documentation, Semantics};
89pub use ide_db::{ 89pub use ide_db::{
90 change::AnalysisChange, 90 change::AnalysisChange,
91 label::Label,
91 line_index::{LineCol, LineIndex}, 92 line_index::{LineCol, LineIndex},
92 search::SearchScope, 93 search::SearchScope,
93 source_change::{FileSystemEdit, SourceChange, SourceFileEdit}, 94 source_change::{FileSystemEdit, SourceChange, SourceFileEdit},
@@ -99,34 +100,6 @@ pub use text_edit::{Indel, TextEdit};
99 100
100pub type Cancelable<T> = Result<T, Canceled>; 101pub type Cancelable<T> = Result<T, Canceled>;
101 102
102#[derive(Debug)]
103pub struct Diagnostic {
104 pub message: String,
105 pub range: TextRange,
106 pub severity: Severity,
107 pub fix: Option<Fix>,
108}
109
110#[derive(Debug)]
111pub struct Fix {
112 pub label: String,
113 pub source_change: SourceChange,
114 /// Allows to trigger the fix only when the caret is in the range given
115 pub fix_trigger_range: TextRange,
116}
117
118impl Fix {
119 pub fn new(
120 label: impl Into<String>,
121 source_change: SourceChange,
122 fix_trigger_range: TextRange,
123 ) -> Self {
124 let label = label.into();
125 assert!(label.starts_with(char::is_uppercase) && !label.ends_with('.'));
126 Self { label, source_change, fix_trigger_range }
127 }
128}
129
130/// Info associated with a text range. 103/// Info associated with a text range.
131#[derive(Debug)] 104#[derive(Debug)]
132pub struct RangeInfo<T> { 105pub struct RangeInfo<T> {
@@ -494,10 +467,10 @@ impl Analysis {
494 /// Computes the set of diagnostics for the given file. 467 /// Computes the set of diagnostics for the given file.
495 pub fn diagnostics( 468 pub fn diagnostics(
496 &self, 469 &self,
470 config: &DiagnosticsConfig,
497 file_id: FileId, 471 file_id: FileId,
498 enable_experimental: bool,
499 ) -> Cancelable<Vec<Diagnostic>> { 472 ) -> Cancelable<Vec<Diagnostic>> {
500 self.with_db(|db| diagnostics::diagnostics(db, file_id, enable_experimental)) 473 self.with_db(|db| diagnostics::diagnostics(db, config, file_id))
501 } 474 }
502 475
503 /// Returns the edit required to rename reference at the position to the new 476 /// Returns the edit required to rename reference at the position to the new
diff --git a/crates/ide_db/src/label.rs b/crates/ide_db/src/label.rs
new file mode 100644
index 000000000..c0e89e72f
--- /dev/null
+++ b/crates/ide_db/src/label.rs
@@ -0,0 +1,49 @@
1//! See `Label`
2use std::fmt;
3
4/// A type to specify UI label, like an entry in the list of assists. Enforces
5/// proper casing:
6///
7/// Frobnicate bar
8///
9/// Note the upper-case first letter and the absence of `.` at the end.
10#[derive(Clone)]
11pub struct Label(String);
12
13impl PartialEq<str> for Label {
14 fn eq(&self, other: &str) -> bool {
15 self.0 == other
16 }
17}
18
19impl PartialEq<&'_ str> for Label {
20 fn eq(&self, other: &&str) -> bool {
21 self == *other
22 }
23}
24
25impl From<Label> for String {
26 fn from(label: Label) -> String {
27 label.0
28 }
29}
30
31impl Label {
32 pub fn new(label: impl Into<String>) -> Label {
33 let label = label.into();
34 assert!(label.starts_with(char::is_uppercase) && !label.ends_with('.'));
35 Label(label)
36 }
37}
38
39impl fmt::Display for Label {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 fmt::Display::fmt(&self.0, f)
42 }
43}
44
45impl fmt::Debug for Label {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 fmt::Debug::fmt(&self.0, f)
48 }
49}
diff --git a/crates/ide_db/src/lib.rs b/crates/ide_db/src/lib.rs
index fd474cd0f..70ada02f3 100644
--- a/crates/ide_db/src/lib.rs
+++ b/crates/ide_db/src/lib.rs
@@ -2,6 +2,7 @@
2//! 2//!
3//! It is mainly a `HirDatabase` for semantic analysis, plus a `SymbolsDatabase`, for fuzzy search. 3//! It is mainly a `HirDatabase` for semantic analysis, plus a `SymbolsDatabase`, for fuzzy search.
4 4
5pub mod label;
5pub mod line_index; 6pub mod line_index;
6pub mod symbol_index; 7pub mod symbol_index;
7pub mod change; 8pub mod change;
diff --git a/crates/proc_macro_api/src/lib.rs b/crates/proc_macro_api/src/lib.rs
index 15db57eb2..d5e87cf7d 100644
--- a/crates/proc_macro_api/src/lib.rs
+++ b/crates/proc_macro_api/src/lib.rs
@@ -89,9 +89,8 @@ impl ProcMacroClient {
89 macros 89 macros
90 .into_iter() 90 .into_iter()
91 .filter_map(|(name, kind)| { 91 .filter_map(|(name, kind)| {
92 // FIXME: Support custom derive only for now.
93 match kind { 92 match kind {
94 ProcMacroKind::CustomDerive => { 93 ProcMacroKind::CustomDerive | ProcMacroKind::FuncLike => {
95 let name = SmolStr::new(&name); 94 let name = SmolStr::new(&name);
96 let expander: Arc<dyn tt::TokenExpander> = 95 let expander: Arc<dyn tt::TokenExpander> =
97 Arc::new(ProcMacroProcessExpander { 96 Arc::new(ProcMacroProcessExpander {
@@ -101,7 +100,8 @@ impl ProcMacroClient {
101 }); 100 });
102 Some((name, expander)) 101 Some((name, expander))
103 } 102 }
104 _ => None, 103 // FIXME: Attribute macro are currently unsupported.
104 ProcMacroKind::Attr => None,
105 } 105 }
106 }) 106 })
107 .collect() 107 .collect()
diff --git a/crates/rust-analyzer/src/cli/analysis_bench.rs b/crates/rust-analyzer/src/cli/analysis_bench.rs
index 0f614f9e0..c312e0a2e 100644
--- a/crates/rust-analyzer/src/cli/analysis_bench.rs
+++ b/crates/rust-analyzer/src/cli/analysis_bench.rs
@@ -7,7 +7,10 @@ use base_db::{
7 salsa::{Database, Durability}, 7 salsa::{Database, Durability},
8 FileId, 8 FileId,
9}; 9};
10use ide::{Analysis, AnalysisChange, AnalysisHost, CompletionConfig, FilePosition, LineCol}; 10use ide::{
11 Analysis, AnalysisChange, AnalysisHost, CompletionConfig, DiagnosticsConfig, FilePosition,
12 LineCol,
13};
11use vfs::AbsPathBuf; 14use vfs::AbsPathBuf;
12 15
13use crate::{ 16use crate::{
@@ -71,7 +74,7 @@ impl BenchCmd {
71 match &self.what { 74 match &self.what {
72 BenchWhat::Highlight { .. } => { 75 BenchWhat::Highlight { .. } => {
73 let res = do_work(&mut host, file_id, |analysis| { 76 let res = do_work(&mut host, file_id, |analysis| {
74 analysis.diagnostics(file_id, true).unwrap(); 77 analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap();
75 analysis.highlight_as_html(file_id, false).unwrap() 78 analysis.highlight_as_html(file_id, false).unwrap()
76 }); 79 });
77 if verbosity.is_verbose() { 80 if verbosity.is_verbose() {
diff --git a/crates/rust-analyzer/src/cli/diagnostics.rs b/crates/rust-analyzer/src/cli/diagnostics.rs
index 3371c4fd3..c424aa6e2 100644
--- a/crates/rust-analyzer/src/cli/diagnostics.rs
+++ b/crates/rust-analyzer/src/cli/diagnostics.rs
@@ -8,7 +8,7 @@ use rustc_hash::FxHashSet;
8 8
9use base_db::SourceDatabaseExt; 9use base_db::SourceDatabaseExt;
10use hir::Crate; 10use hir::Crate;
11use ide::Severity; 11use ide::{DiagnosticsConfig, Severity};
12 12
13use crate::cli::{load_cargo::load_cargo, Result}; 13use crate::cli::{load_cargo::load_cargo, Result};
14 14
@@ -47,7 +47,8 @@ pub fn diagnostics(
47 String::from("unknown") 47 String::from("unknown")
48 }; 48 };
49 println!("processing crate: {}, module: {}", crate_name, _vfs.file_path(file_id)); 49 println!("processing crate: {}, module: {}", crate_name, _vfs.file_path(file_id));
50 for diagnostic in analysis.diagnostics(file_id, true).unwrap() { 50 for diagnostic in analysis.diagnostics(&DiagnosticsConfig::default(), file_id).unwrap()
51 {
51 if matches!(diagnostic.severity, Severity::Error) { 52 if matches!(diagnostic.severity, Severity::Error) {
52 found_error = true; 53 found_error = true;
53 } 54 }
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs
index 33fb5e9c2..99f7751ac 100644
--- a/crates/rust-analyzer/src/config.rs
+++ b/crates/rust-analyzer/src/config.rs
@@ -10,21 +10,22 @@
10use std::{ffi::OsString, path::PathBuf}; 10use std::{ffi::OsString, path::PathBuf};
11 11
12use flycheck::FlycheckConfig; 12use flycheck::FlycheckConfig;
13use ide::{AssistConfig, CompletionConfig, HoverConfig, InlayHintsConfig}; 13use ide::{AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig};
14use lsp_types::ClientCapabilities; 14use lsp_types::ClientCapabilities;
15use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest}; 15use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest};
16use rustc_hash::FxHashSet;
16use serde::Deserialize; 17use serde::Deserialize;
17use vfs::AbsPathBuf; 18use vfs::AbsPathBuf;
18 19
19use crate::diagnostics::DiagnosticsConfig; 20use crate::diagnostics::DiagnosticsMapConfig;
20 21
21#[derive(Debug, Clone)] 22#[derive(Debug, Clone)]
22pub struct Config { 23pub struct Config {
23 pub client_caps: ClientCapsConfig, 24 pub client_caps: ClientCapsConfig,
24 25
25 pub publish_diagnostics: bool, 26 pub publish_diagnostics: bool,
26 pub experimental_diagnostics: bool,
27 pub diagnostics: DiagnosticsConfig, 27 pub diagnostics: DiagnosticsConfig,
28 pub diagnostics_map: DiagnosticsMapConfig,
28 pub lru_capacity: Option<usize>, 29 pub lru_capacity: Option<usize>,
29 pub proc_macro_srv: Option<(PathBuf, Vec<OsString>)>, 30 pub proc_macro_srv: Option<(PathBuf, Vec<OsString>)>,
30 pub files: FilesConfig, 31 pub files: FilesConfig,
@@ -138,8 +139,8 @@ impl Config {
138 139
139 with_sysroot: true, 140 with_sysroot: true,
140 publish_diagnostics: true, 141 publish_diagnostics: true,
141 experimental_diagnostics: true,
142 diagnostics: DiagnosticsConfig::default(), 142 diagnostics: DiagnosticsConfig::default(),
143 diagnostics_map: DiagnosticsMapConfig::default(),
143 lru_capacity: None, 144 lru_capacity: None,
144 proc_macro_srv: None, 145 proc_macro_srv: None,
145 files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() }, 146 files: FilesConfig { watcher: FilesWatcher::Notify, exclude: Vec::new() },
@@ -190,8 +191,11 @@ impl Config {
190 191
191 self.with_sysroot = data.withSysroot; 192 self.with_sysroot = data.withSysroot;
192 self.publish_diagnostics = data.diagnostics_enable; 193 self.publish_diagnostics = data.diagnostics_enable;
193 self.experimental_diagnostics = data.diagnostics_enableExperimental;
194 self.diagnostics = DiagnosticsConfig { 194 self.diagnostics = DiagnosticsConfig {
195 disable_experimental: !data.diagnostics_enableExperimental,
196 disabled: data.diagnostics_disabled,
197 };
198 self.diagnostics_map = DiagnosticsMapConfig {
195 warnings_as_info: data.diagnostics_warningsAsInfo, 199 warnings_as_info: data.diagnostics_warningsAsInfo,
196 warnings_as_hint: data.diagnostics_warningsAsHint, 200 warnings_as_hint: data.diagnostics_warningsAsHint,
197 }; 201 };
@@ -414,6 +418,7 @@ config_data! {
414 418
415 diagnostics_enable: bool = true, 419 diagnostics_enable: bool = true,
416 diagnostics_enableExperimental: bool = true, 420 diagnostics_enableExperimental: bool = true,
421 diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
417 diagnostics_warningsAsHint: Vec<String> = Vec::new(), 422 diagnostics_warningsAsHint: Vec<String> = Vec::new(),
418 diagnostics_warningsAsInfo: Vec<String> = Vec::new(), 423 diagnostics_warningsAsInfo: Vec<String> = Vec::new(),
419 424
diff --git a/crates/rust-analyzer/src/diagnostics.rs b/crates/rust-analyzer/src/diagnostics.rs
index 108df3eb0..ee6f2a867 100644
--- a/crates/rust-analyzer/src/diagnostics.rs
+++ b/crates/rust-analyzer/src/diagnostics.rs
@@ -11,7 +11,7 @@ use crate::lsp_ext;
11pub(crate) type CheckFixes = Arc<FxHashMap<FileId, Vec<Fix>>>; 11pub(crate) type CheckFixes = Arc<FxHashMap<FileId, Vec<Fix>>>;
12 12
13#[derive(Debug, Default, Clone)] 13#[derive(Debug, Default, Clone)]
14pub struct DiagnosticsConfig { 14pub struct DiagnosticsMapConfig {
15 pub warnings_as_info: Vec<String>, 15 pub warnings_as_info: Vec<String>,
16 pub warnings_as_hint: Vec<String>, 16 pub warnings_as_hint: Vec<String>,
17} 17}
diff --git a/crates/rust-analyzer/src/diagnostics/to_proto.rs b/crates/rust-analyzer/src/diagnostics/to_proto.rs
index 6d5408156..df5583897 100644
--- a/crates/rust-analyzer/src/diagnostics/to_proto.rs
+++ b/crates/rust-analyzer/src/diagnostics/to_proto.rs
@@ -7,11 +7,11 @@ use stdx::format_to;
7 7
8use crate::{lsp_ext, to_proto::url_from_abs_path}; 8use crate::{lsp_ext, to_proto::url_from_abs_path};
9 9
10use super::DiagnosticsConfig; 10use super::DiagnosticsMapConfig;
11 11
12/// Determines the LSP severity from a diagnostic 12/// Determines the LSP severity from a diagnostic
13fn diagnostic_severity( 13fn diagnostic_severity(
14 config: &DiagnosticsConfig, 14 config: &DiagnosticsMapConfig,
15 level: flycheck::DiagnosticLevel, 15 level: flycheck::DiagnosticLevel,
16 code: Option<flycheck::DiagnosticCode>, 16 code: Option<flycheck::DiagnosticCode>,
17) -> Option<lsp_types::DiagnosticSeverity> { 17) -> Option<lsp_types::DiagnosticSeverity> {
@@ -141,7 +141,7 @@ pub(crate) struct MappedRustDiagnostic {
141/// 141///
142/// If the diagnostic has no primary span this will return `None` 142/// If the diagnostic has no primary span this will return `None`
143pub(crate) fn map_rust_diagnostic_to_lsp( 143pub(crate) fn map_rust_diagnostic_to_lsp(
144 config: &DiagnosticsConfig, 144 config: &DiagnosticsMapConfig,
145 rd: &flycheck::Diagnostic, 145 rd: &flycheck::Diagnostic,
146 workspace_root: &Path, 146 workspace_root: &Path,
147) -> Vec<MappedRustDiagnostic> { 147) -> Vec<MappedRustDiagnostic> {
@@ -259,10 +259,10 @@ mod tests {
259 use expect::{expect_file, ExpectFile}; 259 use expect::{expect_file, ExpectFile};
260 260
261 fn check(diagnostics_json: &str, expect: ExpectFile) { 261 fn check(diagnostics_json: &str, expect: ExpectFile) {
262 check_with_config(DiagnosticsConfig::default(), diagnostics_json, expect) 262 check_with_config(DiagnosticsMapConfig::default(), diagnostics_json, expect)
263 } 263 }
264 264
265 fn check_with_config(config: DiagnosticsConfig, diagnostics_json: &str, expect: ExpectFile) { 265 fn check_with_config(config: DiagnosticsMapConfig, diagnostics_json: &str, expect: ExpectFile) {
266 let diagnostic: flycheck::Diagnostic = serde_json::from_str(diagnostics_json).unwrap(); 266 let diagnostic: flycheck::Diagnostic = serde_json::from_str(diagnostics_json).unwrap();
267 let workspace_root = Path::new("/test/"); 267 let workspace_root = Path::new("/test/");
268 let actual = map_rust_diagnostic_to_lsp(&config, &diagnostic, workspace_root); 268 let actual = map_rust_diagnostic_to_lsp(&config, &diagnostic, workspace_root);
@@ -402,9 +402,9 @@ mod tests {
402 #[cfg(not(windows))] 402 #[cfg(not(windows))]
403 fn rustc_unused_variable_as_info() { 403 fn rustc_unused_variable_as_info() {
404 check_with_config( 404 check_with_config(
405 DiagnosticsConfig { 405 DiagnosticsMapConfig {
406 warnings_as_info: vec!["unused_variables".to_string()], 406 warnings_as_info: vec!["unused_variables".to_string()],
407 ..DiagnosticsConfig::default() 407 ..DiagnosticsMapConfig::default()
408 }, 408 },
409 r##"{ 409 r##"{
410 "message": "unused variable: `foo`", 410 "message": "unused variable: `foo`",
@@ -486,9 +486,9 @@ mod tests {
486 #[cfg(not(windows))] 486 #[cfg(not(windows))]
487 fn rustc_unused_variable_as_hint() { 487 fn rustc_unused_variable_as_hint() {
488 check_with_config( 488 check_with_config(
489 DiagnosticsConfig { 489 DiagnosticsMapConfig {
490 warnings_as_hint: vec!["unused_variables".to_string()], 490 warnings_as_hint: vec!["unused_variables".to_string()],
491 ..DiagnosticsConfig::default() 491 ..DiagnosticsMapConfig::default()
492 }, 492 },
493 r##"{ 493 r##"{
494 "message": "unused variable: `foo`", 494 "message": "unused variable: `foo`",
diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs
index 74f73655a..33e60b500 100644
--- a/crates/rust-analyzer/src/handlers.rs
+++ b/crates/rust-analyzer/src/handlers.rs
@@ -271,19 +271,24 @@ pub(crate) fn handle_document_symbol(
271 }; 271 };
272 parents.push((doc_symbol, symbol.parent)); 272 parents.push((doc_symbol, symbol.parent));
273 } 273 }
274 let mut document_symbols = Vec::new(); 274
275 while let Some((node, parent)) = parents.pop() { 275 // Builds hierarchy from a flat list, in reverse order (so that indices
276 match parent { 276 // makes sense)
277 None => document_symbols.push(node), 277 let document_symbols = {
278 Some(i) => { 278 let mut acc = Vec::new();
279 let children = &mut parents[i].0.children; 279 while let Some((mut node, parent_idx)) = parents.pop() {
280 if children.is_none() { 280 if let Some(children) = &mut node.children {
281 *children = Some(Vec::new()); 281 children.reverse();
282 }
283 children.as_mut().unwrap().push(node);
284 } 282 }
283 let parent = match parent_idx {
284 None => &mut acc,
285 Some(i) => parents[i].0.children.get_or_insert_with(Vec::new),
286 };
287 parent.push(node);
285 } 288 }
286 } 289 acc.reverse();
290 acc
291 };
287 292
288 let res = if snap.config.client_caps.hierarchical_symbols { 293 let res = if snap.config.client_caps.hierarchical_symbols {
289 document_symbols.into() 294 document_symbols.into()
@@ -770,17 +775,16 @@ fn handle_fixes(
770 None => {} 775 None => {}
771 }; 776 };
772 777
773 let diagnostics = snap.analysis.diagnostics(file_id, snap.config.experimental_diagnostics)?; 778 let diagnostics = snap.analysis.diagnostics(&snap.config.diagnostics, file_id)?;
774 779
775 for fix in diagnostics 780 for fix in diagnostics
776 .into_iter() 781 .into_iter()
777 .filter_map(|d| d.fix) 782 .filter_map(|d| d.fix)
778 .filter(|fix| fix.fix_trigger_range.intersect(range).is_some()) 783 .filter(|fix| fix.fix_trigger_range.intersect(range).is_some())
779 { 784 {
780 let title = fix.label;
781 let edit = to_proto::snippet_workspace_edit(&snap, fix.source_change)?; 785 let edit = to_proto::snippet_workspace_edit(&snap, fix.source_change)?;
782 let action = lsp_ext::CodeAction { 786 let action = lsp_ext::CodeAction {
783 title, 787 title: fix.label.to_string(),
784 id: None, 788 id: None,
785 group: None, 789 group: None,
786 kind: Some(CodeActionKind::QUICKFIX), 790 kind: Some(CodeActionKind::QUICKFIX),
@@ -859,10 +863,10 @@ pub(crate) fn handle_resolve_code_action(
859 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect()); 863 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
860 864
861 let assists = snap.analysis.resolved_assists(&snap.config.assist, frange)?; 865 let assists = snap.analysis.resolved_assists(&snap.config.assist, frange)?;
862 let (id_string, index) = split_once(&params.id, ':').unwrap(); 866 let (id, index) = split_once(&params.id, ':').unwrap();
863 let index = index.parse::<usize>().unwrap(); 867 let index = index.parse::<usize>().unwrap();
864 let assist = &assists[index]; 868 let assist = &assists[index];
865 assert!(assist.assist.id().0 == id_string); 869 assert!(assist.assist.id.0 == id);
866 Ok(to_proto::resolved_code_action(&snap, assist.clone())?.edit) 870 Ok(to_proto::resolved_code_action(&snap, assist.clone())?.edit)
867} 871}
868 872
@@ -1042,9 +1046,10 @@ pub(crate) fn publish_diagnostics(
1042) -> Result<Vec<Diagnostic>> { 1046) -> Result<Vec<Diagnostic>> {
1043 let _p = profile::span("publish_diagnostics"); 1047 let _p = profile::span("publish_diagnostics");
1044 let line_index = snap.analysis.file_line_index(file_id)?; 1048 let line_index = snap.analysis.file_line_index(file_id)?;
1049
1045 let diagnostics: Vec<Diagnostic> = snap 1050 let diagnostics: Vec<Diagnostic> = snap
1046 .analysis 1051 .analysis
1047 .diagnostics(file_id, snap.config.experimental_diagnostics)? 1052 .diagnostics(&snap.config.diagnostics, file_id)?
1048 .into_iter() 1053 .into_iter()
1049 .map(|d| Diagnostic { 1054 .map(|d| Diagnostic {
1050 range: to_proto::range(&line_index, d.range), 1055 range: to_proto::range(&line_index, d.range),
diff --git a/crates/rust-analyzer/src/lsp_ext.rs b/crates/rust-analyzer/src/lsp_ext.rs
index 3976b6529..e1a28b1b4 100644
--- a/crates/rust-analyzer/src/lsp_ext.rs
+++ b/crates/rust-analyzer/src/lsp_ext.rs
@@ -237,8 +237,13 @@ pub enum Status {
237 Invalid, 237 Invalid,
238} 238}
239 239
240#[derive(Deserialize, Serialize)]
241pub struct StatusParams {
242 pub status: Status,
243}
244
240impl Notification for StatusNotification { 245impl Notification for StatusNotification {
241 type Params = Status; 246 type Params = StatusParams;
242 const METHOD: &'static str = "rust-analyzer/status"; 247 const METHOD: &'static str = "rust-analyzer/status";
243} 248}
244 249
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs
index 66e04653a..f039cdc31 100644
--- a/crates/rust-analyzer/src/main_loop.rs
+++ b/crates/rust-analyzer/src/main_loop.rs
@@ -248,7 +248,7 @@ impl GlobalState {
248 Event::Flycheck(task) => match task { 248 Event::Flycheck(task) => match task {
249 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => { 249 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
250 let diagnostics = crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp( 250 let diagnostics = crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
251 &self.config.diagnostics, 251 &self.config.diagnostics_map,
252 &diagnostic, 252 &diagnostic,
253 &workspace_root, 253 &workspace_root,
254 ); 254 );
diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs
index a2cfb4e0d..505505a77 100644
--- a/crates/rust-analyzer/src/reload.rs
+++ b/crates/rust-analyzer/src/reload.rs
@@ -13,6 +13,7 @@ use crate::{
13 lsp_ext, 13 lsp_ext,
14 main_loop::Task, 14 main_loop::Task,
15}; 15};
16use lsp_ext::StatusParams;
16 17
17impl GlobalState { 18impl GlobalState {
18 pub(crate) fn update_configuration(&mut self, config: Config) { 19 pub(crate) fn update_configuration(&mut self, config: Config) {
@@ -85,7 +86,9 @@ impl GlobalState {
85 Status::Invalid => lsp_ext::Status::Invalid, 86 Status::Invalid => lsp_ext::Status::Invalid,
86 Status::NeedsReload => lsp_ext::Status::NeedsReload, 87 Status::NeedsReload => lsp_ext::Status::NeedsReload,
87 }; 88 };
88 self.send_notification::<lsp_ext::StatusNotification>(lsp_status); 89 self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
90 status: lsp_status,
91 });
89 } 92 }
90 } 93 }
91 pub(crate) fn fetch_workspaces(&mut self) { 94 pub(crate) fn fetch_workspaces(&mut self) {
diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs
index 44c006e4c..a5191c16e 100644
--- a/crates/rust-analyzer/src/to_proto.rs
+++ b/crates/rust-analyzer/src/to_proto.rs
@@ -705,10 +705,10 @@ pub(crate) fn unresolved_code_action(
705 index: usize, 705 index: usize,
706) -> Result<lsp_ext::CodeAction> { 706) -> Result<lsp_ext::CodeAction> {
707 let res = lsp_ext::CodeAction { 707 let res = lsp_ext::CodeAction {
708 title: assist.label(), 708 title: assist.label.to_string(),
709 id: Some(format!("{}:{}", assist.id().0.to_owned(), index.to_string())), 709 id: Some(format!("{}:{}", assist.id.0, index.to_string())),
710 group: assist.group().filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0), 710 group: assist.group.filter(|_| snap.config.client_caps.code_action_group).map(|gr| gr.0),
711 kind: Some(code_action_kind(assist.id().1)), 711 kind: Some(code_action_kind(assist.id.1)),
712 edit: None, 712 edit: None,
713 is_preferred: None, 713 is_preferred: None,
714 }; 714 };
diff --git a/crates/rust-analyzer/tests/heavy_tests/main.rs b/crates/rust-analyzer/tests/rust-analyzer/main.rs
index 7370505f8..fa315ff8e 100644
--- a/crates/rust-analyzer/tests/heavy_tests/main.rs
+++ b/crates/rust-analyzer/tests/rust-analyzer/main.rs
@@ -1,3 +1,13 @@
1//! The most high-level integrated tests for rust-analyzer.
2//!
3//! This tests run a full LSP event loop, spawn cargo and process stdlib from
4//! sysroot. For this reason, the tests here are very slow, and should be
5//! avoided unless absolutely necessary.
6//!
7//! In particular, it's fine *not* to test that client & server agree on
8//! specific JSON shapes here -- there's little value in such tests, as we can't
9//! be sure without a real client anyway.
10
1mod testdir; 11mod testdir;
2mod support; 12mod support;
3 13
diff --git a/crates/rust-analyzer/tests/heavy_tests/support.rs b/crates/rust-analyzer/tests/rust-analyzer/support.rs
index 5bafeba79..5bafeba79 100644
--- a/crates/rust-analyzer/tests/heavy_tests/support.rs
+++ b/crates/rust-analyzer/tests/rust-analyzer/support.rs
diff --git a/crates/rust-analyzer/tests/heavy_tests/testdir.rs b/crates/rust-analyzer/tests/rust-analyzer/testdir.rs
index 7487e7429..7487e7429 100644
--- a/crates/rust-analyzer/tests/heavy_tests/testdir.rs
+++ b/crates/rust-analyzer/tests/rust-analyzer/testdir.rs
diff --git a/crates/ssr/Cargo.toml b/crates/ssr/Cargo.toml
index 56c1f7761..7c2090de3 100644
--- a/crates/ssr/Cargo.toml
+++ b/crates/ssr/Cargo.toml
@@ -12,6 +12,7 @@ doctest = false
12 12
13[dependencies] 13[dependencies]
14rustc-hash = "1.1.0" 14rustc-hash = "1.1.0"
15itertools = "0.9.0"
15 16
16text_edit = { path = "../text_edit" } 17text_edit = { path = "../text_edit" }
17syntax = { path = "../syntax" } 18syntax = { path = "../syntax" }
diff --git a/crates/ssr/src/lib.rs b/crates/ssr/src/lib.rs
index 292bd5b9a..ba669fd56 100644
--- a/crates/ssr/src/lib.rs
+++ b/crates/ssr/src/lib.rs
@@ -21,7 +21,10 @@
21// code in the `foo` module, we'll insert just `Bar`. 21// code in the `foo` module, we'll insert just `Bar`.
22// 22//
23// Inherent method calls should generally be written in UFCS form. e.g. `foo::Bar::baz($s, $a)` will 23// Inherent method calls should generally be written in UFCS form. e.g. `foo::Bar::baz($s, $a)` will
24// match `$s.baz($a)`, provided the method call `baz` resolves to the method `foo::Bar::baz`. 24// match `$s.baz($a)`, provided the method call `baz` resolves to the method `foo::Bar::baz`. When a
25// placeholder is the receiver of a method call in the search pattern (e.g. `$s.foo()`), but not in
26// the replacement template (e.g. `bar($s)`), then *, & and &mut will be added as needed to mirror
27// whatever autoderef and autoref was happening implicitly in the matched code.
25// 28//
26// The scope of the search / replace will be restricted to the current selection if any, otherwise 29// The scope of the search / replace will be restricted to the current selection if any, otherwise
27// it will apply to the whole workspace. 30// it will apply to the whole workspace.
diff --git a/crates/ssr/src/matching.rs b/crates/ssr/src/matching.rs
index ffc7202ae..8bb5ced90 100644
--- a/crates/ssr/src/matching.rs
+++ b/crates/ssr/src/matching.rs
@@ -2,7 +2,7 @@
2//! process of matching, placeholder values are recorded. 2//! process of matching, placeholder values are recorded.
3 3
4use crate::{ 4use crate::{
5 parsing::{Constraint, NodeKind, Placeholder}, 5 parsing::{Constraint, NodeKind, Placeholder, Var},
6 resolving::{ResolvedPattern, ResolvedRule, UfcsCallInfo}, 6 resolving::{ResolvedPattern, ResolvedRule, UfcsCallInfo},
7 SsrMatches, 7 SsrMatches,
8}; 8};
@@ -56,10 +56,6 @@ pub struct Match {
56 pub(crate) rendered_template_paths: FxHashMap<SyntaxNode, hir::ModPath>, 56 pub(crate) rendered_template_paths: FxHashMap<SyntaxNode, hir::ModPath>,
57} 57}
58 58
59/// Represents a `$var` in an SSR query.
60#[derive(Debug, Clone, PartialEq, Eq, Hash)]
61pub(crate) struct Var(pub String);
62
63/// Information about a placeholder bound in a match. 59/// Information about a placeholder bound in a match.
64#[derive(Debug)] 60#[derive(Debug)]
65pub(crate) struct PlaceholderMatch { 61pub(crate) struct PlaceholderMatch {
@@ -69,6 +65,10 @@ pub(crate) struct PlaceholderMatch {
69 pub(crate) range: FileRange, 65 pub(crate) range: FileRange,
70 /// More matches, found within `node`. 66 /// More matches, found within `node`.
71 pub(crate) inner_matches: SsrMatches, 67 pub(crate) inner_matches: SsrMatches,
68 /// How many times the code that the placeholder matched needed to be dereferenced. Will only be
69 /// non-zero if the placeholder matched to the receiver of a method call.
70 pub(crate) autoderef_count: usize,
71 pub(crate) autoref_kind: ast::SelfParamKind,
72} 72}
73 73
74#[derive(Debug)] 74#[derive(Debug)]
@@ -173,7 +173,7 @@ impl<'db, 'sema> Matcher<'db, 'sema> {
173 code: &SyntaxNode, 173 code: &SyntaxNode,
174 ) -> Result<(), MatchFailed> { 174 ) -> Result<(), MatchFailed> {
175 // Handle placeholders. 175 // Handle placeholders.
176 if let Some(placeholder) = self.get_placeholder(&SyntaxElement::Node(pattern.clone())) { 176 if let Some(placeholder) = self.get_placeholder_for_node(pattern) {
177 for constraint in &placeholder.constraints { 177 for constraint in &placeholder.constraints {
178 self.check_constraint(constraint, code)?; 178 self.check_constraint(constraint, code)?;
179 } 179 }
@@ -183,8 +183,8 @@ impl<'db, 'sema> Matcher<'db, 'sema> {
183 // probably can't fail range validation, but just to be safe... 183 // probably can't fail range validation, but just to be safe...
184 self.validate_range(&original_range)?; 184 self.validate_range(&original_range)?;
185 matches_out.placeholder_values.insert( 185 matches_out.placeholder_values.insert(
186 Var(placeholder.ident.to_string()), 186 placeholder.ident.clone(),
187 PlaceholderMatch::new(code, original_range), 187 PlaceholderMatch::new(Some(code), original_range),
188 ); 188 );
189 } 189 }
190 return Ok(()); 190 return Ok(());
@@ -487,7 +487,7 @@ impl<'db, 'sema> Matcher<'db, 'sema> {
487 } 487 }
488 if let Phase::Second(match_out) = phase { 488 if let Phase::Second(match_out) = phase {
489 match_out.placeholder_values.insert( 489 match_out.placeholder_values.insert(
490 Var(placeholder.ident.to_string()), 490 placeholder.ident.clone(),
491 PlaceholderMatch::from_range(FileRange { 491 PlaceholderMatch::from_range(FileRange {
492 file_id: self.sema.original_range(code).file_id, 492 file_id: self.sema.original_range(code).file_id,
493 range: first_matched_token 493 range: first_matched_token
@@ -536,18 +536,40 @@ impl<'db, 'sema> Matcher<'db, 'sema> {
536 if pattern_ufcs.function != code_resolved_function { 536 if pattern_ufcs.function != code_resolved_function {
537 fail_match!("Method call resolved to a different function"); 537 fail_match!("Method call resolved to a different function");
538 } 538 }
539 if code_resolved_function.has_self_param(self.sema.db) {
540 if let (Some(pattern_type), Some(expr)) = (&pattern_ufcs.qualifier_type, &code.expr()) {
541 self.check_expr_type(pattern_type, expr)?;
542 }
543 }
544 // Check arguments. 539 // Check arguments.
545 let mut pattern_args = pattern_ufcs 540 let mut pattern_args = pattern_ufcs
546 .call_expr 541 .call_expr
547 .arg_list() 542 .arg_list()
548 .ok_or_else(|| match_error!("Pattern function call has no args"))? 543 .ok_or_else(|| match_error!("Pattern function call has no args"))?
549 .args(); 544 .args();
550 self.attempt_match_opt(phase, pattern_args.next(), code.expr())?; 545 // If the function we're calling takes a self parameter, then we store additional
546 // information on the placeholder match about autoderef and autoref. This allows us to use
547 // the placeholder in a context where autoderef and autoref don't apply.
548 if code_resolved_function.has_self_param(self.sema.db) {
549 if let (Some(pattern_type), Some(expr)) = (&pattern_ufcs.qualifier_type, &code.expr()) {
550 let deref_count = self.check_expr_type(pattern_type, expr)?;
551 let pattern_receiver = pattern_args.next();
552 self.attempt_match_opt(phase, pattern_receiver.clone(), code.expr())?;
553 if let Phase::Second(match_out) = phase {
554 if let Some(placeholder_value) = pattern_receiver
555 .and_then(|n| self.get_placeholder_for_node(n.syntax()))
556 .and_then(|placeholder| {
557 match_out.placeholder_values.get_mut(&placeholder.ident)
558 })
559 {
560 placeholder_value.autoderef_count = deref_count;
561 placeholder_value.autoref_kind = self
562 .sema
563 .resolve_method_call_as_callable(code)
564 .and_then(|callable| callable.receiver_param(self.sema.db))
565 .map(|self_param| self_param.kind())
566 .unwrap_or(ast::SelfParamKind::Owned);
567 }
568 }
569 }
570 } else {
571 self.attempt_match_opt(phase, pattern_args.next(), code.expr())?;
572 }
551 let mut code_args = 573 let mut code_args =
552 code.arg_list().ok_or_else(|| match_error!("Code method call has no args"))?.args(); 574 code.arg_list().ok_or_else(|| match_error!("Code method call has no args"))?.args();
553 loop { 575 loop {
@@ -575,26 +597,35 @@ impl<'db, 'sema> Matcher<'db, 'sema> {
575 self.attempt_match_node_children(phase, pattern_ufcs.call_expr.syntax(), code.syntax()) 597 self.attempt_match_node_children(phase, pattern_ufcs.call_expr.syntax(), code.syntax())
576 } 598 }
577 599
600 /// Verifies that `expr` matches `pattern_type`, possibly after dereferencing some number of
601 /// times. Returns the number of times it needed to be dereferenced.
578 fn check_expr_type( 602 fn check_expr_type(
579 &self, 603 &self,
580 pattern_type: &hir::Type, 604 pattern_type: &hir::Type,
581 expr: &ast::Expr, 605 expr: &ast::Expr,
582 ) -> Result<(), MatchFailed> { 606 ) -> Result<usize, MatchFailed> {
583 use hir::HirDisplay; 607 use hir::HirDisplay;
584 let code_type = self.sema.type_of_expr(&expr).ok_or_else(|| { 608 let code_type = self.sema.type_of_expr(&expr).ok_or_else(|| {
585 match_error!("Failed to get receiver type for `{}`", expr.syntax().text()) 609 match_error!("Failed to get receiver type for `{}`", expr.syntax().text())
586 })?; 610 })?;
587 if !code_type 611 // Temporary needed to make the borrow checker happy.
612 let res = code_type
588 .autoderef(self.sema.db) 613 .autoderef(self.sema.db)
589 .any(|deref_code_type| *pattern_type == deref_code_type) 614 .enumerate()
590 { 615 .find(|(_, deref_code_type)| pattern_type == deref_code_type)
591 fail_match!( 616 .map(|(count, _)| count)
592 "Pattern type `{}` didn't match code type `{}`", 617 .ok_or_else(|| {
593 pattern_type.display(self.sema.db), 618 match_error!(
594 code_type.display(self.sema.db) 619 "Pattern type `{}` didn't match code type `{}`",
595 ); 620 pattern_type.display(self.sema.db),
596 } 621 code_type.display(self.sema.db)
597 Ok(()) 622 )
623 });
624 res
625 }
626
627 fn get_placeholder_for_node(&self, node: &SyntaxNode) -> Option<&Placeholder> {
628 self.get_placeholder(&SyntaxElement::Node(node.clone()))
598 } 629 }
599 630
600 fn get_placeholder(&self, element: &SyntaxElement) -> Option<&Placeholder> { 631 fn get_placeholder(&self, element: &SyntaxElement) -> Option<&Placeholder> {
@@ -676,12 +707,18 @@ fn recording_match_fail_reasons() -> bool {
676} 707}
677 708
678impl PlaceholderMatch { 709impl PlaceholderMatch {
679 fn new(node: &SyntaxNode, range: FileRange) -> Self { 710 fn new(node: Option<&SyntaxNode>, range: FileRange) -> Self {
680 Self { node: Some(node.clone()), range, inner_matches: SsrMatches::default() } 711 Self {
712 node: node.cloned(),
713 range,
714 inner_matches: SsrMatches::default(),
715 autoderef_count: 0,
716 autoref_kind: ast::SelfParamKind::Owned,
717 }
681 } 718 }
682 719
683 fn from_range(range: FileRange) -> Self { 720 fn from_range(range: FileRange) -> Self {
684 Self { node: None, range, inner_matches: SsrMatches::default() } 721 Self::new(None, range)
685 } 722 }
686} 723}
687 724
diff --git a/crates/ssr/src/parsing.rs b/crates/ssr/src/parsing.rs
index 9570e96e3..05b66dcd7 100644
--- a/crates/ssr/src/parsing.rs
+++ b/crates/ssr/src/parsing.rs
@@ -8,7 +8,7 @@
8use crate::errors::bail; 8use crate::errors::bail;
9use crate::{SsrError, SsrPattern, SsrRule}; 9use crate::{SsrError, SsrPattern, SsrRule};
10use rustc_hash::{FxHashMap, FxHashSet}; 10use rustc_hash::{FxHashMap, FxHashSet};
11use std::str::FromStr; 11use std::{fmt::Display, str::FromStr};
12use syntax::{ast, AstNode, SmolStr, SyntaxKind, SyntaxNode, T}; 12use syntax::{ast, AstNode, SmolStr, SyntaxKind, SyntaxNode, T};
13use test_utils::mark; 13use test_utils::mark;
14 14
@@ -34,12 +34,16 @@ pub(crate) enum PatternElement {
34#[derive(Clone, Debug, PartialEq, Eq)] 34#[derive(Clone, Debug, PartialEq, Eq)]
35pub(crate) struct Placeholder { 35pub(crate) struct Placeholder {
36 /// The name of this placeholder. e.g. for "$a", this would be "a" 36 /// The name of this placeholder. e.g. for "$a", this would be "a"
37 pub(crate) ident: SmolStr, 37 pub(crate) ident: Var,
38 /// A unique name used in place of this placeholder when we parse the pattern as Rust code. 38 /// A unique name used in place of this placeholder when we parse the pattern as Rust code.
39 stand_in_name: String, 39 stand_in_name: String,
40 pub(crate) constraints: Vec<Constraint>, 40 pub(crate) constraints: Vec<Constraint>,
41} 41}
42 42
43/// Represents a `$var` in an SSR query.
44#[derive(Debug, Clone, PartialEq, Eq, Hash)]
45pub(crate) struct Var(pub String);
46
43#[derive(Clone, Debug, PartialEq, Eq)] 47#[derive(Clone, Debug, PartialEq, Eq)]
44pub(crate) enum Constraint { 48pub(crate) enum Constraint {
45 Kind(NodeKind), 49 Kind(NodeKind),
@@ -205,7 +209,7 @@ fn parse_pattern(pattern_str: &str) -> Result<Vec<PatternElement>, SsrError> {
205 if token.kind == T![$] { 209 if token.kind == T![$] {
206 let placeholder = parse_placeholder(&mut tokens)?; 210 let placeholder = parse_placeholder(&mut tokens)?;
207 if !placeholder_names.insert(placeholder.ident.clone()) { 211 if !placeholder_names.insert(placeholder.ident.clone()) {
208 bail!("Name `{}` repeats more than once", placeholder.ident); 212 bail!("Placeholder `{}` repeats more than once", placeholder.ident);
209 } 213 }
210 res.push(PatternElement::Placeholder(placeholder)); 214 res.push(PatternElement::Placeholder(placeholder));
211 } else { 215 } else {
@@ -228,7 +232,7 @@ fn validate_rule(rule: &SsrRule) -> Result<(), SsrError> {
228 for p in &rule.template.tokens { 232 for p in &rule.template.tokens {
229 if let PatternElement::Placeholder(placeholder) = p { 233 if let PatternElement::Placeholder(placeholder) = p {
230 if !defined_placeholders.contains(&placeholder.ident) { 234 if !defined_placeholders.contains(&placeholder.ident) {
231 undefined.push(format!("${}", placeholder.ident)); 235 undefined.push(placeholder.ident.to_string());
232 } 236 }
233 if !placeholder.constraints.is_empty() { 237 if !placeholder.constraints.is_empty() {
234 bail!("Replacement placeholders cannot have constraints"); 238 bail!("Replacement placeholders cannot have constraints");
@@ -344,7 +348,17 @@ impl NodeKind {
344 348
345impl Placeholder { 349impl Placeholder {
346 fn new(name: SmolStr, constraints: Vec<Constraint>) -> Self { 350 fn new(name: SmolStr, constraints: Vec<Constraint>) -> Self {
347 Self { stand_in_name: format!("__placeholder_{}", name), constraints, ident: name } 351 Self {
352 stand_in_name: format!("__placeholder_{}", name),
353 constraints,
354 ident: Var(name.to_string()),
355 }
356 }
357}
358
359impl Display for Var {
360 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361 write!(f, "${}", self.0)
348 } 362 }
349} 363}
350 364
diff --git a/crates/ssr/src/replacing.rs b/crates/ssr/src/replacing.rs
index 8f8fe6149..29284e3f1 100644
--- a/crates/ssr/src/replacing.rs
+++ b/crates/ssr/src/replacing.rs
@@ -1,10 +1,11 @@
1//! Code for applying replacement templates for matches that have previously been found. 1//! Code for applying replacement templates for matches that have previously been found.
2 2
3use crate::matching::Var;
4use crate::{resolving::ResolvedRule, Match, SsrMatches}; 3use crate::{resolving::ResolvedRule, Match, SsrMatches};
4use itertools::Itertools;
5use rustc_hash::{FxHashMap, FxHashSet}; 5use rustc_hash::{FxHashMap, FxHashSet};
6use syntax::ast::{self, AstToken}; 6use syntax::ast::{self, AstToken};
7use syntax::{SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize}; 7use syntax::{SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize};
8use test_utils::mark;
8use text_edit::TextEdit; 9use text_edit::TextEdit;
9 10
10/// Returns a text edit that will replace each match in `matches` with its corresponding replacement 11/// Returns a text edit that will replace each match in `matches` with its corresponding replacement
@@ -114,11 +115,33 @@ impl ReplacementRenderer<'_> {
114 fn render_token(&mut self, token: &SyntaxToken) { 115 fn render_token(&mut self, token: &SyntaxToken) {
115 if let Some(placeholder) = self.rule.get_placeholder(&token) { 116 if let Some(placeholder) = self.rule.get_placeholder(&token) {
116 if let Some(placeholder_value) = 117 if let Some(placeholder_value) =
117 self.match_info.placeholder_values.get(&Var(placeholder.ident.to_string())) 118 self.match_info.placeholder_values.get(&placeholder.ident)
118 { 119 {
119 let range = &placeholder_value.range.range; 120 let range = &placeholder_value.range.range;
120 let mut matched_text = 121 let mut matched_text =
121 self.file_src[usize::from(range.start())..usize::from(range.end())].to_owned(); 122 self.file_src[usize::from(range.start())..usize::from(range.end())].to_owned();
123 // If a method call is performed directly on the placeholder, then autoderef and
124 // autoref will apply, so we can just substitute whatever the placeholder matched to
125 // directly. If we're not applying a method call, then we need to add explicitly
126 // deref and ref in order to match whatever was being done implicitly at the match
127 // site.
128 if !token_is_method_call_receiver(token)
129 && (placeholder_value.autoderef_count > 0
130 || placeholder_value.autoref_kind != ast::SelfParamKind::Owned)
131 {
132 mark::hit!(replace_autoref_autoderef_capture);
133 let ref_kind = match placeholder_value.autoref_kind {
134 ast::SelfParamKind::Owned => "",
135 ast::SelfParamKind::Ref => "&",
136 ast::SelfParamKind::MutRef => "&mut ",
137 };
138 matched_text = format!(
139 "{}{}{}",
140 ref_kind,
141 "*".repeat(placeholder_value.autoderef_count),
142 matched_text
143 );
144 }
122 let edit = matches_to_edit_at_offset( 145 let edit = matches_to_edit_at_offset(
123 &placeholder_value.inner_matches, 146 &placeholder_value.inner_matches,
124 self.file_src, 147 self.file_src,
@@ -179,6 +202,29 @@ impl ReplacementRenderer<'_> {
179 } 202 }
180} 203}
181 204
205/// Returns whether token is the receiver of a method call. Note, being within the receiver of a
206/// method call doesn't count. e.g. if the token is `$a`, then `$a.foo()` will return true, while
207/// `($a + $b).foo()` or `x.foo($a)` will return false.
208fn token_is_method_call_receiver(token: &SyntaxToken) -> bool {
209 use syntax::ast::AstNode;
210 // Find the first method call among the ancestors of `token`, then check if the only token
211 // within the receiver is `token`.
212 if let Some(receiver) =
213 token.ancestors().find_map(ast::MethodCallExpr::cast).and_then(|call| call.expr())
214 {
215 let tokens = receiver.syntax().descendants_with_tokens().filter_map(|node_or_token| {
216 match node_or_token {
217 SyntaxElement::Token(t) => Some(t),
218 _ => None,
219 }
220 });
221 if let Some((only_token,)) = tokens.collect_tuple() {
222 return only_token == *token;
223 }
224 }
225 false
226}
227
182fn parse_as_kind(code: &str, kind: SyntaxKind) -> Option<SyntaxNode> { 228fn parse_as_kind(code: &str, kind: SyntaxKind) -> Option<SyntaxNode> {
183 use syntax::ast::AstNode; 229 use syntax::ast::AstNode;
184 if ast::Expr::can_cast(kind) { 230 if ast::Expr::can_cast(kind) {
diff --git a/crates/ssr/src/tests.rs b/crates/ssr/src/tests.rs
index 0d0a00090..e45c88864 100644
--- a/crates/ssr/src/tests.rs
+++ b/crates/ssr/src/tests.rs
@@ -31,7 +31,7 @@ fn parser_two_delimiters() {
31fn parser_repeated_name() { 31fn parser_repeated_name() {
32 assert_eq!( 32 assert_eq!(
33 parse_error_text("foo($a, $a) ==>>"), 33 parse_error_text("foo($a, $a) ==>>"),
34 "Parse error: Name `a` repeats more than once" 34 "Parse error: Placeholder `$a` repeats more than once"
35 ); 35 );
36} 36}
37 37
@@ -1172,3 +1172,110 @@ fn match_trait_method_call() {
1172 assert_matches("Bar::foo($a, $b)", code, &["v1.foo(1)", "Bar::foo(&v1, 3)", "v1_ref.foo(5)"]); 1172 assert_matches("Bar::foo($a, $b)", code, &["v1.foo(1)", "Bar::foo(&v1, 3)", "v1_ref.foo(5)"]);
1173 assert_matches("Bar2::foo($a, $b)", code, &["v2.foo(2)", "Bar2::foo(&v2, 4)", "v2_ref.foo(6)"]); 1173 assert_matches("Bar2::foo($a, $b)", code, &["v2.foo(2)", "Bar2::foo(&v2, 4)", "v2_ref.foo(6)"]);
1174} 1174}
1175
1176#[test]
1177fn replace_autoref_autoderef_capture() {
1178 // Here we have several calls to `$a.foo()`. In the first case autoref is applied, in the
1179 // second, we already have a reference, so it isn't. When $a is used in a context where autoref
1180 // doesn't apply, we need to prefix it with `&`. Finally, we have some cases where autoderef
1181 // needs to be applied.
1182 mark::check!(replace_autoref_autoderef_capture);
1183 let code = r#"
1184 struct Foo {}
1185 impl Foo {
1186 fn foo(&self) {}
1187 fn foo2(&self) {}
1188 }
1189 fn bar(_: &Foo) {}
1190 fn main() {
1191 let f = Foo {};
1192 let fr = &f;
1193 let fr2 = &fr;
1194 let fr3 = &fr2;
1195 f.foo();
1196 fr.foo();
1197 fr2.foo();
1198 fr3.foo();
1199 }
1200 "#;
1201 assert_ssr_transform(
1202 "Foo::foo($a) ==>> bar($a)",
1203 code,
1204 expect![[r#"
1205 struct Foo {}
1206 impl Foo {
1207 fn foo(&self) {}
1208 fn foo2(&self) {}
1209 }
1210 fn bar(_: &Foo) {}
1211 fn main() {
1212 let f = Foo {};
1213 let fr = &f;
1214 let fr2 = &fr;
1215 let fr3 = &fr2;
1216 bar(&f);
1217 bar(&*fr);
1218 bar(&**fr2);
1219 bar(&***fr3);
1220 }
1221 "#]],
1222 );
1223 // If the placeholder is used as the receiver of another method call, then we don't need to
1224 // explicitly autoderef or autoref.
1225 assert_ssr_transform(
1226 "Foo::foo($a) ==>> $a.foo2()",
1227 code,
1228 expect![[r#"
1229 struct Foo {}
1230 impl Foo {
1231 fn foo(&self) {}
1232 fn foo2(&self) {}
1233 }
1234 fn bar(_: &Foo) {}
1235 fn main() {
1236 let f = Foo {};
1237 let fr = &f;
1238 let fr2 = &fr;
1239 let fr3 = &fr2;
1240 f.foo2();
1241 fr.foo2();
1242 fr2.foo2();
1243 fr3.foo2();
1244 }
1245 "#]],
1246 );
1247}
1248
1249#[test]
1250fn replace_autoref_mut() {
1251 let code = r#"
1252 struct Foo {}
1253 impl Foo {
1254 fn foo(&mut self) {}
1255 }
1256 fn bar(_: &mut Foo) {}
1257 fn main() {
1258 let mut f = Foo {};
1259 f.foo();
1260 let fr = &mut f;
1261 fr.foo();
1262 }
1263 "#;
1264 assert_ssr_transform(
1265 "Foo::foo($a) ==>> bar($a)",
1266 code,
1267 expect![[r#"
1268 struct Foo {}
1269 impl Foo {
1270 fn foo(&mut self) {}
1271 }
1272 fn bar(_: &mut Foo) {}
1273 fn main() {
1274 let mut f = Foo {};
1275 bar(&mut f);
1276 let fr = &mut f;
1277 bar(&mut *fr);
1278 }
1279 "#]],
1280 );
1281}
diff --git a/crates/stdx/src/lib.rs b/crates/stdx/src/lib.rs
index 3c5027fe5..273b0f55b 100644
--- a/crates/stdx/src/lib.rs
+++ b/crates/stdx/src/lib.rs
@@ -1,5 +1,8 @@
1//! Missing batteries for standard libraries. 1//! Missing batteries for standard libraries.
2use std::time::Instant; 2use std::{
3 sync::atomic::{AtomicUsize, Ordering},
4 time::Instant,
5};
3 6
4mod macros; 7mod macros;
5 8
@@ -17,7 +20,7 @@ pub fn timeit(label: &'static str) -> impl Drop {
17 20
18 impl Drop for Guard { 21 impl Drop for Guard {
19 fn drop(&mut self) { 22 fn drop(&mut self) {
20 eprintln!("{}: {:?}", self.label, self.start.elapsed()) 23 eprintln!("{}: {:.2?}", self.label, self.start.elapsed())
21 } 24 }
22 } 25 }
23 26
@@ -134,6 +137,31 @@ where
134 left 137 left
135} 138}
136 139
140pub struct RacyFlag(AtomicUsize);
141
142impl RacyFlag {
143 pub const fn new() -> RacyFlag {
144 RacyFlag(AtomicUsize::new(!0))
145 }
146
147 pub fn get(&self, init: impl FnMut() -> bool) -> bool {
148 let mut init = Some(init);
149 self.get_impl(&mut || init.take().map_or(false, |mut f| f()))
150 }
151
152 fn get_impl(&self, init: &mut dyn FnMut() -> bool) -> bool {
153 match self.0.load(Ordering::Relaxed) {
154 0 => false,
155 1 => true,
156 _ => {
157 let res = init();
158 self.0.store(if res { 1 } else { 0 }, Ordering::Relaxed);
159 res
160 }
161 }
162 }
163}
164
137#[cfg(test)] 165#[cfg(test)]
138mod tests { 166mod tests {
139 use super::*; 167 use super::*;
diff --git a/crates/syntax/Cargo.toml b/crates/syntax/Cargo.toml
index 47e351f9d..ec3132da8 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 = "671.0.0", package = "rustc-ap-rustc_lexer" } 16rustc_lexer = { version = "673.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"
diff --git a/crates/syntax/src/ast/edit.rs b/crates/syntax/src/ast/edit.rs
index 190746e09..060b20966 100644
--- a/crates/syntax/src/ast/edit.rs
+++ b/crates/syntax/src/ast/edit.rs
@@ -91,29 +91,52 @@ impl ast::AssocItemList {
91 res = make_multiline(res); 91 res = make_multiline(res);
92 } 92 }
93 items.into_iter().for_each(|it| res = res.append_item(it)); 93 items.into_iter().for_each(|it| res = res.append_item(it));
94 res 94 res.fixup_trailing_whitespace().unwrap_or(res)
95 } 95 }
96 96
97 #[must_use] 97 #[must_use]
98 pub fn append_item(&self, item: ast::AssocItem) -> ast::AssocItemList { 98 pub fn append_item(&self, item: ast::AssocItem) -> ast::AssocItemList {
99 let (indent, position) = match self.assoc_items().last() { 99 let (indent, position, whitespace) = match self.assoc_items().last() {
100 Some(it) => ( 100 Some(it) => (
101 leading_indent(it.syntax()).unwrap_or_default().to_string(), 101 leading_indent(it.syntax()).unwrap_or_default().to_string(),
102 InsertPosition::After(it.syntax().clone().into()), 102 InsertPosition::After(it.syntax().clone().into()),
103 "\n\n",
103 ), 104 ),
104 None => match self.l_curly_token() { 105 None => match self.l_curly_token() {
105 Some(it) => ( 106 Some(it) => (
106 " ".to_string() + &leading_indent(self.syntax()).unwrap_or_default(), 107 " ".to_string() + &leading_indent(self.syntax()).unwrap_or_default(),
107 InsertPosition::After(it.into()), 108 InsertPosition::After(it.into()),
109 "\n",
108 ), 110 ),
109 None => return self.clone(), 111 None => return self.clone(),
110 }, 112 },
111 }; 113 };
112 let ws = tokens::WsBuilder::new(&format!("\n{}", indent)); 114 let ws = tokens::WsBuilder::new(&format!("{}{}", whitespace, indent));
113 let to_insert: ArrayVec<[SyntaxElement; 2]> = 115 let to_insert: ArrayVec<[SyntaxElement; 2]> =
114 [ws.ws().into(), item.syntax().clone().into()].into(); 116 [ws.ws().into(), item.syntax().clone().into()].into();
115 self.insert_children(position, to_insert) 117 self.insert_children(position, to_insert)
116 } 118 }
119
120 /// Remove extra whitespace between last item and closing curly brace.
121 fn fixup_trailing_whitespace(&self) -> Option<ast::AssocItemList> {
122 let first_token_after_items =
123 self.assoc_items().last()?.syntax().next_sibling_or_token()?;
124 let last_token_before_curly = self.r_curly_token()?.prev_sibling_or_token()?;
125 if last_token_before_curly != first_token_after_items {
126 // there is something more between last item and
127 // right curly than just whitespace - bail out
128 return None;
129 }
130 let whitespace =
131 last_token_before_curly.clone().into_token().and_then(ast::Whitespace::cast)?;
132 let text = whitespace.syntax().text();
133 let newline = text.rfind("\n")?;
134 let keep = tokens::WsBuilder::new(&text[newline..]);
135 Some(self.replace_children(
136 first_token_after_items..=last_token_before_curly,
137 std::iter::once(keep.ws().into()),
138 ))
139 }
117} 140}
118 141
119impl ast::RecordExprFieldList { 142impl ast::RecordExprFieldList {