]> git.lizzy.rs Git - rust.git/commitdiff
Extract call_info and completion into separate crates
authorIgor Aleksanov <popzxc@yandex.ru>
Sun, 18 Oct 2020 10:09:00 +0000 (13:09 +0300)
committerIgor Aleksanov <popzxc@yandex.ru>
Sun, 18 Oct 2020 10:09:00 +0000 (13:09 +0300)
57 files changed:
Cargo.lock
crates/call_info/Cargo.toml [new file with mode: 0644]
crates/call_info/src/lib.rs [new file with mode: 0644]
crates/completion/Cargo.toml [new file with mode: 0644]
crates/completion/src/complete_attribute.rs [new file with mode: 0644]
crates/completion/src/complete_dot.rs [new file with mode: 0644]
crates/completion/src/complete_fn_param.rs [new file with mode: 0644]
crates/completion/src/complete_keyword.rs [new file with mode: 0644]
crates/completion/src/complete_macro_in_item_position.rs [new file with mode: 0644]
crates/completion/src/complete_mod.rs [new file with mode: 0644]
crates/completion/src/complete_pattern.rs [new file with mode: 0644]
crates/completion/src/complete_postfix.rs [new file with mode: 0644]
crates/completion/src/complete_postfix/format_like.rs [new file with mode: 0644]
crates/completion/src/complete_qualified_path.rs [new file with mode: 0644]
crates/completion/src/complete_record.rs [new file with mode: 0644]
crates/completion/src/complete_snippet.rs [new file with mode: 0644]
crates/completion/src/complete_trait_impl.rs [new file with mode: 0644]
crates/completion/src/complete_unqualified_path.rs [new file with mode: 0644]
crates/completion/src/completion_config.rs [new file with mode: 0644]
crates/completion/src/completion_context.rs [new file with mode: 0644]
crates/completion/src/completion_item.rs [new file with mode: 0644]
crates/completion/src/generated_features.rs [new file with mode: 0644]
crates/completion/src/lib.rs [new file with mode: 0644]
crates/completion/src/patterns.rs [new file with mode: 0644]
crates/completion/src/presentation.rs [new file with mode: 0644]
crates/completion/src/test_utils.rs [new file with mode: 0644]
crates/ide/Cargo.toml
crates/ide/src/call_hierarchy.rs
crates/ide/src/call_info.rs [deleted file]
crates/ide/src/completion.rs [deleted file]
crates/ide/src/completion/complete_attribute.rs [deleted file]
crates/ide/src/completion/complete_dot.rs [deleted file]
crates/ide/src/completion/complete_fn_param.rs [deleted file]
crates/ide/src/completion/complete_keyword.rs [deleted file]
crates/ide/src/completion/complete_macro_in_item_position.rs [deleted file]
crates/ide/src/completion/complete_mod.rs [deleted file]
crates/ide/src/completion/complete_pattern.rs [deleted file]
crates/ide/src/completion/complete_postfix.rs [deleted file]
crates/ide/src/completion/complete_postfix/format_like.rs [deleted file]
crates/ide/src/completion/complete_qualified_path.rs [deleted file]
crates/ide/src/completion/complete_record.rs [deleted file]
crates/ide/src/completion/complete_snippet.rs [deleted file]
crates/ide/src/completion/complete_trait_impl.rs [deleted file]
crates/ide/src/completion/complete_unqualified_path.rs [deleted file]
crates/ide/src/completion/completion_config.rs [deleted file]
crates/ide/src/completion/completion_context.rs [deleted file]
crates/ide/src/completion/completion_item.rs [deleted file]
crates/ide/src/completion/generated_features.rs [deleted file]
crates/ide/src/completion/patterns.rs [deleted file]
crates/ide/src/completion/presentation.rs [deleted file]
crates/ide/src/completion/test_utils.rs [deleted file]
crates/ide/src/display.rs
crates/ide/src/lib.rs
crates/ide/src/syntax_highlighting/injection.rs
crates/syntax/src/display.rs [new file with mode: 0644]
crates/syntax/src/lib.rs
xtask/tests/tidy.rs

index c724d13481d4171a70f389c2340df0ccf16b5966..fa08b615225ea4f2f74136e93c63125c9a3bcc5d 100644 (file)
@@ -127,6 +127,20 @@ version = "1.3.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de"
 
+[[package]]
+name = "call_info"
+version = "0.0.0"
+dependencies = [
+ "base_db",
+ "either",
+ "expect-test",
+ "hir",
+ "ide_db",
+ "stdx",
+ "syntax",
+ "test_utils",
+]
+
 [[package]]
 name = "cargo_metadata"
 version = "0.11.4"
@@ -249,6 +263,26 @@ dependencies = [
  "cc",
 ]
 
+[[package]]
+name = "completion"
+version = "0.0.0"
+dependencies = [
+ "assists",
+ "base_db",
+ "call_info",
+ "expect-test",
+ "hir",
+ "ide_db",
+ "itertools",
+ "log",
+ "profile",
+ "rustc-hash",
+ "stdx",
+ "syntax",
+ "test_utils",
+ "text_edit",
+]
+
 [[package]]
 name = "const_fn"
 version = "0.4.2"
@@ -609,7 +643,9 @@ version = "0.0.0"
 dependencies = [
  "assists",
  "base_db",
+ "call_info",
  "cfg",
+ "completion",
  "either",
  "expect-test",
  "hir",
diff --git a/crates/call_info/Cargo.toml b/crates/call_info/Cargo.toml
new file mode 100644 (file)
index 0000000..98c0bd6
--- /dev/null
@@ -0,0 +1,26 @@
+[package]
+name = "call_info"
+version = "0.0.0"
+description = "TBD"
+license = "MIT OR Apache-2.0"
+authors = ["rust-analyzer developers"]
+edition = "2018"
+
+[lib]
+doctest = false
+
+[dependencies]
+either = "1.5.3"
+
+stdx = { path = "../stdx", version = "0.0.0" }
+syntax = { path = "../syntax", version = "0.0.0" }
+base_db = { path = "../base_db", version = "0.0.0" }
+ide_db = { path = "../ide_db", version = "0.0.0" }
+test_utils = { path = "../test_utils", version = "0.0.0" }
+
+# call_info crate should depend only on the top-level `hir` package. if you need
+# something from some `hir_xxx` subpackage, reexport the API via `hir`.
+hir = { path = "../hir", version = "0.0.0" }
+
+[dev-dependencies]
+expect-test = "1.0"
diff --git a/crates/call_info/src/lib.rs b/crates/call_info/src/lib.rs
new file mode 100644 (file)
index 0000000..c45406c
--- /dev/null
@@ -0,0 +1,755 @@
+//! This crate provides primitives for tracking the information about a call site.
+use base_db::FilePosition;
+use either::Either;
+use hir::{HasAttrs, HirDisplay, Semantics, Type};
+use ide_db::RootDatabase;
+use stdx::format_to;
+use syntax::{
+    ast::{self, ArgListOwner},
+    match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, TextSize,
+};
+use test_utils::mark;
+
+/// Contains information about a call site. Specifically the
+/// `FunctionSignature`and current parameter.
+#[derive(Debug)]
+pub struct CallInfo {
+    pub doc: Option<String>,
+    pub signature: String,
+    pub active_parameter: Option<usize>,
+    parameters: Vec<TextRange>,
+}
+
+impl CallInfo {
+    pub fn parameter_labels(&self) -> impl Iterator<Item = &str> + '_ {
+        self.parameters.iter().map(move |&it| &self.signature[it])
+    }
+    pub fn parameter_ranges(&self) -> &[TextRange] {
+        &self.parameters
+    }
+    fn push_param(&mut self, param: &str) {
+        if !self.signature.ends_with('(') {
+            self.signature.push_str(", ");
+        }
+        let start = TextSize::of(&self.signature);
+        self.signature.push_str(param);
+        let end = TextSize::of(&self.signature);
+        self.parameters.push(TextRange::new(start, end))
+    }
+}
+
+/// Computes parameter information for the given call expression.
+pub fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
+    let sema = Semantics::new(db);
+    let file = sema.parse(position.file_id);
+    let file = file.syntax();
+    let token = file.token_at_offset(position.offset).next()?;
+    let token = sema.descend_into_macros(token);
+
+    let (callable, active_parameter) = call_info_impl(&sema, token)?;
+
+    let mut res =
+        CallInfo { doc: None, signature: String::new(), parameters: vec![], active_parameter };
+
+    match callable.kind() {
+        hir::CallableKind::Function(func) => {
+            res.doc = func.docs(db).map(|it| it.as_str().to_string());
+            format_to!(res.signature, "fn {}", func.name(db));
+        }
+        hir::CallableKind::TupleStruct(strukt) => {
+            res.doc = strukt.docs(db).map(|it| it.as_str().to_string());
+            format_to!(res.signature, "struct {}", strukt.name(db));
+        }
+        hir::CallableKind::TupleEnumVariant(variant) => {
+            res.doc = variant.docs(db).map(|it| it.as_str().to_string());
+            format_to!(
+                res.signature,
+                "enum {}::{}",
+                variant.parent_enum(db).name(db),
+                variant.name(db)
+            );
+        }
+        hir::CallableKind::Closure => (),
+    }
+
+    res.signature.push('(');
+    {
+        if let Some(self_param) = callable.receiver_param(db) {
+            format_to!(res.signature, "{}", self_param)
+        }
+        let mut buf = String::new();
+        for (pat, ty) in callable.params(db) {
+            buf.clear();
+            if let Some(pat) = pat {
+                match pat {
+                    Either::Left(_self) => format_to!(buf, "self: "),
+                    Either::Right(pat) => format_to!(buf, "{}: ", pat),
+                }
+            }
+            format_to!(buf, "{}", ty.display(db));
+            res.push_param(&buf);
+        }
+    }
+    res.signature.push(')');
+
+    match callable.kind() {
+        hir::CallableKind::Function(_) | hir::CallableKind::Closure => {
+            let ret_type = callable.return_type();
+            if !ret_type.is_unit() {
+                format_to!(res.signature, " -> {}", ret_type.display(db));
+            }
+        }
+        hir::CallableKind::TupleStruct(_) | hir::CallableKind::TupleEnumVariant(_) => {}
+    }
+    Some(res)
+}
+
+fn call_info_impl(
+    sema: &Semantics<RootDatabase>,
+    token: SyntaxToken,
+) -> Option<(hir::Callable, Option<usize>)> {
+    // Find the calling expression and it's NameRef
+    let calling_node = FnCallNode::with_node(&token.parent())?;
+
+    let callable = match &calling_node {
+        FnCallNode::CallExpr(call) => sema.type_of_expr(&call.expr()?)?.as_callable(sema.db)?,
+        FnCallNode::MethodCallExpr(call) => sema.resolve_method_call_as_callable(call)?,
+    };
+    let active_param = if let Some(arg_list) = calling_node.arg_list() {
+        // Number of arguments specified at the call site
+        let num_args_at_callsite = arg_list.args().count();
+
+        let arg_list_range = arg_list.syntax().text_range();
+        if !arg_list_range.contains_inclusive(token.text_range().start()) {
+            mark::hit!(call_info_bad_offset);
+            return None;
+        }
+        let param = std::cmp::min(
+            num_args_at_callsite,
+            arg_list
+                .args()
+                .take_while(|arg| arg.syntax().text_range().end() <= token.text_range().start())
+                .count(),
+        );
+
+        Some(param)
+    } else {
+        None
+    };
+    Some((callable, active_param))
+}
+
+#[derive(Debug)]
+pub struct ActiveParameter {
+    pub ty: Type,
+    pub name: String,
+}
+
+impl ActiveParameter {
+    pub fn at(db: &RootDatabase, position: FilePosition) -> Option<Self> {
+        let sema = Semantics::new(db);
+        let file = sema.parse(position.file_id);
+        let file = file.syntax();
+        let token = file.token_at_offset(position.offset).next()?;
+        let token = sema.descend_into_macros(token);
+        Self::at_token(&sema, token)
+    }
+
+    pub fn at_token(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<Self> {
+        let (signature, active_parameter) = call_info_impl(&sema, token)?;
+
+        let idx = active_parameter?;
+        let mut params = signature.params(sema.db);
+        if !(idx < params.len()) {
+            mark::hit!(too_many_arguments);
+            return None;
+        }
+        let (pat, ty) = params.swap_remove(idx);
+        let name = pat?.to_string();
+        Some(ActiveParameter { ty, name })
+    }
+}
+
+#[derive(Debug)]
+pub enum FnCallNode {
+    CallExpr(ast::CallExpr),
+    MethodCallExpr(ast::MethodCallExpr),
+}
+
+impl FnCallNode {
+    fn with_node(syntax: &SyntaxNode) -> Option<FnCallNode> {
+        syntax.ancestors().find_map(|node| {
+            match_ast! {
+                match node {
+                    ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)),
+                    ast::MethodCallExpr(it) => {
+                        let arg_list = it.arg_list()?;
+                        if !arg_list.syntax().text_range().contains_range(syntax.text_range()) {
+                            return None;
+                        }
+                        Some(FnCallNode::MethodCallExpr(it))
+                    },
+                    _ => None,
+                }
+            }
+        })
+    }
+
+    pub fn with_node_exact(node: &SyntaxNode) -> Option<FnCallNode> {
+        match_ast! {
+            match node {
+                ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)),
+                ast::MethodCallExpr(it) => Some(FnCallNode::MethodCallExpr(it)),
+                _ => None,
+            }
+        }
+    }
+
+    pub fn name_ref(&self) -> Option<ast::NameRef> {
+        match self {
+            FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? {
+                ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
+                _ => return None,
+            }),
+
+            FnCallNode::MethodCallExpr(call_expr) => {
+                call_expr.syntax().children().filter_map(ast::NameRef::cast).next()
+            }
+        }
+    }
+
+    fn arg_list(&self) -> Option<ast::ArgList> {
+        match self {
+            FnCallNode::CallExpr(expr) => expr.arg_list(),
+            FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use base_db::{fixture::ChangeFixture, FilePosition};
+    use expect_test::{expect, Expect};
+    use ide_db::RootDatabase;
+    use test_utils::{mark, RangeOrOffset};
+
+    /// Creates analysis from a multi-file fixture, returns positions marked with <|>.
+    pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) {
+        let change_fixture = ChangeFixture::parse(ra_fixture);
+        let mut database = RootDatabase::default();
+        database.apply_change(change_fixture.change);
+        let (file_id, range_or_offset) =
+            change_fixture.file_position.expect("expected a marker (<|>)");
+        let offset = match range_or_offset {
+            RangeOrOffset::Range(_) => panic!(),
+            RangeOrOffset::Offset(it) => it,
+        };
+        (database, FilePosition { file_id, offset })
+    }
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let (db, position) = position(ra_fixture);
+        let call_info = crate::call_info(&db, position);
+        let actual = match call_info {
+            Some(call_info) => {
+                let docs = match &call_info.doc {
+                    None => "".to_string(),
+                    Some(docs) => format!("{}\n------\n", docs.as_str()),
+                };
+                let params = call_info
+                    .parameter_labels()
+                    .enumerate()
+                    .map(|(i, param)| {
+                        if Some(i) == call_info.active_parameter {
+                            format!("<{}>", param)
+                        } else {
+                            param.to_string()
+                        }
+                    })
+                    .collect::<Vec<_>>()
+                    .join(", ");
+                format!("{}{}\n({})\n", docs, call_info.signature, params)
+            }
+            None => String::new(),
+        };
+        expect.assert_eq(&actual);
+    }
+
+    #[test]
+    fn test_fn_signature_two_args() {
+        check(
+            r#"
+fn foo(x: u32, y: u32) -> u32 {x + y}
+fn bar() { foo(<|>3, ); }
+"#,
+            expect![[r#"
+                fn foo(x: u32, y: u32) -> u32
+                (<x: u32>, y: u32)
+            "#]],
+        );
+        check(
+            r#"
+fn foo(x: u32, y: u32) -> u32 {x + y}
+fn bar() { foo(3<|>, ); }
+"#,
+            expect![[r#"
+                fn foo(x: u32, y: u32) -> u32
+                (<x: u32>, y: u32)
+            "#]],
+        );
+        check(
+            r#"
+fn foo(x: u32, y: u32) -> u32 {x + y}
+fn bar() { foo(3,<|> ); }
+"#,
+            expect![[r#"
+                fn foo(x: u32, y: u32) -> u32
+                (x: u32, <y: u32>)
+            "#]],
+        );
+        check(
+            r#"
+fn foo(x: u32, y: u32) -> u32 {x + y}
+fn bar() { foo(3, <|>); }
+"#,
+            expect![[r#"
+                fn foo(x: u32, y: u32) -> u32
+                (x: u32, <y: u32>)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_two_args_empty() {
+        check(
+            r#"
+fn foo(x: u32, y: u32) -> u32 {x + y}
+fn bar() { foo(<|>); }
+"#,
+            expect![[r#"
+                fn foo(x: u32, y: u32) -> u32
+                (<x: u32>, y: u32)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_two_args_first_generics() {
+        check(
+            r#"
+fn foo<T, U: Copy + Display>(x: T, y: U) -> u32
+    where T: Copy + Display, U: Debug
+{ x + y }
+
+fn bar() { foo(<|>3, ); }
+"#,
+            expect![[r#"
+                fn foo(x: i32, y: {unknown}) -> u32
+                (<x: i32>, y: {unknown})
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_no_params() {
+        check(
+            r#"
+fn foo<T>() -> T where T: Copy + Display {}
+fn bar() { foo(<|>); }
+"#,
+            expect![[r#"
+                fn foo() -> {unknown}
+                ()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_for_impl() {
+        check(
+            r#"
+struct F;
+impl F { pub fn new() { } }
+fn bar() {
+    let _ : F = F::new(<|>);
+}
+"#,
+            expect![[r#"
+                fn new()
+                ()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_for_method_self() {
+        check(
+            r#"
+struct S;
+impl S { pub fn do_it(&self) {} }
+
+fn bar() {
+    let s: S = S;
+    s.do_it(<|>);
+}
+"#,
+            expect![[r#"
+                fn do_it(&self)
+                ()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_for_method_with_arg() {
+        check(
+            r#"
+struct S;
+impl S {
+    fn foo(&self, x: i32) {}
+}
+
+fn main() { S.foo(<|>); }
+"#,
+            expect![[r#"
+                fn foo(&self, x: i32)
+                (<x: i32>)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_for_method_with_arg_as_assoc_fn() {
+        check(
+            r#"
+struct S;
+impl S {
+    fn foo(&self, x: i32) {}
+}
+
+fn main() { S::foo(<|>); }
+"#,
+            expect![[r#"
+                fn foo(self: &S, x: i32)
+                (<self: &S>, x: i32)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_with_docs_simple() {
+        check(
+            r#"
+/// test
+// non-doc-comment
+fn foo(j: u32) -> u32 {
+    j
+}
+
+fn bar() {
+    let _ = foo(<|>);
+}
+"#,
+            expect![[r#"
+                test
+                ------
+                fn foo(j: u32) -> u32
+                (<j: u32>)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_with_docs() {
+        check(
+            r#"
+/// Adds one to the number given.
+///
+/// # Examples
+///
+/// ```
+/// let five = 5;
+///
+/// assert_eq!(6, my_crate::add_one(5));
+/// ```
+pub fn add_one(x: i32) -> i32 {
+    x + 1
+}
+
+pub fn do() {
+    add_one(<|>
+}"#,
+            expect![[r##"
+                Adds one to the number given.
+
+                # Examples
+
+                ```
+                let five = 5;
+
+                assert_eq!(6, my_crate::add_one(5));
+                ```
+                ------
+                fn add_one(x: i32) -> i32
+                (<x: i32>)
+            "##]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_with_docs_impl() {
+        check(
+            r#"
+struct addr;
+impl addr {
+    /// Adds one to the number given.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let five = 5;
+    ///
+    /// assert_eq!(6, my_crate::add_one(5));
+    /// ```
+    pub fn add_one(x: i32) -> i32 {
+        x + 1
+    }
+}
+
+pub fn do_it() {
+    addr {};
+    addr::add_one(<|>);
+}
+"#,
+            expect![[r##"
+                Adds one to the number given.
+
+                # Examples
+
+                ```
+                let five = 5;
+
+                assert_eq!(6, my_crate::add_one(5));
+                ```
+                ------
+                fn add_one(x: i32) -> i32
+                (<x: i32>)
+            "##]],
+        );
+    }
+
+    #[test]
+    fn test_fn_signature_with_docs_from_actix() {
+        check(
+            r#"
+struct WriteHandler<E>;
+
+impl<E> WriteHandler<E> {
+    /// Method is called when writer emits error.
+    ///
+    /// If this method returns `ErrorAction::Continue` writer processing
+    /// continues otherwise stream processing stops.
+    fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running {
+        Running::Stop
+    }
+
+    /// Method is called when writer finishes.
+    ///
+    /// By default this method stops actor's `Context`.
+    fn finished(&mut self, ctx: &mut Self::Context) {
+        ctx.stop()
+    }
+}
+
+pub fn foo(mut r: WriteHandler<()>) {
+    r.finished(<|>);
+}
+"#,
+            expect![[r#"
+                Method is called when writer finishes.
+
+                By default this method stops actor's `Context`.
+                ------
+                fn finished(&mut self, ctx: &mut {unknown})
+                (<ctx: &mut {unknown}>)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn call_info_bad_offset() {
+        mark::check!(call_info_bad_offset);
+        check(
+            r#"
+fn foo(x: u32, y: u32) -> u32 {x + y}
+fn bar() { foo <|> (3, ); }
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn test_nested_method_in_lambda() {
+        check(
+            r#"
+struct Foo;
+impl Foo { fn bar(&self, _: u32) { } }
+
+fn bar(_: u32) { }
+
+fn main() {
+    let foo = Foo;
+    std::thread::spawn(move || foo.bar(<|>));
+}
+"#,
+            expect![[r#"
+                fn bar(&self, _: u32)
+                (<_: u32>)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn works_for_tuple_structs() {
+        check(
+            r#"
+/// A cool tuple struct
+struct S(u32, i32);
+fn main() {
+    let s = S(0, <|>);
+}
+"#,
+            expect![[r#"
+                A cool tuple struct
+                ------
+                struct S(u32, i32)
+                (u32, <i32>)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn generic_struct() {
+        check(
+            r#"
+struct S<T>(T);
+fn main() {
+    let s = S(<|>);
+}
+"#,
+            expect![[r#"
+                struct S({unknown})
+                (<{unknown}>)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn works_for_enum_variants() {
+        check(
+            r#"
+enum E {
+    /// A Variant
+    A(i32),
+    /// Another
+    B,
+    /// And C
+    C { a: i32, b: i32 }
+}
+
+fn main() {
+    let a = E::A(<|>);
+}
+"#,
+            expect![[r#"
+                A Variant
+                ------
+                enum E::A(i32)
+                (<i32>)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn cant_call_struct_record() {
+        check(
+            r#"
+struct S { x: u32, y: i32 }
+fn main() {
+    let s = S(<|>);
+}
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn cant_call_enum_record() {
+        check(
+            r#"
+enum E {
+    /// A Variant
+    A(i32),
+    /// Another
+    B,
+    /// And C
+    C { a: i32, b: i32 }
+}
+
+fn main() {
+    let a = E::C(<|>);
+}
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn fn_signature_for_call_in_macro() {
+        check(
+            r#"
+macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
+fn foo() { }
+id! {
+    fn bar() { foo(<|>); }
+}
+"#,
+            expect![[r#"
+                fn foo()
+                ()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn call_info_for_lambdas() {
+        check(
+            r#"
+struct S;
+fn foo(s: S) -> i32 { 92 }
+fn main() {
+    (|s| foo(s))(<|>)
+}
+        "#,
+            expect![[r#"
+                (S) -> i32
+                (<S>)
+            "#]],
+        )
+    }
+
+    #[test]
+    fn call_info_for_fn_ptr() {
+        check(
+            r#"
+fn main(f: fn(i32, f64) -> char) {
+    f(0, <|>)
+}
+        "#,
+            expect![[r#"
+                (i32, f64) -> char
+                (i32, <f64>)
+            "#]],
+        )
+    }
+}
diff --git a/crates/completion/Cargo.toml b/crates/completion/Cargo.toml
new file mode 100644 (file)
index 0000000..99087c7
--- /dev/null
@@ -0,0 +1,32 @@
+[package]
+name = "completion"
+version = "0.0.0"
+description = "TBD"
+license = "MIT OR Apache-2.0"
+authors = ["rust-analyzer developers"]
+edition = "2018"
+
+[lib]
+doctest = false
+
+[dependencies]
+itertools = "0.9.0"
+log = "0.4.8"
+rustc-hash = "1.1.0"
+
+syntax = { path = "../syntax", version = "0.0.0" }
+text_edit = { path = "../text_edit", version = "0.0.0" }
+base_db = { path = "../base_db", version = "0.0.0" }
+ide_db = { path = "../ide_db", version = "0.0.0" }
+profile = { path = "../profile", version = "0.0.0" }
+test_utils = { path = "../test_utils", version = "0.0.0" }
+assists = { path = "../assists", version = "0.0.0" }
+call_info = { path = "../call_info", version = "0.0.0" }
+
+# completions crate should depend only on the top-level `hir` package. if you need
+# something from some `hir_xxx` subpackage, reexport the API via `hir`.
+hir = { path = "../hir", version = "0.0.0" }
+
+[dev-dependencies]
+expect-test = "1.0"
+stdx = { path = "../stdx", version = "0.0.0" }
diff --git a/crates/completion/src/complete_attribute.rs b/crates/completion/src/complete_attribute.rs
new file mode 100644 (file)
index 0000000..ea8ad25
--- /dev/null
@@ -0,0 +1,657 @@
+//! Completion for attributes
+//!
+//! This module uses a bit of static metadata to provide completions
+//! for built-in attributes.
+
+use rustc_hash::FxHashSet;
+use syntax::{ast, AstNode, SyntaxKind};
+
+use crate::{
+    completion_context::CompletionContext,
+    completion_item::{CompletionItem, CompletionItemKind, CompletionKind, Completions},
+    generated_features::FEATURES,
+};
+
+pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
+    if ctx.mod_declaration_under_caret.is_some() {
+        return None;
+    }
+
+    let attribute = ctx.attribute_under_caret.as_ref()?;
+    match (attribute.path(), attribute.token_tree()) {
+        (Some(path), Some(token_tree)) if path.to_string() == "derive" => {
+            complete_derive(acc, ctx, token_tree)
+        }
+        (Some(path), Some(token_tree)) if path.to_string() == "feature" => {
+            complete_lint(acc, ctx, token_tree, FEATURES)
+        }
+        (Some(path), Some(token_tree))
+            if ["allow", "warn", "deny", "forbid"]
+                .iter()
+                .any(|lint_level| lint_level == &path.to_string()) =>
+        {
+            complete_lint(acc, ctx, token_tree, DEFAULT_LINT_COMPLETIONS)
+        }
+        (_, Some(_token_tree)) => {}
+        _ => complete_attribute_start(acc, ctx, attribute),
+    }
+    Some(())
+}
+
+fn complete_attribute_start(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) {
+    for attr_completion in ATTRIBUTES {
+        let mut item = CompletionItem::new(
+            CompletionKind::Attribute,
+            ctx.source_range(),
+            attr_completion.label,
+        )
+        .kind(CompletionItemKind::Attribute);
+
+        if let Some(lookup) = attr_completion.lookup {
+            item = item.lookup_by(lookup);
+        }
+
+        match (attr_completion.snippet, ctx.config.snippet_cap) {
+            (Some(snippet), Some(cap)) => {
+                item = item.insert_snippet(cap, snippet);
+            }
+            _ => {}
+        }
+
+        if attribute.kind() == ast::AttrKind::Inner || !attr_completion.prefer_inner {
+            acc.add(item);
+        }
+    }
+}
+
+struct AttrCompletion {
+    label: &'static str,
+    lookup: Option<&'static str>,
+    snippet: Option<&'static str>,
+    prefer_inner: bool,
+}
+
+impl AttrCompletion {
+    const fn prefer_inner(self) -> AttrCompletion {
+        AttrCompletion { prefer_inner: true, ..self }
+    }
+}
+
+const fn attr(
+    label: &'static str,
+    lookup: Option<&'static str>,
+    snippet: Option<&'static str>,
+) -> AttrCompletion {
+    AttrCompletion { label, lookup, snippet, prefer_inner: false }
+}
+
+const ATTRIBUTES: &[AttrCompletion] = &[
+    attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
+    attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
+    attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
+    attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
+    attr(r#"deprecated = "…""#, Some("deprecated"), Some(r#"deprecated = "${0:reason}""#)),
+    attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
+    attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
+    attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
+    attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
+    // FIXME: resolve through macro resolution?
+    attr("global_allocator", None, None).prefer_inner(),
+    attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
+    attr("inline(…)", Some("inline"), Some("inline(${0:lint})")),
+    attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
+    attr("link", None, None),
+    attr("macro_export", None, None),
+    attr("macro_use", None, None),
+    attr(r#"must_use = "…""#, Some("must_use"), Some(r#"must_use = "${0:reason}""#)),
+    attr("no_mangle", None, None),
+    attr("no_std", None, None).prefer_inner(),
+    attr("non_exhaustive", None, None),
+    attr("panic_handler", None, None).prefer_inner(),
+    attr("path = \"…\"", Some("path"), Some("path =\"${0:path}\"")),
+    attr("proc_macro", None, None),
+    attr("proc_macro_attribute", None, None),
+    attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
+    attr("recursion_limit = …", Some("recursion_limit"), Some("recursion_limit = ${0:128}"))
+        .prefer_inner(),
+    attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
+    attr(
+        "should_panic(…)",
+        Some("should_panic"),
+        Some(r#"should_panic(expected = "${0:reason}")"#),
+    ),
+    attr(
+        r#"target_feature = "…""#,
+        Some("target_feature"),
+        Some("target_feature = \"${0:feature}\""),
+    ),
+    attr("test", None, None),
+    attr("used", None, None),
+    attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
+    attr(
+        r#"windows_subsystem = "…""#,
+        Some("windows_subsystem"),
+        Some(r#"windows_subsystem = "${0:subsystem}""#),
+    )
+    .prefer_inner(),
+];
+
+fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input: ast::TokenTree) {
+    if let Ok(existing_derives) = parse_comma_sep_input(derive_input) {
+        for derive_completion in DEFAULT_DERIVE_COMPLETIONS
+            .into_iter()
+            .filter(|completion| !existing_derives.contains(completion.label))
+        {
+            let mut label = derive_completion.label.to_owned();
+            for dependency in derive_completion
+                .dependencies
+                .into_iter()
+                .filter(|&&dependency| !existing_derives.contains(dependency))
+            {
+                label.push_str(", ");
+                label.push_str(dependency);
+            }
+            acc.add(
+                CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label)
+                    .kind(CompletionItemKind::Attribute),
+            );
+        }
+
+        for custom_derive_name in get_derive_names_in_scope(ctx).difference(&existing_derives) {
+            acc.add(
+                CompletionItem::new(
+                    CompletionKind::Attribute,
+                    ctx.source_range(),
+                    custom_derive_name,
+                )
+                .kind(CompletionItemKind::Attribute),
+            );
+        }
+    }
+}
+
+fn complete_lint(
+    acc: &mut Completions,
+    ctx: &CompletionContext,
+    derive_input: ast::TokenTree,
+    lints_completions: &[LintCompletion],
+) {
+    if let Ok(existing_lints) = parse_comma_sep_input(derive_input) {
+        for lint_completion in lints_completions
+            .into_iter()
+            .filter(|completion| !existing_lints.contains(completion.label))
+        {
+            acc.add(
+                CompletionItem::new(
+                    CompletionKind::Attribute,
+                    ctx.source_range(),
+                    lint_completion.label,
+                )
+                .kind(CompletionItemKind::Attribute)
+                .detail(lint_completion.description),
+            );
+        }
+    }
+}
+
+fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Result<FxHashSet<String>, ()> {
+    match (derive_input.left_delimiter_token(), derive_input.right_delimiter_token()) {
+        (Some(left_paren), Some(right_paren))
+            if left_paren.kind() == SyntaxKind::L_PAREN
+                && right_paren.kind() == SyntaxKind::R_PAREN =>
+        {
+            let mut input_derives = FxHashSet::default();
+            let mut current_derive = String::new();
+            for token in derive_input
+                .syntax()
+                .children_with_tokens()
+                .filter_map(|token| token.into_token())
+                .skip_while(|token| token != &left_paren)
+                .skip(1)
+                .take_while(|token| token != &right_paren)
+            {
+                if SyntaxKind::COMMA == token.kind() {
+                    if !current_derive.is_empty() {
+                        input_derives.insert(current_derive);
+                        current_derive = String::new();
+                    }
+                } else {
+                    current_derive.push_str(token.to_string().trim());
+                }
+            }
+
+            if !current_derive.is_empty() {
+                input_derives.insert(current_derive);
+            }
+            Ok(input_derives)
+        }
+        _ => Err(()),
+    }
+}
+
+fn get_derive_names_in_scope(ctx: &CompletionContext) -> FxHashSet<String> {
+    let mut result = FxHashSet::default();
+    ctx.scope.process_all_names(&mut |name, scope_def| {
+        if let hir::ScopeDef::MacroDef(mac) = scope_def {
+            if mac.is_derive_macro() {
+                result.insert(name.to_string());
+            }
+        }
+    });
+    result
+}
+
+struct DeriveCompletion {
+    label: &'static str,
+    dependencies: &'static [&'static str],
+}
+
+/// Standard Rust derives and the information about their dependencies
+/// (the dependencies are needed so that the main derive don't break the compilation when added)
+#[rustfmt::skip]
+const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[
+    DeriveCompletion { label: "Clone", dependencies: &[] },
+    DeriveCompletion { label: "Copy", dependencies: &["Clone"] },
+    DeriveCompletion { label: "Debug", dependencies: &[] },
+    DeriveCompletion { label: "Default", dependencies: &[] },
+    DeriveCompletion { label: "Hash", dependencies: &[] },
+    DeriveCompletion { label: "PartialEq", dependencies: &[] },
+    DeriveCompletion { label: "Eq", dependencies: &["PartialEq"] },
+    DeriveCompletion { label: "PartialOrd", dependencies: &["PartialEq"] },
+    DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] },
+];
+
+pub(super) struct LintCompletion {
+    pub(super) label: &'static str,
+    pub(super) description: &'static str,
+}
+
+#[rustfmt::skip]
+const DEFAULT_LINT_COMPLETIONS: &[LintCompletion] = &[
+    LintCompletion { label: "absolute_paths_not_starting_with_crate", description: r#"fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name"# },
+    LintCompletion { label: "anonymous_parameters", description: r#"detects anonymous parameters"# },
+    LintCompletion { label: "box_pointers", description: r#"use of owned (Box type) heap memory"# },
+    LintCompletion { label: "deprecated_in_future", description: r#"detects use of items that will be deprecated in a future version"# },
+    LintCompletion { label: "elided_lifetimes_in_paths", description: r#"hidden lifetime parameters in types are deprecated"# },
+    LintCompletion { label: "explicit_outlives_requirements", description: r#"outlives requirements can be inferred"# },
+    LintCompletion { label: "indirect_structural_match", description: r#"pattern with const indirectly referencing non-structural-match type"# },
+    LintCompletion { label: "keyword_idents", description: r#"detects edition keywords being used as an identifier"# },
+    LintCompletion { label: "macro_use_extern_crate", description: r#"the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system"# },
+    LintCompletion { label: "meta_variable_misuse", description: r#"possible meta-variable misuse at macro definition"# },
+    LintCompletion { label: "missing_copy_implementations", description: r#"detects potentially-forgotten implementations of `Copy`"# },
+    LintCompletion { label: "missing_crate_level_docs", description: r#"detects crates with no crate-level documentation"# },
+    LintCompletion { label: "missing_debug_implementations", description: r#"detects missing implementations of Debug"# },
+    LintCompletion { label: "missing_docs", description: r#"detects missing documentation for public members"# },
+    LintCompletion { label: "missing_doc_code_examples", description: r#"detects publicly-exported items without code samples in their documentation"# },
+    LintCompletion { label: "non_ascii_idents", description: r#"detects non-ASCII identifiers"# },
+    LintCompletion { label: "private_doc_tests", description: r#"detects code samples in docs of private items not documented by rustdoc"# },
+    LintCompletion { label: "single_use_lifetimes", description: r#"detects lifetime parameters that are only used once"# },
+    LintCompletion { label: "trivial_casts", description: r#"detects trivial casts which could be removed"# },
+    LintCompletion { label: "trivial_numeric_casts", description: r#"detects trivial casts of numeric types which could be removed"# },
+    LintCompletion { label: "unaligned_references", description: r#"detects unaligned references to fields of packed structs"# },
+    LintCompletion { label: "unreachable_pub", description: r#"`pub` items not reachable from crate root"# },
+    LintCompletion { label: "unsafe_code", description: r#"usage of `unsafe` code"# },
+    LintCompletion { label: "unsafe_op_in_unsafe_fn", description: r#"unsafe operations in unsafe functions without an explicit unsafe block are deprecated"# },
+    LintCompletion { label: "unstable_features", description: r#"enabling unstable features (deprecated. do not use)"# },
+    LintCompletion { label: "unused_crate_dependencies", description: r#"crate dependencies that are never used"# },
+    LintCompletion { label: "unused_extern_crates", description: r#"extern crates that are never used"# },
+    LintCompletion { label: "unused_import_braces", description: r#"unnecessary braces around an imported item"# },
+    LintCompletion { label: "unused_lifetimes", description: r#"detects lifetime parameters that are never used"# },
+    LintCompletion { label: "unused_qualifications", description: r#"detects unnecessarily qualified names"# },
+    LintCompletion { label: "unused_results", description: r#"unused result of an expression in a statement"# },
+    LintCompletion { label: "variant_size_differences", description: r#"detects enums with widely varying variant sizes"# },
+    LintCompletion { label: "array_into_iter", description: r#"detects calling `into_iter` on arrays"# },
+    LintCompletion { label: "asm_sub_register", description: r#"using only a subset of a register for inline asm inputs"# },
+    LintCompletion { label: "bare_trait_objects", description: r#"suggest using `dyn Trait` for trait objects"# },
+    LintCompletion { label: "bindings_with_variant_name", description: r#"detects pattern bindings with the same name as one of the matched variants"# },
+    LintCompletion { label: "cenum_impl_drop_cast", description: r#"a C-like enum implementing Drop is cast"# },
+    LintCompletion { label: "clashing_extern_declarations", description: r#"detects when an extern fn has been declared with the same name but different types"# },
+    LintCompletion { label: "coherence_leak_check", description: r#"distinct impls distinguished only by the leak-check code"# },
+    LintCompletion { label: "confusable_idents", description: r#"detects visually confusable pairs between identifiers"# },
+    LintCompletion { label: "dead_code", description: r#"detect unused, unexported items"# },
+    LintCompletion { label: "deprecated", description: r#"detects use of deprecated items"# },
+    LintCompletion { label: "ellipsis_inclusive_range_patterns", description: r#"`...` range patterns are deprecated"# },
+    LintCompletion { label: "exported_private_dependencies", description: r#"public interface leaks type from a private dependency"# },
+    LintCompletion { label: "illegal_floating_point_literal_pattern", description: r#"floating-point literals cannot be used in patterns"# },
+    LintCompletion { label: "improper_ctypes", description: r#"proper use of libc types in foreign modules"# },
+    LintCompletion { label: "improper_ctypes_definitions", description: r#"proper use of libc types in foreign item definitions"# },
+    LintCompletion { label: "incomplete_features", description: r#"incomplete features that may function improperly in some or all cases"# },
+    LintCompletion { label: "inline_no_sanitize", description: r#"detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]`"# },
+    LintCompletion { label: "intra_doc_link_resolution_failure", description: r#"failures in resolving intra-doc link targets"# },
+    LintCompletion { label: "invalid_codeblock_attributes", description: r#"codeblock attribute looks a lot like a known one"# },
+    LintCompletion { label: "invalid_value", description: r#"an invalid value is being created (such as a NULL reference)"# },
+    LintCompletion { label: "irrefutable_let_patterns", description: r#"detects irrefutable patterns in if-let and while-let statements"# },
+    LintCompletion { label: "late_bound_lifetime_arguments", description: r#"detects generic lifetime arguments in path segments with late bound lifetime parameters"# },
+    LintCompletion { label: "mixed_script_confusables", description: r#"detects Unicode scripts whose mixed script confusables codepoints are solely used"# },
+    LintCompletion { label: "mutable_borrow_reservation_conflict", description: r#"reservation of a two-phased borrow conflicts with other shared borrows"# },
+    LintCompletion { label: "non_camel_case_types", description: r#"types, variants, traits and type parameters should have camel case names"# },
+    LintCompletion { label: "non_shorthand_field_patterns", description: r#"using `Struct { x: x }` instead of `Struct { x }` in a pattern"# },
+    LintCompletion { label: "non_snake_case", description: r#"variables, methods, functions, lifetime parameters and modules should have snake case names"# },
+    LintCompletion { label: "non_upper_case_globals", description: r#"static constants should have uppercase identifiers"# },
+    LintCompletion { label: "no_mangle_generic_items", description: r#"generic items must be mangled"# },
+    LintCompletion { label: "overlapping_patterns", description: r#"detects overlapping patterns"# },
+    LintCompletion { label: "path_statements", description: r#"path statements with no effect"# },
+    LintCompletion { label: "private_in_public", description: r#"detect private items in public interfaces not caught by the old implementation"# },
+    LintCompletion { label: "proc_macro_derive_resolution_fallback", description: r#"detects proc macro derives using inaccessible names from parent modules"# },
+    LintCompletion { label: "redundant_semicolons", description: r#"detects unnecessary trailing semicolons"# },
+    LintCompletion { label: "renamed_and_removed_lints", description: r#"lints that have been renamed or removed"# },
+    LintCompletion { label: "safe_packed_borrows", description: r#"safe borrows of fields of packed structs were erroneously allowed"# },
+    LintCompletion { label: "stable_features", description: r#"stable features found in `#[feature]` directive"# },
+    LintCompletion { label: "trivial_bounds", description: r#"these bounds don't depend on an type parameters"# },
+    LintCompletion { label: "type_alias_bounds", description: r#"bounds in type aliases are not enforced"# },
+    LintCompletion { label: "tyvar_behind_raw_pointer", description: r#"raw pointer to an inference variable"# },
+    LintCompletion { label: "uncommon_codepoints", description: r#"detects uncommon Unicode codepoints in identifiers"# },
+    LintCompletion { label: "unconditional_recursion", description: r#"functions that cannot return without calling themselves"# },
+    LintCompletion { label: "unknown_lints", description: r#"unrecognized lint attribute"# },
+    LintCompletion { label: "unnameable_test_items", description: r#"detects an item that cannot be named being marked as `#[test_case]`"# },
+    LintCompletion { label: "unreachable_code", description: r#"detects unreachable code paths"# },
+    LintCompletion { label: "unreachable_patterns", description: r#"detects unreachable patterns"# },
+    LintCompletion { label: "unstable_name_collisions", description: r#"detects name collision with an existing but unstable method"# },
+    LintCompletion { label: "unused_allocation", description: r#"detects unnecessary allocations that can be eliminated"# },
+    LintCompletion { label: "unused_assignments", description: r#"detect assignments that will never be read"# },
+    LintCompletion { label: "unused_attributes", description: r#"detects attributes that were not used by the compiler"# },
+    LintCompletion { label: "unused_braces", description: r#"unnecessary braces around an expression"# },
+    LintCompletion { label: "unused_comparisons", description: r#"comparisons made useless by limits of the types involved"# },
+    LintCompletion { label: "unused_doc_comments", description: r#"detects doc comments that aren't used by rustdoc"# },
+    LintCompletion { label: "unused_features", description: r#"unused features found in crate-level `#[feature]` directives"# },
+    LintCompletion { label: "unused_imports", description: r#"imports that are never used"# },
+    LintCompletion { label: "unused_labels", description: r#"detects labels that are never used"# },
+    LintCompletion { label: "unused_macros", description: r#"detects macros that were not used"# },
+    LintCompletion { label: "unused_must_use", description: r#"unused result of a type flagged as `#[must_use]`"# },
+    LintCompletion { label: "unused_mut", description: r#"detect mut variables which don't need to be mutable"# },
+    LintCompletion { label: "unused_parens", description: r#"`if`, `match`, `while` and `return` do not need parentheses"# },
+    LintCompletion { label: "unused_unsafe", description: r#"unnecessary use of an `unsafe` block"# },
+    LintCompletion { label: "unused_variables", description: r#"detect variables which are not used in any way"# },
+    LintCompletion { label: "warnings", description: r#"mass-change the level for lints which produce warnings"# },
+    LintCompletion { label: "where_clauses_object_safety", description: r#"checks the object safety of where clauses"# },
+    LintCompletion { label: "while_true", description: r#"suggest using `loop { }` instead of `while true { }`"# },
+    LintCompletion { label: "ambiguous_associated_items", description: r#"ambiguous associated items"# },
+    LintCompletion { label: "arithmetic_overflow", description: r#"arithmetic operation overflows"# },
+    LintCompletion { label: "conflicting_repr_hints", description: r#"conflicts between `#[repr(..)]` hints that were previously accepted and used in practice"# },
+    LintCompletion { label: "const_err", description: r#"constant evaluation detected erroneous expression"# },
+    LintCompletion { label: "ill_formed_attribute_input", description: r#"ill-formed attribute inputs that were previously accepted and used in practice"# },
+    LintCompletion { label: "incomplete_include", description: r#"trailing content in included file"# },
+    LintCompletion { label: "invalid_type_param_default", description: r#"type parameter default erroneously allowed in invalid location"# },
+    LintCompletion { label: "macro_expanded_macro_exports_accessed_by_absolute_paths", description: r#"macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths"# },
+    LintCompletion { label: "missing_fragment_specifier", description: r#"detects missing fragment specifiers in unused `macro_rules!` patterns"# },
+    LintCompletion { label: "mutable_transmutes", description: r#"mutating transmuted &mut T from &T may cause undefined behavior"# },
+    LintCompletion { label: "no_mangle_const_items", description: r#"const items will not have their symbols exported"# },
+    LintCompletion { label: "order_dependent_trait_objects", description: r#"trait-object types were treated as different depending on marker-trait order"# },
+    LintCompletion { label: "overflowing_literals", description: r#"literal out of range for its type"# },
+    LintCompletion { label: "patterns_in_fns_without_body", description: r#"patterns in functions without body were erroneously allowed"# },
+    LintCompletion { label: "pub_use_of_private_extern_crate", description: r#"detect public re-exports of private extern crates"# },
+    LintCompletion { label: "soft_unstable", description: r#"a feature gate that doesn't break dependent crates"# },
+    LintCompletion { label: "unconditional_panic", description: r#"operation will cause a panic at runtime"# },
+    LintCompletion { label: "unknown_crate_types", description: r#"unknown crate type found in `#[crate_type]` directive"# },
+];
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{test_utils::completion_list, CompletionKind};
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Attribute);
+        expect.assert_eq(&actual);
+    }
+
+    #[test]
+    fn empty_derive_completion() {
+        check(
+            r#"
+#[derive(<|>)]
+struct Test {}
+        "#,
+            expect![[r#"
+                at Clone
+                at Copy, Clone
+                at Debug
+                at Default
+                at Eq, PartialEq
+                at Hash
+                at Ord, PartialOrd, Eq, PartialEq
+                at PartialEq
+                at PartialOrd, PartialEq
+            "#]],
+        );
+    }
+
+    #[test]
+    fn empty_lint_completion() {
+        check(
+            r#"#[allow(<|>)]"#,
+            expect![[r#"
+                at absolute_paths_not_starting_with_crate fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name
+                at ambiguous_associated_items ambiguous associated items
+                at anonymous_parameters detects anonymous parameters
+                at arithmetic_overflow arithmetic operation overflows
+                at array_into_iter  detects calling `into_iter` on arrays
+                at asm_sub_register using only a subset of a register for inline asm inputs
+                at bare_trait_objects suggest using `dyn Trait` for trait objects
+                at bindings_with_variant_name detects pattern bindings with the same name as one of the matched variants
+                at box_pointers     use of owned (Box type) heap memory
+                at cenum_impl_drop_cast a C-like enum implementing Drop is cast
+                at clashing_extern_declarations detects when an extern fn has been declared with the same name but different types
+                at coherence_leak_check distinct impls distinguished only by the leak-check code
+                at conflicting_repr_hints conflicts between `#[repr(..)]` hints that were previously accepted and used in practice
+                at confusable_idents detects visually confusable pairs between identifiers
+                at const_err        constant evaluation detected erroneous expression
+                at dead_code        detect unused, unexported items
+                at deprecated       detects use of deprecated items
+                at deprecated_in_future detects use of items that will be deprecated in a future version
+                at elided_lifetimes_in_paths hidden lifetime parameters in types are deprecated
+                at ellipsis_inclusive_range_patterns `...` range patterns are deprecated
+                at explicit_outlives_requirements outlives requirements can be inferred
+                at exported_private_dependencies public interface leaks type from a private dependency
+                at ill_formed_attribute_input ill-formed attribute inputs that were previously accepted and used in practice
+                at illegal_floating_point_literal_pattern floating-point literals cannot be used in patterns
+                at improper_ctypes  proper use of libc types in foreign modules
+                at improper_ctypes_definitions proper use of libc types in foreign item definitions
+                at incomplete_features incomplete features that may function improperly in some or all cases
+                at incomplete_include trailing content in included file
+                at indirect_structural_match pattern with const indirectly referencing non-structural-match type
+                at inline_no_sanitize detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]`
+                at intra_doc_link_resolution_failure failures in resolving intra-doc link targets
+                at invalid_codeblock_attributes codeblock attribute looks a lot like a known one
+                at invalid_type_param_default type parameter default erroneously allowed in invalid location
+                at invalid_value    an invalid value is being created (such as a NULL reference)
+                at irrefutable_let_patterns detects irrefutable patterns in if-let and while-let statements
+                at keyword_idents   detects edition keywords being used as an identifier
+                at late_bound_lifetime_arguments detects generic lifetime arguments in path segments with late bound lifetime parameters
+                at macro_expanded_macro_exports_accessed_by_absolute_paths macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths
+                at macro_use_extern_crate the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system
+                at meta_variable_misuse possible meta-variable misuse at macro definition
+                at missing_copy_implementations detects potentially-forgotten implementations of `Copy`
+                at missing_crate_level_docs detects crates with no crate-level documentation
+                at missing_debug_implementations detects missing implementations of Debug
+                at missing_doc_code_examples detects publicly-exported items without code samples in their documentation
+                at missing_docs     detects missing documentation for public members
+                at missing_fragment_specifier detects missing fragment specifiers in unused `macro_rules!` patterns
+                at mixed_script_confusables detects Unicode scripts whose mixed script confusables codepoints are solely used
+                at mutable_borrow_reservation_conflict reservation of a two-phased borrow conflicts with other shared borrows
+                at mutable_transmutes mutating transmuted &mut T from &T may cause undefined behavior
+                at no_mangle_const_items const items will not have their symbols exported
+                at no_mangle_generic_items generic items must be mangled
+                at non_ascii_idents detects non-ASCII identifiers
+                at non_camel_case_types types, variants, traits and type parameters should have camel case names
+                at non_shorthand_field_patterns using `Struct { x: x }` instead of `Struct { x }` in a pattern
+                at non_snake_case   variables, methods, functions, lifetime parameters and modules should have snake case names
+                at non_upper_case_globals static constants should have uppercase identifiers
+                at order_dependent_trait_objects trait-object types were treated as different depending on marker-trait order
+                at overflowing_literals literal out of range for its type
+                at overlapping_patterns detects overlapping patterns
+                at path_statements  path statements with no effect
+                at patterns_in_fns_without_body patterns in functions without body were erroneously allowed
+                at private_doc_tests detects code samples in docs of private items not documented by rustdoc
+                at private_in_public detect private items in public interfaces not caught by the old implementation
+                at proc_macro_derive_resolution_fallback detects proc macro derives using inaccessible names from parent modules
+                at pub_use_of_private_extern_crate detect public re-exports of private extern crates
+                at redundant_semicolons detects unnecessary trailing semicolons
+                at renamed_and_removed_lints lints that have been renamed or removed
+                at safe_packed_borrows safe borrows of fields of packed structs were erroneously allowed
+                at single_use_lifetimes detects lifetime parameters that are only used once
+                at soft_unstable    a feature gate that doesn't break dependent crates
+                at stable_features  stable features found in `#[feature]` directive
+                at trivial_bounds   these bounds don't depend on an type parameters
+                at trivial_casts    detects trivial casts which could be removed
+                at trivial_numeric_casts detects trivial casts of numeric types which could be removed
+                at type_alias_bounds bounds in type aliases are not enforced
+                at tyvar_behind_raw_pointer raw pointer to an inference variable
+                at unaligned_references detects unaligned references to fields of packed structs
+                at uncommon_codepoints detects uncommon Unicode codepoints in identifiers
+                at unconditional_panic operation will cause a panic at runtime
+                at unconditional_recursion functions that cannot return without calling themselves
+                at unknown_crate_types unknown crate type found in `#[crate_type]` directive
+                at unknown_lints    unrecognized lint attribute
+                at unnameable_test_items detects an item that cannot be named being marked as `#[test_case]`
+                at unreachable_code detects unreachable code paths
+                at unreachable_patterns detects unreachable patterns
+                at unreachable_pub  `pub` items not reachable from crate root
+                at unsafe_code      usage of `unsafe` code
+                at unsafe_op_in_unsafe_fn unsafe operations in unsafe functions without an explicit unsafe block are deprecated
+                at unstable_features enabling unstable features (deprecated. do not use)
+                at unstable_name_collisions detects name collision with an existing but unstable method
+                at unused_allocation detects unnecessary allocations that can be eliminated
+                at unused_assignments detect assignments that will never be read
+                at unused_attributes detects attributes that were not used by the compiler
+                at unused_braces    unnecessary braces around an expression
+                at unused_comparisons comparisons made useless by limits of the types involved
+                at unused_crate_dependencies crate dependencies that are never used
+                at unused_doc_comments detects doc comments that aren't used by rustdoc
+                at unused_extern_crates extern crates that are never used
+                at unused_features  unused features found in crate-level `#[feature]` directives
+                at unused_import_braces unnecessary braces around an imported item
+                at unused_imports   imports that are never used
+                at unused_labels    detects labels that are never used
+                at unused_lifetimes detects lifetime parameters that are never used
+                at unused_macros    detects macros that were not used
+                at unused_must_use  unused result of a type flagged as `#[must_use]`
+                at unused_mut       detect mut variables which don't need to be mutable
+                at unused_parens    `if`, `match`, `while` and `return` do not need parentheses
+                at unused_qualifications detects unnecessarily qualified names
+                at unused_results   unused result of an expression in a statement
+                at unused_unsafe    unnecessary use of an `unsafe` block
+                at unused_variables detect variables which are not used in any way
+                at variant_size_differences detects enums with widely varying variant sizes
+                at warnings         mass-change the level for lints which produce warnings
+                at where_clauses_object_safety checks the object safety of where clauses
+                at while_true       suggest using `loop { }` instead of `while true { }`
+        "#]],
+        )
+    }
+
+    #[test]
+    fn no_completion_for_incorrect_derive() {
+        check(
+            r#"
+#[derive{<|>)]
+struct Test {}
+"#,
+            expect![[r#""#]],
+        )
+    }
+
+    #[test]
+    fn derive_with_input_completion() {
+        check(
+            r#"
+#[derive(serde::Serialize, PartialEq, <|>)]
+struct Test {}
+"#,
+            expect![[r#"
+                at Clone
+                at Copy, Clone
+                at Debug
+                at Default
+                at Eq
+                at Hash
+                at Ord, PartialOrd, Eq
+                at PartialOrd
+            "#]],
+        )
+    }
+
+    #[test]
+    fn test_attribute_completion() {
+        check(
+            r#"#[<|>]"#,
+            expect![[r#"
+                at allow(…)
+                at cfg(…)
+                at cfg_attr(…)
+                at deny(…)
+                at deprecated = "…"
+                at derive(…)
+                at doc = "…"
+                at forbid(…)
+                at ignore = "…"
+                at inline(…)
+                at link
+                at link_name = "…"
+                at macro_export
+                at macro_use
+                at must_use = "…"
+                at no_mangle
+                at non_exhaustive
+                at path = "…"
+                at proc_macro
+                at proc_macro_attribute
+                at proc_macro_derive(…)
+                at repr(…)
+                at should_panic(…)
+                at target_feature = "…"
+                at test
+                at used
+                at warn(…)
+            "#]],
+        )
+    }
+
+    #[test]
+    fn test_attribute_completion_inside_nested_attr() {
+        check(r#"#[cfg(<|>)]"#, expect![[]])
+    }
+
+    #[test]
+    fn test_inner_attribute_completion() {
+        check(
+            r"#![<|>]",
+            expect![[r#"
+                at allow(…)
+                at cfg(…)
+                at cfg_attr(…)
+                at deny(…)
+                at deprecated = "…"
+                at derive(…)
+                at doc = "…"
+                at feature(…)
+                at forbid(…)
+                at global_allocator
+                at ignore = "…"
+                at inline(…)
+                at link
+                at link_name = "…"
+                at macro_export
+                at macro_use
+                at must_use = "…"
+                at no_mangle
+                at no_std
+                at non_exhaustive
+                at panic_handler
+                at path = "…"
+                at proc_macro
+                at proc_macro_attribute
+                at proc_macro_derive(…)
+                at recursion_limit = …
+                at repr(…)
+                at should_panic(…)
+                at target_feature = "…"
+                at test
+                at used
+                at warn(…)
+                at windows_subsystem = "…"
+            "#]],
+        );
+    }
+}
diff --git a/crates/completion/src/complete_dot.rs b/crates/completion/src/complete_dot.rs
new file mode 100644 (file)
index 0000000..0eabb48
--- /dev/null
@@ -0,0 +1,431 @@
+//! Completes references after dot (fields and method calls).
+
+use hir::{HasVisibility, Type};
+use rustc_hash::FxHashSet;
+use test_utils::mark;
+
+use crate::{completion_context::CompletionContext, completion_item::Completions};
+
+/// Complete dot accesses, i.e. fields or methods.
+pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
+    let dot_receiver = match &ctx.dot_receiver {
+        Some(expr) => expr,
+        _ => return,
+    };
+
+    let receiver_ty = match ctx.sema.type_of_expr(&dot_receiver) {
+        Some(ty) => ty,
+        _ => return,
+    };
+
+    if ctx.is_call {
+        mark::hit!(test_no_struct_field_completion_for_method_call);
+    } else {
+        complete_fields(acc, ctx, &receiver_ty);
+    }
+    complete_methods(acc, ctx, &receiver_ty);
+}
+
+fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: &Type) {
+    for receiver in receiver.autoderef(ctx.db) {
+        for (field, ty) in receiver.fields(ctx.db) {
+            if ctx.scope.module().map_or(false, |m| !field.is_visible_from(ctx.db, m)) {
+                // Skip private field. FIXME: If the definition location of the
+                // field is editable, we should show the completion
+                continue;
+            }
+            acc.add_field(ctx, field, &ty);
+        }
+        for (i, ty) in receiver.tuple_fields(ctx.db).into_iter().enumerate() {
+            // FIXME: Handle visibility
+            acc.add_tuple_field(ctx, i, &ty);
+        }
+    }
+}
+
+fn complete_methods(acc: &mut Completions, ctx: &CompletionContext, receiver: &Type) {
+    if let Some(krate) = ctx.krate {
+        let mut seen_methods = FxHashSet::default();
+        let traits_in_scope = ctx.scope.traits_in_scope();
+        receiver.iterate_method_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, func| {
+            if func.self_param(ctx.db).is_some()
+                && ctx.scope.module().map_or(true, |m| func.is_visible_from(ctx.db, m))
+                && seen_methods.insert(func.name(ctx.db))
+            {
+                acc.add_function(ctx, func, None);
+            }
+            None::<()>
+        });
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+    use test_utils::mark;
+
+    use crate::{test_utils::completion_list, CompletionKind};
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Reference);
+        expect.assert_eq(&actual);
+    }
+
+    #[test]
+    fn test_struct_field_and_method_completion() {
+        check(
+            r#"
+struct S { foo: u32 }
+impl S {
+    fn bar(&self) {}
+}
+fn foo(s: S) { s.<|> }
+"#,
+            expect![[r#"
+                me bar() fn bar(&self)
+                fd foo   u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_struct_field_completion_self() {
+        check(
+            r#"
+struct S { the_field: (u32,) }
+impl S {
+    fn foo(self) { self.<|> }
+}
+"#,
+            expect![[r#"
+                me foo()     fn foo(self)
+                fd the_field (u32,)
+            "#]],
+        )
+    }
+
+    #[test]
+    fn test_struct_field_completion_autoderef() {
+        check(
+            r#"
+struct A { the_field: (u32, i32) }
+impl A {
+    fn foo(&self) { self.<|> }
+}
+"#,
+            expect![[r#"
+                me foo()     fn foo(&self)
+                fd the_field (u32, i32)
+            "#]],
+        )
+    }
+
+    #[test]
+    fn test_no_struct_field_completion_for_method_call() {
+        mark::check!(test_no_struct_field_completion_for_method_call);
+        check(
+            r#"
+struct A { the_field: u32 }
+fn foo(a: A) { a.<|>() }
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn test_visibility_filtering() {
+        check(
+            r#"
+mod inner {
+    pub struct A {
+        private_field: u32,
+        pub pub_field: u32,
+        pub(crate) crate_field: u32,
+        pub(super) super_field: u32,
+    }
+}
+fn foo(a: inner::A) { a.<|> }
+"#,
+            expect![[r#"
+                fd crate_field u32
+                fd pub_field   u32
+                fd super_field u32
+            "#]],
+        );
+
+        check(
+            r#"
+struct A {}
+mod m {
+    impl super::A {
+        fn private_method(&self) {}
+        pub(super) fn the_method(&self) {}
+    }
+}
+fn foo(a: A) { a.<|> }
+"#,
+            expect![[r#"
+                me the_method() pub(super) fn the_method(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_union_field_completion() {
+        check(
+            r#"
+union U { field: u8, other: u16 }
+fn foo(u: U) { u.<|> }
+"#,
+            expect![[r#"
+                fd field u8
+                fd other u16
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_method_completion_only_fitting_impls() {
+        check(
+            r#"
+struct A<T> {}
+impl A<u32> {
+    fn the_method(&self) {}
+}
+impl A<i32> {
+    fn the_other_method(&self) {}
+}
+fn foo(a: A<u32>) { a.<|> }
+"#,
+            expect![[r#"
+                me the_method() fn the_method(&self)
+            "#]],
+        )
+    }
+
+    #[test]
+    fn test_trait_method_completion() {
+        check(
+            r#"
+struct A {}
+trait Trait { fn the_method(&self); }
+impl Trait for A {}
+fn foo(a: A) { a.<|> }
+"#,
+            expect![[r#"
+                me the_method() fn the_method(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_trait_method_completion_deduplicated() {
+        check(
+            r"
+struct A {}
+trait Trait { fn the_method(&self); }
+impl<T> Trait for T {}
+fn foo(a: &A) { a.<|> }
+",
+            expect![[r#"
+                me the_method() fn the_method(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_trait_method_from_other_module() {
+        check(
+            r"
+struct A {}
+mod m {
+    pub trait Trait { fn the_method(&self); }
+}
+use m::Trait;
+impl Trait for A {}
+fn foo(a: A) { a.<|> }
+",
+            expect![[r#"
+                me the_method() fn the_method(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_no_non_self_method() {
+        check(
+            r#"
+struct A {}
+impl A {
+    fn the_method() {}
+}
+fn foo(a: A) {
+   a.<|>
+}
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn test_tuple_field_completion() {
+        check(
+            r#"
+fn foo() {
+   let b = (0, 3.14);
+   b.<|>
+}
+"#,
+            expect![[r#"
+                fd 0 i32
+                fd 1 f64
+            "#]],
+        )
+    }
+
+    #[test]
+    fn test_tuple_field_inference() {
+        check(
+            r#"
+pub struct S;
+impl S { pub fn blah(&self) {} }
+
+struct T(S);
+
+impl T {
+    fn foo(&self) {
+        // FIXME: This doesn't work without the trailing `a` as `0.` is a float
+        self.0.a<|>
+    }
+}
+"#,
+            expect![[r#"
+                me blah() pub fn blah(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_completion_works_in_consts() {
+        check(
+            r#"
+struct A { the_field: u32 }
+const X: u32 = {
+    A { the_field: 92 }.<|>
+};
+"#,
+            expect![[r#"
+                fd the_field u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn works_in_simple_macro_1() {
+        check(
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+struct A { the_field: u32 }
+fn foo(a: A) {
+    m!(a.x<|>)
+}
+"#,
+            expect![[r#"
+                fd the_field u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn works_in_simple_macro_2() {
+        // this doesn't work yet because the macro doesn't expand without the token -- maybe it can be fixed with better recovery
+        check(
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+struct A { the_field: u32 }
+fn foo(a: A) {
+    m!(a.<|>)
+}
+"#,
+            expect![[r#"
+                fd the_field u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn works_in_simple_macro_recursive_1() {
+        check(
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+struct A { the_field: u32 }
+fn foo(a: A) {
+    m!(m!(m!(a.x<|>)))
+}
+"#,
+            expect![[r#"
+                fd the_field u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn macro_expansion_resilient() {
+        check(
+            r#"
+macro_rules! dbg {
+    () => {};
+    ($val:expr) => {
+        match $val { tmp => { tmp } }
+    };
+    // Trailing comma with single argument is ignored
+    ($val:expr,) => { $crate::dbg!($val) };
+    ($($val:expr),+ $(,)?) => {
+        ($($crate::dbg!($val)),+,)
+    };
+}
+struct A { the_field: u32 }
+fn foo(a: A) {
+    dbg!(a.<|>)
+}
+"#,
+            expect![[r#"
+                fd the_field u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_method_completion_issue_3547() {
+        check(
+            r#"
+struct HashSet<T> {}
+impl<T> HashSet<T> {
+    pub fn the_method(&self) {}
+}
+fn foo() {
+    let s: HashSet<_>;
+    s.<|>
+}
+"#,
+            expect![[r#"
+                me the_method() pub fn the_method(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_method_call_when_receiver_is_a_macro_call() {
+        check(
+            r#"
+struct S;
+impl S { fn foo(&self) {} }
+macro_rules! make_s { () => { S }; }
+fn main() { make_s!().f<|>; }
+"#,
+            expect![[r#"
+                me foo() fn foo(&self)
+            "#]],
+        )
+    }
+}
diff --git a/crates/completion/src/complete_fn_param.rs b/crates/completion/src/complete_fn_param.rs
new file mode 100644 (file)
index 0000000..9189967
--- /dev/null
@@ -0,0 +1,135 @@
+//! See `complete_fn_param`.
+
+use rustc_hash::FxHashMap;
+use syntax::{
+    ast::{self, ModuleItemOwner},
+    match_ast, AstNode,
+};
+
+use crate::{CompletionContext, CompletionItem, CompletionKind, Completions};
+
+/// Complete repeated parameters, both name and type. For example, if all
+/// functions in a file have a `spam: &mut Spam` parameter, a completion with
+/// `spam: &mut Spam` insert text/label and `spam` lookup string will be
+/// suggested.
+pub(super) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) {
+    if !ctx.is_param {
+        return;
+    }
+
+    let mut params = FxHashMap::default();
+
+    let me = ctx.token.ancestors().find_map(ast::Fn::cast);
+    let mut process_fn = |func: ast::Fn| {
+        if Some(&func) == me.as_ref() {
+            return;
+        }
+        func.param_list().into_iter().flat_map(|it| it.params()).for_each(|param| {
+            let text = param.syntax().text().to_string();
+            params.entry(text).or_insert(param);
+        })
+    };
+
+    for node in ctx.token.parent().ancestors() {
+        match_ast! {
+            match node {
+                ast::SourceFile(it) => it.items().filter_map(|item| match item {
+                    ast::Item::Fn(it) => Some(it),
+                    _ => None,
+                }).for_each(&mut process_fn),
+                ast::ItemList(it) => it.items().filter_map(|item| match item {
+                    ast::Item::Fn(it) => Some(it),
+                    _ => None,
+                }).for_each(&mut process_fn),
+                ast::AssocItemList(it) => it.assoc_items().filter_map(|item| match item {
+                    ast::AssocItem::Fn(it) => Some(it),
+                    _ => None,
+                }).for_each(&mut process_fn),
+                _ => continue,
+            }
+        };
+    }
+
+    params
+        .into_iter()
+        .filter_map(|(label, param)| {
+            let lookup = param.pat()?.syntax().text().to_string();
+            Some((label, lookup))
+        })
+        .for_each(|(label, lookup)| {
+            CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label)
+                .kind(crate::CompletionItemKind::Binding)
+                .lookup_by(lookup)
+                .add_to(acc)
+        });
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{test_utils::completion_list, CompletionKind};
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Magic);
+        expect.assert_eq(&actual);
+    }
+
+    #[test]
+    fn test_param_completion_last_param() {
+        check(
+            r#"
+fn foo(file_id: FileId) {}
+fn bar(file_id: FileId) {}
+fn baz(file<|>) {}
+"#,
+            expect![[r#"
+                bn file_id: FileId
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_param_completion_nth_param() {
+        check(
+            r#"
+fn foo(file_id: FileId) {}
+fn baz(file<|>, x: i32) {}
+"#,
+            expect![[r#"
+                bn file_id: FileId
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_param_completion_trait_param() {
+        check(
+            r#"
+pub(crate) trait SourceRoot {
+    pub fn contains(&self, file_id: FileId) -> bool;
+    pub fn module_map(&self) -> &ModuleMap;
+    pub fn lines(&self, file_id: FileId) -> &LineIndex;
+    pub fn syntax(&self, file<|>)
+}
+"#,
+            expect![[r#"
+                bn file_id: FileId
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_param_in_inner_function() {
+        check(
+            r#"
+fn outer(text: String) {
+    fn inner(<|>)
+}
+"#,
+            expect![[r#"
+                bn text: String
+            "#]],
+        )
+    }
+}
diff --git a/crates/completion/src/complete_keyword.rs b/crates/completion/src/complete_keyword.rs
new file mode 100644 (file)
index 0000000..ace914f
--- /dev/null
@@ -0,0 +1,566 @@
+//! Completes keywords.
+
+use syntax::{ast, SyntaxKind};
+use test_utils::mark;
+
+use crate::{CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions};
+
+pub(super) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionContext) {
+    // complete keyword "crate" in use stmt
+    let source_range = ctx.source_range();
+
+    if ctx.use_item_syntax.is_some() {
+        if ctx.path_qual.is_none() {
+            CompletionItem::new(CompletionKind::Keyword, source_range, "crate::")
+                .kind(CompletionItemKind::Keyword)
+                .insert_text("crate::")
+                .add_to(acc);
+        }
+        CompletionItem::new(CompletionKind::Keyword, source_range, "self")
+            .kind(CompletionItemKind::Keyword)
+            .add_to(acc);
+        CompletionItem::new(CompletionKind::Keyword, source_range, "super::")
+            .kind(CompletionItemKind::Keyword)
+            .insert_text("super::")
+            .add_to(acc);
+    }
+
+    // Suggest .await syntax for types that implement Future trait
+    if let Some(receiver) = &ctx.dot_receiver {
+        if let Some(ty) = ctx.sema.type_of_expr(receiver) {
+            if ty.impls_future(ctx.db) {
+                CompletionItem::new(CompletionKind::Keyword, ctx.source_range(), "await")
+                    .kind(CompletionItemKind::Keyword)
+                    .detail("expr.await")
+                    .insert_text("await")
+                    .add_to(acc);
+            }
+        };
+    }
+}
+
+pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) {
+    if ctx.token.kind() == SyntaxKind::COMMENT {
+        mark::hit!(no_keyword_completion_in_comments);
+        return;
+    }
+
+    let has_trait_or_impl_parent = ctx.has_impl_parent || ctx.has_trait_parent;
+    if ctx.trait_as_prev_sibling || ctx.impl_as_prev_sibling {
+        add_keyword(ctx, acc, "where", "where ");
+        return;
+    }
+    if ctx.unsafe_is_prev {
+        if ctx.has_item_list_or_source_file_parent || ctx.block_expr_parent {
+            add_keyword(ctx, acc, "fn", "fn $0() {}")
+        }
+
+        if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
+            add_keyword(ctx, acc, "trait", "trait $0 {}");
+            add_keyword(ctx, acc, "impl", "impl $0 {}");
+        }
+
+        return;
+    }
+    if ctx.has_item_list_or_source_file_parent || has_trait_or_impl_parent || ctx.block_expr_parent
+    {
+        add_keyword(ctx, acc, "fn", "fn $0() {}");
+    }
+    if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
+        add_keyword(ctx, acc, "use", "use ");
+        add_keyword(ctx, acc, "impl", "impl $0 {}");
+        add_keyword(ctx, acc, "trait", "trait $0 {}");
+    }
+
+    if ctx.has_item_list_or_source_file_parent {
+        add_keyword(ctx, acc, "enum", "enum $0 {}");
+        add_keyword(ctx, acc, "struct", "struct $0");
+        add_keyword(ctx, acc, "union", "union $0 {}");
+    }
+
+    if ctx.is_expr {
+        add_keyword(ctx, acc, "match", "match $0 {}");
+        add_keyword(ctx, acc, "while", "while $0 {}");
+        add_keyword(ctx, acc, "loop", "loop {$0}");
+        add_keyword(ctx, acc, "if", "if ");
+        add_keyword(ctx, acc, "if let", "if let ");
+    }
+
+    if ctx.if_is_prev || ctx.block_expr_parent {
+        add_keyword(ctx, acc, "let", "let ");
+    }
+
+    if ctx.after_if {
+        add_keyword(ctx, acc, "else", "else {$0}");
+        add_keyword(ctx, acc, "else if", "else if $0 {}");
+    }
+    if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
+        add_keyword(ctx, acc, "mod", "mod $0 {}");
+    }
+    if ctx.bind_pat_parent || ctx.ref_pat_parent {
+        add_keyword(ctx, acc, "mut", "mut ");
+    }
+    if ctx.has_item_list_or_source_file_parent || has_trait_or_impl_parent || ctx.block_expr_parent
+    {
+        add_keyword(ctx, acc, "const", "const ");
+        add_keyword(ctx, acc, "type", "type ");
+    }
+    if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
+        add_keyword(ctx, acc, "static", "static ");
+    };
+    if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
+        add_keyword(ctx, acc, "extern", "extern ");
+    }
+    if ctx.has_item_list_or_source_file_parent
+        || has_trait_or_impl_parent
+        || ctx.block_expr_parent
+        || ctx.is_match_arm
+    {
+        add_keyword(ctx, acc, "unsafe", "unsafe ");
+    }
+    if ctx.in_loop_body {
+        if ctx.can_be_stmt {
+            add_keyword(ctx, acc, "continue", "continue;");
+            add_keyword(ctx, acc, "break", "break;");
+        } else {
+            add_keyword(ctx, acc, "continue", "continue");
+            add_keyword(ctx, acc, "break", "break");
+        }
+    }
+    if ctx.has_item_list_or_source_file_parent || ctx.has_impl_parent | ctx.has_field_list_parent {
+        add_keyword(ctx, acc, "pub(crate)", "pub(crate) ");
+        add_keyword(ctx, acc, "pub", "pub ");
+    }
+
+    if !ctx.is_trivial_path {
+        return;
+    }
+    let fn_def = match &ctx.function_syntax {
+        Some(it) => it,
+        None => return,
+    };
+    acc.add_all(complete_return(ctx, &fn_def, ctx.can_be_stmt));
+}
+
+fn keyword(ctx: &CompletionContext, kw: &str, snippet: &str) -> CompletionItem {
+    let res = CompletionItem::new(CompletionKind::Keyword, ctx.source_range(), kw)
+        .kind(CompletionItemKind::Keyword);
+
+    match ctx.config.snippet_cap {
+        Some(cap) => res.insert_snippet(cap, snippet),
+        _ => res.insert_text(if snippet.contains('$') { kw } else { snippet }),
+    }
+    .build()
+}
+
+fn add_keyword(ctx: &CompletionContext, acc: &mut Completions, kw: &str, snippet: &str) {
+    acc.add(keyword(ctx, kw, snippet));
+}
+
+fn complete_return(
+    ctx: &CompletionContext,
+    fn_def: &ast::Fn,
+    can_be_stmt: bool,
+) -> Option<CompletionItem> {
+    let snip = match (can_be_stmt, fn_def.ret_type().is_some()) {
+        (true, true) => "return $0;",
+        (true, false) => "return;",
+        (false, true) => "return $0",
+        (false, false) => "return",
+    };
+    Some(keyword(ctx, "return", snip))
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{
+        test_utils::{check_edit, completion_list},
+        CompletionKind,
+    };
+    use test_utils::mark;
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Keyword);
+        expect.assert_eq(&actual)
+    }
+
+    #[test]
+    fn test_keywords_in_use_stmt() {
+        check(
+            r"use <|>",
+            expect![[r#"
+                kw crate::
+                kw self
+                kw super::
+            "#]],
+        );
+
+        check(
+            r"use a::<|>",
+            expect![[r#"
+                kw self
+                kw super::
+            "#]],
+        );
+
+        check(
+            r"use a::{b, <|>}",
+            expect![[r#"
+                kw self
+                kw super::
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_at_source_file_level() {
+        check(
+            r"m<|>",
+            expect![[r#"
+                kw const
+                kw enum
+                kw extern
+                kw fn
+                kw impl
+                kw mod
+                kw pub
+                kw pub(crate)
+                kw static
+                kw struct
+                kw trait
+                kw type
+                kw union
+                kw unsafe
+                kw use
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_in_function() {
+        check(
+            r"fn quux() { <|> }",
+            expect![[r#"
+                kw const
+                kw extern
+                kw fn
+                kw if
+                kw if let
+                kw impl
+                kw let
+                kw loop
+                kw match
+                kw mod
+                kw return
+                kw static
+                kw trait
+                kw type
+                kw unsafe
+                kw use
+                kw while
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_inside_block() {
+        check(
+            r"fn quux() { if true { <|> } }",
+            expect![[r#"
+                kw const
+                kw extern
+                kw fn
+                kw if
+                kw if let
+                kw impl
+                kw let
+                kw loop
+                kw match
+                kw mod
+                kw return
+                kw static
+                kw trait
+                kw type
+                kw unsafe
+                kw use
+                kw while
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_after_if() {
+        check(
+            r#"fn quux() { if true { () } <|> }"#,
+            expect![[r#"
+                kw const
+                kw else
+                kw else if
+                kw extern
+                kw fn
+                kw if
+                kw if let
+                kw impl
+                kw let
+                kw loop
+                kw match
+                kw mod
+                kw return
+                kw static
+                kw trait
+                kw type
+                kw unsafe
+                kw use
+                kw while
+            "#]],
+        );
+        check_edit(
+            "else",
+            r#"fn quux() { if true { () } <|> }"#,
+            r#"fn quux() { if true { () } else {$0} }"#,
+        );
+    }
+
+    #[test]
+    fn test_keywords_in_match_arm() {
+        check(
+            r#"
+fn quux() -> i32 {
+    match () { () => <|> }
+}
+"#,
+            expect![[r#"
+                kw if
+                kw if let
+                kw loop
+                kw match
+                kw return
+                kw unsafe
+                kw while
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_in_trait_def() {
+        check(
+            r"trait My { <|> }",
+            expect![[r#"
+                kw const
+                kw fn
+                kw type
+                kw unsafe
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_in_impl_def() {
+        check(
+            r"impl My { <|> }",
+            expect![[r#"
+                kw const
+                kw fn
+                kw pub
+                kw pub(crate)
+                kw type
+                kw unsafe
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_in_loop() {
+        check(
+            r"fn my() { loop { <|> } }",
+            expect![[r#"
+                kw break
+                kw const
+                kw continue
+                kw extern
+                kw fn
+                kw if
+                kw if let
+                kw impl
+                kw let
+                kw loop
+                kw match
+                kw mod
+                kw return
+                kw static
+                kw trait
+                kw type
+                kw unsafe
+                kw use
+                kw while
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_after_unsafe_in_item_list() {
+        check(
+            r"unsafe <|>",
+            expect![[r#"
+                kw fn
+                kw impl
+                kw trait
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_keywords_after_unsafe_in_block_expr() {
+        check(
+            r"fn my_fn() { unsafe <|> }",
+            expect![[r#"
+                kw fn
+                kw impl
+                kw trait
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_mut_in_ref_and_in_fn_parameters_list() {
+        check(
+            r"fn my_fn(&<|>) {}",
+            expect![[r#"
+                kw mut
+            "#]],
+        );
+        check(
+            r"fn my_fn(<|>) {}",
+            expect![[r#"
+                kw mut
+            "#]],
+        );
+        check(
+            r"fn my_fn() { let &<|> }",
+            expect![[r#"
+                kw mut
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_where_keyword() {
+        check(
+            r"trait A <|>",
+            expect![[r#"
+                kw where
+            "#]],
+        );
+        check(
+            r"impl A <|>",
+            expect![[r#"
+                kw where
+            "#]],
+        );
+    }
+
+    #[test]
+    fn no_keyword_completion_in_comments() {
+        mark::check!(no_keyword_completion_in_comments);
+        check(
+            r#"
+fn test() {
+    let x = 2; // A comment<|>
+}
+"#,
+            expect![[""]],
+        );
+        check(
+            r#"
+/*
+Some multi-line comment<|>
+*/
+"#,
+            expect![[""]],
+        );
+        check(
+            r#"
+/// Some doc comment
+/// let test<|> = 1
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn test_completion_await_impls_future() {
+        check(
+            r#"
+//- /main.rs crate:main deps:std
+use std::future::*;
+struct A {}
+impl Future for A {}
+fn foo(a: A) { a.<|> }
+
+//- /std/lib.rs crate:std
+pub mod future {
+    #[lang = "future_trait"]
+    pub trait Future {}
+}
+"#,
+            expect![[r#"
+                kw await expr.await
+            "#]],
+        );
+
+        check(
+            r#"
+//- /main.rs crate:main deps:std
+use std::future::*;
+fn foo() {
+    let a = async {};
+    a.<|>
+}
+
+//- /std/lib.rs crate:std
+pub mod future {
+    #[lang = "future_trait"]
+    pub trait Future {
+        type Output;
+    }
+}
+"#,
+            expect![[r#"
+                kw await expr.await
+            "#]],
+        )
+    }
+
+    #[test]
+    fn after_let() {
+        check(
+            r#"fn main() { let _ = <|> }"#,
+            expect![[r#"
+                kw if
+                kw if let
+                kw loop
+                kw match
+                kw return
+                kw while
+            "#]],
+        )
+    }
+
+    #[test]
+    fn before_field() {
+        check(
+            r#"
+struct Foo {
+    <|>
+    pub f: i32,
+}
+"#,
+            expect![[r#"
+                kw pub
+                kw pub(crate)
+            "#]],
+        )
+    }
+}
diff --git a/crates/completion/src/complete_macro_in_item_position.rs b/crates/completion/src/complete_macro_in_item_position.rs
new file mode 100644 (file)
index 0000000..d1d8c23
--- /dev/null
@@ -0,0 +1,41 @@
+//! Completes macro invocations used in item position.
+
+use crate::{CompletionContext, Completions};
+
+pub(super) fn complete_macro_in_item_position(acc: &mut Completions, ctx: &CompletionContext) {
+    // Show only macros in top level.
+    if ctx.is_new_item {
+        ctx.scope.process_all_names(&mut |name, res| {
+            if let hir::ScopeDef::MacroDef(mac) = res {
+                acc.add_macro(ctx, Some(name.to_string()), mac);
+            }
+        })
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{test_utils::completion_list, CompletionKind};
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Reference);
+        expect.assert_eq(&actual)
+    }
+
+    #[test]
+    fn completes_macros_as_item() {
+        check(
+            r#"
+macro_rules! foo { () => {} }
+fn foo() {}
+
+<|>
+"#,
+            expect![[r#"
+                ma foo!(…) macro_rules! foo
+            "#]],
+        )
+    }
+}
diff --git a/crates/completion/src/complete_mod.rs b/crates/completion/src/complete_mod.rs
new file mode 100644 (file)
index 0000000..35a57ab
--- /dev/null
@@ -0,0 +1,324 @@
+//! Completes mod declarations.
+
+use base_db::{SourceDatabaseExt, VfsPath};
+use hir::{Module, ModuleSource};
+use ide_db::RootDatabase;
+use rustc_hash::FxHashSet;
+
+use crate::{CompletionItem, CompletionItemKind};
+
+use super::{
+    completion_context::CompletionContext, completion_item::CompletionKind,
+    completion_item::Completions,
+};
+
+/// Complete mod declaration, i.e. `mod <|> ;`
+pub(super) fn complete_mod(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
+    let mod_under_caret = match &ctx.mod_declaration_under_caret {
+        Some(mod_under_caret) if mod_under_caret.item_list().is_some() => return None,
+        Some(mod_under_caret) => mod_under_caret,
+        None => return None,
+    };
+
+    let _p = profile::span("completion::complete_mod");
+
+    let current_module = ctx.scope.module()?;
+
+    let module_definition_file =
+        current_module.definition_source(ctx.db).file_id.original_file(ctx.db);
+    let source_root = ctx.db.source_root(ctx.db.file_source_root(module_definition_file));
+    let directory_to_look_for_submodules = directory_to_look_for_submodules(
+        current_module,
+        ctx.db,
+        source_root.path_for_file(&module_definition_file)?,
+    )?;
+
+    let existing_mod_declarations = current_module
+        .children(ctx.db)
+        .filter_map(|module| Some(module.name(ctx.db)?.to_string()))
+        .collect::<FxHashSet<_>>();
+
+    let module_declaration_file =
+        current_module.declaration_source(ctx.db).map(|module_declaration_source_file| {
+            module_declaration_source_file.file_id.original_file(ctx.db)
+        });
+
+    source_root
+        .iter()
+        .filter(|submodule_candidate_file| submodule_candidate_file != &module_definition_file)
+        .filter(|submodule_candidate_file| {
+            Some(submodule_candidate_file) != module_declaration_file.as_ref()
+        })
+        .filter_map(|submodule_file| {
+            let submodule_path = source_root.path_for_file(&submodule_file)?;
+            let directory_with_submodule = submodule_path.parent()?;
+            match submodule_path.name_and_extension()? {
+                ("lib", Some("rs")) | ("main", Some("rs")) => None,
+                ("mod", Some("rs")) => {
+                    if directory_with_submodule.parent()? == directory_to_look_for_submodules {
+                        match directory_with_submodule.name_and_extension()? {
+                            (directory_name, None) => Some(directory_name.to_owned()),
+                            _ => None,
+                        }
+                    } else {
+                        None
+                    }
+                }
+                (file_name, Some("rs"))
+                    if directory_with_submodule == directory_to_look_for_submodules =>
+                {
+                    Some(file_name.to_owned())
+                }
+                _ => None,
+            }
+        })
+        .filter(|name| !existing_mod_declarations.contains(name))
+        .for_each(|submodule_name| {
+            let mut label = submodule_name;
+            if mod_under_caret.semicolon_token().is_none() {
+                label.push(';')
+            }
+            acc.add(
+                CompletionItem::new(CompletionKind::Magic, ctx.source_range(), &label)
+                    .kind(CompletionItemKind::Module),
+            )
+        });
+
+    Some(())
+}
+
+fn directory_to_look_for_submodules(
+    module: Module,
+    db: &RootDatabase,
+    module_file_path: &VfsPath,
+) -> Option<VfsPath> {
+    let directory_with_module_path = module_file_path.parent()?;
+    let base_directory = match module_file_path.name_and_extension()? {
+        ("mod", Some("rs")) | ("lib", Some("rs")) | ("main", Some("rs")) => {
+            Some(directory_with_module_path)
+        }
+        (regular_rust_file_name, Some("rs")) => {
+            if matches!(
+                (
+                    directory_with_module_path
+                        .parent()
+                        .as_ref()
+                        .and_then(|path| path.name_and_extension()),
+                    directory_with_module_path.name_and_extension(),
+                ),
+                (Some(("src", None)), Some(("bin", None)))
+            ) {
+                // files in /src/bin/ can import each other directly
+                Some(directory_with_module_path)
+            } else {
+                directory_with_module_path.join(regular_rust_file_name)
+            }
+        }
+        _ => None,
+    }?;
+
+    let mut resulting_path = base_directory;
+    for module in module_chain_to_containing_module_file(module, db) {
+        if let Some(name) = module.name(db) {
+            resulting_path = resulting_path.join(&name.to_string())?;
+        }
+    }
+
+    Some(resulting_path)
+}
+
+fn module_chain_to_containing_module_file(
+    current_module: Module,
+    db: &RootDatabase,
+) -> Vec<Module> {
+    let mut path = Vec::new();
+
+    let mut current_module = Some(current_module);
+    while let Some(ModuleSource::Module(_)) =
+        current_module.map(|module| module.definition_source(db).value)
+    {
+        if let Some(module) = current_module {
+            path.insert(0, module);
+            current_module = module.parent(db);
+        } else {
+            current_module = None;
+        }
+    }
+
+    path
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::{test_utils::completion_list, CompletionKind};
+    use expect_test::{expect, Expect};
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Magic);
+        expect.assert_eq(&actual);
+    }
+
+    #[test]
+    fn lib_module_completion() {
+        check(
+            r#"
+            //- /lib.rs
+            mod <|>
+            //- /foo.rs
+            fn foo() {}
+            //- /foo/ignored_foo.rs
+            fn ignored_foo() {}
+            //- /bar/mod.rs
+            fn bar() {}
+            //- /bar/ignored_bar.rs
+            fn ignored_bar() {}
+        "#,
+            expect![[r#"
+                md bar;
+                md foo;
+            "#]],
+        );
+    }
+
+    #[test]
+    fn no_module_completion_with_module_body() {
+        check(
+            r#"
+            //- /lib.rs
+            mod <|> {
+
+            }
+            //- /foo.rs
+            fn foo() {}
+        "#,
+            expect![[r#""#]],
+        );
+    }
+
+    #[test]
+    fn main_module_completion() {
+        check(
+            r#"
+            //- /main.rs
+            mod <|>
+            //- /foo.rs
+            fn foo() {}
+            //- /foo/ignored_foo.rs
+            fn ignored_foo() {}
+            //- /bar/mod.rs
+            fn bar() {}
+            //- /bar/ignored_bar.rs
+            fn ignored_bar() {}
+        "#,
+            expect![[r#"
+                md bar;
+                md foo;
+            "#]],
+        );
+    }
+
+    #[test]
+    fn main_test_module_completion() {
+        check(
+            r#"
+            //- /main.rs
+            mod tests {
+                mod <|>;
+            }
+            //- /tests/foo.rs
+            fn foo() {}
+        "#,
+            expect![[r#"
+                md foo
+            "#]],
+        );
+    }
+
+    #[test]
+    fn directly_nested_module_completion() {
+        check(
+            r#"
+            //- /lib.rs
+            mod foo;
+            //- /foo.rs
+            mod <|>;
+            //- /foo/bar.rs
+            fn bar() {}
+            //- /foo/bar/ignored_bar.rs
+            fn ignored_bar() {}
+            //- /foo/baz/mod.rs
+            fn baz() {}
+            //- /foo/moar/ignored_moar.rs
+            fn ignored_moar() {}
+        "#,
+            expect![[r#"
+                md bar
+                md baz
+            "#]],
+        );
+    }
+
+    #[test]
+    fn nested_in_source_module_completion() {
+        check(
+            r#"
+            //- /lib.rs
+            mod foo;
+            //- /foo.rs
+            mod bar {
+                mod <|>
+            }
+            //- /foo/bar/baz.rs
+            fn baz() {}
+        "#,
+            expect![[r#"
+                md baz;
+            "#]],
+        );
+    }
+
+    // FIXME binary modules are not supported in tests properly
+    // Binary modules are a bit special, they allow importing the modules from `/src/bin`
+    // and that's why are good to test two things:
+    // * no cycles are allowed in mod declarations
+    // * no modules from the parent directory are proposed
+    // Unfortunately, binary modules support is in cargo not rustc,
+    // hence the test does not work now
+    //
+    // #[test]
+    // fn regular_bin_module_completion() {
+    //     check(
+    //         r#"
+    //         //- /src/bin.rs
+    //         fn main() {}
+    //         //- /src/bin/foo.rs
+    //         mod <|>
+    //         //- /src/bin/bar.rs
+    //         fn bar() {}
+    //         //- /src/bin/bar/bar_ignored.rs
+    //         fn bar_ignored() {}
+    //     "#,
+    //         expect![[r#"
+    //             md bar;
+    //         "#]],foo
+    //     );
+    // }
+
+    #[test]
+    fn already_declared_bin_module_completion_omitted() {
+        check(
+            r#"
+            //- /src/bin.rs crate:main
+            fn main() {}
+            //- /src/bin/foo.rs
+            mod <|>
+            //- /src/bin/bar.rs
+            mod foo;
+            fn bar() {}
+            //- /src/bin/bar/bar_ignored.rs
+            fn bar_ignored() {}
+        "#,
+            expect![[r#""#]],
+        );
+    }
+}
diff --git a/crates/completion/src/complete_pattern.rs b/crates/completion/src/complete_pattern.rs
new file mode 100644 (file)
index 0000000..5606dcd
--- /dev/null
@@ -0,0 +1,88 @@
+//! Completes constats and paths in patterns.
+
+use crate::{CompletionContext, Completions};
+
+/// Completes constats and paths in patterns.
+pub(super) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) {
+    if !ctx.is_pat_binding_or_const {
+        return;
+    }
+    if ctx.record_pat_syntax.is_some() {
+        return;
+    }
+
+    // FIXME: ideally, we should look at the type we are matching against and
+    // suggest variants + auto-imports
+    ctx.scope.process_all_names(&mut |name, res| {
+        match &res {
+            hir::ScopeDef::ModuleDef(def) => match def {
+                hir::ModuleDef::Adt(hir::Adt::Enum(..))
+                | hir::ModuleDef::Adt(hir::Adt::Struct(..))
+                | hir::ModuleDef::EnumVariant(..)
+                | hir::ModuleDef::Const(..)
+                | hir::ModuleDef::Module(..) => (),
+                _ => return,
+            },
+            hir::ScopeDef::MacroDef(_) => (),
+            _ => return,
+        };
+
+        acc.add_resolution(ctx, name.to_string(), &res)
+    });
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{test_utils::completion_list, CompletionKind};
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Reference);
+        expect.assert_eq(&actual)
+    }
+
+    #[test]
+    fn completes_enum_variants_and_modules() {
+        check(
+            r#"
+enum E { X }
+use self::E::X;
+const Z: E = E::X;
+mod m {}
+
+static FOO: E = E::X;
+struct Bar { f: u32 }
+
+fn foo() {
+   match E::X { <|> }
+}
+"#,
+            expect![[r#"
+                st Bar
+                en E
+                ev X   ()
+                ct Z
+                md m
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_in_simple_macro_call() {
+        check(
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+enum E { X }
+
+fn foo() {
+   m!(match E::X { <|> })
+}
+"#,
+            expect![[r#"
+                en E
+                ma m!(…) macro_rules! m
+            "#]],
+        );
+    }
+}
diff --git a/crates/completion/src/complete_postfix.rs b/crates/completion/src/complete_postfix.rs
new file mode 100644 (file)
index 0000000..700573c
--- /dev/null
@@ -0,0 +1,452 @@
+//! Postfix completions, like `Ok(10).ifl<|>` => `if let Ok() = Ok(10) { <|> }`.
+
+mod format_like;
+
+use assists::utils::TryEnum;
+use syntax::{
+    ast::{self, AstNode, AstToken},
+    TextRange, TextSize,
+};
+use text_edit::TextEdit;
+
+use self::format_like::add_format_like_completions;
+use crate::{
+    completion_config::SnippetCap,
+    completion_context::CompletionContext,
+    completion_item::{Builder, CompletionKind, Completions},
+    CompletionItem, CompletionItemKind,
+};
+
+pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
+    if !ctx.config.enable_postfix_completions {
+        return;
+    }
+
+    let dot_receiver = match &ctx.dot_receiver {
+        Some(it) => it,
+        None => return,
+    };
+
+    let receiver_text =
+        get_receiver_text(dot_receiver, ctx.dot_receiver_is_ambiguous_float_literal);
+
+    let receiver_ty = match ctx.sema.type_of_expr(&dot_receiver) {
+        Some(it) => it,
+        None => return,
+    };
+
+    let cap = match ctx.config.snippet_cap {
+        Some(it) => it,
+        None => return,
+    };
+    let try_enum = TryEnum::from_ty(&ctx.sema, &receiver_ty);
+    if let Some(try_enum) = &try_enum {
+        match try_enum {
+            TryEnum::Result => {
+                postfix_snippet(
+                    ctx,
+                    cap,
+                    &dot_receiver,
+                    "ifl",
+                    "if let Ok {}",
+                    &format!("if let Ok($1) = {} {{\n    $0\n}}", receiver_text),
+                )
+                .add_to(acc);
+
+                postfix_snippet(
+                    ctx,
+                    cap,
+                    &dot_receiver,
+                    "while",
+                    "while let Ok {}",
+                    &format!("while let Ok($1) = {} {{\n    $0\n}}", receiver_text),
+                )
+                .add_to(acc);
+            }
+            TryEnum::Option => {
+                postfix_snippet(
+                    ctx,
+                    cap,
+                    &dot_receiver,
+                    "ifl",
+                    "if let Some {}",
+                    &format!("if let Some($1) = {} {{\n    $0\n}}", receiver_text),
+                )
+                .add_to(acc);
+
+                postfix_snippet(
+                    ctx,
+                    cap,
+                    &dot_receiver,
+                    "while",
+                    "while let Some {}",
+                    &format!("while let Some($1) = {} {{\n    $0\n}}", receiver_text),
+                )
+                .add_to(acc);
+            }
+        }
+    } else if receiver_ty.is_bool() || receiver_ty.is_unknown() {
+        postfix_snippet(
+            ctx,
+            cap,
+            &dot_receiver,
+            "if",
+            "if expr {}",
+            &format!("if {} {{\n    $0\n}}", receiver_text),
+        )
+        .add_to(acc);
+        postfix_snippet(
+            ctx,
+            cap,
+            &dot_receiver,
+            "while",
+            "while expr {}",
+            &format!("while {} {{\n    $0\n}}", receiver_text),
+        )
+        .add_to(acc);
+        postfix_snippet(ctx, cap, &dot_receiver, "not", "!expr", &format!("!{}", receiver_text))
+            .add_to(acc);
+    }
+
+    postfix_snippet(ctx, cap, &dot_receiver, "ref", "&expr", &format!("&{}", receiver_text))
+        .add_to(acc);
+    postfix_snippet(
+        ctx,
+        cap,
+        &dot_receiver,
+        "refm",
+        "&mut expr",
+        &format!("&mut {}", receiver_text),
+    )
+    .add_to(acc);
+
+    // The rest of the postfix completions create an expression that moves an argument,
+    // so it's better to consider references now to avoid breaking the compilation
+    let dot_receiver = include_references(dot_receiver);
+    let receiver_text =
+        get_receiver_text(&dot_receiver, ctx.dot_receiver_is_ambiguous_float_literal);
+
+    match try_enum {
+        Some(try_enum) => match try_enum {
+            TryEnum::Result => {
+                postfix_snippet(
+                    ctx,
+                    cap,
+                    &dot_receiver,
+                    "match",
+                    "match expr {}",
+                    &format!("match {} {{\n    Ok(${{1:_}}) => {{$2}},\n    Err(${{3:_}}) => {{$0}},\n}}", receiver_text),
+                )
+                .add_to(acc);
+            }
+            TryEnum::Option => {
+                postfix_snippet(
+                    ctx,
+                    cap,
+                    &dot_receiver,
+                    "match",
+                    "match expr {}",
+                    &format!(
+                        "match {} {{\n    Some(${{1:_}}) => {{$2}},\n    None => {{$0}},\n}}",
+                        receiver_text
+                    ),
+                )
+                .add_to(acc);
+            }
+        },
+        None => {
+            postfix_snippet(
+                ctx,
+                cap,
+                &dot_receiver,
+                "match",
+                "match expr {}",
+                &format!("match {} {{\n    ${{1:_}} => {{$0}},\n}}", receiver_text),
+            )
+            .add_to(acc);
+        }
+    }
+
+    postfix_snippet(
+        ctx,
+        cap,
+        &dot_receiver,
+        "box",
+        "Box::new(expr)",
+        &format!("Box::new({})", receiver_text),
+    )
+    .add_to(acc);
+
+    postfix_snippet(ctx, cap, &dot_receiver, "ok", "Ok(expr)", &format!("Ok({})", receiver_text))
+        .add_to(acc);
+
+    postfix_snippet(
+        ctx,
+        cap,
+        &dot_receiver,
+        "dbg",
+        "dbg!(expr)",
+        &format!("dbg!({})", receiver_text),
+    )
+    .add_to(acc);
+
+    postfix_snippet(
+        ctx,
+        cap,
+        &dot_receiver,
+        "dbgr",
+        "dbg!(&expr)",
+        &format!("dbg!(&{})", receiver_text),
+    )
+    .add_to(acc);
+
+    postfix_snippet(
+        ctx,
+        cap,
+        &dot_receiver,
+        "call",
+        "function(expr)",
+        &format!("${{1}}({})", receiver_text),
+    )
+    .add_to(acc);
+
+    if let ast::Expr::Literal(literal) = dot_receiver.clone() {
+        if let Some(literal_text) = ast::String::cast(literal.token()) {
+            add_format_like_completions(acc, ctx, &dot_receiver, cap, &literal_text);
+        }
+    }
+}
+
+fn get_receiver_text(receiver: &ast::Expr, receiver_is_ambiguous_float_literal: bool) -> String {
+    if receiver_is_ambiguous_float_literal {
+        let text = receiver.syntax().text();
+        let without_dot = ..text.len() - TextSize::of('.');
+        text.slice(without_dot).to_string()
+    } else {
+        receiver.to_string()
+    }
+}
+
+fn include_references(initial_element: &ast::Expr) -> ast::Expr {
+    let mut resulting_element = initial_element.clone();
+    while let Some(parent_ref_element) =
+        resulting_element.syntax().parent().and_then(ast::RefExpr::cast)
+    {
+        resulting_element = ast::Expr::from(parent_ref_element);
+    }
+    resulting_element
+}
+
+fn postfix_snippet(
+    ctx: &CompletionContext,
+    cap: SnippetCap,
+    receiver: &ast::Expr,
+    label: &str,
+    detail: &str,
+    snippet: &str,
+) -> Builder {
+    let edit = {
+        let receiver_syntax = receiver.syntax();
+        let receiver_range = ctx.sema.original_range(receiver_syntax).range;
+        let delete_range = TextRange::new(receiver_range.start(), ctx.source_range().end());
+        TextEdit::replace(delete_range, snippet.to_string())
+    };
+    CompletionItem::new(CompletionKind::Postfix, ctx.source_range(), label)
+        .detail(detail)
+        .kind(CompletionItemKind::Snippet)
+        .snippet_edit(cap, edit)
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{
+        test_utils::{check_edit, completion_list},
+        CompletionKind,
+    };
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Postfix);
+        expect.assert_eq(&actual)
+    }
+
+    #[test]
+    fn postfix_completion_works_for_trivial_path_expression() {
+        check(
+            r#"
+fn main() {
+    let bar = true;
+    bar.<|>
+}
+"#,
+            expect![[r#"
+                sn box   Box::new(expr)
+                sn call  function(expr)
+                sn dbg   dbg!(expr)
+                sn dbgr  dbg!(&expr)
+                sn if    if expr {}
+                sn match match expr {}
+                sn not   !expr
+                sn ok    Ok(expr)
+                sn ref   &expr
+                sn refm  &mut expr
+                sn while while expr {}
+            "#]],
+        );
+    }
+
+    #[test]
+    fn postfix_type_filtering() {
+        check(
+            r#"
+fn main() {
+    let bar: u8 = 12;
+    bar.<|>
+}
+"#,
+            expect![[r#"
+                sn box   Box::new(expr)
+                sn call  function(expr)
+                sn dbg   dbg!(expr)
+                sn dbgr  dbg!(&expr)
+                sn match match expr {}
+                sn ok    Ok(expr)
+                sn ref   &expr
+                sn refm  &mut expr
+            "#]],
+        )
+    }
+
+    #[test]
+    fn option_iflet() {
+        check_edit(
+            "ifl",
+            r#"
+enum Option<T> { Some(T), None }
+
+fn main() {
+    let bar = Option::Some(true);
+    bar.<|>
+}
+"#,
+            r#"
+enum Option<T> { Some(T), None }
+
+fn main() {
+    let bar = Option::Some(true);
+    if let Some($1) = bar {
+    $0
+}
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn result_match() {
+        check_edit(
+            "match",
+            r#"
+enum Result<T, E> { Ok(T), Err(E) }
+
+fn main() {
+    let bar = Result::Ok(true);
+    bar.<|>
+}
+"#,
+            r#"
+enum Result<T, E> { Ok(T), Err(E) }
+
+fn main() {
+    let bar = Result::Ok(true);
+    match bar {
+    Ok(${1:_}) => {$2},
+    Err(${3:_}) => {$0},
+}
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn postfix_completion_works_for_ambiguous_float_literal() {
+        check_edit("refm", r#"fn main() { 42.<|> }"#, r#"fn main() { &mut 42 }"#)
+    }
+
+    #[test]
+    fn works_in_simple_macro() {
+        check_edit(
+            "dbg",
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+fn main() {
+    let bar: u8 = 12;
+    m!(bar.d<|>)
+}
+"#,
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+fn main() {
+    let bar: u8 = 12;
+    m!(dbg!(bar))
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn postfix_completion_for_references() {
+        check_edit("dbg", r#"fn main() { &&42.<|> }"#, r#"fn main() { dbg!(&&42) }"#);
+        check_edit("refm", r#"fn main() { &&42.<|> }"#, r#"fn main() { &&&mut 42 }"#);
+    }
+
+    #[test]
+    fn postfix_completion_for_format_like_strings() {
+        check_edit(
+            "fmt",
+            r#"fn main() { "{some_var:?}".<|> }"#,
+            r#"fn main() { format!("{:?}", some_var) }"#,
+        );
+        check_edit(
+            "panic",
+            r#"fn main() { "Panic with {a}".<|> }"#,
+            r#"fn main() { panic!("Panic with {}", a) }"#,
+        );
+        check_edit(
+            "println",
+            r#"fn main() { "{ 2+2 } { SomeStruct { val: 1, other: 32 } :?}".<|> }"#,
+            r#"fn main() { println!("{} {:?}", 2+2, SomeStruct { val: 1, other: 32 }) }"#,
+        );
+        check_edit(
+            "loge",
+            r#"fn main() { "{2+2}".<|> }"#,
+            r#"fn main() { log::error!("{}", 2+2) }"#,
+        );
+        check_edit(
+            "logt",
+            r#"fn main() { "{2+2}".<|> }"#,
+            r#"fn main() { log::trace!("{}", 2+2) }"#,
+        );
+        check_edit(
+            "logd",
+            r#"fn main() { "{2+2}".<|> }"#,
+            r#"fn main() { log::debug!("{}", 2+2) }"#,
+        );
+        check_edit(
+            "logi",
+            r#"fn main() { "{2+2}".<|> }"#,
+            r#"fn main() { log::info!("{}", 2+2) }"#,
+        );
+        check_edit(
+            "logw",
+            r#"fn main() { "{2+2}".<|> }"#,
+            r#"fn main() { log::warn!("{}", 2+2) }"#,
+        );
+        check_edit(
+            "loge",
+            r#"fn main() { "{2+2}".<|> }"#,
+            r#"fn main() { log::error!("{}", 2+2) }"#,
+        );
+    }
+}
diff --git a/crates/completion/src/complete_postfix/format_like.rs b/crates/completion/src/complete_postfix/format_like.rs
new file mode 100644 (file)
index 0000000..205c384
--- /dev/null
@@ -0,0 +1,279 @@
+// Feature: Format String Completion.
+//
+// `"Result {result} is {2 + 2}"` is expanded to the `"Result {} is {}", result, 2 + 2`.
+//
+// The following postfix snippets are available:
+//
+// - `format` -> `format!(...)`
+// - `panic` -> `panic!(...)`
+// - `println` -> `println!(...)`
+// - `log`:
+//   + `logd` -> `log::debug!(...)`
+//   + `logt` -> `log::trace!(...)`
+//   + `logi` -> `log::info!(...)`
+//   + `logw` -> `log::warn!(...)`
+//   + `loge` -> `log::error!(...)`
+
+use crate::{
+    complete_postfix::postfix_snippet, completion_config::SnippetCap,
+    completion_context::CompletionContext, completion_item::Completions,
+};
+use syntax::ast::{self, AstToken};
+
+/// Mapping ("postfix completion item" => "macro to use")
+static KINDS: &[(&str, &str)] = &[
+    ("fmt", "format!"),
+    ("panic", "panic!"),
+    ("println", "println!"),
+    ("eprintln", "eprintln!"),
+    ("logd", "log::debug!"),
+    ("logt", "log::trace!"),
+    ("logi", "log::info!"),
+    ("logw", "log::warn!"),
+    ("loge", "log::error!"),
+];
+
+pub(super) fn add_format_like_completions(
+    acc: &mut Completions,
+    ctx: &CompletionContext,
+    dot_receiver: &ast::Expr,
+    cap: SnippetCap,
+    receiver_text: &ast::String,
+) {
+    let input = match string_literal_contents(receiver_text) {
+        // It's not a string literal, do not parse input.
+        Some(input) => input,
+        None => return,
+    };
+
+    let mut parser = FormatStrParser::new(input);
+
+    if parser.parse().is_ok() {
+        for (label, macro_name) in KINDS {
+            let snippet = parser.into_suggestion(macro_name);
+
+            postfix_snippet(ctx, cap, &dot_receiver, label, macro_name, &snippet).add_to(acc);
+        }
+    }
+}
+
+/// Checks whether provided item is a string literal.
+fn string_literal_contents(item: &ast::String) -> Option<String> {
+    let item = item.text();
+    if item.len() >= 2 && item.starts_with("\"") && item.ends_with("\"") {
+        return Some(item[1..item.len() - 1].to_owned());
+    }
+
+    None
+}
+
+/// Parser for a format-like string. It is more allowing in terms of string contents,
+/// as we expect variable placeholders to be filled with expressions.
+#[derive(Debug)]
+pub struct FormatStrParser {
+    input: String,
+    output: String,
+    extracted_expressions: Vec<String>,
+    state: State,
+    parsed: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+enum State {
+    NotExpr,
+    MaybeExpr,
+    Expr,
+    MaybeIncorrect,
+    FormatOpts,
+}
+
+impl FormatStrParser {
+    pub fn new(input: String) -> Self {
+        Self {
+            input: input.into(),
+            output: String::new(),
+            extracted_expressions: Vec::new(),
+            state: State::NotExpr,
+            parsed: false,
+        }
+    }
+
+    pub fn parse(&mut self) -> Result<(), ()> {
+        let mut current_expr = String::new();
+
+        let mut placeholder_id = 1;
+
+        // Count of open braces inside of an expression.
+        // We assume that user knows what they're doing, thus we treat it like a correct pattern, e.g.
+        // "{MyStruct { val_a: 0, val_b: 1 }}".
+        let mut inexpr_open_count = 0;
+
+        for chr in self.input.chars() {
+            match (self.state, chr) {
+                (State::NotExpr, '{') => {
+                    self.output.push(chr);
+                    self.state = State::MaybeExpr;
+                }
+                (State::NotExpr, '}') => {
+                    self.output.push(chr);
+                    self.state = State::MaybeIncorrect;
+                }
+                (State::NotExpr, _) => {
+                    self.output.push(chr);
+                }
+                (State::MaybeIncorrect, '}') => {
+                    // It's okay, we met "}}".
+                    self.output.push(chr);
+                    self.state = State::NotExpr;
+                }
+                (State::MaybeIncorrect, _) => {
+                    // Error in the string.
+                    return Err(());
+                }
+                (State::MaybeExpr, '{') => {
+                    self.output.push(chr);
+                    self.state = State::NotExpr;
+                }
+                (State::MaybeExpr, '}') => {
+                    // This is an empty sequence '{}'. Replace it with placeholder.
+                    self.output.push(chr);
+                    self.extracted_expressions.push(format!("${}", placeholder_id));
+                    placeholder_id += 1;
+                    self.state = State::NotExpr;
+                }
+                (State::MaybeExpr, _) => {
+                    current_expr.push(chr);
+                    self.state = State::Expr;
+                }
+                (State::Expr, '}') => {
+                    if inexpr_open_count == 0 {
+                        self.output.push(chr);
+                        self.extracted_expressions.push(current_expr.trim().into());
+                        current_expr = String::new();
+                        self.state = State::NotExpr;
+                    } else {
+                        // We're closing one brace met before inside of the expression.
+                        current_expr.push(chr);
+                        inexpr_open_count -= 1;
+                    }
+                }
+                (State::Expr, ':') => {
+                    if inexpr_open_count == 0 {
+                        // We're outside of braces, thus assume that it's a specifier, like "{Some(value):?}"
+                        self.output.push(chr);
+                        self.extracted_expressions.push(current_expr.trim().into());
+                        current_expr = String::new();
+                        self.state = State::FormatOpts;
+                    } else {
+                        // We're inside of braced expression, assume that it's a struct field name/value delimeter.
+                        current_expr.push(chr);
+                    }
+                }
+                (State::Expr, '{') => {
+                    current_expr.push(chr);
+                    inexpr_open_count += 1;
+                }
+                (State::Expr, _) => {
+                    current_expr.push(chr);
+                }
+                (State::FormatOpts, '}') => {
+                    self.output.push(chr);
+                    self.state = State::NotExpr;
+                }
+                (State::FormatOpts, _) => {
+                    self.output.push(chr);
+                }
+            }
+        }
+
+        if self.state != State::NotExpr {
+            return Err(());
+        }
+
+        self.parsed = true;
+        Ok(())
+    }
+
+    pub fn into_suggestion(&self, macro_name: &str) -> String {
+        assert!(self.parsed, "Attempt to get a suggestion from not parsed expression");
+
+        let expressions_as_string = self.extracted_expressions.join(", ");
+        format!(r#"{}("{}", {})"#, macro_name, self.output, expressions_as_string)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use expect_test::{expect, Expect};
+
+    fn check(input: &str, expect: &Expect) {
+        let mut parser = FormatStrParser::new((*input).to_owned());
+        let outcome_repr = if parser.parse().is_ok() {
+            // Parsing should be OK, expected repr is "string; expr_1, expr_2".
+            if parser.extracted_expressions.is_empty() {
+                parser.output
+            } else {
+                format!("{}; {}", parser.output, parser.extracted_expressions.join(", "))
+            }
+        } else {
+            // Parsing should fail, expected repr is "-".
+            "-".to_owned()
+        };
+
+        expect.assert_eq(&outcome_repr);
+    }
+
+    #[test]
+    fn format_str_parser() {
+        let test_vector = &[
+            ("no expressions", expect![["no expressions"]]),
+            ("{expr} is {2 + 2}", expect![["{} is {}; expr, 2 + 2"]]),
+            ("{expr:?}", expect![["{:?}; expr"]]),
+            ("{malformed", expect![["-"]]),
+            ("malformed}", expect![["-"]]),
+            ("{{correct", expect![["{{correct"]]),
+            ("correct}}", expect![["correct}}"]]),
+            ("{correct}}}", expect![["{}}}; correct"]]),
+            ("{correct}}}}}", expect![["{}}}}}; correct"]]),
+            ("{incorrect}}", expect![["-"]]),
+            ("placeholders {} {}", expect![["placeholders {} {}; $1, $2"]]),
+            ("mixed {} {2 + 2} {}", expect![["mixed {} {} {}; $1, 2 + 2, $2"]]),
+            (
+                "{SomeStruct { val_a: 0, val_b: 1 }}",
+                expect![["{}; SomeStruct { val_a: 0, val_b: 1 }"]],
+            ),
+            ("{expr:?} is {2.32f64:.5}", expect![["{:?} is {:.5}; expr, 2.32f64"]]),
+            (
+                "{SomeStruct { val_a: 0, val_b: 1 }:?}",
+                expect![["{:?}; SomeStruct { val_a: 0, val_b: 1 }"]],
+            ),
+            ("{     2 + 2        }", expect![["{}; 2 + 2"]]),
+        ];
+
+        for (input, output) in test_vector {
+            check(input, output)
+        }
+    }
+
+    #[test]
+    fn test_into_suggestion() {
+        let test_vector = &[
+            ("println!", "{}", r#"println!("{}", $1)"#),
+            ("eprintln!", "{}", r#"eprintln!("{}", $1)"#),
+            (
+                "log::info!",
+                "{} {expr} {} {2 + 2}",
+                r#"log::info!("{} {} {} {}", $1, expr, $2, 2 + 2)"#,
+            ),
+            ("format!", "{expr:?}", r#"format!("{:?}", expr)"#),
+        ];
+
+        for (kind, input, output) in test_vector {
+            let mut parser = FormatStrParser::new((*input).to_owned());
+            parser.parse().expect("Parsing must succeed");
+
+            assert_eq!(&parser.into_suggestion(*kind), output);
+        }
+    }
+}
diff --git a/crates/completion/src/complete_qualified_path.rs b/crates/completion/src/complete_qualified_path.rs
new file mode 100644 (file)
index 0000000..80b271f
--- /dev/null
@@ -0,0 +1,755 @@
+//! Completion of paths, i.e. `some::prefix::<|>`.
+
+use hir::{Adt, HasVisibility, PathResolution, ScopeDef};
+use rustc_hash::FxHashSet;
+use syntax::AstNode;
+use test_utils::mark;
+
+use crate::{CompletionContext, Completions};
+
+pub(super) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionContext) {
+    let path = match &ctx.path_qual {
+        Some(path) => path.clone(),
+        None => return,
+    };
+
+    if ctx.attribute_under_caret.is_some() || ctx.mod_declaration_under_caret.is_some() {
+        return;
+    }
+
+    let context_module = ctx.scope.module();
+
+    let resolution = match ctx.sema.resolve_path(&path) {
+        Some(res) => res,
+        None => return,
+    };
+
+    // Add associated types on type parameters and `Self`.
+    resolution.assoc_type_shorthand_candidates(ctx.db, |alias| {
+        acc.add_type_alias(ctx, alias);
+        None::<()>
+    });
+
+    match resolution {
+        PathResolution::Def(hir::ModuleDef::Module(module)) => {
+            let module_scope = module.scope(ctx.db, context_module);
+            for (name, def) in module_scope {
+                if ctx.use_item_syntax.is_some() {
+                    if let ScopeDef::Unknown = def {
+                        if let Some(name_ref) = ctx.name_ref_syntax.as_ref() {
+                            if name_ref.syntax().text() == name.to_string().as_str() {
+                                // for `use self::foo<|>`, don't suggest `foo` as a completion
+                                mark::hit!(dont_complete_current_use);
+                                continue;
+                            }
+                        }
+                    }
+                }
+
+                acc.add_resolution(ctx, name.to_string(), &def);
+            }
+        }
+        PathResolution::Def(def @ hir::ModuleDef::Adt(_))
+        | PathResolution::Def(def @ hir::ModuleDef::TypeAlias(_)) => {
+            if let hir::ModuleDef::Adt(Adt::Enum(e)) = def {
+                for variant in e.variants(ctx.db) {
+                    acc.add_enum_variant(ctx, variant, None);
+                }
+            }
+            let ty = match def {
+                hir::ModuleDef::Adt(adt) => adt.ty(ctx.db),
+                hir::ModuleDef::TypeAlias(a) => a.ty(ctx.db),
+                _ => unreachable!(),
+            };
+
+            // XXX: For parity with Rust bug #22519, this does not complete Ty::AssocType.
+            // (where AssocType is defined on a trait, not an inherent impl)
+
+            let krate = ctx.krate;
+            if let Some(krate) = krate {
+                let traits_in_scope = ctx.scope.traits_in_scope();
+                ty.iterate_path_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, item| {
+                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
+                        return None;
+                    }
+                    match item {
+                        hir::AssocItem::Function(func) => {
+                            acc.add_function(ctx, func, None);
+                        }
+                        hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
+                        hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
+                    }
+                    None::<()>
+                });
+
+                // Iterate assoc types separately
+                ty.iterate_assoc_items(ctx.db, krate, |item| {
+                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
+                        return None;
+                    }
+                    match item {
+                        hir::AssocItem::Function(_) | hir::AssocItem::Const(_) => {}
+                        hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
+                    }
+                    None::<()>
+                });
+            }
+        }
+        PathResolution::Def(hir::ModuleDef::Trait(t)) => {
+            // Handles `Trait::assoc` as well as `<Ty as Trait>::assoc`.
+            for item in t.items(ctx.db) {
+                if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
+                    continue;
+                }
+                match item {
+                    hir::AssocItem::Function(func) => {
+                        acc.add_function(ctx, func, None);
+                    }
+                    hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
+                    hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
+                }
+            }
+        }
+        PathResolution::TypeParam(_) | PathResolution::SelfType(_) => {
+            if let Some(krate) = ctx.krate {
+                let ty = match resolution {
+                    PathResolution::TypeParam(param) => param.ty(ctx.db),
+                    PathResolution::SelfType(impl_def) => impl_def.target_ty(ctx.db),
+                    _ => return,
+                };
+
+                let traits_in_scope = ctx.scope.traits_in_scope();
+                let mut seen = FxHashSet::default();
+                ty.iterate_path_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, item| {
+                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
+                        return None;
+                    }
+
+                    // We might iterate candidates of a trait multiple times here, so deduplicate
+                    // them.
+                    if seen.insert(item) {
+                        match item {
+                            hir::AssocItem::Function(func) => {
+                                acc.add_function(ctx, func, None);
+                            }
+                            hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
+                            hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
+                        }
+                    }
+                    None::<()>
+                });
+            }
+        }
+        _ => {}
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+    use test_utils::mark;
+
+    use crate::{
+        test_utils::{check_edit, completion_list},
+        CompletionKind,
+    };
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Reference);
+        expect.assert_eq(&actual);
+    }
+
+    fn check_builtin(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::BuiltinType);
+        expect.assert_eq(&actual);
+    }
+
+    #[test]
+    fn dont_complete_current_use() {
+        mark::check!(dont_complete_current_use);
+        check(r#"use self::foo<|>;"#, expect![[""]]);
+    }
+
+    #[test]
+    fn dont_complete_current_use_in_braces_with_glob() {
+        check(
+            r#"
+mod foo { pub struct S; }
+use self::{foo::*, bar<|>};
+"#,
+            expect![[r#"
+                st S
+                md foo
+            "#]],
+        );
+    }
+
+    #[test]
+    fn dont_complete_primitive_in_use() {
+        check_builtin(r#"use self::<|>;"#, expect![[""]]);
+    }
+
+    #[test]
+    fn dont_complete_primitive_in_module_scope() {
+        check_builtin(r#"fn foo() { self::<|> }"#, expect![[""]]);
+    }
+
+    #[test]
+    fn completes_primitives() {
+        check_builtin(
+            r#"fn main() { let _: <|> = 92; }"#,
+            expect![[r#"
+                bt bool
+                bt char
+                bt f32
+                bt f64
+                bt i128
+                bt i16
+                bt i32
+                bt i64
+                bt i8
+                bt isize
+                bt str
+                bt u128
+                bt u16
+                bt u32
+                bt u64
+                bt u8
+                bt usize
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_mod_with_same_name_as_function() {
+        check(
+            r#"
+use self::my::<|>;
+
+mod my { pub struct Bar; }
+fn my() {}
+"#,
+            expect![[r#"
+                st Bar
+            "#]],
+        );
+    }
+
+    #[test]
+    fn filters_visibility() {
+        check(
+            r#"
+use self::my::<|>;
+
+mod my {
+    struct Bar;
+    pub struct Foo;
+    pub use Bar as PublicBar;
+}
+"#,
+            expect![[r#"
+                st Foo
+                st PublicBar
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_use_item_starting_with_self() {
+        check(
+            r#"
+use self::m::<|>;
+
+mod m { pub struct Bar; }
+"#,
+            expect![[r#"
+                st Bar
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_use_item_starting_with_crate() {
+        check(
+            r#"
+//- /lib.rs
+mod foo;
+struct Spam;
+//- /foo.rs
+use crate::Sp<|>
+"#,
+            expect![[r#"
+                st Spam
+                md foo
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_nested_use_tree() {
+        check(
+            r#"
+//- /lib.rs
+mod foo;
+struct Spam;
+//- /foo.rs
+use crate::{Sp<|>};
+"#,
+            expect![[r#"
+                st Spam
+                md foo
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_deeply_nested_use_tree() {
+        check(
+            r#"
+//- /lib.rs
+mod foo;
+pub mod bar {
+    pub mod baz {
+        pub struct Spam;
+    }
+}
+//- /foo.rs
+use crate::{bar::{baz::Sp<|>}};
+"#,
+            expect![[r#"
+                st Spam
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_enum_variant() {
+        check(
+            r#"
+enum E { Foo, Bar(i32) }
+fn foo() { let _ = E::<|> }
+"#,
+            expect![[r#"
+                ev Bar(…) (i32)
+                ev Foo    ()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_struct_associated_items() {
+        check(
+            r#"
+//- /lib.rs
+struct S;
+
+impl S {
+    fn a() {}
+    fn b(&self) {}
+    const C: i32 = 42;
+    type T = i32;
+}
+
+fn foo() { let _ = S::<|> }
+"#,
+            expect![[r#"
+                ct C   const C: i32 = 42;
+                ta T   type T = i32;
+                fn a() fn a()
+                me b() fn b(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn associated_item_visibility() {
+        check(
+            r#"
+struct S;
+
+mod m {
+    impl super::S {
+        pub(super) fn public_method() { }
+        fn private_method() { }
+        pub(super) type PublicType = u32;
+        type PrivateType = u32;
+        pub(super) const PUBLIC_CONST: u32 = 1;
+        const PRIVATE_CONST: u32 = 1;
+    }
+}
+
+fn foo() { let _ = S::<|> }
+"#,
+            expect![[r#"
+                ct PUBLIC_CONST    pub(super) const PUBLIC_CONST: u32 = 1;
+                ta PublicType      pub(super) type PublicType = u32;
+                fn public_method() pub(super) fn public_method()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_enum_associated_method() {
+        check(
+            r#"
+enum E {};
+impl E { fn m() { } }
+
+fn foo() { let _ = E::<|> }
+        "#,
+            expect![[r#"
+                fn m() fn m()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_union_associated_method() {
+        check(
+            r#"
+union U {};
+impl U { fn m() { } }
+
+fn foo() { let _ = U::<|> }
+"#,
+            expect![[r#"
+                fn m() fn m()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_use_paths_across_crates() {
+        check(
+            r#"
+//- /main.rs crate:main deps:foo
+use foo::<|>;
+
+//- /foo/lib.rs crate:foo
+pub mod bar { pub struct S; }
+"#,
+            expect![[r#"
+                md bar
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_trait_associated_method_1() {
+        check(
+            r#"
+trait Trait { fn m(); }
+
+fn foo() { let _ = Trait::<|> }
+"#,
+            expect![[r#"
+                fn m() fn m()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_trait_associated_method_2() {
+        check(
+            r#"
+trait Trait { fn m(); }
+
+struct S;
+impl Trait for S {}
+
+fn foo() { let _ = S::<|> }
+"#,
+            expect![[r#"
+                fn m() fn m()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_trait_associated_method_3() {
+        check(
+            r#"
+trait Trait { fn m(); }
+
+struct S;
+impl Trait for S {}
+
+fn foo() { let _ = <S as Trait>::<|> }
+"#,
+            expect![[r#"
+                fn m() fn m()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_ty_param_assoc_ty() {
+        check(
+            r#"
+trait Super {
+    type Ty;
+    const CONST: u8;
+    fn func() {}
+    fn method(&self) {}
+}
+
+trait Sub: Super {
+    type SubTy;
+    const C2: ();
+    fn subfunc() {}
+    fn submethod(&self) {}
+}
+
+fn foo<T: Sub>() { T::<|> }
+"#,
+            expect![[r#"
+                ct C2          const C2: ();
+                ct CONST       const CONST: u8;
+                ta SubTy       type SubTy;
+                ta Ty          type Ty;
+                fn func()      fn func()
+                me method()    fn method(&self)
+                fn subfunc()   fn subfunc()
+                me submethod() fn submethod(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_self_param_assoc_ty() {
+        check(
+            r#"
+trait Super {
+    type Ty;
+    const CONST: u8 = 0;
+    fn func() {}
+    fn method(&self) {}
+}
+
+trait Sub: Super {
+    type SubTy;
+    const C2: () = ();
+    fn subfunc() {}
+    fn submethod(&self) {}
+}
+
+struct Wrap<T>(T);
+impl<T> Super for Wrap<T> {}
+impl<T> Sub for Wrap<T> {
+    fn subfunc() {
+        // Should be able to assume `Self: Sub + Super`
+        Self::<|>
+    }
+}
+"#,
+            expect![[r#"
+                ct C2          const C2: () = ();
+                ct CONST       const CONST: u8 = 0;
+                ta SubTy       type SubTy;
+                ta Ty          type Ty;
+                fn func()      fn func()
+                me method()    fn method(&self)
+                fn subfunc()   fn subfunc()
+                me submethod() fn submethod(&self)
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_type_alias() {
+        check(
+            r#"
+struct S;
+impl S { fn foo() {} }
+type T = S;
+impl T { fn bar() {} }
+
+fn main() { T::<|>; }
+"#,
+            expect![[r#"
+                fn bar() fn bar()
+                fn foo() fn foo()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_qualified_macros() {
+        check(
+            r#"
+#[macro_export]
+macro_rules! foo { () => {} }
+
+fn main() { let _ = crate::<|> }
+        "#,
+            expect![[r##"
+                ma foo!(…) #[macro_export]
+                macro_rules! foo
+                fn main()  fn main()
+            "##]],
+        );
+    }
+
+    #[test]
+    fn test_super_super_completion() {
+        check(
+            r#"
+mod a {
+    const A: usize = 0;
+    mod b {
+        const B: usize = 0;
+        mod c { use super::super::<|> }
+    }
+}
+"#,
+            expect![[r#"
+                ct A
+                md b
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_reexported_items_under_correct_name() {
+        check(
+            r#"
+fn foo() { self::m::<|> }
+
+mod m {
+    pub use super::p::wrong_fn as right_fn;
+    pub use super::p::WRONG_CONST as RIGHT_CONST;
+    pub use super::p::WrongType as RightType;
+}
+mod p {
+    fn wrong_fn() {}
+    const WRONG_CONST: u32 = 1;
+    struct WrongType {};
+}
+"#,
+            expect![[r#"
+                ct RIGHT_CONST
+                st RightType
+                fn right_fn()  fn wrong_fn()
+            "#]],
+        );
+
+        check_edit(
+            "RightType",
+            r#"
+fn foo() { self::m::<|> }
+
+mod m {
+    pub use super::p::wrong_fn as right_fn;
+    pub use super::p::WRONG_CONST as RIGHT_CONST;
+    pub use super::p::WrongType as RightType;
+}
+mod p {
+    fn wrong_fn() {}
+    const WRONG_CONST: u32 = 1;
+    struct WrongType {};
+}
+"#,
+            r#"
+fn foo() { self::m::RightType }
+
+mod m {
+    pub use super::p::wrong_fn as right_fn;
+    pub use super::p::WRONG_CONST as RIGHT_CONST;
+    pub use super::p::WrongType as RightType;
+}
+mod p {
+    fn wrong_fn() {}
+    const WRONG_CONST: u32 = 1;
+    struct WrongType {};
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn completes_in_simple_macro_call() {
+        check(
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+fn main() { m!(self::f<|>); }
+fn foo() {}
+"#,
+            expect![[r#"
+                fn foo()  fn foo()
+                fn main() fn main()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn function_mod_share_name() {
+        check(
+            r#"
+fn foo() { self::m::<|> }
+
+mod m {
+    pub mod z {}
+    pub fn z() {}
+}
+"#,
+            expect![[r#"
+                md z
+                fn z() pub fn z()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_hashmap_new() {
+        check(
+            r#"
+struct RandomState;
+struct HashMap<K, V, S = RandomState> {}
+
+impl<K, V> HashMap<K, V, RandomState> {
+    pub fn new() -> HashMap<K, V, RandomState> { }
+}
+fn foo() {
+    HashMap::<|>
+}
+"#,
+            expect![[r#"
+                fn new() pub fn new() -> HashMap<K, V, RandomState>
+            "#]],
+        );
+    }
+
+    #[test]
+    fn dont_complete_attr() {
+        check(
+            r#"
+mod foo { pub struct Foo; }
+#[foo::<|>]
+fn f() {}
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn completes_function() {
+        check(
+            r#"
+fn foo(
+    a: i32,
+    b: i32
+) {
+
+}
+
+fn main() {
+    fo<|>
+}
+"#,
+            expect![[r#"
+                fn foo(…) fn foo(a: i32, b: i32)
+                fn main() fn main()
+            "#]],
+        );
+    }
+}
diff --git a/crates/completion/src/complete_record.rs b/crates/completion/src/complete_record.rs
new file mode 100644 (file)
index 0000000..129ddc0
--- /dev/null
@@ -0,0 +1,226 @@
+//! Complete fields in record literals and patterns.
+use crate::{CompletionContext, Completions};
+
+pub(super) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
+    let missing_fields = match (ctx.record_pat_syntax.as_ref(), ctx.record_lit_syntax.as_ref()) {
+        (None, None) => return None,
+        (Some(_), Some(_)) => unreachable!("A record cannot be both a literal and a pattern"),
+        (Some(record_pat), _) => ctx.sema.record_pattern_missing_fields(record_pat),
+        (_, Some(record_lit)) => ctx.sema.record_literal_missing_fields(record_lit),
+    };
+
+    for (field, ty) in missing_fields {
+        acc.add_field(ctx, field, &ty)
+    }
+
+    Some(())
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{test_utils::completion_list, CompletionKind};
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Reference);
+        expect.assert_eq(&actual);
+    }
+
+    #[test]
+    fn test_record_pattern_field() {
+        check(
+            r#"
+struct S { foo: u32 }
+
+fn process(f: S) {
+    match f {
+        S { f<|>: 92 } => (),
+    }
+}
+"#,
+            expect![[r#"
+                fd foo u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_record_pattern_enum_variant() {
+        check(
+            r#"
+enum E { S { foo: u32, bar: () } }
+
+fn process(e: E) {
+    match e {
+        E::S { <|> } => (),
+    }
+}
+"#,
+            expect![[r#"
+                fd bar ()
+                fd foo u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_record_pattern_field_in_simple_macro() {
+        check(
+            r"
+macro_rules! m { ($e:expr) => { $e } }
+struct S { foo: u32 }
+
+fn process(f: S) {
+    m!(match f {
+        S { f<|>: 92 } => (),
+    })
+}
+",
+            expect![[r#"
+                fd foo u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn only_missing_fields_are_completed_in_destruct_pats() {
+        check(
+            r#"
+struct S {
+    foo1: u32, foo2: u32,
+    bar: u32, baz: u32,
+}
+
+fn main() {
+    let s = S {
+        foo1: 1, foo2: 2,
+        bar: 3, baz: 4,
+    };
+    if let S { foo1, foo2: a, <|> } = s {}
+}
+"#,
+            expect![[r#"
+                fd bar u32
+                fd baz u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_record_literal_field() {
+        check(
+            r#"
+struct A { the_field: u32 }
+fn foo() {
+   A { the<|> }
+}
+"#,
+            expect![[r#"
+                fd the_field u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_record_literal_enum_variant() {
+        check(
+            r#"
+enum E { A { a: u32 } }
+fn foo() {
+    let _ = E::A { <|> }
+}
+"#,
+            expect![[r#"
+                fd a u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_record_literal_two_structs() {
+        check(
+            r#"
+struct A { a: u32 }
+struct B { b: u32 }
+
+fn foo() {
+   let _: A = B { <|> }
+}
+"#,
+            expect![[r#"
+                fd b u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_record_literal_generic_struct() {
+        check(
+            r#"
+struct A<T> { a: T }
+
+fn foo() {
+   let _: A<u32> = A { <|> }
+}
+"#,
+            expect![[r#"
+                fd a u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn test_record_literal_field_in_simple_macro() {
+        check(
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+struct A { the_field: u32 }
+fn foo() {
+   m!(A { the<|> })
+}
+"#,
+            expect![[r#"
+                fd the_field u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn only_missing_fields_are_completed() {
+        check(
+            r#"
+struct S {
+    foo1: u32, foo2: u32,
+    bar: u32, baz: u32,
+}
+
+fn main() {
+    let foo1 = 1;
+    let s = S { foo1, foo2: 5, <|> }
+}
+"#,
+            expect![[r#"
+                fd bar u32
+                fd baz u32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_functional_update() {
+        check(
+            r#"
+struct S { foo1: u32, foo2: u32 }
+
+fn main() {
+    let foo1 = 1;
+    let s = S { foo1, <|> .. loop {} }
+}
+"#,
+            expect![[r#"
+                fd foo2 u32
+            "#]],
+        );
+    }
+}
diff --git a/crates/completion/src/complete_snippet.rs b/crates/completion/src/complete_snippet.rs
new file mode 100644 (file)
index 0000000..0609672
--- /dev/null
@@ -0,0 +1,114 @@
+//! This file provides snippet completions, like `pd` => `eprintln!(...)`.
+
+use crate::{
+    completion_config::SnippetCap, completion_item::Builder, CompletionContext, CompletionItem,
+    CompletionItemKind, CompletionKind, Completions,
+};
+
+fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder {
+    CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), label)
+        .insert_snippet(cap, snippet)
+        .kind(CompletionItemKind::Snippet)
+}
+
+pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) {
+    if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) {
+        return;
+    }
+    let cap = match ctx.config.snippet_cap {
+        Some(it) => it,
+        None => return,
+    };
+
+    snippet(ctx, cap, "pd", "eprintln!(\"$0 = {:?}\", $0);").add_to(acc);
+    snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc);
+}
+
+pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) {
+    if !ctx.is_new_item {
+        return;
+    }
+    let cap = match ctx.config.snippet_cap {
+        Some(it) => it,
+        None => return,
+    };
+
+    snippet(
+        ctx,
+        cap,
+        "tmod (Test module)",
+        "\
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn ${1:test_name}() {
+        $0
+    }
+}",
+    )
+    .lookup_by("tmod")
+    .add_to(acc);
+
+    snippet(
+        ctx,
+        cap,
+        "tfn (Test function)",
+        "\
+#[test]
+fn ${1:feature}() {
+    $0
+}",
+    )
+    .lookup_by("tfn")
+    .add_to(acc);
+
+    snippet(ctx, cap, "macro_rules", "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}").add_to(acc);
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{test_utils::completion_list, CompletionKind};
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Snippet);
+        expect.assert_eq(&actual)
+    }
+
+    #[test]
+    fn completes_snippets_in_expressions() {
+        check(
+            r#"fn foo(x: i32) { <|> }"#,
+            expect![[r#"
+                sn pd
+                sn ppd
+            "#]],
+        );
+    }
+
+    #[test]
+    fn should_not_complete_snippets_in_path() {
+        check(r#"fn foo(x: i32) { ::foo<|> }"#, expect![[""]]);
+        check(r#"fn foo(x: i32) { ::<|> }"#, expect![[""]]);
+    }
+
+    #[test]
+    fn completes_snippets_in_items() {
+        check(
+            r#"
+#[cfg(test)]
+mod tests {
+    <|>
+}
+"#,
+            expect![[r#"
+                sn macro_rules
+                sn tfn (Test function)
+                sn tmod (Test module)
+            "#]],
+        )
+    }
+}
diff --git a/crates/completion/src/complete_trait_impl.rs b/crates/completion/src/complete_trait_impl.rs
new file mode 100644 (file)
index 0000000..c06af99
--- /dev/null
@@ -0,0 +1,736 @@
+//! Completion for associated items in a trait implementation.
+//!
+//! This module adds the completion items related to implementing associated
+//! items within a `impl Trait for Struct` block. The current context node
+//! must be within either a `FN`, `TYPE_ALIAS`, or `CONST` node
+//! and an direct child of an `IMPL`.
+//!
+//! # Examples
+//!
+//! Considering the following trait `impl`:
+//!
+//! ```ignore
+//! trait SomeTrait {
+//!     fn foo();
+//! }
+//!
+//! impl SomeTrait for () {
+//!     fn f<|>
+//! }
+//! ```
+//!
+//! may result in the completion of the following method:
+//!
+//! ```ignore
+//! # trait SomeTrait {
+//! #    fn foo();
+//! # }
+//!
+//! impl SomeTrait for () {
+//!     fn foo() {}<|>
+//! }
+//! ```
+
+use assists::utils::get_missing_assoc_items;
+use hir::{self, HasAttrs, HasSource};
+use syntax::{
+    ast::{self, edit, Impl},
+    display::function_declaration,
+    AstNode, SyntaxKind, SyntaxNode, TextRange, T,
+};
+use text_edit::TextEdit;
+
+use crate::{
+    CompletionContext,
+    CompletionItem,
+    CompletionItemKind,
+    CompletionKind,
+    Completions,
+    // display::function_declaration,
+};
+
+#[derive(Debug, PartialEq, Eq)]
+enum ImplCompletionKind {
+    All,
+    Fn,
+    TypeAlias,
+    Const,
+}
+
+pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext) {
+    if let Some((kind, trigger, impl_def)) = completion_match(ctx) {
+        get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| match item {
+            hir::AssocItem::Function(fn_item)
+                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
+            {
+                add_function_impl(&trigger, acc, ctx, fn_item)
+            }
+            hir::AssocItem::TypeAlias(type_item)
+                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
+            {
+                add_type_alias_impl(&trigger, acc, ctx, type_item)
+            }
+            hir::AssocItem::Const(const_item)
+                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
+            {
+                add_const_impl(&trigger, acc, ctx, const_item)
+            }
+            _ => {}
+        });
+    }
+}
+
+fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> {
+    let mut token = ctx.token.clone();
+    // For keywork without name like `impl .. { fn <|> }`, the current position is inside
+    // the whitespace token, which is outside `FN` syntax node.
+    // We need to follow the previous token in this case.
+    if token.kind() == SyntaxKind::WHITESPACE {
+        token = token.prev_token()?;
+    }
+
+    let impl_item_offset = match token.kind() {
+        // `impl .. { const <|> }`
+        // ERROR      0
+        //   CONST_KW <- *
+        SyntaxKind::CONST_KW => 0,
+        // `impl .. { fn/type <|> }`
+        // FN/TYPE_ALIAS  0
+        //   FN_KW        <- *
+        SyntaxKind::FN_KW | SyntaxKind::TYPE_KW => 0,
+        // `impl .. { fn/type/const foo<|> }`
+        // FN/TYPE_ALIAS/CONST  1
+        //  NAME                0
+        //    IDENT             <- *
+        SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1,
+        // `impl .. { foo<|> }`
+        // MACRO_CALL       3
+        //  PATH            2
+        //    PATH_SEGMENT  1
+        //      NAME_REF    0
+        //        IDENT     <- *
+        SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME_REF => 3,
+        _ => return None,
+    };
+
+    let impl_item = token.ancestors().nth(impl_item_offset)?;
+    // Must directly belong to an impl block.
+    // IMPL
+    //   ASSOC_ITEM_LIST
+    //     <item>
+    let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
+    let kind = match impl_item.kind() {
+        // `impl ... { const <|> fn/type/const }`
+        _ if token.kind() == SyntaxKind::CONST_KW => ImplCompletionKind::Const,
+        SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
+        SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
+        SyntaxKind::FN => ImplCompletionKind::Fn,
+        SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
+        _ => return None,
+    };
+    Some((kind, impl_item, impl_def))
+}
+
+fn add_function_impl(
+    fn_def_node: &SyntaxNode,
+    acc: &mut Completions,
+    ctx: &CompletionContext,
+    func: hir::Function,
+) {
+    let fn_name = func.name(ctx.db).to_string();
+
+    let label = if func.params(ctx.db).is_empty() {
+        format!("fn {}()", fn_name)
+    } else {
+        format!("fn {}(..)", fn_name)
+    };
+
+    let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label)
+        .lookup_by(fn_name)
+        .set_documentation(func.docs(ctx.db));
+
+    let completion_kind = if func.self_param(ctx.db).is_some() {
+        CompletionItemKind::Method
+    } else {
+        CompletionItemKind::Function
+    };
+    let range = TextRange::new(fn_def_node.text_range().start(), ctx.source_range().end());
+
+    let function_decl = function_declaration(&func.source(ctx.db).value);
+    match ctx.config.snippet_cap {
+        Some(cap) => {
+            let snippet = format!("{} {{\n    $0\n}}", function_decl);
+            builder.snippet_edit(cap, TextEdit::replace(range, snippet))
+        }
+        None => {
+            let header = format!("{} {{", function_decl);
+            builder.text_edit(TextEdit::replace(range, header))
+        }
+    }
+    .kind(completion_kind)
+    .add_to(acc);
+}
+
+fn add_type_alias_impl(
+    type_def_node: &SyntaxNode,
+    acc: &mut Completions,
+    ctx: &CompletionContext,
+    type_alias: hir::TypeAlias,
+) {
+    let alias_name = type_alias.name(ctx.db).to_string();
+
+    let snippet = format!("type {} = ", alias_name);
+
+    let range = TextRange::new(type_def_node.text_range().start(), ctx.source_range().end());
+
+    CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
+        .text_edit(TextEdit::replace(range, snippet))
+        .lookup_by(alias_name)
+        .kind(CompletionItemKind::TypeAlias)
+        .set_documentation(type_alias.docs(ctx.db))
+        .add_to(acc);
+}
+
+fn add_const_impl(
+    const_def_node: &SyntaxNode,
+    acc: &mut Completions,
+    ctx: &CompletionContext,
+    const_: hir::Const,
+) {
+    let const_name = const_.name(ctx.db).map(|n| n.to_string());
+
+    if let Some(const_name) = const_name {
+        let snippet = make_const_compl_syntax(&const_.source(ctx.db).value);
+
+        let range = TextRange::new(const_def_node.text_range().start(), ctx.source_range().end());
+
+        CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
+            .text_edit(TextEdit::replace(range, snippet))
+            .lookup_by(const_name)
+            .kind(CompletionItemKind::Const)
+            .set_documentation(const_.docs(ctx.db))
+            .add_to(acc);
+    }
+}
+
+fn make_const_compl_syntax(const_: &ast::Const) -> String {
+    let const_ = edit::remove_attrs_and_docs(const_);
+
+    let const_start = const_.syntax().text_range().start();
+    let const_end = const_.syntax().text_range().end();
+
+    let start =
+        const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
+
+    let end = const_
+        .syntax()
+        .children_with_tokens()
+        .find(|s| s.kind() == T![;] || s.kind() == T![=])
+        .map_or(const_end, |f| f.text_range().start());
+
+    let len = end - start;
+    let range = TextRange::new(0.into(), len);
+
+    let syntax = const_.syntax().text().slice(range).to_string();
+
+    format!("{} = ", syntax.trim_end())
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+
+    use crate::{
+        test_utils::{check_edit, completion_list},
+        CompletionKind,
+    };
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Magic);
+        expect.assert_eq(&actual)
+    }
+
+    #[test]
+    fn name_ref_function_type_const() {
+        check(
+            r#"
+trait Test {
+    type TestType;
+    const TEST_CONST: u16;
+    fn test();
+}
+struct T;
+
+impl Test for T {
+    t<|>
+}
+"#,
+            expect![["
+ct const TEST_CONST: u16 = \n\
+fn fn test()
+ta type TestType = \n\
+            "]],
+        );
+    }
+
+    #[test]
+    fn no_completion_inside_fn() {
+        check(
+            r"
+trait Test { fn test(); fn test2(); }
+struct T;
+
+impl Test for T {
+    fn test() {
+        t<|>
+    }
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { fn test(); fn test2(); }
+struct T;
+
+impl Test for T {
+    fn test() {
+        fn t<|>
+    }
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { fn test(); fn test2(); }
+struct T;
+
+impl Test for T {
+    fn test() {
+        fn <|>
+    }
+}
+",
+            expect![[""]],
+        );
+
+        // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
+        check(
+            r"
+trait Test { fn test(); fn test2(); }
+struct T;
+
+impl Test for T {
+    fn test() {
+        foo.<|>
+    }
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { fn test(_: i32); fn test2(); }
+struct T;
+
+impl Test for T {
+    fn test(t<|>)
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { fn test(_: fn()); fn test2(); }
+struct T;
+
+impl Test for T {
+    fn test(f: fn <|>)
+}
+",
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn no_completion_inside_const() {
+        check(
+            r"
+trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
+struct T;
+
+impl Test for T {
+    const TEST: fn <|>
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
+struct T;
+
+impl Test for T {
+    const TEST: T<|>
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
+struct T;
+
+impl Test for T {
+    const TEST: u32 = f<|>
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
+struct T;
+
+impl Test for T {
+    const TEST: u32 = {
+        t<|>
+    };
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
+struct T;
+
+impl Test for T {
+    const TEST: u32 = {
+        fn <|>
+    };
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
+struct T;
+
+impl Test for T {
+    const TEST: u32 = {
+        fn t<|>
+    };
+}
+",
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn no_completion_inside_type() {
+        check(
+            r"
+trait Test { type Test; type Test2; fn test(); }
+struct T;
+
+impl Test for T {
+    type Test = T<|>;
+}
+",
+            expect![[""]],
+        );
+
+        check(
+            r"
+trait Test { type Test; type Test2; fn test(); }
+struct T;
+
+impl Test for T {
+    type Test = fn <|>;
+}
+",
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn name_ref_single_function() {
+        check_edit(
+            "test",
+            r#"
+trait Test {
+    fn test();
+}
+struct T;
+
+impl Test for T {
+    t<|>
+}
+"#,
+            r#"
+trait Test {
+    fn test();
+}
+struct T;
+
+impl Test for T {
+    fn test() {
+    $0
+}
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn single_function() {
+        check_edit(
+            "test",
+            r#"
+trait Test {
+    fn test();
+}
+struct T;
+
+impl Test for T {
+    fn t<|>
+}
+"#,
+            r#"
+trait Test {
+    fn test();
+}
+struct T;
+
+impl Test for T {
+    fn test() {
+    $0
+}
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn hide_implemented_fn() {
+        check(
+            r#"
+trait Test {
+    fn foo();
+    fn foo_bar();
+}
+struct T;
+
+impl Test for T {
+    fn foo() {}
+    fn f<|>
+}
+"#,
+            expect![[r#"
+                fn fn foo_bar()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn generic_fn() {
+        check_edit(
+            "foo",
+            r#"
+trait Test {
+    fn foo<T>();
+}
+struct T;
+
+impl Test for T {
+    fn f<|>
+}
+"#,
+            r#"
+trait Test {
+    fn foo<T>();
+}
+struct T;
+
+impl Test for T {
+    fn foo<T>() {
+    $0
+}
+}
+"#,
+        );
+        check_edit(
+            "foo",
+            r#"
+trait Test {
+    fn foo<T>() where T: Into<String>;
+}
+struct T;
+
+impl Test for T {
+    fn f<|>
+}
+"#,
+            r#"
+trait Test {
+    fn foo<T>() where T: Into<String>;
+}
+struct T;
+
+impl Test for T {
+    fn foo<T>()
+where T: Into<String> {
+    $0
+}
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn associated_type() {
+        check_edit(
+            "SomeType",
+            r#"
+trait Test {
+    type SomeType;
+}
+
+impl Test for () {
+    type S<|>
+}
+"#,
+            "
+trait Test {
+    type SomeType;
+}
+
+impl Test for () {
+    type SomeType = \n\
+}
+",
+        );
+    }
+
+    #[test]
+    fn associated_const() {
+        check_edit(
+            "SOME_CONST",
+            r#"
+trait Test {
+    const SOME_CONST: u16;
+}
+
+impl Test for () {
+    const S<|>
+}
+"#,
+            "
+trait Test {
+    const SOME_CONST: u16;
+}
+
+impl Test for () {
+    const SOME_CONST: u16 = \n\
+}
+",
+        );
+
+        check_edit(
+            "SOME_CONST",
+            r#"
+trait Test {
+    const SOME_CONST: u16 = 92;
+}
+
+impl Test for () {
+    const S<|>
+}
+"#,
+            "
+trait Test {
+    const SOME_CONST: u16 = 92;
+}
+
+impl Test for () {
+    const SOME_CONST: u16 = \n\
+}
+",
+        );
+    }
+
+    #[test]
+    fn complete_without_name() {
+        let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
+            println!(
+                "completion='{}', hint='{}', next_sibling='{}'",
+                completion, hint, next_sibling
+            );
+
+            check_edit(
+                completion,
+                &format!(
+                    r#"
+trait Test {{
+    type Foo;
+    const CONST: u16;
+    fn bar();
+}}
+struct T;
+
+impl Test for T {{
+    {}
+    {}
+}}
+"#,
+                    hint, next_sibling
+                ),
+                &format!(
+                    r#"
+trait Test {{
+    type Foo;
+    const CONST: u16;
+    fn bar();
+}}
+struct T;
+
+impl Test for T {{
+    {}
+    {}
+}}
+"#,
+                    completed, next_sibling
+                ),
+            )
+        };
+
+        // Enumerate some possible next siblings.
+        for next_sibling in &[
+            "",
+            "fn other_fn() {}", // `const <|> fn` -> `const fn`
+            "type OtherType = i32;",
+            "const OTHER_CONST: i32 = 0;",
+            "async fn other_fn() {}",
+            "unsafe fn other_fn() {}",
+            "default fn other_fn() {}",
+            "default type OtherType = i32;",
+            "default const OTHER_CONST: i32 = 0;",
+        ] {
+            test("bar", "fn <|>", "fn bar() {\n    $0\n}", next_sibling);
+            test("Foo", "type <|>", "type Foo = ", next_sibling);
+            test("CONST", "const <|>", "const CONST: u16 = ", next_sibling);
+        }
+    }
+}
diff --git a/crates/completion/src/complete_unqualified_path.rs b/crates/completion/src/complete_unqualified_path.rs
new file mode 100644 (file)
index 0000000..5464a16
--- /dev/null
@@ -0,0 +1,679 @@
+//! Completion of names from the current scope, e.g. locals and imported items.
+
+use hir::{Adt, ModuleDef, ScopeDef, Type};
+use syntax::AstNode;
+use test_utils::mark;
+
+use crate::{CompletionContext, Completions};
+
+pub(super) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) {
+    if !(ctx.is_trivial_path || ctx.is_pat_binding_or_const) {
+        return;
+    }
+    if ctx.record_lit_syntax.is_some()
+        || ctx.record_pat_syntax.is_some()
+        || ctx.attribute_under_caret.is_some()
+        || ctx.mod_declaration_under_caret.is_some()
+    {
+        return;
+    }
+
+    if let Some(ty) = &ctx.expected_type {
+        complete_enum_variants(acc, ctx, ty);
+    }
+
+    if ctx.is_pat_binding_or_const {
+        return;
+    }
+
+    ctx.scope.process_all_names(&mut |name, res| {
+        if ctx.use_item_syntax.is_some() {
+            if let (ScopeDef::Unknown, Some(name_ref)) = (&res, &ctx.name_ref_syntax) {
+                if name_ref.syntax().text() == name.to_string().as_str() {
+                    mark::hit!(self_fulfilling_completion);
+                    return;
+                }
+            }
+        }
+        acc.add_resolution(ctx, name.to_string(), &res)
+    });
+}
+
+fn complete_enum_variants(acc: &mut Completions, ctx: &CompletionContext, ty: &Type) {
+    if let Some(Adt::Enum(enum_data)) = ty.as_adt() {
+        let variants = enum_data.variants(ctx.db);
+
+        let module = if let Some(module) = ctx.scope.module() {
+            // Compute path from the completion site if available.
+            module
+        } else {
+            // Otherwise fall back to the enum's definition site.
+            enum_data.module(ctx.db)
+        };
+
+        for variant in variants {
+            if let Some(path) = module.find_use_path(ctx.db, ModuleDef::from(variant)) {
+                // Variants with trivial paths are already added by the existing completion logic,
+                // so we should avoid adding these twice
+                if path.segments.len() > 1 {
+                    acc.add_qualified_enum_variant(ctx, variant, path);
+                }
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use expect_test::{expect, Expect};
+    use test_utils::mark;
+
+    use crate::{
+        test_utils::{check_edit, completion_list},
+        CompletionKind,
+    };
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = completion_list(ra_fixture, CompletionKind::Reference);
+        expect.assert_eq(&actual)
+    }
+
+    #[test]
+    fn self_fulfilling_completion() {
+        mark::check!(self_fulfilling_completion);
+        check(
+            r#"
+use foo<|>
+use std::collections;
+"#,
+            expect![[r#"
+                ?? collections
+            "#]],
+        );
+    }
+
+    #[test]
+    fn bind_pat_and_path_ignore_at() {
+        check(
+            r#"
+enum Enum { A, B }
+fn quux(x: Option<Enum>) {
+    match x {
+        None => (),
+        Some(en<|> @ Enum::A) => (),
+    }
+}
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn bind_pat_and_path_ignore_ref() {
+        check(
+            r#"
+enum Enum { A, B }
+fn quux(x: Option<Enum>) {
+    match x {
+        None => (),
+        Some(ref en<|>) => (),
+    }
+}
+"#,
+            expect![[""]],
+        );
+    }
+
+    #[test]
+    fn bind_pat_and_path() {
+        check(
+            r#"
+enum Enum { A, B }
+fn quux(x: Option<Enum>) {
+    match x {
+        None => (),
+        Some(En<|>) => (),
+    }
+}
+"#,
+            expect![[r#"
+                en Enum
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_bindings_from_let() {
+        check(
+            r#"
+fn quux(x: i32) {
+    let y = 92;
+    1 + <|>;
+    let z = ();
+}
+"#,
+            expect![[r#"
+                fn quux(…) fn quux(x: i32)
+                bn x       i32
+                bn y       i32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_bindings_from_if_let() {
+        check(
+            r#"
+fn quux() {
+    if let Some(x) = foo() {
+        let y = 92;
+    };
+    if let Some(a) = bar() {
+        let b = 62;
+        1 + <|>
+    }
+}
+"#,
+            expect![[r#"
+                bn a
+                bn b      i32
+                fn quux() fn quux()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_bindings_from_for() {
+        check(
+            r#"
+fn quux() {
+    for x in &[1, 2, 3] { <|> }
+}
+"#,
+            expect![[r#"
+                fn quux() fn quux()
+                bn x
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_if_prefix_is_keyword() {
+        mark::check!(completes_if_prefix_is_keyword);
+        check_edit(
+            "wherewolf",
+            r#"
+fn main() {
+    let wherewolf = 92;
+    drop(where<|>)
+}
+"#,
+            r#"
+fn main() {
+    let wherewolf = 92;
+    drop(wherewolf)
+}
+"#,
+        )
+    }
+
+    #[test]
+    fn completes_generic_params() {
+        check(
+            r#"fn quux<T>() { <|> }"#,
+            expect![[r#"
+                tp T
+                fn quux() fn quux<T>()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_generic_params_in_struct() {
+        check(
+            r#"struct S<T> { x: <|>}"#,
+            expect![[r#"
+                st S<…>
+                tp Self
+                tp T
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_self_in_enum() {
+        check(
+            r#"enum X { Y(<|>) }"#,
+            expect![[r#"
+                tp Self
+                en X
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_module_items() {
+        check(
+            r#"
+struct S;
+enum E {}
+fn quux() { <|> }
+"#,
+            expect![[r#"
+                en E
+                st S
+                fn quux() fn quux()
+            "#]],
+        );
+    }
+
+    /// Regression test for issue #6091.
+    #[test]
+    fn correctly_completes_module_items_prefixed_with_underscore() {
+        check_edit(
+            "_alpha",
+            r#"
+fn main() {
+    _<|>
+}
+fn _alpha() {}
+"#,
+            r#"
+fn main() {
+    _alpha()$0
+}
+fn _alpha() {}
+"#,
+        )
+    }
+
+    #[test]
+    fn completes_extern_prelude() {
+        check(
+            r#"
+//- /lib.rs crate:main deps:other_crate
+use <|>;
+
+//- /other_crate/lib.rs crate:other_crate
+// nothing here
+"#,
+            expect![[r#"
+                md other_crate
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_module_items_in_nested_modules() {
+        check(
+            r#"
+struct Foo;
+mod m {
+    struct Bar;
+    fn quux() { <|> }
+}
+"#,
+            expect![[r#"
+                st Bar
+                fn quux() fn quux()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_return_type() {
+        check(
+            r#"
+struct Foo;
+fn x() -> <|>
+"#,
+            expect![[r#"
+                st Foo
+                fn x() fn x()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn dont_show_both_completions_for_shadowing() {
+        check(
+            r#"
+fn foo() {
+    let bar = 92;
+    {
+        let bar = 62;
+        drop(<|>)
+    }
+}
+"#,
+            // FIXME: should be only one bar here
+            expect![[r#"
+                bn bar   i32
+                bn bar   i32
+                fn foo() fn foo()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_self_in_methods() {
+        check(
+            r#"impl S { fn foo(&self) { <|> } }"#,
+            expect![[r#"
+                tp Self
+                bn self &{unknown}
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_prelude() {
+        check(
+            r#"
+//- /main.rs crate:main deps:std
+fn foo() { let x: <|> }
+
+//- /std/lib.rs crate:std
+#[prelude_import]
+use prelude::*;
+
+mod prelude { struct Option; }
+"#,
+            expect![[r#"
+                st Option
+                fn foo()  fn foo()
+                md std
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_std_prelude_if_core_is_defined() {
+        check(
+            r#"
+//- /main.rs crate:main deps:core,std
+fn foo() { let x: <|> }
+
+//- /core/lib.rs crate:core
+#[prelude_import]
+use prelude::*;
+
+mod prelude { struct Option; }
+
+//- /std/lib.rs crate:std deps:core
+#[prelude_import]
+use prelude::*;
+
+mod prelude { struct String; }
+"#,
+            expect![[r#"
+                st String
+                md core
+                fn foo()  fn foo()
+                md std
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_macros_as_value() {
+        check(
+            r#"
+macro_rules! foo { () => {} }
+
+#[macro_use]
+mod m1 {
+    macro_rules! bar { () => {} }
+}
+
+mod m2 {
+    macro_rules! nope { () => {} }
+
+    #[macro_export]
+    macro_rules! baz { () => {} }
+}
+
+fn main() { let v = <|> }
+"#,
+            expect![[r##"
+                ma bar!(…) macro_rules! bar
+                ma baz!(…) #[macro_export]
+                macro_rules! baz
+                ma foo!(…) macro_rules! foo
+                md m1
+                md m2
+                fn main()  fn main()
+            "##]],
+        );
+    }
+
+    #[test]
+    fn completes_both_macro_and_value() {
+        check(
+            r#"
+macro_rules! foo { () => {} }
+fn foo() { <|> }
+"#,
+            expect![[r#"
+                ma foo!(…) macro_rules! foo
+                fn foo()   fn foo()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_macros_as_type() {
+        check(
+            r#"
+macro_rules! foo { () => {} }
+fn main() { let x: <|> }
+"#,
+            expect![[r#"
+                ma foo!(…) macro_rules! foo
+                fn main()  fn main()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_macros_as_stmt() {
+        check(
+            r#"
+macro_rules! foo { () => {} }
+fn main() { <|> }
+"#,
+            expect![[r#"
+                ma foo!(…) macro_rules! foo
+                fn main()  fn main()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_local_item() {
+        check(
+            r#"
+fn main() {
+    return f<|>;
+    fn frobnicate() {}
+}
+"#,
+            expect![[r#"
+                fn frobnicate() fn frobnicate()
+                fn main()       fn main()
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_in_simple_macro_1() {
+        check(
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+fn quux(x: i32) {
+    let y = 92;
+    m!(<|>);
+}
+"#,
+            expect![[r#"
+                ma m!(…)   macro_rules! m
+                fn quux(…) fn quux(x: i32)
+                bn x       i32
+                bn y       i32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_in_simple_macro_2() {
+        check(
+            r"
+macro_rules! m { ($e:expr) => { $e } }
+fn quux(x: i32) {
+    let y = 92;
+    m!(x<|>);
+}
+",
+            expect![[r#"
+                ma m!(…)   macro_rules! m
+                fn quux(…) fn quux(x: i32)
+                bn x       i32
+                bn y       i32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_in_simple_macro_without_closing_parens() {
+        check(
+            r#"
+macro_rules! m { ($e:expr) => { $e } }
+fn quux(x: i32) {
+    let y = 92;
+    m!(x<|>
+}
+"#,
+            expect![[r#"
+                ma m!(…)   macro_rules! m
+                fn quux(…) fn quux(x: i32)
+                bn x       i32
+                bn y       i32
+            "#]],
+        );
+    }
+
+    #[test]
+    fn completes_unresolved_uses() {
+        check(
+            r#"
+use spam::Quux;
+
+fn main() { <|> }
+"#,
+            expect![[r#"
+                ?? Quux
+                fn main() fn main()
+            "#]],
+        );
+    }
+    #[test]
+    fn completes_enum_variant_matcharm() {
+        check(
+            r#"
+enum Foo { Bar, Baz, Quux }
+
+fn main() {
+    let foo = Foo::Quux;
+    match foo { Qu<|> }
+}
+"#,
+            expect![[r#"
+                en Foo
+                ev Foo::Bar  ()
+                ev Foo::Baz  ()
+                ev Foo::Quux ()
+            "#]],
+        )
+    }
+
+    #[test]
+    fn completes_enum_variant_iflet() {
+        check(
+            r#"
+enum Foo { Bar, Baz, Quux }
+
+fn main() {
+    let foo = Foo::Quux;
+    if let Qu<|> = foo { }
+}
+"#,
+            expect![[r#"
+                en Foo
+                ev Foo::Bar  ()
+                ev Foo::Baz  ()
+                ev Foo::Quux ()
+            "#]],
+        )
+    }
+
+    #[test]
+    fn completes_enum_variant_basic_expr() {
+        check(
+            r#"
+enum Foo { Bar, Baz, Quux }
+fn main() { let foo: Foo = Q<|> }
+"#,
+            expect![[r#"
+                en Foo
+                ev Foo::Bar  ()
+                ev Foo::Baz  ()
+                ev Foo::Quux ()
+                fn main()    fn main()
+            "#]],
+        )
+    }
+
+    #[test]
+    fn completes_enum_variant_from_module() {
+        check(
+            r#"
+mod m { pub enum E { V } }
+fn f() -> m::E { V<|> }
+"#,
+            expect![[r#"
+                fn f()     fn f() -> m::E
+                md m
+                ev m::E::V ()
+            "#]],
+        )
+    }
+
+    #[test]
+    fn dont_complete_attr() {
+        check(
+            r#"
+struct Foo;
+#[<|>]
+fn f() {}
+"#,
+            expect![[""]],
+        )
+    }
+
+    #[test]
+    fn completes_type_or_trait_in_impl_block() {
+        check(
+            r#"
+trait MyTrait {}
+struct MyStruct {}
+
+impl My<|>
+"#,
+            expect![[r#"
+                st MyStruct
+                tt MyTrait
+                tp Self
+            "#]],
+        )
+    }
+}
diff --git a/crates/completion/src/completion_config.rs b/crates/completion/src/completion_config.rs
new file mode 100644 (file)
index 0000000..71b49ac
--- /dev/null
@@ -0,0 +1,35 @@
+//! Settings for tweaking completion.
+//!
+//! The fun thing here is `SnippetCap` -- this type can only be created in this
+//! module, and we use to statically check that we only produce snippet
+//! completions if we are allowed to.
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CompletionConfig {
+    pub enable_postfix_completions: bool,
+    pub add_call_parenthesis: bool,
+    pub add_call_argument_snippets: bool,
+    pub snippet_cap: Option<SnippetCap>,
+}
+
+impl CompletionConfig {
+    pub fn allow_snippets(&mut self, yes: bool) {
+        self.snippet_cap = if yes { Some(SnippetCap { _private: () }) } else { None }
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SnippetCap {
+    _private: (),
+}
+
+impl Default for CompletionConfig {
+    fn default() -> Self {
+        CompletionConfig {
+            enable_postfix_completions: true,
+            add_call_parenthesis: true,
+            add_call_argument_snippets: true,
+            snippet_cap: Some(SnippetCap { _private: () }),
+        }
+    }
+}
diff --git a/crates/completion/src/completion_context.rs b/crates/completion/src/completion_context.rs
new file mode 100644 (file)
index 0000000..dc4e136
--- /dev/null
@@ -0,0 +1,520 @@
+//! See `CompletionContext` structure.
+
+use base_db::{FilePosition, SourceDatabase};
+use call_info::ActiveParameter;
+use hir::{Local, ScopeDef, Semantics, SemanticsScope, Type};
+use ide_db::RootDatabase;
+use syntax::{
+    algo::{find_covering_element, find_node_at_offset},
+    ast, match_ast, AstNode, NodeOrToken,
+    SyntaxKind::*,
+    SyntaxNode, SyntaxToken, TextRange, TextSize,
+};
+use test_utils::mark;
+use text_edit::Indel;
+
+use crate::{
+    patterns::{
+        fn_is_prev, for_is_prev2, has_bind_pat_parent, has_block_expr_parent,
+        has_field_list_parent, has_impl_as_prev_sibling, has_impl_parent,
+        has_item_list_or_source_file_parent, has_ref_parent, has_trait_as_prev_sibling,
+        has_trait_parent, if_is_prev, inside_impl_trait_block, is_in_loop_body, is_match_arm,
+        unsafe_is_prev,
+    },
+    CompletionConfig,
+};
+
+/// `CompletionContext` is created early during completion to figure out, where
+/// exactly is the cursor, syntax-wise.
+#[derive(Debug)]
+pub(crate) struct CompletionContext<'a> {
+    pub(super) sema: Semantics<'a, RootDatabase>,
+    pub(super) scope: SemanticsScope<'a>,
+    pub(super) db: &'a RootDatabase,
+    pub(super) config: &'a CompletionConfig,
+    pub(super) position: FilePosition,
+    /// The token before the cursor, in the original file.
+    pub(super) original_token: SyntaxToken,
+    /// The token before the cursor, in the macro-expanded file.
+    pub(super) token: SyntaxToken,
+    pub(super) krate: Option<hir::Crate>,
+    pub(super) expected_type: Option<Type>,
+    pub(super) name_ref_syntax: Option<ast::NameRef>,
+    pub(super) function_syntax: Option<ast::Fn>,
+    pub(super) use_item_syntax: Option<ast::Use>,
+    pub(super) record_lit_syntax: Option<ast::RecordExpr>,
+    pub(super) record_pat_syntax: Option<ast::RecordPat>,
+    pub(super) record_field_syntax: Option<ast::RecordExprField>,
+    pub(super) impl_def: Option<ast::Impl>,
+    /// FIXME: `ActiveParameter` is string-based, which is very very wrong
+    pub(super) active_parameter: Option<ActiveParameter>,
+    pub(super) is_param: bool,
+    /// If a name-binding or reference to a const in a pattern.
+    /// Irrefutable patterns (like let) are excluded.
+    pub(super) is_pat_binding_or_const: bool,
+    /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
+    pub(super) is_trivial_path: bool,
+    /// If not a trivial path, the prefix (qualifier).
+    pub(super) path_qual: Option<ast::Path>,
+    pub(super) after_if: bool,
+    /// `true` if we are a statement or a last expr in the block.
+    pub(super) can_be_stmt: bool,
+    /// `true` if we expect an expression at the cursor position.
+    pub(super) is_expr: bool,
+    /// Something is typed at the "top" level, in module or impl/trait.
+    pub(super) is_new_item: bool,
+    /// The receiver if this is a field or method access, i.e. writing something.<|>
+    pub(super) dot_receiver: Option<ast::Expr>,
+    pub(super) dot_receiver_is_ambiguous_float_literal: bool,
+    /// If this is a call (method or function) in particular, i.e. the () are already there.
+    pub(super) is_call: bool,
+    /// Like `is_call`, but for tuple patterns.
+    pub(super) is_pattern_call: bool,
+    /// If this is a macro call, i.e. the () are already there.
+    pub(super) is_macro_call: bool,
+    pub(super) is_path_type: bool,
+    pub(super) has_type_args: bool,
+    pub(super) attribute_under_caret: Option<ast::Attr>,
+    pub(super) mod_declaration_under_caret: Option<ast::Module>,
+    pub(super) unsafe_is_prev: bool,
+    pub(super) if_is_prev: bool,
+    pub(super) block_expr_parent: bool,
+    pub(super) bind_pat_parent: bool,
+    pub(super) ref_pat_parent: bool,
+    pub(super) in_loop_body: bool,
+    pub(super) has_trait_parent: bool,
+    pub(super) has_impl_parent: bool,
+    pub(super) inside_impl_trait_block: bool,
+    pub(super) has_field_list_parent: bool,
+    pub(super) trait_as_prev_sibling: bool,
+    pub(super) impl_as_prev_sibling: bool,
+    pub(super) is_match_arm: bool,
+    pub(super) has_item_list_or_source_file_parent: bool,
+    pub(super) for_is_prev2: bool,
+    pub(super) fn_is_prev: bool,
+    pub(super) locals: Vec<(String, Local)>,
+}
+
+impl<'a> CompletionContext<'a> {
+    pub(super) fn new(
+        db: &'a RootDatabase,
+        position: FilePosition,
+        config: &'a CompletionConfig,
+    ) -> Option<CompletionContext<'a>> {
+        let sema = Semantics::new(db);
+
+        let original_file = sema.parse(position.file_id);
+
+        // Insert a fake ident to get a valid parse tree. We will use this file
+        // to determine context, though the original_file will be used for
+        // actual completion.
+        let file_with_fake_ident = {
+            let parse = db.parse(position.file_id);
+            let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
+            parse.reparse(&edit).tree()
+        };
+        let fake_ident_token =
+            file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
+
+        let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
+        let original_token =
+            original_file.syntax().token_at_offset(position.offset).left_biased()?;
+        let token = sema.descend_into_macros(original_token.clone());
+        let scope = sema.scope_at_offset(&token.parent(), position.offset);
+        let mut locals = vec![];
+        scope.process_all_names(&mut |name, scope| {
+            if let ScopeDef::Local(local) = scope {
+                locals.push((name.to_string(), local));
+            }
+        });
+        let mut ctx = CompletionContext {
+            sema,
+            scope,
+            db,
+            config,
+            original_token,
+            token,
+            position,
+            krate,
+            expected_type: None,
+            name_ref_syntax: None,
+            function_syntax: None,
+            use_item_syntax: None,
+            record_lit_syntax: None,
+            record_pat_syntax: None,
+            record_field_syntax: None,
+            impl_def: None,
+            active_parameter: ActiveParameter::at(db, position),
+            is_param: false,
+            is_pat_binding_or_const: false,
+            is_trivial_path: false,
+            path_qual: None,
+            after_if: false,
+            can_be_stmt: false,
+            is_expr: false,
+            is_new_item: false,
+            dot_receiver: None,
+            is_call: false,
+            is_pattern_call: false,
+            is_macro_call: false,
+            is_path_type: false,
+            has_type_args: false,
+            dot_receiver_is_ambiguous_float_literal: false,
+            attribute_under_caret: None,
+            mod_declaration_under_caret: None,
+            unsafe_is_prev: false,
+            in_loop_body: false,
+            ref_pat_parent: false,
+            bind_pat_parent: false,
+            block_expr_parent: false,
+            has_trait_parent: false,
+            has_impl_parent: false,
+            inside_impl_trait_block: false,
+            has_field_list_parent: false,
+            trait_as_prev_sibling: false,
+            impl_as_prev_sibling: false,
+            if_is_prev: false,
+            is_match_arm: false,
+            has_item_list_or_source_file_parent: false,
+            for_is_prev2: false,
+            fn_is_prev: false,
+            locals,
+        };
+
+        let mut original_file = original_file.syntax().clone();
+        let mut hypothetical_file = file_with_fake_ident.syntax().clone();
+        let mut offset = position.offset;
+        let mut fake_ident_token = fake_ident_token;
+
+        // Are we inside a macro call?
+        while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
+            find_node_at_offset::<ast::MacroCall>(&original_file, offset),
+            find_node_at_offset::<ast::MacroCall>(&hypothetical_file, offset),
+        ) {
+            if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
+                != macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
+            {
+                break;
+            }
+            let hypothetical_args = match macro_call_with_fake_ident.token_tree() {
+                Some(tt) => tt,
+                None => break,
+            };
+            if let (Some(actual_expansion), Some(hypothetical_expansion)) = (
+                ctx.sema.expand(&actual_macro_call),
+                ctx.sema.speculative_expand(
+                    &actual_macro_call,
+                    &hypothetical_args,
+                    fake_ident_token,
+                ),
+            ) {
+                let new_offset = hypothetical_expansion.1.text_range().start();
+                if new_offset > actual_expansion.text_range().end() {
+                    break;
+                }
+                original_file = actual_expansion;
+                hypothetical_file = hypothetical_expansion.0;
+                fake_ident_token = hypothetical_expansion.1;
+                offset = new_offset;
+            } else {
+                break;
+            }
+        }
+        ctx.fill_keyword_patterns(&hypothetical_file, offset);
+        ctx.fill(&original_file, hypothetical_file, offset);
+        Some(ctx)
+    }
+
+    /// Checks whether completions in that particular case don't make much sense.
+    /// Examples:
+    /// - `fn <|>` -- we expect function name, it's unlikely that "hint" will be helpful.
+    ///   Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
+    /// - `for _ i<|>` -- obviously, it'll be "in" keyword.
+    pub(crate) fn no_completion_required(&self) -> bool {
+        (self.fn_is_prev && !self.inside_impl_trait_block) || self.for_is_prev2
+    }
+
+    /// The range of the identifier that is being completed.
+    pub(crate) fn source_range(&self) -> TextRange {
+        // check kind of macro-expanded token, but use range of original token
+        let kind = self.token.kind();
+        if kind == IDENT || kind == UNDERSCORE || kind.is_keyword() {
+            mark::hit!(completes_if_prefix_is_keyword);
+            self.original_token.text_range()
+        } else {
+            TextRange::empty(self.position.offset)
+        }
+    }
+
+    fn fill_keyword_patterns(&mut self, file_with_fake_ident: &SyntaxNode, offset: TextSize) {
+        let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
+        let syntax_element = NodeOrToken::Token(fake_ident_token);
+        self.block_expr_parent = has_block_expr_parent(syntax_element.clone());
+        self.unsafe_is_prev = unsafe_is_prev(syntax_element.clone());
+        self.if_is_prev = if_is_prev(syntax_element.clone());
+        self.bind_pat_parent = has_bind_pat_parent(syntax_element.clone());
+        self.ref_pat_parent = has_ref_parent(syntax_element.clone());
+        self.in_loop_body = is_in_loop_body(syntax_element.clone());
+        self.has_trait_parent = has_trait_parent(syntax_element.clone());
+        self.has_impl_parent = has_impl_parent(syntax_element.clone());
+        self.inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
+        self.has_field_list_parent = has_field_list_parent(syntax_element.clone());
+        self.impl_as_prev_sibling = has_impl_as_prev_sibling(syntax_element.clone());
+        self.trait_as_prev_sibling = has_trait_as_prev_sibling(syntax_element.clone());
+        self.is_match_arm = is_match_arm(syntax_element.clone());
+        self.has_item_list_or_source_file_parent =
+            has_item_list_or_source_file_parent(syntax_element.clone());
+        self.mod_declaration_under_caret =
+            find_node_at_offset::<ast::Module>(&file_with_fake_ident, offset)
+                .filter(|module| module.item_list().is_none());
+        self.for_is_prev2 = for_is_prev2(syntax_element.clone());
+        self.fn_is_prev = fn_is_prev(syntax_element.clone());
+    }
+
+    fn fill(
+        &mut self,
+        original_file: &SyntaxNode,
+        file_with_fake_ident: SyntaxNode,
+        offset: TextSize,
+    ) {
+        // FIXME: this is wrong in at least two cases:
+        //  * when there's no token `foo(<|>)`
+        //  * when there is a token, but it happens to have type of it's own
+        self.expected_type = self
+            .token
+            .ancestors()
+            .find_map(|node| {
+                let ty = match_ast! {
+                    match node {
+                        ast::Pat(it) => self.sema.type_of_pat(&it),
+                        ast::Expr(it) => self.sema.type_of_expr(&it),
+                        _ => return None,
+                    }
+                };
+                Some(ty)
+            })
+            .flatten();
+        self.attribute_under_caret = find_node_at_offset(&file_with_fake_ident, offset);
+
+        // First, let's try to complete a reference to some declaration.
+        if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(&file_with_fake_ident, offset) {
+            // Special case, `trait T { fn foo(i_am_a_name_ref) {} }`.
+            // See RFC#1685.
+            if is_node::<ast::Param>(name_ref.syntax()) {
+                self.is_param = true;
+                return;
+            }
+            // FIXME: remove this (V) duplication and make the check more precise
+            if name_ref.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
+                self.record_pat_syntax =
+                    self.sema.find_node_at_offset_with_macros(&original_file, offset);
+            }
+            self.classify_name_ref(original_file, name_ref, offset);
+        }
+
+        // Otherwise, see if this is a declaration. We can use heuristics to
+        // suggest declaration names, see `CompletionKind::Magic`.
+        if let Some(name) = find_node_at_offset::<ast::Name>(&file_with_fake_ident, offset) {
+            if let Some(bind_pat) = name.syntax().ancestors().find_map(ast::IdentPat::cast) {
+                self.is_pat_binding_or_const = true;
+                if bind_pat.at_token().is_some()
+                    || bind_pat.ref_token().is_some()
+                    || bind_pat.mut_token().is_some()
+                {
+                    self.is_pat_binding_or_const = false;
+                }
+                if bind_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast).is_some() {
+                    self.is_pat_binding_or_const = false;
+                }
+                if let Some(let_stmt) = bind_pat.syntax().ancestors().find_map(ast::LetStmt::cast) {
+                    if let Some(pat) = let_stmt.pat() {
+                        if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range())
+                        {
+                            self.is_pat_binding_or_const = false;
+                        }
+                    }
+                }
+            }
+            if is_node::<ast::Param>(name.syntax()) {
+                self.is_param = true;
+                return;
+            }
+            // FIXME: remove this (^) duplication and make the check more precise
+            if name.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
+                self.record_pat_syntax =
+                    self.sema.find_node_at_offset_with_macros(&original_file, offset);
+            }
+        }
+    }
+
+    fn classify_name_ref(
+        &mut self,
+        original_file: &SyntaxNode,
+        name_ref: ast::NameRef,
+        offset: TextSize,
+    ) {
+        self.name_ref_syntax =
+            find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
+        let name_range = name_ref.syntax().text_range();
+        if ast::RecordExprField::for_field_name(&name_ref).is_some() {
+            self.record_lit_syntax =
+                self.sema.find_node_at_offset_with_macros(&original_file, offset);
+        }
+
+        self.impl_def = self
+            .sema
+            .ancestors_with_macros(self.token.parent())
+            .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
+            .find_map(ast::Impl::cast);
+
+        let top_node = name_ref
+            .syntax()
+            .ancestors()
+            .take_while(|it| it.text_range() == name_range)
+            .last()
+            .unwrap();
+
+        match top_node.parent().map(|it| it.kind()) {
+            Some(SOURCE_FILE) | Some(ITEM_LIST) => {
+                self.is_new_item = true;
+                return;
+            }
+            _ => (),
+        }
+
+        self.use_item_syntax =
+            self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::Use::cast);
+
+        self.function_syntax = self
+            .sema
+            .ancestors_with_macros(self.token.parent())
+            .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
+            .find_map(ast::Fn::cast);
+
+        self.record_field_syntax = self
+            .sema
+            .ancestors_with_macros(self.token.parent())
+            .take_while(|it| {
+                it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR
+            })
+            .find_map(ast::RecordExprField::cast);
+
+        let parent = match name_ref.syntax().parent() {
+            Some(it) => it,
+            None => return,
+        };
+
+        if let Some(segment) = ast::PathSegment::cast(parent.clone()) {
+            let path = segment.parent_path();
+            self.is_call = path
+                .syntax()
+                .parent()
+                .and_then(ast::PathExpr::cast)
+                .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
+                .is_some();
+            self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some();
+            self.is_pattern_call =
+                path.syntax().parent().and_then(ast::TupleStructPat::cast).is_some();
+
+            self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some();
+            self.has_type_args = segment.generic_arg_list().is_some();
+
+            if let Some(path) = path_or_use_tree_qualifier(&path) {
+                self.path_qual = path
+                    .segment()
+                    .and_then(|it| {
+                        find_node_with_range::<ast::PathSegment>(
+                            original_file,
+                            it.syntax().text_range(),
+                        )
+                    })
+                    .map(|it| it.parent_path());
+                return;
+            }
+
+            if let Some(segment) = path.segment() {
+                if segment.coloncolon_token().is_some() {
+                    return;
+                }
+            }
+
+            self.is_trivial_path = true;
+
+            // Find either enclosing expr statement (thing with `;`) or a
+            // block. If block, check that we are the last expr.
+            self.can_be_stmt = name_ref
+                .syntax()
+                .ancestors()
+                .find_map(|node| {
+                    if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
+                        return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
+                    }
+                    if let Some(block) = ast::BlockExpr::cast(node) {
+                        return Some(
+                            block.expr().map(|e| e.syntax().text_range())
+                                == Some(name_ref.syntax().text_range()),
+                        );
+                    }
+                    None
+                })
+                .unwrap_or(false);
+            self.is_expr = path.syntax().parent().and_then(ast::PathExpr::cast).is_some();
+
+            if let Some(off) = name_ref.syntax().text_range().start().checked_sub(2.into()) {
+                if let Some(if_expr) =
+                    self.sema.find_node_at_offset_with_macros::<ast::IfExpr>(original_file, off)
+                {
+                    if if_expr.syntax().text_range().end() < name_ref.syntax().text_range().start()
+                    {
+                        self.after_if = true;
+                    }
+                }
+            }
+        }
+        if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
+            // The receiver comes before the point of insertion of the fake
+            // ident, so it should have the same range in the non-modified file
+            self.dot_receiver = field_expr
+                .expr()
+                .map(|e| e.syntax().text_range())
+                .and_then(|r| find_node_with_range(original_file, r));
+            self.dot_receiver_is_ambiguous_float_literal =
+                if let Some(ast::Expr::Literal(l)) = &self.dot_receiver {
+                    match l.kind() {
+                        ast::LiteralKind::FloatNumber { .. } => l.token().text().ends_with('.'),
+                        _ => false,
+                    }
+                } else {
+                    false
+                };
+        }
+        if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
+            // As above
+            self.dot_receiver = method_call_expr
+                .receiver()
+                .map(|e| e.syntax().text_range())
+                .and_then(|r| find_node_with_range(original_file, r));
+            self.is_call = true;
+        }
+    }
+}
+
+fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
+    find_covering_element(syntax, range).ancestors().find_map(N::cast)
+}
+
+fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
+    match node.ancestors().find_map(N::cast) {
+        None => false,
+        Some(n) => n.syntax().text_range() == node.text_range(),
+    }
+}
+
+fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<ast::Path> {
+    if let Some(qual) = path.qualifier() {
+        return Some(qual);
+    }
+    let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
+    let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
+    use_tree.path()
+}
diff --git a/crates/completion/src/completion_item.rs b/crates/completion/src/completion_item.rs
new file mode 100644 (file)
index 0000000..f8be0ad
--- /dev/null
@@ -0,0 +1,384 @@
+//! See `CompletionItem` structure.
+
+use std::fmt;
+
+use hir::Documentation;
+use syntax::TextRange;
+use text_edit::TextEdit;
+
+use crate::completion_config::SnippetCap;
+
+/// `CompletionItem` describes a single completion variant in the editor pop-up.
+/// It is basically a POD with various properties. To construct a
+/// `CompletionItem`, use `new` method and the `Builder` struct.
+pub struct CompletionItem {
+    /// Used only internally in tests, to check only specific kind of
+    /// completion (postfix, keyword, reference, etc).
+    #[allow(unused)]
+    pub(crate) completion_kind: CompletionKind,
+    /// Label in the completion pop up which identifies completion.
+    label: String,
+    /// Range of identifier that is being completed.
+    ///
+    /// It should be used primarily for UI, but we also use this to convert
+    /// genetic TextEdit into LSP's completion edit (see conv.rs).
+    ///
+    /// `source_range` must contain the completion offset. `insert_text` should
+    /// start with what `source_range` points to, or VSCode will filter out the
+    /// completion silently.
+    source_range: TextRange,
+    /// What happens when user selects this item.
+    ///
+    /// Typically, replaces `source_range` with new identifier.
+    text_edit: TextEdit,
+    insert_text_format: InsertTextFormat,
+
+    /// What item (struct, function, etc) are we completing.
+    kind: Option<CompletionItemKind>,
+
+    /// Lookup is used to check if completion item indeed can complete current
+    /// ident.
+    ///
+    /// That is, in `foo.bar<|>` lookup of `abracadabra` will be accepted (it
+    /// contains `bar` sub sequence), and `quux` will rejected.
+    lookup: Option<String>,
+
+    /// Additional info to show in the UI pop up.
+    detail: Option<String>,
+    documentation: Option<Documentation>,
+
+    /// Whether this item is marked as deprecated
+    deprecated: bool,
+
+    /// If completing a function call, ask the editor to show parameter popup
+    /// after completion.
+    trigger_call_info: bool,
+
+    /// Score is useful to pre select or display in better order completion items
+    score: Option<CompletionScore>,
+}
+
+// We use custom debug for CompletionItem to make snapshot tests more readable.
+impl fmt::Debug for CompletionItem {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let mut s = f.debug_struct("CompletionItem");
+        s.field("label", &self.label()).field("source_range", &self.source_range());
+        if self.text_edit().len() == 1 {
+            let atom = &self.text_edit().iter().next().unwrap();
+            s.field("delete", &atom.delete);
+            s.field("insert", &atom.insert);
+        } else {
+            s.field("text_edit", &self.text_edit);
+        }
+        if let Some(kind) = self.kind().as_ref() {
+            s.field("kind", kind);
+        }
+        if self.lookup() != self.label() {
+            s.field("lookup", &self.lookup());
+        }
+        if let Some(detail) = self.detail() {
+            s.field("detail", &detail);
+        }
+        if let Some(documentation) = self.documentation() {
+            s.field("documentation", &documentation);
+        }
+        if self.deprecated {
+            s.field("deprecated", &true);
+        }
+        if let Some(score) = &self.score {
+            s.field("score", score);
+        }
+        if self.trigger_call_info {
+            s.field("trigger_call_info", &true);
+        }
+        s.finish()
+    }
+}
+
+#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq)]
+pub enum CompletionScore {
+    /// If only type match
+    TypeMatch,
+    /// If type and name match
+    TypeAndNameMatch,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CompletionItemKind {
+    Snippet,
+    Keyword,
+    Module,
+    Function,
+    BuiltinType,
+    Struct,
+    Enum,
+    EnumVariant,
+    Binding,
+    Field,
+    Static,
+    Const,
+    Trait,
+    TypeAlias,
+    Method,
+    TypeParam,
+    Macro,
+    Attribute,
+    UnresolvedReference,
+}
+
+impl CompletionItemKind {
+    #[cfg(test)]
+    pub(crate) fn tag(&self) -> &'static str {
+        match self {
+            CompletionItemKind::Attribute => "at",
+            CompletionItemKind::Binding => "bn",
+            CompletionItemKind::BuiltinType => "bt",
+            CompletionItemKind::Const => "ct",
+            CompletionItemKind::Enum => "en",
+            CompletionItemKind::EnumVariant => "ev",
+            CompletionItemKind::Field => "fd",
+            CompletionItemKind::Function => "fn",
+            CompletionItemKind::Keyword => "kw",
+            CompletionItemKind::Macro => "ma",
+            CompletionItemKind::Method => "me",
+            CompletionItemKind::Module => "md",
+            CompletionItemKind::Snippet => "sn",
+            CompletionItemKind::Static => "sc",
+            CompletionItemKind::Struct => "st",
+            CompletionItemKind::Trait => "tt",
+            CompletionItemKind::TypeAlias => "ta",
+            CompletionItemKind::TypeParam => "tp",
+            CompletionItemKind::UnresolvedReference => "??",
+        }
+    }
+}
+
+#[derive(Debug, PartialEq, Eq, Copy, Clone)]
+pub(crate) enum CompletionKind {
+    /// Parser-based keyword completion.
+    Keyword,
+    /// Your usual "complete all valid identifiers".
+    Reference,
+    /// "Secret sauce" completions.
+    Magic,
+    Snippet,
+    Postfix,
+    BuiltinType,
+    Attribute,
+}
+
+#[derive(Debug, PartialEq, Eq, Copy, Clone)]
+pub enum InsertTextFormat {
+    PlainText,
+    Snippet,
+}
+
+impl CompletionItem {
+    pub(crate) fn new(
+        completion_kind: CompletionKind,
+        source_range: TextRange,
+        label: impl Into<String>,
+    ) -> Builder {
+        let label = label.into();
+        Builder {
+            source_range,
+            completion_kind,
+            label,
+            insert_text: None,
+            insert_text_format: InsertTextFormat::PlainText,
+            detail: None,
+            documentation: None,
+            lookup: None,
+            kind: None,
+            text_edit: None,
+            deprecated: None,
+            trigger_call_info: None,
+            score: None,
+        }
+    }
+    /// What user sees in pop-up in the UI.
+    pub fn label(&self) -> &str {
+        &self.label
+    }
+    pub fn source_range(&self) -> TextRange {
+        self.source_range
+    }
+
+    pub fn insert_text_format(&self) -> InsertTextFormat {
+        self.insert_text_format
+    }
+
+    pub fn text_edit(&self) -> &TextEdit {
+        &self.text_edit
+    }
+
+    /// Short one-line additional information, like a type
+    pub fn detail(&self) -> Option<&str> {
+        self.detail.as_deref()
+    }
+    /// A doc-comment
+    pub fn documentation(&self) -> Option<Documentation> {
+        self.documentation.clone()
+    }
+    /// What string is used for filtering.
+    pub fn lookup(&self) -> &str {
+        self.lookup.as_deref().unwrap_or(&self.label)
+    }
+
+    pub fn kind(&self) -> Option<CompletionItemKind> {
+        self.kind
+    }
+
+    pub fn deprecated(&self) -> bool {
+        self.deprecated
+    }
+
+    pub fn score(&self) -> Option<CompletionScore> {
+        self.score
+    }
+
+    pub fn trigger_call_info(&self) -> bool {
+        self.trigger_call_info
+    }
+}
+
+/// A helper to make `CompletionItem`s.
+#[must_use]
+pub(crate) struct Builder {
+    source_range: TextRange,
+    completion_kind: CompletionKind,
+    label: String,
+    insert_text: Option<String>,
+    insert_text_format: InsertTextFormat,
+    detail: Option<String>,
+    documentation: Option<Documentation>,
+    lookup: Option<String>,
+    kind: Option<CompletionItemKind>,
+    text_edit: Option<TextEdit>,
+    deprecated: Option<bool>,
+    trigger_call_info: Option<bool>,
+    score: Option<CompletionScore>,
+}
+
+impl Builder {
+    pub(crate) fn add_to(self, acc: &mut Completions) {
+        acc.add(self.build())
+    }
+
+    pub(crate) fn build(self) -> CompletionItem {
+        let label = self.label;
+        let text_edit = match self.text_edit {
+            Some(it) => it,
+            None => TextEdit::replace(
+                self.source_range,
+                self.insert_text.unwrap_or_else(|| label.clone()),
+            ),
+        };
+
+        CompletionItem {
+            source_range: self.source_range,
+            label,
+            insert_text_format: self.insert_text_format,
+            text_edit,
+            detail: self.detail,
+            documentation: self.documentation,
+            lookup: self.lookup,
+            kind: self.kind,
+            completion_kind: self.completion_kind,
+            deprecated: self.deprecated.unwrap_or(false),
+            trigger_call_info: self.trigger_call_info.unwrap_or(false),
+            score: self.score,
+        }
+    }
+    pub(crate) fn lookup_by(mut self, lookup: impl Into<String>) -> Builder {
+        self.lookup = Some(lookup.into());
+        self
+    }
+    pub(crate) fn label(mut self, label: impl Into<String>) -> Builder {
+        self.label = label.into();
+        self
+    }
+    pub(crate) fn insert_text(mut self, insert_text: impl Into<String>) -> Builder {
+        self.insert_text = Some(insert_text.into());
+        self
+    }
+    pub(crate) fn insert_snippet(
+        mut self,
+        _cap: SnippetCap,
+        snippet: impl Into<String>,
+    ) -> Builder {
+        self.insert_text_format = InsertTextFormat::Snippet;
+        self.insert_text(snippet)
+    }
+    pub(crate) fn kind(mut self, kind: CompletionItemKind) -> Builder {
+        self.kind = Some(kind);
+        self
+    }
+    pub(crate) fn text_edit(mut self, edit: TextEdit) -> Builder {
+        self.text_edit = Some(edit);
+        self
+    }
+    pub(crate) fn snippet_edit(mut self, _cap: SnippetCap, edit: TextEdit) -> Builder {
+        self.insert_text_format = InsertTextFormat::Snippet;
+        self.text_edit(edit)
+    }
+    #[allow(unused)]
+    pub(crate) fn detail(self, detail: impl Into<String>) -> Builder {
+        self.set_detail(Some(detail))
+    }
+    pub(crate) fn set_detail(mut self, detail: Option<impl Into<String>>) -> Builder {
+        self.detail = detail.map(Into::into);
+        self
+    }
+    #[allow(unused)]
+    pub(crate) fn documentation(self, docs: Documentation) -> Builder {
+        self.set_documentation(Some(docs))
+    }
+    pub(crate) fn set_documentation(mut self, docs: Option<Documentation>) -> Builder {
+        self.documentation = docs.map(Into::into);
+        self
+    }
+    pub(crate) fn set_deprecated(mut self, deprecated: bool) -> Builder {
+        self.deprecated = Some(deprecated);
+        self
+    }
+    pub(crate) fn set_score(mut self, score: CompletionScore) -> Builder {
+        self.score = Some(score);
+        self
+    }
+    pub(crate) fn trigger_call_info(mut self) -> Builder {
+        self.trigger_call_info = Some(true);
+        self
+    }
+}
+
+impl<'a> Into<CompletionItem> for Builder {
+    fn into(self) -> CompletionItem {
+        self.build()
+    }
+}
+
+/// Represents an in-progress set of completions being built.
+#[derive(Debug, Default)]
+pub struct Completions {
+    buf: Vec<CompletionItem>,
+}
+
+impl Completions {
+    pub fn add(&mut self, item: impl Into<CompletionItem>) {
+        self.buf.push(item.into())
+    }
+    pub fn add_all<I>(&mut self, items: I)
+    where
+        I: IntoIterator,
+        I::Item: Into<CompletionItem>,
+    {
+        items.into_iter().for_each(|item| self.add(item.into()))
+    }
+}
+
+impl Into<Vec<CompletionItem>> for Completions {
+    fn into(self) -> Vec<CompletionItem> {
+        self.buf
+    }
+}
diff --git a/crates/completion/src/generated_features.rs b/crates/completion/src/generated_features.rs
new file mode 100644 (file)
index 0000000..090cad2
--- /dev/null
@@ -0,0 +1,4 @@
+//! Generated file, do not edit by hand, see `xtask/src/codegen`
+
+use crate::complete_attribute::LintCompletion;
+pub ( 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/completion/src/lib.rs b/crates/completion/src/lib.rs
new file mode 100644 (file)
index 0000000..9988fe7
--- /dev/null
@@ -0,0 +1,264 @@
+//! `completions` crate provides utilities for generating completions of user input.
+
+mod completion_config;
+mod completion_item;
+mod completion_context;
+mod presentation;
+mod patterns;
+mod generated_features;
+#[cfg(test)]
+mod test_utils;
+
+mod complete_attribute;
+mod complete_dot;
+mod complete_record;
+mod complete_pattern;
+mod complete_fn_param;
+mod complete_keyword;
+mod complete_snippet;
+mod complete_qualified_path;
+mod complete_unqualified_path;
+mod complete_postfix;
+mod complete_macro_in_item_position;
+mod complete_trait_impl;
+mod complete_mod;
+
+use base_db::FilePosition;
+use ide_db::RootDatabase;
+
+use crate::{
+    completion_context::CompletionContext,
+    completion_item::{CompletionKind, Completions},
+};
+
+pub use crate::{
+    completion_config::CompletionConfig,
+    completion_item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat},
+};
+
+//FIXME: split the following feature into fine-grained features.
+
+// Feature: Magic Completions
+//
+// In addition to usual reference completion, rust-analyzer provides some ✨magic✨
+// completions as well:
+//
+// Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
+// is placed at the appropriate position. Even though `if` is easy to type, you
+// still want to complete it, to get ` { }` for free! `return` is inserted with a
+// space or `;` depending on the return type of the function.
+//
+// When completing a function call, `()` are automatically inserted. If a function
+// takes arguments, the cursor is positioned inside the parenthesis.
+//
+// There are postfix completions, which can be triggered by typing something like
+// `foo().if`. The word after `.` determines postfix completion. Possible variants are:
+//
+// - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
+// - `expr.match` -> `match expr {}`
+// - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
+// - `expr.ref` -> `&expr`
+// - `expr.refm` -> `&mut expr`
+// - `expr.not` -> `!expr`
+// - `expr.dbg` -> `dbg!(expr)`
+// - `expr.dbgr` -> `dbg!(&expr)`
+// - `expr.call` -> `(expr)`
+//
+// There also snippet completions:
+//
+// .Expressions
+// - `pd` -> `eprintln!(" = {:?}", );`
+// - `ppd` -> `eprintln!(" = {:#?}", );`
+//
+// .Items
+// - `tfn` -> `#[test] fn feature(){}`
+// - `tmod` ->
+// ```rust
+// #[cfg(test)]
+// mod tests {
+//     use super::*;
+//
+//     #[test]
+//     fn test_name() {}
+// }
+// ```
+
+/// Main entry point for completion. We run completion as a two-phase process.
+///
+/// First, we look at the position and collect a so-called `CompletionContext.
+/// This is a somewhat messy process, because, during completion, syntax tree is
+/// incomplete and can look really weird.
+///
+/// Once the context is collected, we run a series of completion routines which
+/// look at the context and produce completion items. One subtlety about this
+/// phase is that completion engine should not filter by the substring which is
+/// already present, it should give all possible variants for the identifier at
+/// the caret. In other words, for
+///
+/// ```no_run
+/// fn f() {
+///     let foo = 92;
+///     let _ = bar<|>
+/// }
+/// ```
+///
+/// `foo` *should* be present among the completion variants. Filtering by
+/// identifier prefix/fuzzy match should be done higher in the stack, together
+/// with ordering of completions (currently this is done by the client).
+pub fn completions(
+    db: &RootDatabase,
+    config: &CompletionConfig,
+    position: FilePosition,
+) -> Option<Completions> {
+    let ctx = CompletionContext::new(db, position, config)?;
+
+    if ctx.no_completion_required() {
+        // No work required here.
+        return None;
+    }
+
+    let mut acc = Completions::default();
+    complete_attribute::complete_attribute(&mut acc, &ctx);
+    complete_fn_param::complete_fn_param(&mut acc, &ctx);
+    complete_keyword::complete_expr_keyword(&mut acc, &ctx);
+    complete_keyword::complete_use_tree_keyword(&mut acc, &ctx);
+    complete_snippet::complete_expr_snippet(&mut acc, &ctx);
+    complete_snippet::complete_item_snippet(&mut acc, &ctx);
+    complete_qualified_path::complete_qualified_path(&mut acc, &ctx);
+    complete_unqualified_path::complete_unqualified_path(&mut acc, &ctx);
+    complete_dot::complete_dot(&mut acc, &ctx);
+    complete_record::complete_record(&mut acc, &ctx);
+    complete_pattern::complete_pattern(&mut acc, &ctx);
+    complete_postfix::complete_postfix(&mut acc, &ctx);
+    complete_macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
+    complete_trait_impl::complete_trait_impl(&mut acc, &ctx);
+    complete_mod::complete_mod(&mut acc, &ctx);
+
+    Some(acc)
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::completion_config::CompletionConfig;
+    use crate::test_utils;
+
+    struct DetailAndDocumentation<'a> {
+        detail: &'a str,
+        documentation: &'a str,
+    }
+
+    fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
+        let (db, position) = test_utils::position(ra_fixture);
+        let config = CompletionConfig::default();
+        let completions: Vec<_> = crate::completions(&db, &config, position).unwrap().into();
+        for item in completions {
+            if item.detail() == Some(expected.detail) {
+                let opt = item.documentation();
+                let doc = opt.as_ref().map(|it| it.as_str());
+                assert_eq!(doc, Some(expected.documentation));
+                return;
+            }
+        }
+        panic!("completion detail not found: {}", expected.detail)
+    }
+
+    fn check_no_completion(ra_fixture: &str) {
+        let (db, position) = test_utils::position(ra_fixture);
+        let config = CompletionConfig::default();
+
+        let completions: Option<Vec<String>> = crate::completions(&db, &config, position)
+            .and_then(|completions| {
+                let completions: Vec<_> = completions.into();
+                if completions.is_empty() {
+                    None
+                } else {
+                    Some(completions)
+                }
+            })
+            .map(|completions| {
+                completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
+            });
+
+        // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
+        assert_eq!(completions, None, "Completions were generated, but weren't expected");
+    }
+
+    #[test]
+    fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
+        check_detail_and_documentation(
+            r#"
+            //- /lib.rs
+            macro_rules! bar {
+                () => {
+                    struct Bar;
+                    impl Bar {
+                        #[doc = "Do the foo"]
+                        fn foo(&self) {}
+                    }
+                }
+            }
+
+            bar!();
+
+            fn foo() {
+                let bar = Bar;
+                bar.fo<|>;
+            }
+            "#,
+            DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
+        );
+    }
+
+    #[test]
+    fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
+        check_detail_and_documentation(
+            r#"
+            //- /lib.rs
+            macro_rules! bar {
+                () => {
+                    struct Bar;
+                    impl Bar {
+                        /// Do the foo
+                        fn foo(&self) {}
+                    }
+                }
+            }
+
+            bar!();
+
+            fn foo() {
+                let bar = Bar;
+                bar.fo<|>;
+            }
+            "#,
+            DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
+        );
+    }
+
+    #[test]
+    fn test_no_completions_required() {
+        // There must be no hint for 'in' keyword.
+        check_no_completion(
+            r#"
+            fn foo() {
+                for i i<|>
+            }
+            "#,
+        );
+        // After 'in' keyword hints may be spawned.
+        check_detail_and_documentation(
+            r#"
+            /// Do the foo
+            fn foo() -> &'static str { "foo" }
+
+            fn bar() {
+                for c in fo<|>
+            }
+            "#,
+            DetailAndDocumentation {
+                detail: "fn foo() -> &'static str",
+                documentation: "Do the foo",
+            },
+        );
+    }
+}
diff --git a/crates/completion/src/patterns.rs b/crates/completion/src/patterns.rs
new file mode 100644 (file)
index 0000000..b0f35f9
--- /dev/null
@@ -0,0 +1,249 @@
+//! Patterns telling us certain facts about current syntax element, they are used in completion context
+
+use syntax::{
+    algo::non_trivia_sibling,
+    ast::{self, LoopBodyOwner},
+    match_ast, AstNode, Direction, NodeOrToken, SyntaxElement,
+    SyntaxKind::*,
+    SyntaxNode, SyntaxToken,
+};
+
+#[cfg(test)]
+use crate::test_utils::{check_pattern_is_applicable, check_pattern_is_not_applicable};
+
+pub(crate) fn has_trait_parent(element: SyntaxElement) -> bool {
+    not_same_range_ancestor(element)
+        .filter(|it| it.kind() == ASSOC_ITEM_LIST)
+        .and_then(|it| it.parent())
+        .filter(|it| it.kind() == TRAIT)
+        .is_some()
+}
+#[test]
+fn test_has_trait_parent() {
+    check_pattern_is_applicable(r"trait A { f<|> }", has_trait_parent);
+}
+
+pub(crate) fn has_impl_parent(element: SyntaxElement) -> bool {
+    not_same_range_ancestor(element)
+        .filter(|it| it.kind() == ASSOC_ITEM_LIST)
+        .and_then(|it| it.parent())
+        .filter(|it| it.kind() == IMPL)
+        .is_some()
+}
+#[test]
+fn test_has_impl_parent() {
+    check_pattern_is_applicable(r"impl A { f<|> }", has_impl_parent);
+}
+
+pub(crate) fn inside_impl_trait_block(element: SyntaxElement) -> bool {
+    // Here we search `impl` keyword up through the all ancestors, unlike in `has_impl_parent`,
+    // where we only check the first parent with different text range.
+    element
+        .ancestors()
+        .find(|it| it.kind() == IMPL)
+        .map(|it| ast::Impl::cast(it).unwrap())
+        .map(|it| it.trait_().is_some())
+        .unwrap_or(false)
+}
+#[test]
+fn test_inside_impl_trait_block() {
+    check_pattern_is_applicable(r"impl Foo for Bar { f<|> }", inside_impl_trait_block);
+    check_pattern_is_applicable(r"impl Foo for Bar { fn f<|> }", inside_impl_trait_block);
+    check_pattern_is_not_applicable(r"impl A { f<|> }", inside_impl_trait_block);
+    check_pattern_is_not_applicable(r"impl A { fn f<|> }", inside_impl_trait_block);
+}
+
+pub(crate) fn has_field_list_parent(element: SyntaxElement) -> bool {
+    not_same_range_ancestor(element).filter(|it| it.kind() == RECORD_FIELD_LIST).is_some()
+}
+#[test]
+fn test_has_field_list_parent() {
+    check_pattern_is_applicable(r"struct Foo { f<|> }", has_field_list_parent);
+    check_pattern_is_applicable(r"struct Foo { f<|> pub f: i32}", has_field_list_parent);
+}
+
+pub(crate) fn has_block_expr_parent(element: SyntaxElement) -> bool {
+    not_same_range_ancestor(element).filter(|it| it.kind() == BLOCK_EXPR).is_some()
+}
+#[test]
+fn test_has_block_expr_parent() {
+    check_pattern_is_applicable(r"fn my_fn() { let a = 2; f<|> }", has_block_expr_parent);
+}
+
+pub(crate) fn has_bind_pat_parent(element: SyntaxElement) -> bool {
+    element.ancestors().find(|it| it.kind() == IDENT_PAT).is_some()
+}
+#[test]
+fn test_has_bind_pat_parent() {
+    check_pattern_is_applicable(r"fn my_fn(m<|>) {}", has_bind_pat_parent);
+    check_pattern_is_applicable(r"fn my_fn() { let m<|> }", has_bind_pat_parent);
+}
+
+pub(crate) fn has_ref_parent(element: SyntaxElement) -> bool {
+    not_same_range_ancestor(element)
+        .filter(|it| it.kind() == REF_PAT || it.kind() == REF_EXPR)
+        .is_some()
+}
+#[test]
+fn test_has_ref_parent() {
+    check_pattern_is_applicable(r"fn my_fn(&m<|>) {}", has_ref_parent);
+    check_pattern_is_applicable(r"fn my() { let &m<|> }", has_ref_parent);
+}
+
+pub(crate) fn has_item_list_or_source_file_parent(element: SyntaxElement) -> bool {
+    let ancestor = not_same_range_ancestor(element);
+    if !ancestor.is_some() {
+        return true;
+    }
+    ancestor.filter(|it| it.kind() == SOURCE_FILE || it.kind() == ITEM_LIST).is_some()
+}
+#[test]
+fn test_has_item_list_or_source_file_parent() {
+    check_pattern_is_applicable(r"i<|>", has_item_list_or_source_file_parent);
+    check_pattern_is_applicable(r"mod foo { f<|> }", has_item_list_or_source_file_parent);
+}
+
+pub(crate) fn is_match_arm(element: SyntaxElement) -> bool {
+    not_same_range_ancestor(element.clone()).filter(|it| it.kind() == MATCH_ARM).is_some()
+        && previous_sibling_or_ancestor_sibling(element)
+            .and_then(|it| it.into_token())
+            .filter(|it| it.kind() == FAT_ARROW)
+            .is_some()
+}
+#[test]
+fn test_is_match_arm() {
+    check_pattern_is_applicable(r"fn my_fn() { match () { () => m<|> } }", is_match_arm);
+}
+
+pub(crate) fn unsafe_is_prev(element: SyntaxElement) -> bool {
+    element
+        .into_token()
+        .and_then(|it| previous_non_trivia_token(it))
+        .filter(|it| it.kind() == UNSAFE_KW)
+        .is_some()
+}
+#[test]
+fn test_unsafe_is_prev() {
+    check_pattern_is_applicable(r"unsafe i<|>", unsafe_is_prev);
+}
+
+pub(crate) fn if_is_prev(element: SyntaxElement) -> bool {
+    element
+        .into_token()
+        .and_then(|it| previous_non_trivia_token(it))
+        .filter(|it| it.kind() == IF_KW)
+        .is_some()
+}
+
+pub(crate) fn fn_is_prev(element: SyntaxElement) -> bool {
+    element
+        .into_token()
+        .and_then(|it| previous_non_trivia_token(it))
+        .filter(|it| it.kind() == FN_KW)
+        .is_some()
+}
+#[test]
+fn test_fn_is_prev() {
+    check_pattern_is_applicable(r"fn l<|>", fn_is_prev);
+}
+
+/// Check if the token previous to the previous one is `for`.
+/// For example, `for _ i<|>` => true.
+pub(crate) fn for_is_prev2(element: SyntaxElement) -> bool {
+    element
+        .into_token()
+        .and_then(|it| previous_non_trivia_token(it))
+        .and_then(|it| previous_non_trivia_token(it))
+        .filter(|it| it.kind() == FOR_KW)
+        .is_some()
+}
+#[test]
+fn test_for_is_prev2() {
+    check_pattern_is_applicable(r"for i i<|>", for_is_prev2);
+}
+
+#[test]
+fn test_if_is_prev() {
+    check_pattern_is_applicable(r"if l<|>", if_is_prev);
+}
+
+pub(crate) fn has_trait_as_prev_sibling(element: SyntaxElement) -> bool {
+    previous_sibling_or_ancestor_sibling(element).filter(|it| it.kind() == TRAIT).is_some()
+}
+#[test]
+fn test_has_trait_as_prev_sibling() {
+    check_pattern_is_applicable(r"trait A w<|> {}", has_trait_as_prev_sibling);
+}
+
+pub(crate) fn has_impl_as_prev_sibling(element: SyntaxElement) -> bool {
+    previous_sibling_or_ancestor_sibling(element).filter(|it| it.kind() == IMPL).is_some()
+}
+#[test]
+fn test_has_impl_as_prev_sibling() {
+    check_pattern_is_applicable(r"impl A w<|> {}", has_impl_as_prev_sibling);
+}
+
+pub(crate) fn is_in_loop_body(element: SyntaxElement) -> bool {
+    let leaf = match element {
+        NodeOrToken::Node(node) => node,
+        NodeOrToken::Token(token) => token.parent(),
+    };
+    for node in leaf.ancestors() {
+        if node.kind() == FN || node.kind() == CLOSURE_EXPR {
+            break;
+        }
+        let loop_body = match_ast! {
+            match node {
+                ast::ForExpr(it) => it.loop_body(),
+                ast::WhileExpr(it) => it.loop_body(),
+                ast::LoopExpr(it) => it.loop_body(),
+                _ => None,
+            }
+        };
+        if let Some(body) = loop_body {
+            if body.syntax().text_range().contains_range(leaf.text_range()) {
+                return true;
+            }
+        }
+    }
+    false
+}
+
+fn not_same_range_ancestor(element: SyntaxElement) -> Option<SyntaxNode> {
+    element
+        .ancestors()
+        .take_while(|it| it.text_range() == element.text_range())
+        .last()
+        .and_then(|it| it.parent())
+}
+
+fn previous_non_trivia_token(token: SyntaxToken) -> Option<SyntaxToken> {
+    let mut token = token.prev_token();
+    while let Some(inner) = token.clone() {
+        if !inner.kind().is_trivia() {
+            return Some(inner);
+        } else {
+            token = inner.prev_token();
+        }
+    }
+    None
+}
+
+fn previous_sibling_or_ancestor_sibling(element: SyntaxElement) -> Option<SyntaxElement> {
+    let token_sibling = non_trivia_sibling(element.clone(), Direction::Prev);
+    if let Some(sibling) = token_sibling {
+        Some(sibling)
+    } else {
+        // if not trying to find first ancestor which has such a sibling
+        let node = match element {
+            NodeOrToken::Node(node) => node,
+            NodeOrToken::Token(token) => token.parent(),
+        };
+        let range = node.text_range();
+        let top_node = node.ancestors().take_while(|it| it.text_range() == range).last()?;
+        let prev_sibling_node = top_node.ancestors().find(|it| {
+            non_trivia_sibling(NodeOrToken::Node(it.to_owned()), Direction::Prev).is_some()
+        })?;
+        non_trivia_sibling(NodeOrToken::Node(prev_sibling_node), Direction::Prev)
+    }
+}
diff --git a/crates/completion/src/presentation.rs b/crates/completion/src/presentation.rs
new file mode 100644 (file)
index 0000000..0a0dc1c
--- /dev/null
@@ -0,0 +1,1341 @@
+//! This modules takes care of rendering various definitions as completion items.
+//! It also handles scoring (sorting) completions.
+
+use hir::{HasAttrs, HasSource, HirDisplay, ModPath, ScopeDef, StructKind, Type};
+use itertools::Itertools;
+use syntax::{ast::NameOwner, display::*};
+use test_utils::mark;
+
+use crate::{
+    // display::{const_label, function_declaration, macro_label, type_label},
+    CompletionScore,
+    RootDatabase,
+    {
+        completion_item::Builder, CompletionContext, CompletionItem, CompletionItemKind,
+        CompletionKind, Completions,
+    },
+};
+
+impl Completions {
+    pub(crate) fn add_field(&mut self, ctx: &CompletionContext, field: hir::Field, ty: &Type) {
+        let is_deprecated = is_deprecated(field, ctx.db);
+        let name = field.name(ctx.db);
+        let mut completion_item =
+            CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.to_string())
+                .kind(CompletionItemKind::Field)
+                .detail(ty.display(ctx.db).to_string())
+                .set_documentation(field.docs(ctx.db))
+                .set_deprecated(is_deprecated);
+
+        if let Some(score) = compute_score(ctx, &ty, &name.to_string()) {
+            completion_item = completion_item.set_score(score);
+        }
+
+        completion_item.add_to(self);
+    }
+
+    pub(crate) fn add_tuple_field(&mut self, ctx: &CompletionContext, field: usize, ty: &Type) {
+        CompletionItem::new(CompletionKind::Reference, ctx.source_range(), field.to_string())
+            .kind(CompletionItemKind::Field)
+            .detail(ty.display(ctx.db).to_string())
+            .add_to(self);
+    }
+
+    pub(crate) fn add_resolution(
+        &mut self,
+        ctx: &CompletionContext,
+        local_name: String,
+        resolution: &ScopeDef,
+    ) {
+        use hir::ModuleDef::*;
+
+        let completion_kind = match resolution {
+            ScopeDef::ModuleDef(BuiltinType(..)) => CompletionKind::BuiltinType,
+            _ => CompletionKind::Reference,
+        };
+
+        let kind = match resolution {
+            ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::Module,
+            ScopeDef::ModuleDef(Function(func)) => {
+                return self.add_function(ctx, *func, Some(local_name));
+            }
+            ScopeDef::ModuleDef(Adt(hir::Adt::Struct(_))) => CompletionItemKind::Struct,
+            // FIXME: add CompletionItemKind::Union
+            ScopeDef::ModuleDef(Adt(hir::Adt::Union(_))) => CompletionItemKind::Struct,
+            ScopeDef::ModuleDef(Adt(hir::Adt::Enum(_))) => CompletionItemKind::Enum,
+
+            ScopeDef::ModuleDef(EnumVariant(var)) => {
+                return self.add_enum_variant(ctx, *var, Some(local_name));
+            }
+            ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::Const,
+            ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::Static,
+            ScopeDef::ModuleDef(Trait(..)) => CompletionItemKind::Trait,
+            ScopeDef::ModuleDef(TypeAlias(..)) => CompletionItemKind::TypeAlias,
+            ScopeDef::ModuleDef(BuiltinType(..)) => CompletionItemKind::BuiltinType,
+            ScopeDef::GenericParam(..) => CompletionItemKind::TypeParam,
+            ScopeDef::Local(..) => CompletionItemKind::Binding,
+            // (does this need its own kind?)
+            ScopeDef::AdtSelfType(..) | ScopeDef::ImplSelfType(..) => CompletionItemKind::TypeParam,
+            ScopeDef::MacroDef(mac) => {
+                return self.add_macro(ctx, Some(local_name), *mac);
+            }
+            ScopeDef::Unknown => {
+                return self.add(
+                    CompletionItem::new(CompletionKind::Reference, ctx.source_range(), local_name)
+                        .kind(CompletionItemKind::UnresolvedReference),
+                );
+            }
+        };
+
+        let docs = match resolution {
+            ScopeDef::ModuleDef(Module(it)) => it.docs(ctx.db),
+            ScopeDef::ModuleDef(Adt(it)) => it.docs(ctx.db),
+            ScopeDef::ModuleDef(EnumVariant(it)) => it.docs(ctx.db),
+            ScopeDef::ModuleDef(Const(it)) => it.docs(ctx.db),
+            ScopeDef::ModuleDef(Static(it)) => it.docs(ctx.db),
+            ScopeDef::ModuleDef(Trait(it)) => it.docs(ctx.db),
+            ScopeDef::ModuleDef(TypeAlias(it)) => it.docs(ctx.db),
+            _ => None,
+        };
+
+        let mut completion_item =
+            CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone());
+        if let ScopeDef::Local(local) = resolution {
+            let ty = local.ty(ctx.db);
+            if !ty.is_unknown() {
+                completion_item = completion_item.detail(ty.display(ctx.db).to_string());
+            }
+        };
+
+        if let ScopeDef::Local(local) = resolution {
+            if let Some(score) = compute_score(ctx, &local.ty(ctx.db), &local_name) {
+                completion_item = completion_item.set_score(score);
+            }
+        }
+
+        // Add `<>` for generic types
+        if ctx.is_path_type && !ctx.has_type_args && ctx.config.add_call_parenthesis {
+            if let Some(cap) = ctx.config.snippet_cap {
+                let has_non_default_type_params = match resolution {
+                    ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db),
+                    ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db),
+                    _ => false,
+                };
+                if has_non_default_type_params {
+                    mark::hit!(inserts_angle_brackets_for_generics);
+                    completion_item = completion_item
+                        .lookup_by(local_name.clone())
+                        .label(format!("{}<…>", local_name))
+                        .insert_snippet(cap, format!("{}<$0>", local_name));
+                }
+            }
+        }
+
+        completion_item.kind(kind).set_documentation(docs).add_to(self)
+    }
+
+    pub(crate) fn add_macro(
+        &mut self,
+        ctx: &CompletionContext,
+        name: Option<String>,
+        macro_: hir::MacroDef,
+    ) {
+        // FIXME: Currently proc-macro do not have ast-node,
+        // such that it does not have source
+        if macro_.is_proc_macro() {
+            return;
+        }
+
+        let name = match name {
+            Some(it) => it,
+            None => return,
+        };
+
+        let ast_node = macro_.source(ctx.db).value;
+        let detail = macro_label(&ast_node);
+
+        let docs = macro_.docs(ctx.db);
+
+        let mut builder = CompletionItem::new(
+            CompletionKind::Reference,
+            ctx.source_range(),
+            &format!("{}!", name),
+        )
+        .kind(CompletionItemKind::Macro)
+        .set_documentation(docs.clone())
+        .set_deprecated(is_deprecated(macro_, ctx.db))
+        .detail(detail);
+
+        let needs_bang = ctx.use_item_syntax.is_none() && !ctx.is_macro_call;
+        builder = match ctx.config.snippet_cap {
+            Some(cap) if needs_bang => {
+                let docs = docs.as_ref().map_or("", |s| s.as_str());
+                let (bra, ket) = guess_macro_braces(&name, docs);
+                builder
+                    .insert_snippet(cap, format!("{}!{}$0{}", name, bra, ket))
+                    .label(format!("{}!{}…{}", name, bra, ket))
+                    .lookup_by(format!("{}!", name))
+            }
+            None if needs_bang => builder.insert_text(format!("{}!", name)),
+            _ => {
+                mark::hit!(dont_insert_macro_call_parens_unncessary);
+                builder.insert_text(name)
+            }
+        };
+
+        self.add(builder);
+    }
+
+    pub(crate) fn add_function(
+        &mut self,
+        ctx: &CompletionContext,
+        func: hir::Function,
+        local_name: Option<String>,
+    ) {
+        fn add_arg(arg: &str, ty: &Type, ctx: &CompletionContext) -> String {
+            if let Some(derefed_ty) = ty.remove_ref() {
+                for (name, local) in ctx.locals.iter() {
+                    if name == arg && local.ty(ctx.db) == derefed_ty {
+                        return (if ty.is_mutable_reference() { "&mut " } else { "&" }).to_string()
+                            + &arg.to_string();
+                    }
+                }
+            }
+            arg.to_string()
+        };
+        let name = local_name.unwrap_or_else(|| func.name(ctx.db).to_string());
+        let ast_node = func.source(ctx.db).value;
+
+        let mut builder =
+            CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.clone())
+                .kind(if func.self_param(ctx.db).is_some() {
+                    CompletionItemKind::Method
+                } else {
+                    CompletionItemKind::Function
+                })
+                .set_documentation(func.docs(ctx.db))
+                .set_deprecated(is_deprecated(func, ctx.db))
+                .detail(function_declaration(&ast_node));
+
+        let params_ty = func.params(ctx.db);
+        let params = ast_node
+            .param_list()
+            .into_iter()
+            .flat_map(|it| it.params())
+            .zip(params_ty)
+            .flat_map(|(it, param_ty)| {
+                if let Some(pat) = it.pat() {
+                    let name = pat.to_string();
+                    let arg = name.trim_start_matches("mut ").trim_start_matches('_');
+                    return Some(add_arg(arg, param_ty.ty(), ctx));
+                }
+                None
+            })
+            .collect();
+
+        builder = builder.add_call_parens(ctx, name, Params::Named(params));
+
+        self.add(builder)
+    }
+
+    pub(crate) fn add_const(&mut self, ctx: &CompletionContext, constant: hir::Const) {
+        let ast_node = constant.source(ctx.db).value;
+        let name = match ast_node.name() {
+            Some(name) => name,
+            _ => return,
+        };
+        let detail = const_label(&ast_node);
+
+        CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.text().to_string())
+            .kind(CompletionItemKind::Const)
+            .set_documentation(constant.docs(ctx.db))
+            .set_deprecated(is_deprecated(constant, ctx.db))
+            .detail(detail)
+            .add_to(self);
+    }
+
+    pub(crate) fn add_type_alias(&mut self, ctx: &CompletionContext, type_alias: hir::TypeAlias) {
+        let type_def = type_alias.source(ctx.db).value;
+        let name = match type_def.name() {
+            Some(name) => name,
+            _ => return,
+        };
+        let detail = type_label(&type_def);
+
+        CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.text().to_string())
+            .kind(CompletionItemKind::TypeAlias)
+            .set_documentation(type_alias.docs(ctx.db))
+            .set_deprecated(is_deprecated(type_alias, ctx.db))
+            .detail(detail)
+            .add_to(self);
+    }
+
+    pub(crate) fn add_qualified_enum_variant(
+        &mut self,
+        ctx: &CompletionContext,
+        variant: hir::EnumVariant,
+        path: ModPath,
+    ) {
+        self.add_enum_variant_impl(ctx, variant, None, Some(path))
+    }
+
+    pub(crate) fn add_enum_variant(
+        &mut self,
+        ctx: &CompletionContext,
+        variant: hir::EnumVariant,
+        local_name: Option<String>,
+    ) {
+        self.add_enum_variant_impl(ctx, variant, local_name, None)
+    }
+
+    fn add_enum_variant_impl(
+        &mut self,
+        ctx: &CompletionContext,
+        variant: hir::EnumVariant,
+        local_name: Option<String>,
+        path: Option<ModPath>,
+    ) {
+        let is_deprecated = is_deprecated(variant, ctx.db);
+        let name = local_name.unwrap_or_else(|| variant.name(ctx.db).to_string());
+        let qualified_name = match &path {
+            Some(it) => it.to_string(),
+            None => name.to_string(),
+        };
+        let detail_types = variant
+            .fields(ctx.db)
+            .into_iter()
+            .map(|field| (field.name(ctx.db), field.signature_ty(ctx.db)));
+        let variant_kind = variant.kind(ctx.db);
+        let detail = match variant_kind {
+            StructKind::Tuple | StructKind::Unit => format!(
+                "({})",
+                detail_types.map(|(_, t)| t.display(ctx.db).to_string()).format(", ")
+            ),
+            StructKind::Record => format!(
+                "{{ {} }}",
+                detail_types
+                    .map(|(n, t)| format!("{}: {}", n, t.display(ctx.db).to_string()))
+                    .format(", ")
+            ),
+        };
+        let mut res = CompletionItem::new(
+            CompletionKind::Reference,
+            ctx.source_range(),
+            qualified_name.clone(),
+        )
+        .kind(CompletionItemKind::EnumVariant)
+        .set_documentation(variant.docs(ctx.db))
+        .set_deprecated(is_deprecated)
+        .detail(detail);
+
+        if path.is_some() {
+            res = res.lookup_by(name);
+        }
+
+        if variant_kind == StructKind::Tuple {
+            mark::hit!(inserts_parens_for_tuple_enums);
+            let params = Params::Anonymous(variant.fields(ctx.db).len());
+            res = res.add_call_parens(ctx, qualified_name, params)
+        }
+
+        res.add_to(self);
+    }
+}
+
+pub(crate) fn compute_score(
+    ctx: &CompletionContext,
+    ty: &Type,
+    name: &str,
+) -> Option<CompletionScore> {
+    let (active_name, active_type) = if let Some(record_field) = &ctx.record_field_syntax {
+        mark::hit!(record_field_type_match);
+        let (struct_field, _local) = ctx.sema.resolve_record_field(record_field)?;
+        (struct_field.name(ctx.db).to_string(), struct_field.signature_ty(ctx.db))
+    } else if let Some(active_parameter) = &ctx.active_parameter {
+        mark::hit!(active_param_type_match);
+        (active_parameter.name.clone(), active_parameter.ty.clone())
+    } else {
+        return None;
+    };
+
+    // Compute score
+    // For the same type
+    if &active_type != ty {
+        return None;
+    }
+
+    let mut res = CompletionScore::TypeMatch;
+
+    // If same type + same name then go top position
+    if active_name == name {
+        res = CompletionScore::TypeAndNameMatch
+    }
+
+    Some(res)
+}
+
+enum Params {
+    Named(Vec<String>),
+    Anonymous(usize),
+}
+
+impl Params {
+    fn len(&self) -> usize {
+        match self {
+            Params::Named(xs) => xs.len(),
+            Params::Anonymous(len) => *len,
+        }
+    }
+
+    fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+}
+
+impl Builder {
+    fn add_call_parens(mut self, ctx: &CompletionContext, name: String, params: Params) -> Builder {
+        if !ctx.config.add_call_parenthesis {
+            return self;
+        }
+        if ctx.use_item_syntax.is_some() {
+            mark::hit!(no_parens_in_use_item);
+            return self;
+        }
+        if ctx.is_pattern_call {
+            mark::hit!(dont_duplicate_pattern_parens);
+            return self;
+        }
+        if ctx.is_call {
+            return self;
+        }
+
+        // Don't add parentheses if the expected type is some function reference.
+        if let Some(ty) = &ctx.expected_type {
+            if ty.is_fn() {
+                mark::hit!(no_call_parens_if_fn_ptr_needed);
+                return self;
+            }
+        }
+
+        let cap = match ctx.config.snippet_cap {
+            Some(it) => it,
+            None => return self,
+        };
+        // If not an import, add parenthesis automatically.
+        mark::hit!(inserts_parens_for_function_calls);
+
+        let (snippet, label) = if params.is_empty() {
+            (format!("{}()$0", name), format!("{}()", name))
+        } else {
+            self = self.trigger_call_info();
+            let snippet = match (ctx.config.add_call_argument_snippets, params) {
+                (true, Params::Named(params)) => {
+                    let function_params_snippet =
+                        params.iter().enumerate().format_with(", ", |(index, param_name), f| {
+                            f(&format_args!("${{{}:{}}}", index + 1, param_name))
+                        });
+                    format!("{}({})$0", name, function_params_snippet)
+                }
+                _ => {
+                    mark::hit!(suppress_arg_snippets);
+                    format!("{}($0)", name)
+                }
+            };
+
+            (snippet, format!("{}(…)", name))
+        };
+        self.lookup_by(name).label(label).insert_snippet(cap, snippet)
+    }
+}
+
+fn is_deprecated(node: impl HasAttrs, db: &RootDatabase) -> bool {
+    node.attrs(db).by_key("deprecated").exists()
+}
+
+fn guess_macro_braces(macro_name: &str, docs: &str) -> (&'static str, &'static str) {
+    let mut votes = [0, 0, 0];
+    for (idx, s) in docs.match_indices(&macro_name) {
+        let (before, after) = (&docs[..idx], &docs[idx + s.len()..]);
+        // Ensure to match the full word
+        if after.starts_with('!')
+            && !before.ends_with(|c: char| c == '_' || c.is_ascii_alphanumeric())
+        {
+            // It may have spaces before the braces like `foo! {}`
+            match after[1..].chars().find(|&c| !c.is_whitespace()) {
+                Some('{') => votes[0] += 1,
+                Some('[') => votes[1] += 1,
+                Some('(') => votes[2] += 1,
+                _ => {}
+            }
+        }
+    }
+
+    // Insert a space before `{}`.
+    // We prefer the last one when some votes equal.
+    let (_vote, (bra, ket)) = votes
+        .iter()
+        .zip(&[(" {", "}"), ("[", "]"), ("(", ")")])
+        .max_by_key(|&(&vote, _)| vote)
+        .unwrap();
+    (*bra, *ket)
+}
+
+#[cfg(test)]
+mod tests {
+    use std::cmp::Reverse;
+
+    use expect_test::{expect, Expect};
+    use test_utils::mark;
+
+    use crate::{
+        test_utils::{check_edit, check_edit_with_config, do_completion, get_all_completion_items},
+        CompletionConfig, CompletionKind, CompletionScore,
+    };
+
+    fn check(ra_fixture: &str, expect: Expect) {
+        let actual = do_completion(ra_fixture, CompletionKind::Reference);
+        expect.assert_debug_eq(&actual);
+    }
+
+    fn check_scores(ra_fixture: &str, expect: Expect) {
+        fn display_score(score: Option<CompletionScore>) -> &'static str {
+            match score {
+                Some(CompletionScore::TypeMatch) => "[type]",
+                Some(CompletionScore::TypeAndNameMatch) => "[type+name]",
+                None => "[]".into(),
+            }
+        }
+
+        let mut completions = get_all_completion_items(CompletionConfig::default(), ra_fixture);
+        completions.sort_by_key(|it| (Reverse(it.score()), it.label().to_string()));
+        let actual = completions
+            .into_iter()
+            .filter(|it| it.completion_kind == CompletionKind::Reference)
+            .map(|it| {
+                let tag = it.kind().unwrap().tag();
+                let score = display_score(it.score());
+                format!("{} {} {}\n", tag, it.label(), score)
+            })
+            .collect::<String>();
+        expect.assert_eq(&actual);
+    }
+
+    #[test]
+    fn enum_detail_includes_record_fields() {
+        check(
+            r#"
+enum Foo { Foo { x: i32, y: i32 } }
+
+fn main() { Foo::Fo<|> }
+"#,
+            expect![[r#"
+                [
+                    CompletionItem {
+                        label: "Foo",
+                        source_range: 54..56,
+                        delete: 54..56,
+                        insert: "Foo",
+                        kind: EnumVariant,
+                        detail: "{ x: i32, y: i32 }",
+                    },
+                ]
+            "#]],
+        );
+    }
+
+    #[test]
+    fn enum_detail_doesnt_include_tuple_fields() {
+        check(
+            r#"
+enum Foo { Foo (i32, i32) }
+
+fn main() { Foo::Fo<|> }
+"#,
+            expect![[r#"
+                [
+                    CompletionItem {
+                        label: "Foo(…)",
+                        source_range: 46..48,
+                        delete: 46..48,
+                        insert: "Foo($0)",
+                        kind: EnumVariant,
+                        lookup: "Foo",
+                        detail: "(i32, i32)",
+                        trigger_call_info: true,
+                    },
+                ]
+            "#]],
+        );
+    }
+
+    #[test]
+    fn enum_detail_just_parentheses_for_unit() {
+        check(
+            r#"
+enum Foo { Foo }
+
+fn main() { Foo::Fo<|> }
+"#,
+            expect![[r#"
+                [
+                    CompletionItem {
+                        label: "Foo",
+                        source_range: 35..37,
+                        delete: 35..37,
+                        insert: "Foo",
+                        kind: EnumVariant,
+                        detail: "()",
+                    },
+                ]
+            "#]],
+        );
+    }
+
+    #[test]
+    fn sets_deprecated_flag_in_completion_items() {
+        check(
+            r#"
+#[deprecated]
+fn something_deprecated() {}
+#[deprecated(since = "1.0.0")]
+fn something_else_deprecated() {}
+
+fn main() { som<|> }
+"#,
+            expect![[r#"
+                [
+                    CompletionItem {
+                        label: "main()",
+                        source_range: 121..124,
+                        delete: 121..124,
+                        insert: "main()$0",
+                        kind: Function,
+                        lookup: "main",
+                        detail: "fn main()",
+                    },
+                    CompletionItem {
+                        label: "something_deprecated()",
+                        source_range: 121..124,
+                        delete: 121..124,
+                        insert: "something_deprecated()$0",
+                        kind: Function,
+                        lookup: "something_deprecated",
+                        detail: "fn something_deprecated()",
+                        deprecated: true,
+                    },
+                    CompletionItem {
+                        label: "something_else_deprecated()",
+                        source_range: 121..124,
+                        delete: 121..124,
+                        insert: "something_else_deprecated()$0",
+                        kind: Function,
+                        lookup: "something_else_deprecated",
+                        detail: "fn something_else_deprecated()",
+                        deprecated: true,
+                    },
+                ]
+            "#]],
+        );
+
+        check(
+            r#"
+struct A { #[deprecated] the_field: u32 }
+fn foo() { A { the<|> } }
+"#,
+            expect![[r#"
+                [
+                    CompletionItem {
+                        label: "the_field",
+                        source_range: 57..60,
+                        delete: 57..60,
+                        insert: "the_field",
+                        kind: Field,
+                        detail: "u32",
+                        deprecated: true,
+                    },
+                ]
+            "#]],
+        );
+    }
+
+    #[test]
+    fn renders_docs() {
+        check(
+            r#"
+struct S {
+    /// Field docs
+    foo:
+}
+impl S {
+    /// Method docs
+    fn bar(self) { self.<|> }
+}"#,
+            expect![[r#"
+                [
+                    CompletionItem {
+                        label: "bar()",
+                        source_range: 94..94,
+                        delete: 94..94,
+                        insert: "bar()$0",
+                        kind: Method,
+                        lookup: "bar",
+                        detail: "fn bar(self)",
+                        documentation: Documentation(
+                            "Method docs",
+                        ),
+                    },
+                    CompletionItem {
+                        label: "foo",
+                        source_range: 94..94,
+                        delete: 94..94,
+                        insert: "foo",
+                        kind: Field,
+                        detail: "{unknown}",
+                        documentation: Documentation(
+                            "Field docs",
+                        ),
+                    },
+                ]
+            "#]],
+        );
+
+        check(
+            r#"
+use self::my<|>;
+
+/// mod docs
+mod my { }
+
+/// enum docs
+enum E {
+    /// variant docs
+    V
+}
+use self::E::*;
+"#,
+            expect![[r#"
+                [
+                    CompletionItem {
+                        label: "E",
+                        source_range: 10..12,
+                        delete: 10..12,
+                        insert: "E",
+                        kind: Enum,
+                        documentation: Documentation(
+                            "enum docs",
+                        ),
+                    },
+                    CompletionItem {
+                        label: "V",
+                        source_range: 10..12,
+                        delete: 10..12,
+                        insert: "V",
+                        kind: EnumVariant,
+                        detail: "()",
+                        documentation: Documentation(
+                            "variant docs",
+                        ),
+                    },
+                    CompletionItem {
+                        label: "my",
+                        source_range: 10..12,
+                        delete: 10..12,
+                        insert: "my",
+                        kind: Module,
+                        documentation: Documentation(
+                            "mod docs",
+                        ),
+                    },
+                ]
+            "#]],
+        )
+    }
+
+    #[test]
+    fn dont_render_attrs() {
+        check(
+            r#"
+struct S;
+impl S {
+    #[inline]
+    fn the_method(&self) { }
+}
+fn foo(s: S) { s.<|> }
+"#,
+            expect![[r#"
+                [
+                    CompletionItem {
+                        label: "the_method()",
+                        source_range: 81..81,
+                        delete: 81..81,
+                        insert: "the_method()$0",
+                        kind: Method,
+                        lookup: "the_method",
+                        detail: "fn the_method(&self)",
+                    },
+                ]
+            "#]],
+        )
+    }
+
+    #[test]
+    fn inserts_parens_for_function_calls() {
+        mark::check!(inserts_parens_for_function_calls);
+        check_edit(
+            "no_args",
+            r#"
+fn no_args() {}
+fn main() { no_<|> }
+"#,
+            r#"
+fn no_args() {}
+fn main() { no_args()$0 }
+"#,
+        );
+
+        check_edit(
+            "with_args",
+            r#"
+fn with_args(x: i32, y: String) {}
+fn main() { with_<|> }
+"#,
+            r#"
+fn with_args(x: i32, y: String) {}
+fn main() { with_args(${1:x}, ${2:y})$0 }
+"#,
+        );
+
+        check_edit(
+            "foo",
+            r#"
+struct S;
+impl S {
+    fn foo(&self) {}
+}
+fn bar(s: &S) { s.f<|> }
+"#,
+            r#"
+struct S;
+impl S {
+    fn foo(&self) {}
+}
+fn bar(s: &S) { s.foo()$0 }
+"#,
+        );
+
+        check_edit(
+            "foo",
+            r#"
+struct S {}
+impl S {
+    fn foo(&self, x: i32) {}
+}
+fn bar(s: &S) {
+    s.f<|>
+}
+"#,
+            r#"
+struct S {}
+impl S {
+    fn foo(&self, x: i32) {}
+}
+fn bar(s: &S) {
+    s.foo(${1:x})$0
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn suppress_arg_snippets() {
+        mark::check!(suppress_arg_snippets);
+        check_edit_with_config(
+            CompletionConfig { add_call_argument_snippets: false, ..CompletionConfig::default() },
+            "with_args",
+            r#"
+fn with_args(x: i32, y: String) {}
+fn main() { with_<|> }
+"#,
+            r#"
+fn with_args(x: i32, y: String) {}
+fn main() { with_args($0) }
+"#,
+        );
+    }
+
+    #[test]
+    fn strips_underscores_from_args() {
+        check_edit(
+            "foo",
+            r#"
+fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
+fn main() { f<|> }
+"#,
+            r#"
+fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
+fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
+"#,
+        );
+    }
+
+    #[test]
+    fn insert_ref_when_matching_local_in_scope() {
+        check_edit(
+            "ref_arg",
+            r#"
+struct Foo {}
+fn ref_arg(x: &Foo) {}
+fn main() {
+    let x = Foo {};
+    ref_ar<|>
+}
+"#,
+            r#"
+struct Foo {}
+fn ref_arg(x: &Foo) {}
+fn main() {
+    let x = Foo {};
+    ref_arg(${1:&x})$0
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn insert_mut_ref_when_matching_local_in_scope() {
+        check_edit(
+            "ref_arg",
+            r#"
+struct Foo {}
+fn ref_arg(x: &mut Foo) {}
+fn main() {
+    let x = Foo {};
+    ref_ar<|>
+}
+"#,
+            r#"
+struct Foo {}
+fn ref_arg(x: &mut Foo) {}
+fn main() {
+    let x = Foo {};
+    ref_arg(${1:&mut x})$0
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn insert_ref_when_matching_local_in_scope_for_method() {
+        check_edit(
+            "apply_foo",
+            r#"
+struct Foo {}
+struct Bar {}
+impl Bar {
+    fn apply_foo(&self, x: &Foo) {}
+}
+
+fn main() {
+    let x = Foo {};
+    let y = Bar {};
+    y.<|>
+}
+"#,
+            r#"
+struct Foo {}
+struct Bar {}
+impl Bar {
+    fn apply_foo(&self, x: &Foo) {}
+}
+
+fn main() {
+    let x = Foo {};
+    let y = Bar {};
+    y.apply_foo(${1:&x})$0
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn trim_mut_keyword_in_func_completion() {
+        check_edit(
+            "take_mutably",
+            r#"
+fn take_mutably(mut x: &i32) {}
+
+fn main() {
+    take_m<|>
+}
+"#,
+            r#"
+fn take_mutably(mut x: &i32) {}
+
+fn main() {
+    take_mutably(${1:x})$0
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn inserts_parens_for_tuple_enums() {
+        mark::check!(inserts_parens_for_tuple_enums);
+        check_edit(
+            "Some",
+            r#"
+enum Option<T> { Some(T), None }
+use Option::*;
+fn main() -> Option<i32> {
+    Som<|>
+}
+"#,
+            r#"
+enum Option<T> { Some(T), None }
+use Option::*;
+fn main() -> Option<i32> {
+    Some($0)
+}
+"#,
+        );
+        check_edit(
+            "Some",
+            r#"
+enum Option<T> { Some(T), None }
+use Option::*;
+fn main(value: Option<i32>) {
+    match value {
+        Som<|>
+    }
+}
+"#,
+            r#"
+enum Option<T> { Some(T), None }
+use Option::*;
+fn main(value: Option<i32>) {
+    match value {
+        Some($0)
+    }
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn dont_duplicate_pattern_parens() {
+        mark::check!(dont_duplicate_pattern_parens);
+        check_edit(
+            "Var",
+            r#"
+enum E { Var(i32) }
+fn main() {
+    match E::Var(92) {
+        E::<|>(92) => (),
+    }
+}
+"#,
+            r#"
+enum E { Var(i32) }
+fn main() {
+    match E::Var(92) {
+        E::Var(92) => (),
+    }
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn no_call_parens_if_fn_ptr_needed() {
+        mark::check!(no_call_parens_if_fn_ptr_needed);
+        check_edit(
+            "foo",
+            r#"
+fn foo(foo: u8, bar: u8) {}
+struct ManualVtable { f: fn(u8, u8) }
+
+fn main() -> ManualVtable {
+    ManualVtable { f: f<|> }
+}
+"#,
+            r#"
+fn foo(foo: u8, bar: u8) {}
+struct ManualVtable { f: fn(u8, u8) }
+
+fn main() -> ManualVtable {
+    ManualVtable { f: foo }
+}
+"#,
+        );
+    }
+
+    #[test]
+    fn no_parens_in_use_item() {
+        mark::check!(no_parens_in_use_item);
+        check_edit(
+            "foo",
+            r#"
+mod m { pub fn foo() {} }
+use crate::m::f<|>;
+"#,
+            r#"
+mod m { pub fn foo() {} }
+use crate::m::foo;
+"#,
+        );
+    }
+
+    #[test]
+    fn no_parens_in_call() {
+        check_edit(
+            "foo",
+            r#"
+fn foo(x: i32) {}
+fn main() { f<|>(); }
+"#,
+            r#"
+fn foo(x: i32) {}
+fn main() { foo(); }
+"#,
+        );
+        check_edit(
+            "foo",
+            r#"
+struct Foo;
+impl Foo { fn foo(&self){} }
+fn f(foo: &Foo) { foo.f<|>(); }
+"#,
+            r#"
+struct Foo;
+impl Foo { fn foo(&self){} }
+fn f(foo: &Foo) { foo.foo(); }
+"#,
+        );
+    }
+
+    #[test]
+    fn inserts_angle_brackets_for_generics() {
+        mark::check!(inserts_angle_brackets_for_generics);
+        check_edit(
+            "Vec",
+            r#"
+struct Vec<T> {}
+fn foo(xs: Ve<|>)
+"#,
+            r#"
+struct Vec<T> {}
+fn foo(xs: Vec<$0>)
+"#,
+        );
+        check_edit(
+            "Vec",
+            r#"
+type Vec<T> = (T,);
+fn foo(xs: Ve<|>)
+"#,
+            r#"
+type Vec<T> = (T,);
+fn foo(xs: Vec<$0>)
+"#,
+        );
+        check_edit(
+            "Vec",
+            r#"
+struct Vec<T = i128> {}
+fn foo(xs: Ve<|>)
+"#,
+            r#"
+struct Vec<T = i128> {}
+fn foo(xs: Vec)
+"#,
+        );
+        check_edit(
+            "Vec",
+            r#"
+struct Vec<T> {}
+fn foo(xs: Ve<|><i128>)
+"#,
+            r#"
+struct Vec<T> {}
+fn foo(xs: Vec<i128>)
+"#,
+        );
+    }
+
+    #[test]
+    fn dont_insert_macro_call_parens_unncessary() {
+        mark::check!(dont_insert_macro_call_parens_unncessary);
+        check_edit(
+            "frobnicate!",
+            r#"
+//- /main.rs crate:main deps:foo
+use foo::<|>;
+//- /foo/lib.rs crate:foo
+#[macro_export]
+macro_rules frobnicate { () => () }
+"#,
+            r#"
+use foo::frobnicate;
+"#,
+        );
+
+        check_edit(
+            "frobnicate!",
+            r#"
+macro_rules frobnicate { () => () }
+fn main() { frob<|>!(); }
+"#,
+            r#"
+macro_rules frobnicate { () => () }
+fn main() { frobnicate!(); }
+"#,
+        );
+    }
+
+    #[test]
+    fn active_param_score() {
+        mark::check!(active_param_type_match);
+        check_scores(
+            r#"
+struct S { foo: i64, bar: u32, baz: u32 }
+fn test(bar: u32) { }
+fn foo(s: S) { test(s.<|>) }
+"#,
+            expect![[r#"
+                fd bar [type+name]
+                fd baz [type]
+                fd foo []
+            "#]],
+        );
+    }
+
+    #[test]
+    fn record_field_scores() {
+        mark::check!(record_field_type_match);
+        check_scores(
+            r#"
+struct A { foo: i64, bar: u32, baz: u32 }
+struct B { x: (), y: f32, bar: u32 }
+fn foo(a: A) { B { bar: a.<|> }; }
+"#,
+            expect![[r#"
+                fd bar [type+name]
+                fd baz [type]
+                fd foo []
+            "#]],
+        )
+    }
+
+    #[test]
+    fn record_field_and_call_scores() {
+        check_scores(
+            r#"
+struct A { foo: i64, bar: u32, baz: u32 }
+struct B { x: (), y: f32, bar: u32 }
+fn f(foo: i64) {  }
+fn foo(a: A) { B { bar: f(a.<|>) }; }
+"#,
+            expect![[r#"
+                fd foo [type+name]
+                fd bar []
+                fd baz []
+            "#]],
+        );
+        check_scores(
+            r#"
+struct A { foo: i64, bar: u32, baz: u32 }
+struct B { x: (), y: f32, bar: u32 }
+fn f(foo: i64) {  }
+fn foo(a: A) { f(B { bar: a.<|> }); }
+"#,
+            expect![[r#"
+                fd bar [type+name]
+                fd baz [type]
+                fd foo []
+            "#]],
+        );
+    }
+
+    #[test]
+    fn prioritize_exact_ref_match() {
+        check_scores(
+            r#"
+struct WorldSnapshot { _f: () };
+fn go(world: &WorldSnapshot) { go(w<|>) }
+"#,
+            expect![[r#"
+                bn world [type+name]
+                st WorldSnapshot []
+                fn go(…) []
+            "#]],
+        );
+    }
+
+    #[test]
+    fn too_many_arguments() {
+        check_scores(
+            r#"
+struct Foo;
+fn f(foo: &Foo) { f(foo, w<|>) }
+"#,
+            expect![[r#"
+                st Foo []
+                fn f(…) []
+                bn foo []
+            "#]],
+        );
+    }
+
+    #[test]
+    fn guesses_macro_braces() {
+        check_edit(
+            "vec!",
+            r#"
+/// Creates a [`Vec`] containing the arguments.
+///
+/// ```
+/// let v = vec![1, 2, 3];
+/// assert_eq!(v[0], 1);
+/// assert_eq!(v[1], 2);
+/// assert_eq!(v[2], 3);
+/// ```
+macro_rules! vec { () => {} }
+
+fn fn main() { v<|> }
+"#,
+            r#"
+/// Creates a [`Vec`] containing the arguments.
+///
+/// ```
+/// let v = vec![1, 2, 3];
+/// assert_eq!(v[0], 1);
+/// assert_eq!(v[1], 2);
+/// assert_eq!(v[2], 3);
+/// ```
+macro_rules! vec { () => {} }
+
+fn fn main() { vec![$0] }
+"#,
+        );
+
+        check_edit(
+            "foo!",
+            r#"
+/// Foo
+///
+/// Don't call `fooo!()` `fooo!()`, or `_foo![]` `_foo![]`,
+/// call as `let _=foo!  { hello world };`
+macro_rules! foo { () => {} }
+fn main() { <|> }
+"#,
+            r#"
+/// Foo
+///
+/// Don't call `fooo!()` `fooo!()`, or `_foo![]` `_foo![]`,
+/// call as `let _=foo!  { hello world };`
+macro_rules! foo { () => {} }
+fn main() { foo! {$0} }
+"#,
+        )
+    }
+}
diff --git a/crates/completion/src/test_utils.rs b/crates/completion/src/test_utils.rs
new file mode 100644 (file)
index 0000000..f2cf256
--- /dev/null
@@ -0,0 +1,130 @@
+//! Runs completion for testing purposes.
+
+use base_db::{fixture::ChangeFixture, FileLoader, FilePosition};
+use hir::Semantics;
+use ide_db::RootDatabase;
+use itertools::Itertools;
+use stdx::{format_to, trim_indent};
+use syntax::{AstNode, NodeOrToken, SyntaxElement};
+use test_utils::{assert_eq_text, RangeOrOffset};
+
+use crate::{completion_item::CompletionKind, CompletionConfig, CompletionItem};
+
+/// Creates analysis from a multi-file fixture, returns positions marked with <|>.
+pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) {
+    let change_fixture = ChangeFixture::parse(ra_fixture);
+    let mut database = RootDatabase::default();
+    database.apply_change(change_fixture.change);
+    let (file_id, range_or_offset) = change_fixture.file_position.expect("expected a marker (<|>)");
+    let offset = match range_or_offset {
+        RangeOrOffset::Range(_) => panic!(),
+        RangeOrOffset::Offset(it) => it,
+    };
+    (database, FilePosition { file_id, offset })
+}
+
+pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
+    do_completion_with_config(CompletionConfig::default(), code, kind)
+}
+
+pub(crate) fn do_completion_with_config(
+    config: CompletionConfig,
+    code: &str,
+    kind: CompletionKind,
+) -> Vec<CompletionItem> {
+    let mut kind_completions: Vec<CompletionItem> = get_all_completion_items(config, code)
+        .into_iter()
+        .filter(|c| c.completion_kind == kind)
+        .collect();
+    kind_completions.sort_by(|l, r| l.label().cmp(r.label()));
+    kind_completions
+}
+
+pub(crate) fn completion_list(code: &str, kind: CompletionKind) -> String {
+    completion_list_with_config(CompletionConfig::default(), code, kind)
+}
+
+pub(crate) fn completion_list_with_config(
+    config: CompletionConfig,
+    code: &str,
+    kind: CompletionKind,
+) -> String {
+    let mut kind_completions: Vec<CompletionItem> = get_all_completion_items(config, code)
+        .into_iter()
+        .filter(|c| c.completion_kind == kind)
+        .collect();
+    kind_completions.sort_by_key(|c| c.label().to_owned());
+    let label_width = kind_completions
+        .iter()
+        .map(|it| monospace_width(it.label()))
+        .max()
+        .unwrap_or_default()
+        .min(16);
+    kind_completions
+        .into_iter()
+        .map(|it| {
+            let tag = it.kind().unwrap().tag();
+            let var_name = format!("{} {}", tag, it.label());
+            let mut buf = var_name;
+            if let Some(detail) = it.detail() {
+                let width = label_width.saturating_sub(monospace_width(it.label()));
+                format_to!(buf, "{:width$} {}", "", detail, width = width);
+            }
+            format_to!(buf, "\n");
+            buf
+        })
+        .collect()
+}
+
+fn monospace_width(s: &str) -> usize {
+    s.chars().count()
+}
+
+pub(crate) fn check_edit(what: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
+    check_edit_with_config(CompletionConfig::default(), what, ra_fixture_before, ra_fixture_after)
+}
+
+pub(crate) fn check_edit_with_config(
+    config: CompletionConfig,
+    what: &str,
+    ra_fixture_before: &str,
+    ra_fixture_after: &str,
+) {
+    let ra_fixture_after = trim_indent(ra_fixture_after);
+    let (db, position) = position(ra_fixture_before);
+    let completions: Vec<CompletionItem> =
+        crate::completions(&db, &config, position).unwrap().into();
+    let (completion,) = completions
+        .iter()
+        .filter(|it| it.lookup() == what)
+        .collect_tuple()
+        .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions));
+    let mut actual = db.file_text(position.file_id).to_string();
+    completion.text_edit().apply(&mut actual);
+    assert_eq_text!(&ra_fixture_after, &actual)
+}
+
+pub(crate) fn check_pattern_is_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
+    let (db, pos) = position(code);
+
+    let sema = Semantics::new(&db);
+    let original_file = sema.parse(pos.file_id);
+    let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
+    assert!(check(NodeOrToken::Token(token)));
+}
+
+pub(crate) fn check_pattern_is_not_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
+    let (db, pos) = position(code);
+    let sema = Semantics::new(&db);
+    let original_file = sema.parse(pos.file_id);
+    let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
+    assert!(!check(NodeOrToken::Token(token)));
+}
+
+pub(crate) fn get_all_completion_items(
+    config: CompletionConfig,
+    code: &str,
+) -> Vec<CompletionItem> {
+    let (db, position) = position(code);
+    crate::completions(&db, &config, position).unwrap().into()
+}
index 29dc9a6a8e34d78b5321a23c74fd3255d44cb1c3..63299dc31dcf66aae2a1dea5cdb62c95135dfdbc 100644 (file)
@@ -30,6 +30,8 @@ profile = { path = "../profile", version = "0.0.0" }
 test_utils = { path = "../test_utils", version = "0.0.0" }
 assists = { path = "../assists", version = "0.0.0" }
 ssr = { path = "../ssr", version = "0.0.0" }
+call_info = { path = "../call_info", version = "0.0.0" }
+completion = { path = "../completion", version = "0.0.0" }
 
 # ide should depend only on the top-level `hir` package. if you need
 # something from some `hir_xxx` subpackage, reexport the API via `hir`.
index d2cf2cc7dfae713dc2bb92a5b0cdbe61b72d8d87..9d6433fe078c50cee58bc9645efb597b1bc00662 100644 (file)
@@ -2,13 +2,13 @@
 
 use indexmap::IndexMap;
 
+use call_info::FnCallNode;
 use hir::Semantics;
 use ide_db::RootDatabase;
 use syntax::{ast, match_ast, AstNode, TextRange};
 
 use crate::{
-    call_info::FnCallNode, display::ToNav, goto_definition, references, FilePosition,
-    NavigationTarget, RangeInfo,
+    display::ToNav, goto_definition, references, FilePosition, NavigationTarget, RangeInfo,
 };
 
 #[derive(Debug, Clone)]
diff --git a/crates/ide/src/call_info.rs b/crates/ide/src/call_info.rs
deleted file mode 100644 (file)
index d7b2b92..0000000
+++ /dev/null
@@ -1,742 +0,0 @@
-//! FIXME: write short doc here
-use either::Either;
-use hir::{HasAttrs, HirDisplay, Semantics, Type};
-use ide_db::RootDatabase;
-use stdx::format_to;
-use syntax::{
-    ast::{self, ArgListOwner},
-    match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, TextSize,
-};
-use test_utils::mark;
-
-use crate::FilePosition;
-
-/// Contains information about a call site. Specifically the
-/// `FunctionSignature`and current parameter.
-#[derive(Debug)]
-pub struct CallInfo {
-    pub doc: Option<String>,
-    pub signature: String,
-    pub active_parameter: Option<usize>,
-    parameters: Vec<TextRange>,
-}
-
-impl CallInfo {
-    pub fn parameter_labels(&self) -> impl Iterator<Item = &str> + '_ {
-        self.parameters.iter().map(move |&it| &self.signature[it])
-    }
-    pub fn parameter_ranges(&self) -> &[TextRange] {
-        &self.parameters
-    }
-    fn push_param(&mut self, param: &str) {
-        if !self.signature.ends_with('(') {
-            self.signature.push_str(", ");
-        }
-        let start = TextSize::of(&self.signature);
-        self.signature.push_str(param);
-        let end = TextSize::of(&self.signature);
-        self.parameters.push(TextRange::new(start, end))
-    }
-}
-
-/// Computes parameter information for the given call expression.
-pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
-    let sema = Semantics::new(db);
-    let file = sema.parse(position.file_id);
-    let file = file.syntax();
-    let token = file.token_at_offset(position.offset).next()?;
-    let token = sema.descend_into_macros(token);
-
-    let (callable, active_parameter) = call_info_impl(&sema, token)?;
-
-    let mut res =
-        CallInfo { doc: None, signature: String::new(), parameters: vec![], active_parameter };
-
-    match callable.kind() {
-        hir::CallableKind::Function(func) => {
-            res.doc = func.docs(db).map(|it| it.as_str().to_string());
-            format_to!(res.signature, "fn {}", func.name(db));
-        }
-        hir::CallableKind::TupleStruct(strukt) => {
-            res.doc = strukt.docs(db).map(|it| it.as_str().to_string());
-            format_to!(res.signature, "struct {}", strukt.name(db));
-        }
-        hir::CallableKind::TupleEnumVariant(variant) => {
-            res.doc = variant.docs(db).map(|it| it.as_str().to_string());
-            format_to!(
-                res.signature,
-                "enum {}::{}",
-                variant.parent_enum(db).name(db),
-                variant.name(db)
-            );
-        }
-        hir::CallableKind::Closure => (),
-    }
-
-    res.signature.push('(');
-    {
-        if let Some(self_param) = callable.receiver_param(db) {
-            format_to!(res.signature, "{}", self_param)
-        }
-        let mut buf = String::new();
-        for (pat, ty) in callable.params(db) {
-            buf.clear();
-            if let Some(pat) = pat {
-                match pat {
-                    Either::Left(_self) => format_to!(buf, "self: "),
-                    Either::Right(pat) => format_to!(buf, "{}: ", pat),
-                }
-            }
-            format_to!(buf, "{}", ty.display(db));
-            res.push_param(&buf);
-        }
-    }
-    res.signature.push(')');
-
-    match callable.kind() {
-        hir::CallableKind::Function(_) | hir::CallableKind::Closure => {
-            let ret_type = callable.return_type();
-            if !ret_type.is_unit() {
-                format_to!(res.signature, " -> {}", ret_type.display(db));
-            }
-        }
-        hir::CallableKind::TupleStruct(_) | hir::CallableKind::TupleEnumVariant(_) => {}
-    }
-    Some(res)
-}
-
-fn call_info_impl(
-    sema: &Semantics<RootDatabase>,
-    token: SyntaxToken,
-) -> Option<(hir::Callable, Option<usize>)> {
-    // Find the calling expression and it's NameRef
-    let calling_node = FnCallNode::with_node(&token.parent())?;
-
-    let callable = match &calling_node {
-        FnCallNode::CallExpr(call) => sema.type_of_expr(&call.expr()?)?.as_callable(sema.db)?,
-        FnCallNode::MethodCallExpr(call) => sema.resolve_method_call_as_callable(call)?,
-    };
-    let active_param = if let Some(arg_list) = calling_node.arg_list() {
-        // Number of arguments specified at the call site
-        let num_args_at_callsite = arg_list.args().count();
-
-        let arg_list_range = arg_list.syntax().text_range();
-        if !arg_list_range.contains_inclusive(token.text_range().start()) {
-            mark::hit!(call_info_bad_offset);
-            return None;
-        }
-        let param = std::cmp::min(
-            num_args_at_callsite,
-            arg_list
-                .args()
-                .take_while(|arg| arg.syntax().text_range().end() <= token.text_range().start())
-                .count(),
-        );
-
-        Some(param)
-    } else {
-        None
-    };
-    Some((callable, active_param))
-}
-
-#[derive(Debug)]
-pub(crate) struct ActiveParameter {
-    pub(crate) ty: Type,
-    pub(crate) name: String,
-}
-
-impl ActiveParameter {
-    pub(crate) fn at(db: &RootDatabase, position: FilePosition) -> Option<Self> {
-        let sema = Semantics::new(db);
-        let file = sema.parse(position.file_id);
-        let file = file.syntax();
-        let token = file.token_at_offset(position.offset).next()?;
-        let token = sema.descend_into_macros(token);
-        Self::at_token(&sema, token)
-    }
-
-    pub(crate) fn at_token(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<Self> {
-        let (signature, active_parameter) = call_info_impl(&sema, token)?;
-
-        let idx = active_parameter?;
-        let mut params = signature.params(sema.db);
-        if !(idx < params.len()) {
-            mark::hit!(too_many_arguments);
-            return None;
-        }
-        let (pat, ty) = params.swap_remove(idx);
-        let name = pat?.to_string();
-        Some(ActiveParameter { ty, name })
-    }
-}
-
-#[derive(Debug)]
-pub(crate) enum FnCallNode {
-    CallExpr(ast::CallExpr),
-    MethodCallExpr(ast::MethodCallExpr),
-}
-
-impl FnCallNode {
-    fn with_node(syntax: &SyntaxNode) -> Option<FnCallNode> {
-        syntax.ancestors().find_map(|node| {
-            match_ast! {
-                match node {
-                    ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)),
-                    ast::MethodCallExpr(it) => {
-                        let arg_list = it.arg_list()?;
-                        if !arg_list.syntax().text_range().contains_range(syntax.text_range()) {
-                            return None;
-                        }
-                        Some(FnCallNode::MethodCallExpr(it))
-                    },
-                    _ => None,
-                }
-            }
-        })
-    }
-
-    pub(crate) fn with_node_exact(node: &SyntaxNode) -> Option<FnCallNode> {
-        match_ast! {
-            match node {
-                ast::CallExpr(it) => Some(FnCallNode::CallExpr(it)),
-                ast::MethodCallExpr(it) => Some(FnCallNode::MethodCallExpr(it)),
-                _ => None,
-            }
-        }
-    }
-
-    pub(crate) fn name_ref(&self) -> Option<ast::NameRef> {
-        match self {
-            FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? {
-                ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
-                _ => return None,
-            }),
-
-            FnCallNode::MethodCallExpr(call_expr) => {
-                call_expr.syntax().children().filter_map(ast::NameRef::cast).next()
-            }
-        }
-    }
-
-    fn arg_list(&self) -> Option<ast::ArgList> {
-        match self {
-            FnCallNode::CallExpr(expr) => expr.arg_list(),
-            FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
-        }
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-    use test_utils::mark;
-
-    use crate::fixture;
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let (analysis, position) = fixture::position(ra_fixture);
-        let call_info = analysis.call_info(position).unwrap();
-        let actual = match call_info {
-            Some(call_info) => {
-                let docs = match &call_info.doc {
-                    None => "".to_string(),
-                    Some(docs) => format!("{}\n------\n", docs.as_str()),
-                };
-                let params = call_info
-                    .parameter_labels()
-                    .enumerate()
-                    .map(|(i, param)| {
-                        if Some(i) == call_info.active_parameter {
-                            format!("<{}>", param)
-                        } else {
-                            param.to_string()
-                        }
-                    })
-                    .collect::<Vec<_>>()
-                    .join(", ");
-                format!("{}{}\n({})\n", docs, call_info.signature, params)
-            }
-            None => String::new(),
-        };
-        expect.assert_eq(&actual);
-    }
-
-    #[test]
-    fn test_fn_signature_two_args() {
-        check(
-            r#"
-fn foo(x: u32, y: u32) -> u32 {x + y}
-fn bar() { foo(<|>3, ); }
-"#,
-            expect![[r#"
-                fn foo(x: u32, y: u32) -> u32
-                (<x: u32>, y: u32)
-            "#]],
-        );
-        check(
-            r#"
-fn foo(x: u32, y: u32) -> u32 {x + y}
-fn bar() { foo(3<|>, ); }
-"#,
-            expect![[r#"
-                fn foo(x: u32, y: u32) -> u32
-                (<x: u32>, y: u32)
-            "#]],
-        );
-        check(
-            r#"
-fn foo(x: u32, y: u32) -> u32 {x + y}
-fn bar() { foo(3,<|> ); }
-"#,
-            expect![[r#"
-                fn foo(x: u32, y: u32) -> u32
-                (x: u32, <y: u32>)
-            "#]],
-        );
-        check(
-            r#"
-fn foo(x: u32, y: u32) -> u32 {x + y}
-fn bar() { foo(3, <|>); }
-"#,
-            expect![[r#"
-                fn foo(x: u32, y: u32) -> u32
-                (x: u32, <y: u32>)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_two_args_empty() {
-        check(
-            r#"
-fn foo(x: u32, y: u32) -> u32 {x + y}
-fn bar() { foo(<|>); }
-"#,
-            expect![[r#"
-                fn foo(x: u32, y: u32) -> u32
-                (<x: u32>, y: u32)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_two_args_first_generics() {
-        check(
-            r#"
-fn foo<T, U: Copy + Display>(x: T, y: U) -> u32
-    where T: Copy + Display, U: Debug
-{ x + y }
-
-fn bar() { foo(<|>3, ); }
-"#,
-            expect![[r#"
-                fn foo(x: i32, y: {unknown}) -> u32
-                (<x: i32>, y: {unknown})
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_no_params() {
-        check(
-            r#"
-fn foo<T>() -> T where T: Copy + Display {}
-fn bar() { foo(<|>); }
-"#,
-            expect![[r#"
-                fn foo() -> {unknown}
-                ()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_for_impl() {
-        check(
-            r#"
-struct F;
-impl F { pub fn new() { } }
-fn bar() {
-    let _ : F = F::new(<|>);
-}
-"#,
-            expect![[r#"
-                fn new()
-                ()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_for_method_self() {
-        check(
-            r#"
-struct S;
-impl S { pub fn do_it(&self) {} }
-
-fn bar() {
-    let s: S = S;
-    s.do_it(<|>);
-}
-"#,
-            expect![[r#"
-                fn do_it(&self)
-                ()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_for_method_with_arg() {
-        check(
-            r#"
-struct S;
-impl S {
-    fn foo(&self, x: i32) {}
-}
-
-fn main() { S.foo(<|>); }
-"#,
-            expect![[r#"
-                fn foo(&self, x: i32)
-                (<x: i32>)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_for_method_with_arg_as_assoc_fn() {
-        check(
-            r#"
-struct S;
-impl S {
-    fn foo(&self, x: i32) {}
-}
-
-fn main() { S::foo(<|>); }
-"#,
-            expect![[r#"
-                fn foo(self: &S, x: i32)
-                (<self: &S>, x: i32)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_with_docs_simple() {
-        check(
-            r#"
-/// test
-// non-doc-comment
-fn foo(j: u32) -> u32 {
-    j
-}
-
-fn bar() {
-    let _ = foo(<|>);
-}
-"#,
-            expect![[r#"
-                test
-                ------
-                fn foo(j: u32) -> u32
-                (<j: u32>)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_with_docs() {
-        check(
-            r#"
-/// Adds one to the number given.
-///
-/// # Examples
-///
-/// ```
-/// let five = 5;
-///
-/// assert_eq!(6, my_crate::add_one(5));
-/// ```
-pub fn add_one(x: i32) -> i32 {
-    x + 1
-}
-
-pub fn do() {
-    add_one(<|>
-}"#,
-            expect![[r##"
-                Adds one to the number given.
-
-                # Examples
-
-                ```
-                let five = 5;
-
-                assert_eq!(6, my_crate::add_one(5));
-                ```
-                ------
-                fn add_one(x: i32) -> i32
-                (<x: i32>)
-            "##]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_with_docs_impl() {
-        check(
-            r#"
-struct addr;
-impl addr {
-    /// Adds one to the number given.
-    ///
-    /// # Examples
-    ///
-    /// ```
-    /// let five = 5;
-    ///
-    /// assert_eq!(6, my_crate::add_one(5));
-    /// ```
-    pub fn add_one(x: i32) -> i32 {
-        x + 1
-    }
-}
-
-pub fn do_it() {
-    addr {};
-    addr::add_one(<|>);
-}
-"#,
-            expect![[r##"
-                Adds one to the number given.
-
-                # Examples
-
-                ```
-                let five = 5;
-
-                assert_eq!(6, my_crate::add_one(5));
-                ```
-                ------
-                fn add_one(x: i32) -> i32
-                (<x: i32>)
-            "##]],
-        );
-    }
-
-    #[test]
-    fn test_fn_signature_with_docs_from_actix() {
-        check(
-            r#"
-struct WriteHandler<E>;
-
-impl<E> WriteHandler<E> {
-    /// Method is called when writer emits error.
-    ///
-    /// If this method returns `ErrorAction::Continue` writer processing
-    /// continues otherwise stream processing stops.
-    fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running {
-        Running::Stop
-    }
-
-    /// Method is called when writer finishes.
-    ///
-    /// By default this method stops actor's `Context`.
-    fn finished(&mut self, ctx: &mut Self::Context) {
-        ctx.stop()
-    }
-}
-
-pub fn foo(mut r: WriteHandler<()>) {
-    r.finished(<|>);
-}
-"#,
-            expect![[r#"
-                Method is called when writer finishes.
-
-                By default this method stops actor's `Context`.
-                ------
-                fn finished(&mut self, ctx: &mut {unknown})
-                (<ctx: &mut {unknown}>)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn call_info_bad_offset() {
-        mark::check!(call_info_bad_offset);
-        check(
-            r#"
-fn foo(x: u32, y: u32) -> u32 {x + y}
-fn bar() { foo <|> (3, ); }
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn test_nested_method_in_lambda() {
-        check(
-            r#"
-struct Foo;
-impl Foo { fn bar(&self, _: u32) { } }
-
-fn bar(_: u32) { }
-
-fn main() {
-    let foo = Foo;
-    std::thread::spawn(move || foo.bar(<|>));
-}
-"#,
-            expect![[r#"
-                fn bar(&self, _: u32)
-                (<_: u32>)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn works_for_tuple_structs() {
-        check(
-            r#"
-/// A cool tuple struct
-struct S(u32, i32);
-fn main() {
-    let s = S(0, <|>);
-}
-"#,
-            expect![[r#"
-                A cool tuple struct
-                ------
-                struct S(u32, i32)
-                (u32, <i32>)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn generic_struct() {
-        check(
-            r#"
-struct S<T>(T);
-fn main() {
-    let s = S(<|>);
-}
-"#,
-            expect![[r#"
-                struct S({unknown})
-                (<{unknown}>)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn works_for_enum_variants() {
-        check(
-            r#"
-enum E {
-    /// A Variant
-    A(i32),
-    /// Another
-    B,
-    /// And C
-    C { a: i32, b: i32 }
-}
-
-fn main() {
-    let a = E::A(<|>);
-}
-"#,
-            expect![[r#"
-                A Variant
-                ------
-                enum E::A(i32)
-                (<i32>)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn cant_call_struct_record() {
-        check(
-            r#"
-struct S { x: u32, y: i32 }
-fn main() {
-    let s = S(<|>);
-}
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn cant_call_enum_record() {
-        check(
-            r#"
-enum E {
-    /// A Variant
-    A(i32),
-    /// Another
-    B,
-    /// And C
-    C { a: i32, b: i32 }
-}
-
-fn main() {
-    let a = E::C(<|>);
-}
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn fn_signature_for_call_in_macro() {
-        check(
-            r#"
-macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
-fn foo() { }
-id! {
-    fn bar() { foo(<|>); }
-}
-"#,
-            expect![[r#"
-                fn foo()
-                ()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn call_info_for_lambdas() {
-        check(
-            r#"
-struct S;
-fn foo(s: S) -> i32 { 92 }
-fn main() {
-    (|s| foo(s))(<|>)
-}
-        "#,
-            expect![[r#"
-                (S) -> i32
-                (<S>)
-            "#]],
-        )
-    }
-
-    #[test]
-    fn call_info_for_fn_ptr() {
-        check(
-            r#"
-fn main(f: fn(i32, f64) -> char) {
-    f(0, <|>)
-}
-        "#,
-            expect![[r#"
-                (i32, f64) -> char
-                (i32, <f64>)
-            "#]],
-        )
-    }
-}
diff --git a/crates/ide/src/completion.rs b/crates/ide/src/completion.rs
deleted file mode 100644 (file)
index 69e8750..0000000
+++ /dev/null
@@ -1,260 +0,0 @@
-mod completion_config;
-mod completion_item;
-mod completion_context;
-mod presentation;
-mod patterns;
-mod generated_features;
-#[cfg(test)]
-mod test_utils;
-
-mod complete_attribute;
-mod complete_dot;
-mod complete_record;
-mod complete_pattern;
-mod complete_fn_param;
-mod complete_keyword;
-mod complete_snippet;
-mod complete_qualified_path;
-mod complete_unqualified_path;
-mod complete_postfix;
-mod complete_macro_in_item_position;
-mod complete_trait_impl;
-mod complete_mod;
-
-use ide_db::RootDatabase;
-
-use crate::{
-    completion::{
-        completion_context::CompletionContext,
-        completion_item::{CompletionKind, Completions},
-    },
-    FilePosition,
-};
-
-pub use crate::completion::{
-    completion_config::CompletionConfig,
-    completion_item::{CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat},
-};
-
-//FIXME: split the following feature into fine-grained features.
-
-// Feature: Magic Completions
-//
-// In addition to usual reference completion, rust-analyzer provides some ✨magic✨
-// completions as well:
-//
-// Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
-// is placed at the appropriate position. Even though `if` is easy to type, you
-// still want to complete it, to get ` { }` for free! `return` is inserted with a
-// space or `;` depending on the return type of the function.
-//
-// When completing a function call, `()` are automatically inserted. If a function
-// takes arguments, the cursor is positioned inside the parenthesis.
-//
-// There are postfix completions, which can be triggered by typing something like
-// `foo().if`. The word after `.` determines postfix completion. Possible variants are:
-//
-// - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
-// - `expr.match` -> `match expr {}`
-// - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
-// - `expr.ref` -> `&expr`
-// - `expr.refm` -> `&mut expr`
-// - `expr.not` -> `!expr`
-// - `expr.dbg` -> `dbg!(expr)`
-// - `expr.dbgr` -> `dbg!(&expr)`
-// - `expr.call` -> `(expr)`
-//
-// There also snippet completions:
-//
-// .Expressions
-// - `pd` -> `eprintln!(" = {:?}", );`
-// - `ppd` -> `eprintln!(" = {:#?}", );`
-//
-// .Items
-// - `tfn` -> `#[test] fn feature(){}`
-// - `tmod` ->
-// ```rust
-// #[cfg(test)]
-// mod tests {
-//     use super::*;
-//
-//     #[test]
-//     fn test_name() {}
-// }
-// ```
-
-/// Main entry point for completion. We run completion as a two-phase process.
-///
-/// First, we look at the position and collect a so-called `CompletionContext.
-/// This is a somewhat messy process, because, during completion, syntax tree is
-/// incomplete and can look really weird.
-///
-/// Once the context is collected, we run a series of completion routines which
-/// look at the context and produce completion items. One subtlety about this
-/// phase is that completion engine should not filter by the substring which is
-/// already present, it should give all possible variants for the identifier at
-/// the caret. In other words, for
-///
-/// ```no_run
-/// fn f() {
-///     let foo = 92;
-///     let _ = bar<|>
-/// }
-/// ```
-///
-/// `foo` *should* be present among the completion variants. Filtering by
-/// identifier prefix/fuzzy match should be done higher in the stack, together
-/// with ordering of completions (currently this is done by the client).
-pub(crate) fn completions(
-    db: &RootDatabase,
-    config: &CompletionConfig,
-    position: FilePosition,
-) -> Option<Completions> {
-    let ctx = CompletionContext::new(db, position, config)?;
-
-    if ctx.no_completion_required() {
-        // No work required here.
-        return None;
-    }
-
-    let mut acc = Completions::default();
-    complete_attribute::complete_attribute(&mut acc, &ctx);
-    complete_fn_param::complete_fn_param(&mut acc, &ctx);
-    complete_keyword::complete_expr_keyword(&mut acc, &ctx);
-    complete_keyword::complete_use_tree_keyword(&mut acc, &ctx);
-    complete_snippet::complete_expr_snippet(&mut acc, &ctx);
-    complete_snippet::complete_item_snippet(&mut acc, &ctx);
-    complete_qualified_path::complete_qualified_path(&mut acc, &ctx);
-    complete_unqualified_path::complete_unqualified_path(&mut acc, &ctx);
-    complete_dot::complete_dot(&mut acc, &ctx);
-    complete_record::complete_record(&mut acc, &ctx);
-    complete_pattern::complete_pattern(&mut acc, &ctx);
-    complete_postfix::complete_postfix(&mut acc, &ctx);
-    complete_macro_in_item_position::complete_macro_in_item_position(&mut acc, &ctx);
-    complete_trait_impl::complete_trait_impl(&mut acc, &ctx);
-    complete_mod::complete_mod(&mut acc, &ctx);
-
-    Some(acc)
-}
-
-#[cfg(test)]
-mod tests {
-    use crate::completion::completion_config::CompletionConfig;
-    use crate::fixture;
-
-    struct DetailAndDocumentation<'a> {
-        detail: &'a str,
-        documentation: &'a str,
-    }
-
-    fn check_detail_and_documentation(ra_fixture: &str, expected: DetailAndDocumentation) {
-        let (analysis, position) = fixture::position(ra_fixture);
-        let config = CompletionConfig::default();
-        let completions = analysis.completions(&config, position).unwrap().unwrap();
-        for item in completions {
-            if item.detail() == Some(expected.detail) {
-                let opt = item.documentation();
-                let doc = opt.as_ref().map(|it| it.as_str());
-                assert_eq!(doc, Some(expected.documentation));
-                return;
-            }
-        }
-        panic!("completion detail not found: {}", expected.detail)
-    }
-
-    fn check_no_completion(ra_fixture: &str) {
-        let (analysis, position) = fixture::position(ra_fixture);
-        let config = CompletionConfig::default();
-        analysis.completions(&config, position).unwrap();
-
-        let completions: Option<Vec<String>> = analysis
-            .completions(&config, position)
-            .unwrap()
-            .and_then(|completions| if completions.is_empty() { None } else { Some(completions) })
-            .map(|completions| {
-                completions.into_iter().map(|completion| format!("{:?}", completion)).collect()
-            });
-
-        // `assert_eq` instead of `assert!(completions.is_none())` to get the list of completions if test will panic.
-        assert_eq!(completions, None, "Completions were generated, but weren't expected");
-    }
-
-    #[test]
-    fn test_completion_detail_from_macro_generated_struct_fn_doc_attr() {
-        check_detail_and_documentation(
-            r#"
-            //- /lib.rs
-            macro_rules! bar {
-                () => {
-                    struct Bar;
-                    impl Bar {
-                        #[doc = "Do the foo"]
-                        fn foo(&self) {}
-                    }
-                }
-            }
-
-            bar!();
-
-            fn foo() {
-                let bar = Bar;
-                bar.fo<|>;
-            }
-            "#,
-            DetailAndDocumentation { detail: "fn foo(&self)", documentation: "Do the foo" },
-        );
-    }
-
-    #[test]
-    fn test_completion_detail_from_macro_generated_struct_fn_doc_comment() {
-        check_detail_and_documentation(
-            r#"
-            //- /lib.rs
-            macro_rules! bar {
-                () => {
-                    struct Bar;
-                    impl Bar {
-                        /// Do the foo
-                        fn foo(&self) {}
-                    }
-                }
-            }
-
-            bar!();
-
-            fn foo() {
-                let bar = Bar;
-                bar.fo<|>;
-            }
-            "#,
-            DetailAndDocumentation { detail: "fn foo(&self)", documentation: " Do the foo" },
-        );
-    }
-
-    #[test]
-    fn test_no_completions_required() {
-        // There must be no hint for 'in' keyword.
-        check_no_completion(
-            r#"
-            fn foo() {
-                for i i<|>
-            }
-            "#,
-        );
-        // After 'in' keyword hints may be spawned.
-        check_detail_and_documentation(
-            r#"
-            /// Do the foo
-            fn foo() -> &'static str { "foo" }
-
-            fn bar() {
-                for c in fo<|>
-            }
-            "#,
-            DetailAndDocumentation {
-                detail: "fn foo() -> &'static str",
-                documentation: "Do the foo",
-            },
-        );
-    }
-}
diff --git a/crates/ide/src/completion/complete_attribute.rs b/crates/ide/src/completion/complete_attribute.rs
deleted file mode 100644 (file)
index f4a9864..0000000
+++ /dev/null
@@ -1,657 +0,0 @@
-//! Completion for attributes
-//!
-//! This module uses a bit of static metadata to provide completions
-//! for built-in attributes.
-
-use rustc_hash::FxHashSet;
-use syntax::{ast, AstNode, SyntaxKind};
-
-use crate::completion::{
-    completion_context::CompletionContext,
-    completion_item::{CompletionItem, CompletionItemKind, CompletionKind, Completions},
-    generated_features::FEATURES,
-};
-
-pub(super) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
-    if ctx.mod_declaration_under_caret.is_some() {
-        return None;
-    }
-
-    let attribute = ctx.attribute_under_caret.as_ref()?;
-    match (attribute.path(), attribute.token_tree()) {
-        (Some(path), Some(token_tree)) if path.to_string() == "derive" => {
-            complete_derive(acc, ctx, token_tree)
-        }
-        (Some(path), Some(token_tree)) if path.to_string() == "feature" => {
-            complete_lint(acc, ctx, token_tree, FEATURES)
-        }
-        (Some(path), Some(token_tree))
-            if ["allow", "warn", "deny", "forbid"]
-                .iter()
-                .any(|lint_level| lint_level == &path.to_string()) =>
-        {
-            complete_lint(acc, ctx, token_tree, DEFAULT_LINT_COMPLETIONS)
-        }
-        (_, Some(_token_tree)) => {}
-        _ => complete_attribute_start(acc, ctx, attribute),
-    }
-    Some(())
-}
-
-fn complete_attribute_start(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) {
-    for attr_completion in ATTRIBUTES {
-        let mut item = CompletionItem::new(
-            CompletionKind::Attribute,
-            ctx.source_range(),
-            attr_completion.label,
-        )
-        .kind(CompletionItemKind::Attribute);
-
-        if let Some(lookup) = attr_completion.lookup {
-            item = item.lookup_by(lookup);
-        }
-
-        match (attr_completion.snippet, ctx.config.snippet_cap) {
-            (Some(snippet), Some(cap)) => {
-                item = item.insert_snippet(cap, snippet);
-            }
-            _ => {}
-        }
-
-        if attribute.kind() == ast::AttrKind::Inner || !attr_completion.prefer_inner {
-            acc.add(item);
-        }
-    }
-}
-
-struct AttrCompletion {
-    label: &'static str,
-    lookup: Option<&'static str>,
-    snippet: Option<&'static str>,
-    prefer_inner: bool,
-}
-
-impl AttrCompletion {
-    const fn prefer_inner(self) -> AttrCompletion {
-        AttrCompletion { prefer_inner: true, ..self }
-    }
-}
-
-const fn attr(
-    label: &'static str,
-    lookup: Option<&'static str>,
-    snippet: Option<&'static str>,
-) -> AttrCompletion {
-    AttrCompletion { label, lookup, snippet, prefer_inner: false }
-}
-
-const ATTRIBUTES: &[AttrCompletion] = &[
-    attr("allow(…)", Some("allow"), Some("allow(${0:lint})")),
-    attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")),
-    attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")),
-    attr("deny(…)", Some("deny"), Some("deny(${0:lint})")),
-    attr(r#"deprecated = "…""#, Some("deprecated"), Some(r#"deprecated = "${0:reason}""#)),
-    attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)),
-    attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)),
-    attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(),
-    attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")),
-    // FIXME: resolve through macro resolution?
-    attr("global_allocator", None, None).prefer_inner(),
-    attr(r#"ignore = "…""#, Some("ignore"), Some(r#"ignore = "${0:reason}""#)),
-    attr("inline(…)", Some("inline"), Some("inline(${0:lint})")),
-    attr(r#"link_name = "…""#, Some("link_name"), Some(r#"link_name = "${0:symbol_name}""#)),
-    attr("link", None, None),
-    attr("macro_export", None, None),
-    attr("macro_use", None, None),
-    attr(r#"must_use = "…""#, Some("must_use"), Some(r#"must_use = "${0:reason}""#)),
-    attr("no_mangle", None, None),
-    attr("no_std", None, None).prefer_inner(),
-    attr("non_exhaustive", None, None),
-    attr("panic_handler", None, None).prefer_inner(),
-    attr("path = \"…\"", Some("path"), Some("path =\"${0:path}\"")),
-    attr("proc_macro", None, None),
-    attr("proc_macro_attribute", None, None),
-    attr("proc_macro_derive(…)", Some("proc_macro_derive"), Some("proc_macro_derive(${0:Trait})")),
-    attr("recursion_limit = …", Some("recursion_limit"), Some("recursion_limit = ${0:128}"))
-        .prefer_inner(),
-    attr("repr(…)", Some("repr"), Some("repr(${0:C})")),
-    attr(
-        "should_panic(…)",
-        Some("should_panic"),
-        Some(r#"should_panic(expected = "${0:reason}")"#),
-    ),
-    attr(
-        r#"target_feature = "…""#,
-        Some("target_feature"),
-        Some("target_feature = \"${0:feature}\""),
-    ),
-    attr("test", None, None),
-    attr("used", None, None),
-    attr("warn(…)", Some("warn"), Some("warn(${0:lint})")),
-    attr(
-        r#"windows_subsystem = "…""#,
-        Some("windows_subsystem"),
-        Some(r#"windows_subsystem = "${0:subsystem}""#),
-    )
-    .prefer_inner(),
-];
-
-fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input: ast::TokenTree) {
-    if let Ok(existing_derives) = parse_comma_sep_input(derive_input) {
-        for derive_completion in DEFAULT_DERIVE_COMPLETIONS
-            .into_iter()
-            .filter(|completion| !existing_derives.contains(completion.label))
-        {
-            let mut label = derive_completion.label.to_owned();
-            for dependency in derive_completion
-                .dependencies
-                .into_iter()
-                .filter(|&&dependency| !existing_derives.contains(dependency))
-            {
-                label.push_str(", ");
-                label.push_str(dependency);
-            }
-            acc.add(
-                CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label)
-                    .kind(CompletionItemKind::Attribute),
-            );
-        }
-
-        for custom_derive_name in get_derive_names_in_scope(ctx).difference(&existing_derives) {
-            acc.add(
-                CompletionItem::new(
-                    CompletionKind::Attribute,
-                    ctx.source_range(),
-                    custom_derive_name,
-                )
-                .kind(CompletionItemKind::Attribute),
-            );
-        }
-    }
-}
-
-fn complete_lint(
-    acc: &mut Completions,
-    ctx: &CompletionContext,
-    derive_input: ast::TokenTree,
-    lints_completions: &[LintCompletion],
-) {
-    if let Ok(existing_lints) = parse_comma_sep_input(derive_input) {
-        for lint_completion in lints_completions
-            .into_iter()
-            .filter(|completion| !existing_lints.contains(completion.label))
-        {
-            acc.add(
-                CompletionItem::new(
-                    CompletionKind::Attribute,
-                    ctx.source_range(),
-                    lint_completion.label,
-                )
-                .kind(CompletionItemKind::Attribute)
-                .detail(lint_completion.description),
-            );
-        }
-    }
-}
-
-fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Result<FxHashSet<String>, ()> {
-    match (derive_input.left_delimiter_token(), derive_input.right_delimiter_token()) {
-        (Some(left_paren), Some(right_paren))
-            if left_paren.kind() == SyntaxKind::L_PAREN
-                && right_paren.kind() == SyntaxKind::R_PAREN =>
-        {
-            let mut input_derives = FxHashSet::default();
-            let mut current_derive = String::new();
-            for token in derive_input
-                .syntax()
-                .children_with_tokens()
-                .filter_map(|token| token.into_token())
-                .skip_while(|token| token != &left_paren)
-                .skip(1)
-                .take_while(|token| token != &right_paren)
-            {
-                if SyntaxKind::COMMA == token.kind() {
-                    if !current_derive.is_empty() {
-                        input_derives.insert(current_derive);
-                        current_derive = String::new();
-                    }
-                } else {
-                    current_derive.push_str(token.to_string().trim());
-                }
-            }
-
-            if !current_derive.is_empty() {
-                input_derives.insert(current_derive);
-            }
-            Ok(input_derives)
-        }
-        _ => Err(()),
-    }
-}
-
-fn get_derive_names_in_scope(ctx: &CompletionContext) -> FxHashSet<String> {
-    let mut result = FxHashSet::default();
-    ctx.scope.process_all_names(&mut |name, scope_def| {
-        if let hir::ScopeDef::MacroDef(mac) = scope_def {
-            if mac.is_derive_macro() {
-                result.insert(name.to_string());
-            }
-        }
-    });
-    result
-}
-
-struct DeriveCompletion {
-    label: &'static str,
-    dependencies: &'static [&'static str],
-}
-
-/// Standard Rust derives and the information about their dependencies
-/// (the dependencies are needed so that the main derive don't break the compilation when added)
-#[rustfmt::skip]
-const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[
-    DeriveCompletion { label: "Clone", dependencies: &[] },
-    DeriveCompletion { label: "Copy", dependencies: &["Clone"] },
-    DeriveCompletion { label: "Debug", dependencies: &[] },
-    DeriveCompletion { label: "Default", dependencies: &[] },
-    DeriveCompletion { label: "Hash", dependencies: &[] },
-    DeriveCompletion { label: "PartialEq", dependencies: &[] },
-    DeriveCompletion { label: "Eq", dependencies: &["PartialEq"] },
-    DeriveCompletion { label: "PartialOrd", dependencies: &["PartialEq"] },
-    DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] },
-];
-
-pub(super) struct LintCompletion {
-    pub(super) label: &'static str,
-    pub(super) description: &'static str,
-}
-
-#[rustfmt::skip]
-const DEFAULT_LINT_COMPLETIONS: &[LintCompletion] = &[
-    LintCompletion { label: "absolute_paths_not_starting_with_crate", description: r#"fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name"# },
-    LintCompletion { label: "anonymous_parameters", description: r#"detects anonymous parameters"# },
-    LintCompletion { label: "box_pointers", description: r#"use of owned (Box type) heap memory"# },
-    LintCompletion { label: "deprecated_in_future", description: r#"detects use of items that will be deprecated in a future version"# },
-    LintCompletion { label: "elided_lifetimes_in_paths", description: r#"hidden lifetime parameters in types are deprecated"# },
-    LintCompletion { label: "explicit_outlives_requirements", description: r#"outlives requirements can be inferred"# },
-    LintCompletion { label: "indirect_structural_match", description: r#"pattern with const indirectly referencing non-structural-match type"# },
-    LintCompletion { label: "keyword_idents", description: r#"detects edition keywords being used as an identifier"# },
-    LintCompletion { label: "macro_use_extern_crate", description: r#"the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system"# },
-    LintCompletion { label: "meta_variable_misuse", description: r#"possible meta-variable misuse at macro definition"# },
-    LintCompletion { label: "missing_copy_implementations", description: r#"detects potentially-forgotten implementations of `Copy`"# },
-    LintCompletion { label: "missing_crate_level_docs", description: r#"detects crates with no crate-level documentation"# },
-    LintCompletion { label: "missing_debug_implementations", description: r#"detects missing implementations of Debug"# },
-    LintCompletion { label: "missing_docs", description: r#"detects missing documentation for public members"# },
-    LintCompletion { label: "missing_doc_code_examples", description: r#"detects publicly-exported items without code samples in their documentation"# },
-    LintCompletion { label: "non_ascii_idents", description: r#"detects non-ASCII identifiers"# },
-    LintCompletion { label: "private_doc_tests", description: r#"detects code samples in docs of private items not documented by rustdoc"# },
-    LintCompletion { label: "single_use_lifetimes", description: r#"detects lifetime parameters that are only used once"# },
-    LintCompletion { label: "trivial_casts", description: r#"detects trivial casts which could be removed"# },
-    LintCompletion { label: "trivial_numeric_casts", description: r#"detects trivial casts of numeric types which could be removed"# },
-    LintCompletion { label: "unaligned_references", description: r#"detects unaligned references to fields of packed structs"# },
-    LintCompletion { label: "unreachable_pub", description: r#"`pub` items not reachable from crate root"# },
-    LintCompletion { label: "unsafe_code", description: r#"usage of `unsafe` code"# },
-    LintCompletion { label: "unsafe_op_in_unsafe_fn", description: r#"unsafe operations in unsafe functions without an explicit unsafe block are deprecated"# },
-    LintCompletion { label: "unstable_features", description: r#"enabling unstable features (deprecated. do not use)"# },
-    LintCompletion { label: "unused_crate_dependencies", description: r#"crate dependencies that are never used"# },
-    LintCompletion { label: "unused_extern_crates", description: r#"extern crates that are never used"# },
-    LintCompletion { label: "unused_import_braces", description: r#"unnecessary braces around an imported item"# },
-    LintCompletion { label: "unused_lifetimes", description: r#"detects lifetime parameters that are never used"# },
-    LintCompletion { label: "unused_qualifications", description: r#"detects unnecessarily qualified names"# },
-    LintCompletion { label: "unused_results", description: r#"unused result of an expression in a statement"# },
-    LintCompletion { label: "variant_size_differences", description: r#"detects enums with widely varying variant sizes"# },
-    LintCompletion { label: "array_into_iter", description: r#"detects calling `into_iter` on arrays"# },
-    LintCompletion { label: "asm_sub_register", description: r#"using only a subset of a register for inline asm inputs"# },
-    LintCompletion { label: "bare_trait_objects", description: r#"suggest using `dyn Trait` for trait objects"# },
-    LintCompletion { label: "bindings_with_variant_name", description: r#"detects pattern bindings with the same name as one of the matched variants"# },
-    LintCompletion { label: "cenum_impl_drop_cast", description: r#"a C-like enum implementing Drop is cast"# },
-    LintCompletion { label: "clashing_extern_declarations", description: r#"detects when an extern fn has been declared with the same name but different types"# },
-    LintCompletion { label: "coherence_leak_check", description: r#"distinct impls distinguished only by the leak-check code"# },
-    LintCompletion { label: "confusable_idents", description: r#"detects visually confusable pairs between identifiers"# },
-    LintCompletion { label: "dead_code", description: r#"detect unused, unexported items"# },
-    LintCompletion { label: "deprecated", description: r#"detects use of deprecated items"# },
-    LintCompletion { label: "ellipsis_inclusive_range_patterns", description: r#"`...` range patterns are deprecated"# },
-    LintCompletion { label: "exported_private_dependencies", description: r#"public interface leaks type from a private dependency"# },
-    LintCompletion { label: "illegal_floating_point_literal_pattern", description: r#"floating-point literals cannot be used in patterns"# },
-    LintCompletion { label: "improper_ctypes", description: r#"proper use of libc types in foreign modules"# },
-    LintCompletion { label: "improper_ctypes_definitions", description: r#"proper use of libc types in foreign item definitions"# },
-    LintCompletion { label: "incomplete_features", description: r#"incomplete features that may function improperly in some or all cases"# },
-    LintCompletion { label: "inline_no_sanitize", description: r#"detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]`"# },
-    LintCompletion { label: "intra_doc_link_resolution_failure", description: r#"failures in resolving intra-doc link targets"# },
-    LintCompletion { label: "invalid_codeblock_attributes", description: r#"codeblock attribute looks a lot like a known one"# },
-    LintCompletion { label: "invalid_value", description: r#"an invalid value is being created (such as a NULL reference)"# },
-    LintCompletion { label: "irrefutable_let_patterns", description: r#"detects irrefutable patterns in if-let and while-let statements"# },
-    LintCompletion { label: "late_bound_lifetime_arguments", description: r#"detects generic lifetime arguments in path segments with late bound lifetime parameters"# },
-    LintCompletion { label: "mixed_script_confusables", description: r#"detects Unicode scripts whose mixed script confusables codepoints are solely used"# },
-    LintCompletion { label: "mutable_borrow_reservation_conflict", description: r#"reservation of a two-phased borrow conflicts with other shared borrows"# },
-    LintCompletion { label: "non_camel_case_types", description: r#"types, variants, traits and type parameters should have camel case names"# },
-    LintCompletion { label: "non_shorthand_field_patterns", description: r#"using `Struct { x: x }` instead of `Struct { x }` in a pattern"# },
-    LintCompletion { label: "non_snake_case", description: r#"variables, methods, functions, lifetime parameters and modules should have snake case names"# },
-    LintCompletion { label: "non_upper_case_globals", description: r#"static constants should have uppercase identifiers"# },
-    LintCompletion { label: "no_mangle_generic_items", description: r#"generic items must be mangled"# },
-    LintCompletion { label: "overlapping_patterns", description: r#"detects overlapping patterns"# },
-    LintCompletion { label: "path_statements", description: r#"path statements with no effect"# },
-    LintCompletion { label: "private_in_public", description: r#"detect private items in public interfaces not caught by the old implementation"# },
-    LintCompletion { label: "proc_macro_derive_resolution_fallback", description: r#"detects proc macro derives using inaccessible names from parent modules"# },
-    LintCompletion { label: "redundant_semicolons", description: r#"detects unnecessary trailing semicolons"# },
-    LintCompletion { label: "renamed_and_removed_lints", description: r#"lints that have been renamed or removed"# },
-    LintCompletion { label: "safe_packed_borrows", description: r#"safe borrows of fields of packed structs were erroneously allowed"# },
-    LintCompletion { label: "stable_features", description: r#"stable features found in `#[feature]` directive"# },
-    LintCompletion { label: "trivial_bounds", description: r#"these bounds don't depend on an type parameters"# },
-    LintCompletion { label: "type_alias_bounds", description: r#"bounds in type aliases are not enforced"# },
-    LintCompletion { label: "tyvar_behind_raw_pointer", description: r#"raw pointer to an inference variable"# },
-    LintCompletion { label: "uncommon_codepoints", description: r#"detects uncommon Unicode codepoints in identifiers"# },
-    LintCompletion { label: "unconditional_recursion", description: r#"functions that cannot return without calling themselves"# },
-    LintCompletion { label: "unknown_lints", description: r#"unrecognized lint attribute"# },
-    LintCompletion { label: "unnameable_test_items", description: r#"detects an item that cannot be named being marked as `#[test_case]`"# },
-    LintCompletion { label: "unreachable_code", description: r#"detects unreachable code paths"# },
-    LintCompletion { label: "unreachable_patterns", description: r#"detects unreachable patterns"# },
-    LintCompletion { label: "unstable_name_collisions", description: r#"detects name collision with an existing but unstable method"# },
-    LintCompletion { label: "unused_allocation", description: r#"detects unnecessary allocations that can be eliminated"# },
-    LintCompletion { label: "unused_assignments", description: r#"detect assignments that will never be read"# },
-    LintCompletion { label: "unused_attributes", description: r#"detects attributes that were not used by the compiler"# },
-    LintCompletion { label: "unused_braces", description: r#"unnecessary braces around an expression"# },
-    LintCompletion { label: "unused_comparisons", description: r#"comparisons made useless by limits of the types involved"# },
-    LintCompletion { label: "unused_doc_comments", description: r#"detects doc comments that aren't used by rustdoc"# },
-    LintCompletion { label: "unused_features", description: r#"unused features found in crate-level `#[feature]` directives"# },
-    LintCompletion { label: "unused_imports", description: r#"imports that are never used"# },
-    LintCompletion { label: "unused_labels", description: r#"detects labels that are never used"# },
-    LintCompletion { label: "unused_macros", description: r#"detects macros that were not used"# },
-    LintCompletion { label: "unused_must_use", description: r#"unused result of a type flagged as `#[must_use]`"# },
-    LintCompletion { label: "unused_mut", description: r#"detect mut variables which don't need to be mutable"# },
-    LintCompletion { label: "unused_parens", description: r#"`if`, `match`, `while` and `return` do not need parentheses"# },
-    LintCompletion { label: "unused_unsafe", description: r#"unnecessary use of an `unsafe` block"# },
-    LintCompletion { label: "unused_variables", description: r#"detect variables which are not used in any way"# },
-    LintCompletion { label: "warnings", description: r#"mass-change the level for lints which produce warnings"# },
-    LintCompletion { label: "where_clauses_object_safety", description: r#"checks the object safety of where clauses"# },
-    LintCompletion { label: "while_true", description: r#"suggest using `loop { }` instead of `while true { }`"# },
-    LintCompletion { label: "ambiguous_associated_items", description: r#"ambiguous associated items"# },
-    LintCompletion { label: "arithmetic_overflow", description: r#"arithmetic operation overflows"# },
-    LintCompletion { label: "conflicting_repr_hints", description: r#"conflicts between `#[repr(..)]` hints that were previously accepted and used in practice"# },
-    LintCompletion { label: "const_err", description: r#"constant evaluation detected erroneous expression"# },
-    LintCompletion { label: "ill_formed_attribute_input", description: r#"ill-formed attribute inputs that were previously accepted and used in practice"# },
-    LintCompletion { label: "incomplete_include", description: r#"trailing content in included file"# },
-    LintCompletion { label: "invalid_type_param_default", description: r#"type parameter default erroneously allowed in invalid location"# },
-    LintCompletion { label: "macro_expanded_macro_exports_accessed_by_absolute_paths", description: r#"macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths"# },
-    LintCompletion { label: "missing_fragment_specifier", description: r#"detects missing fragment specifiers in unused `macro_rules!` patterns"# },
-    LintCompletion { label: "mutable_transmutes", description: r#"mutating transmuted &mut T from &T may cause undefined behavior"# },
-    LintCompletion { label: "no_mangle_const_items", description: r#"const items will not have their symbols exported"# },
-    LintCompletion { label: "order_dependent_trait_objects", description: r#"trait-object types were treated as different depending on marker-trait order"# },
-    LintCompletion { label: "overflowing_literals", description: r#"literal out of range for its type"# },
-    LintCompletion { label: "patterns_in_fns_without_body", description: r#"patterns in functions without body were erroneously allowed"# },
-    LintCompletion { label: "pub_use_of_private_extern_crate", description: r#"detect public re-exports of private extern crates"# },
-    LintCompletion { label: "soft_unstable", description: r#"a feature gate that doesn't break dependent crates"# },
-    LintCompletion { label: "unconditional_panic", description: r#"operation will cause a panic at runtime"# },
-    LintCompletion { label: "unknown_crate_types", description: r#"unknown crate type found in `#[crate_type]` directive"# },
-];
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{test_utils::completion_list, CompletionKind};
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Attribute);
-        expect.assert_eq(&actual);
-    }
-
-    #[test]
-    fn empty_derive_completion() {
-        check(
-            r#"
-#[derive(<|>)]
-struct Test {}
-        "#,
-            expect![[r#"
-                at Clone
-                at Copy, Clone
-                at Debug
-                at Default
-                at Eq, PartialEq
-                at Hash
-                at Ord, PartialOrd, Eq, PartialEq
-                at PartialEq
-                at PartialOrd, PartialEq
-            "#]],
-        );
-    }
-
-    #[test]
-    fn empty_lint_completion() {
-        check(
-            r#"#[allow(<|>)]"#,
-            expect![[r#"
-                at absolute_paths_not_starting_with_crate fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name
-                at ambiguous_associated_items ambiguous associated items
-                at anonymous_parameters detects anonymous parameters
-                at arithmetic_overflow arithmetic operation overflows
-                at array_into_iter  detects calling `into_iter` on arrays
-                at asm_sub_register using only a subset of a register for inline asm inputs
-                at bare_trait_objects suggest using `dyn Trait` for trait objects
-                at bindings_with_variant_name detects pattern bindings with the same name as one of the matched variants
-                at box_pointers     use of owned (Box type) heap memory
-                at cenum_impl_drop_cast a C-like enum implementing Drop is cast
-                at clashing_extern_declarations detects when an extern fn has been declared with the same name but different types
-                at coherence_leak_check distinct impls distinguished only by the leak-check code
-                at conflicting_repr_hints conflicts between `#[repr(..)]` hints that were previously accepted and used in practice
-                at confusable_idents detects visually confusable pairs between identifiers
-                at const_err        constant evaluation detected erroneous expression
-                at dead_code        detect unused, unexported items
-                at deprecated       detects use of deprecated items
-                at deprecated_in_future detects use of items that will be deprecated in a future version
-                at elided_lifetimes_in_paths hidden lifetime parameters in types are deprecated
-                at ellipsis_inclusive_range_patterns `...` range patterns are deprecated
-                at explicit_outlives_requirements outlives requirements can be inferred
-                at exported_private_dependencies public interface leaks type from a private dependency
-                at ill_formed_attribute_input ill-formed attribute inputs that were previously accepted and used in practice
-                at illegal_floating_point_literal_pattern floating-point literals cannot be used in patterns
-                at improper_ctypes  proper use of libc types in foreign modules
-                at improper_ctypes_definitions proper use of libc types in foreign item definitions
-                at incomplete_features incomplete features that may function improperly in some or all cases
-                at incomplete_include trailing content in included file
-                at indirect_structural_match pattern with const indirectly referencing non-structural-match type
-                at inline_no_sanitize detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]`
-                at intra_doc_link_resolution_failure failures in resolving intra-doc link targets
-                at invalid_codeblock_attributes codeblock attribute looks a lot like a known one
-                at invalid_type_param_default type parameter default erroneously allowed in invalid location
-                at invalid_value    an invalid value is being created (such as a NULL reference)
-                at irrefutable_let_patterns detects irrefutable patterns in if-let and while-let statements
-                at keyword_idents   detects edition keywords being used as an identifier
-                at late_bound_lifetime_arguments detects generic lifetime arguments in path segments with late bound lifetime parameters
-                at macro_expanded_macro_exports_accessed_by_absolute_paths macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths
-                at macro_use_extern_crate the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system
-                at meta_variable_misuse possible meta-variable misuse at macro definition
-                at missing_copy_implementations detects potentially-forgotten implementations of `Copy`
-                at missing_crate_level_docs detects crates with no crate-level documentation
-                at missing_debug_implementations detects missing implementations of Debug
-                at missing_doc_code_examples detects publicly-exported items without code samples in their documentation
-                at missing_docs     detects missing documentation for public members
-                at missing_fragment_specifier detects missing fragment specifiers in unused `macro_rules!` patterns
-                at mixed_script_confusables detects Unicode scripts whose mixed script confusables codepoints are solely used
-                at mutable_borrow_reservation_conflict reservation of a two-phased borrow conflicts with other shared borrows
-                at mutable_transmutes mutating transmuted &mut T from &T may cause undefined behavior
-                at no_mangle_const_items const items will not have their symbols exported
-                at no_mangle_generic_items generic items must be mangled
-                at non_ascii_idents detects non-ASCII identifiers
-                at non_camel_case_types types, variants, traits and type parameters should have camel case names
-                at non_shorthand_field_patterns using `Struct { x: x }` instead of `Struct { x }` in a pattern
-                at non_snake_case   variables, methods, functions, lifetime parameters and modules should have snake case names
-                at non_upper_case_globals static constants should have uppercase identifiers
-                at order_dependent_trait_objects trait-object types were treated as different depending on marker-trait order
-                at overflowing_literals literal out of range for its type
-                at overlapping_patterns detects overlapping patterns
-                at path_statements  path statements with no effect
-                at patterns_in_fns_without_body patterns in functions without body were erroneously allowed
-                at private_doc_tests detects code samples in docs of private items not documented by rustdoc
-                at private_in_public detect private items in public interfaces not caught by the old implementation
-                at proc_macro_derive_resolution_fallback detects proc macro derives using inaccessible names from parent modules
-                at pub_use_of_private_extern_crate detect public re-exports of private extern crates
-                at redundant_semicolons detects unnecessary trailing semicolons
-                at renamed_and_removed_lints lints that have been renamed or removed
-                at safe_packed_borrows safe borrows of fields of packed structs were erroneously allowed
-                at single_use_lifetimes detects lifetime parameters that are only used once
-                at soft_unstable    a feature gate that doesn't break dependent crates
-                at stable_features  stable features found in `#[feature]` directive
-                at trivial_bounds   these bounds don't depend on an type parameters
-                at trivial_casts    detects trivial casts which could be removed
-                at trivial_numeric_casts detects trivial casts of numeric types which could be removed
-                at type_alias_bounds bounds in type aliases are not enforced
-                at tyvar_behind_raw_pointer raw pointer to an inference variable
-                at unaligned_references detects unaligned references to fields of packed structs
-                at uncommon_codepoints detects uncommon Unicode codepoints in identifiers
-                at unconditional_panic operation will cause a panic at runtime
-                at unconditional_recursion functions that cannot return without calling themselves
-                at unknown_crate_types unknown crate type found in `#[crate_type]` directive
-                at unknown_lints    unrecognized lint attribute
-                at unnameable_test_items detects an item that cannot be named being marked as `#[test_case]`
-                at unreachable_code detects unreachable code paths
-                at unreachable_patterns detects unreachable patterns
-                at unreachable_pub  `pub` items not reachable from crate root
-                at unsafe_code      usage of `unsafe` code
-                at unsafe_op_in_unsafe_fn unsafe operations in unsafe functions without an explicit unsafe block are deprecated
-                at unstable_features enabling unstable features (deprecated. do not use)
-                at unstable_name_collisions detects name collision with an existing but unstable method
-                at unused_allocation detects unnecessary allocations that can be eliminated
-                at unused_assignments detect assignments that will never be read
-                at unused_attributes detects attributes that were not used by the compiler
-                at unused_braces    unnecessary braces around an expression
-                at unused_comparisons comparisons made useless by limits of the types involved
-                at unused_crate_dependencies crate dependencies that are never used
-                at unused_doc_comments detects doc comments that aren't used by rustdoc
-                at unused_extern_crates extern crates that are never used
-                at unused_features  unused features found in crate-level `#[feature]` directives
-                at unused_import_braces unnecessary braces around an imported item
-                at unused_imports   imports that are never used
-                at unused_labels    detects labels that are never used
-                at unused_lifetimes detects lifetime parameters that are never used
-                at unused_macros    detects macros that were not used
-                at unused_must_use  unused result of a type flagged as `#[must_use]`
-                at unused_mut       detect mut variables which don't need to be mutable
-                at unused_parens    `if`, `match`, `while` and `return` do not need parentheses
-                at unused_qualifications detects unnecessarily qualified names
-                at unused_results   unused result of an expression in a statement
-                at unused_unsafe    unnecessary use of an `unsafe` block
-                at unused_variables detect variables which are not used in any way
-                at variant_size_differences detects enums with widely varying variant sizes
-                at warnings         mass-change the level for lints which produce warnings
-                at where_clauses_object_safety checks the object safety of where clauses
-                at while_true       suggest using `loop { }` instead of `while true { }`
-        "#]],
-        )
-    }
-
-    #[test]
-    fn no_completion_for_incorrect_derive() {
-        check(
-            r#"
-#[derive{<|>)]
-struct Test {}
-"#,
-            expect![[r#""#]],
-        )
-    }
-
-    #[test]
-    fn derive_with_input_completion() {
-        check(
-            r#"
-#[derive(serde::Serialize, PartialEq, <|>)]
-struct Test {}
-"#,
-            expect![[r#"
-                at Clone
-                at Copy, Clone
-                at Debug
-                at Default
-                at Eq
-                at Hash
-                at Ord, PartialOrd, Eq
-                at PartialOrd
-            "#]],
-        )
-    }
-
-    #[test]
-    fn test_attribute_completion() {
-        check(
-            r#"#[<|>]"#,
-            expect![[r#"
-                at allow(…)
-                at cfg(…)
-                at cfg_attr(…)
-                at deny(…)
-                at deprecated = "…"
-                at derive(…)
-                at doc = "…"
-                at forbid(…)
-                at ignore = "…"
-                at inline(…)
-                at link
-                at link_name = "…"
-                at macro_export
-                at macro_use
-                at must_use = "…"
-                at no_mangle
-                at non_exhaustive
-                at path = "…"
-                at proc_macro
-                at proc_macro_attribute
-                at proc_macro_derive(…)
-                at repr(…)
-                at should_panic(…)
-                at target_feature = "…"
-                at test
-                at used
-                at warn(…)
-            "#]],
-        )
-    }
-
-    #[test]
-    fn test_attribute_completion_inside_nested_attr() {
-        check(r#"#[cfg(<|>)]"#, expect![[]])
-    }
-
-    #[test]
-    fn test_inner_attribute_completion() {
-        check(
-            r"#![<|>]",
-            expect![[r#"
-                at allow(…)
-                at cfg(…)
-                at cfg_attr(…)
-                at deny(…)
-                at deprecated = "…"
-                at derive(…)
-                at doc = "…"
-                at feature(…)
-                at forbid(…)
-                at global_allocator
-                at ignore = "…"
-                at inline(…)
-                at link
-                at link_name = "…"
-                at macro_export
-                at macro_use
-                at must_use = "…"
-                at no_mangle
-                at no_std
-                at non_exhaustive
-                at panic_handler
-                at path = "…"
-                at proc_macro
-                at proc_macro_attribute
-                at proc_macro_derive(…)
-                at recursion_limit = …
-                at repr(…)
-                at should_panic(…)
-                at target_feature = "…"
-                at test
-                at used
-                at warn(…)
-                at windows_subsystem = "…"
-            "#]],
-        );
-    }
-}
diff --git a/crates/ide/src/completion/complete_dot.rs b/crates/ide/src/completion/complete_dot.rs
deleted file mode 100644 (file)
index f0f9a7f..0000000
+++ /dev/null
@@ -1,431 +0,0 @@
-//! Completes references after dot (fields and method calls).
-
-use hir::{HasVisibility, Type};
-use rustc_hash::FxHashSet;
-use test_utils::mark;
-
-use crate::completion::{completion_context::CompletionContext, completion_item::Completions};
-
-/// Complete dot accesses, i.e. fields or methods.
-pub(super) fn complete_dot(acc: &mut Completions, ctx: &CompletionContext) {
-    let dot_receiver = match &ctx.dot_receiver {
-        Some(expr) => expr,
-        _ => return,
-    };
-
-    let receiver_ty = match ctx.sema.type_of_expr(&dot_receiver) {
-        Some(ty) => ty,
-        _ => return,
-    };
-
-    if ctx.is_call {
-        mark::hit!(test_no_struct_field_completion_for_method_call);
-    } else {
-        complete_fields(acc, ctx, &receiver_ty);
-    }
-    complete_methods(acc, ctx, &receiver_ty);
-}
-
-fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: &Type) {
-    for receiver in receiver.autoderef(ctx.db) {
-        for (field, ty) in receiver.fields(ctx.db) {
-            if ctx.scope.module().map_or(false, |m| !field.is_visible_from(ctx.db, m)) {
-                // Skip private field. FIXME: If the definition location of the
-                // field is editable, we should show the completion
-                continue;
-            }
-            acc.add_field(ctx, field, &ty);
-        }
-        for (i, ty) in receiver.tuple_fields(ctx.db).into_iter().enumerate() {
-            // FIXME: Handle visibility
-            acc.add_tuple_field(ctx, i, &ty);
-        }
-    }
-}
-
-fn complete_methods(acc: &mut Completions, ctx: &CompletionContext, receiver: &Type) {
-    if let Some(krate) = ctx.krate {
-        let mut seen_methods = FxHashSet::default();
-        let traits_in_scope = ctx.scope.traits_in_scope();
-        receiver.iterate_method_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, func| {
-            if func.self_param(ctx.db).is_some()
-                && ctx.scope.module().map_or(true, |m| func.is_visible_from(ctx.db, m))
-                && seen_methods.insert(func.name(ctx.db))
-            {
-                acc.add_function(ctx, func, None);
-            }
-            None::<()>
-        });
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-    use test_utils::mark;
-
-    use crate::completion::{test_utils::completion_list, CompletionKind};
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Reference);
-        expect.assert_eq(&actual);
-    }
-
-    #[test]
-    fn test_struct_field_and_method_completion() {
-        check(
-            r#"
-struct S { foo: u32 }
-impl S {
-    fn bar(&self) {}
-}
-fn foo(s: S) { s.<|> }
-"#,
-            expect![[r#"
-                me bar() fn bar(&self)
-                fd foo   u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_struct_field_completion_self() {
-        check(
-            r#"
-struct S { the_field: (u32,) }
-impl S {
-    fn foo(self) { self.<|> }
-}
-"#,
-            expect![[r#"
-                me foo()     fn foo(self)
-                fd the_field (u32,)
-            "#]],
-        )
-    }
-
-    #[test]
-    fn test_struct_field_completion_autoderef() {
-        check(
-            r#"
-struct A { the_field: (u32, i32) }
-impl A {
-    fn foo(&self) { self.<|> }
-}
-"#,
-            expect![[r#"
-                me foo()     fn foo(&self)
-                fd the_field (u32, i32)
-            "#]],
-        )
-    }
-
-    #[test]
-    fn test_no_struct_field_completion_for_method_call() {
-        mark::check!(test_no_struct_field_completion_for_method_call);
-        check(
-            r#"
-struct A { the_field: u32 }
-fn foo(a: A) { a.<|>() }
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn test_visibility_filtering() {
-        check(
-            r#"
-mod inner {
-    pub struct A {
-        private_field: u32,
-        pub pub_field: u32,
-        pub(crate) crate_field: u32,
-        pub(super) super_field: u32,
-    }
-}
-fn foo(a: inner::A) { a.<|> }
-"#,
-            expect![[r#"
-                fd crate_field u32
-                fd pub_field   u32
-                fd super_field u32
-            "#]],
-        );
-
-        check(
-            r#"
-struct A {}
-mod m {
-    impl super::A {
-        fn private_method(&self) {}
-        pub(super) fn the_method(&self) {}
-    }
-}
-fn foo(a: A) { a.<|> }
-"#,
-            expect![[r#"
-                me the_method() pub(super) fn the_method(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_union_field_completion() {
-        check(
-            r#"
-union U { field: u8, other: u16 }
-fn foo(u: U) { u.<|> }
-"#,
-            expect![[r#"
-                fd field u8
-                fd other u16
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_method_completion_only_fitting_impls() {
-        check(
-            r#"
-struct A<T> {}
-impl A<u32> {
-    fn the_method(&self) {}
-}
-impl A<i32> {
-    fn the_other_method(&self) {}
-}
-fn foo(a: A<u32>) { a.<|> }
-"#,
-            expect![[r#"
-                me the_method() fn the_method(&self)
-            "#]],
-        )
-    }
-
-    #[test]
-    fn test_trait_method_completion() {
-        check(
-            r#"
-struct A {}
-trait Trait { fn the_method(&self); }
-impl Trait for A {}
-fn foo(a: A) { a.<|> }
-"#,
-            expect![[r#"
-                me the_method() fn the_method(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_trait_method_completion_deduplicated() {
-        check(
-            r"
-struct A {}
-trait Trait { fn the_method(&self); }
-impl<T> Trait for T {}
-fn foo(a: &A) { a.<|> }
-",
-            expect![[r#"
-                me the_method() fn the_method(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_trait_method_from_other_module() {
-        check(
-            r"
-struct A {}
-mod m {
-    pub trait Trait { fn the_method(&self); }
-}
-use m::Trait;
-impl Trait for A {}
-fn foo(a: A) { a.<|> }
-",
-            expect![[r#"
-                me the_method() fn the_method(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_no_non_self_method() {
-        check(
-            r#"
-struct A {}
-impl A {
-    fn the_method() {}
-}
-fn foo(a: A) {
-   a.<|>
-}
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn test_tuple_field_completion() {
-        check(
-            r#"
-fn foo() {
-   let b = (0, 3.14);
-   b.<|>
-}
-"#,
-            expect![[r#"
-                fd 0 i32
-                fd 1 f64
-            "#]],
-        )
-    }
-
-    #[test]
-    fn test_tuple_field_inference() {
-        check(
-            r#"
-pub struct S;
-impl S { pub fn blah(&self) {} }
-
-struct T(S);
-
-impl T {
-    fn foo(&self) {
-        // FIXME: This doesn't work without the trailing `a` as `0.` is a float
-        self.0.a<|>
-    }
-}
-"#,
-            expect![[r#"
-                me blah() pub fn blah(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_completion_works_in_consts() {
-        check(
-            r#"
-struct A { the_field: u32 }
-const X: u32 = {
-    A { the_field: 92 }.<|>
-};
-"#,
-            expect![[r#"
-                fd the_field u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn works_in_simple_macro_1() {
-        check(
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-struct A { the_field: u32 }
-fn foo(a: A) {
-    m!(a.x<|>)
-}
-"#,
-            expect![[r#"
-                fd the_field u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn works_in_simple_macro_2() {
-        // this doesn't work yet because the macro doesn't expand without the token -- maybe it can be fixed with better recovery
-        check(
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-struct A { the_field: u32 }
-fn foo(a: A) {
-    m!(a.<|>)
-}
-"#,
-            expect![[r#"
-                fd the_field u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn works_in_simple_macro_recursive_1() {
-        check(
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-struct A { the_field: u32 }
-fn foo(a: A) {
-    m!(m!(m!(a.x<|>)))
-}
-"#,
-            expect![[r#"
-                fd the_field u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn macro_expansion_resilient() {
-        check(
-            r#"
-macro_rules! dbg {
-    () => {};
-    ($val:expr) => {
-        match $val { tmp => { tmp } }
-    };
-    // Trailing comma with single argument is ignored
-    ($val:expr,) => { $crate::dbg!($val) };
-    ($($val:expr),+ $(,)?) => {
-        ($($crate::dbg!($val)),+,)
-    };
-}
-struct A { the_field: u32 }
-fn foo(a: A) {
-    dbg!(a.<|>)
-}
-"#,
-            expect![[r#"
-                fd the_field u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_method_completion_issue_3547() {
-        check(
-            r#"
-struct HashSet<T> {}
-impl<T> HashSet<T> {
-    pub fn the_method(&self) {}
-}
-fn foo() {
-    let s: HashSet<_>;
-    s.<|>
-}
-"#,
-            expect![[r#"
-                me the_method() pub fn the_method(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_method_call_when_receiver_is_a_macro_call() {
-        check(
-            r#"
-struct S;
-impl S { fn foo(&self) {} }
-macro_rules! make_s { () => { S }; }
-fn main() { make_s!().f<|>; }
-"#,
-            expect![[r#"
-                me foo() fn foo(&self)
-            "#]],
-        )
-    }
-}
diff --git a/crates/ide/src/completion/complete_fn_param.rs b/crates/ide/src/completion/complete_fn_param.rs
deleted file mode 100644 (file)
index 9efe254..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-//! See `complete_fn_param`.
-
-use rustc_hash::FxHashMap;
-use syntax::{
-    ast::{self, ModuleItemOwner},
-    match_ast, AstNode,
-};
-
-use crate::completion::{CompletionContext, CompletionItem, CompletionKind, Completions};
-
-/// Complete repeated parameters, both name and type. For example, if all
-/// functions in a file have a `spam: &mut Spam` parameter, a completion with
-/// `spam: &mut Spam` insert text/label and `spam` lookup string will be
-/// suggested.
-pub(super) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext) {
-    if !ctx.is_param {
-        return;
-    }
-
-    let mut params = FxHashMap::default();
-
-    let me = ctx.token.ancestors().find_map(ast::Fn::cast);
-    let mut process_fn = |func: ast::Fn| {
-        if Some(&func) == me.as_ref() {
-            return;
-        }
-        func.param_list().into_iter().flat_map(|it| it.params()).for_each(|param| {
-            let text = param.syntax().text().to_string();
-            params.entry(text).or_insert(param);
-        })
-    };
-
-    for node in ctx.token.parent().ancestors() {
-        match_ast! {
-            match node {
-                ast::SourceFile(it) => it.items().filter_map(|item| match item {
-                    ast::Item::Fn(it) => Some(it),
-                    _ => None,
-                }).for_each(&mut process_fn),
-                ast::ItemList(it) => it.items().filter_map(|item| match item {
-                    ast::Item::Fn(it) => Some(it),
-                    _ => None,
-                }).for_each(&mut process_fn),
-                ast::AssocItemList(it) => it.assoc_items().filter_map(|item| match item {
-                    ast::AssocItem::Fn(it) => Some(it),
-                    _ => None,
-                }).for_each(&mut process_fn),
-                _ => continue,
-            }
-        };
-    }
-
-    params
-        .into_iter()
-        .filter_map(|(label, param)| {
-            let lookup = param.pat()?.syntax().text().to_string();
-            Some((label, lookup))
-        })
-        .for_each(|(label, lookup)| {
-            CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label)
-                .kind(crate::CompletionItemKind::Binding)
-                .lookup_by(lookup)
-                .add_to(acc)
-        });
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{test_utils::completion_list, CompletionKind};
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Magic);
-        expect.assert_eq(&actual);
-    }
-
-    #[test]
-    fn test_param_completion_last_param() {
-        check(
-            r#"
-fn foo(file_id: FileId) {}
-fn bar(file_id: FileId) {}
-fn baz(file<|>) {}
-"#,
-            expect![[r#"
-                bn file_id: FileId
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_param_completion_nth_param() {
-        check(
-            r#"
-fn foo(file_id: FileId) {}
-fn baz(file<|>, x: i32) {}
-"#,
-            expect![[r#"
-                bn file_id: FileId
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_param_completion_trait_param() {
-        check(
-            r#"
-pub(crate) trait SourceRoot {
-    pub fn contains(&self, file_id: FileId) -> bool;
-    pub fn module_map(&self) -> &ModuleMap;
-    pub fn lines(&self, file_id: FileId) -> &LineIndex;
-    pub fn syntax(&self, file<|>)
-}
-"#,
-            expect![[r#"
-                bn file_id: FileId
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_param_in_inner_function() {
-        check(
-            r#"
-fn outer(text: String) {
-    fn inner(<|>)
-}
-"#,
-            expect![[r#"
-                bn text: String
-            "#]],
-        )
-    }
-}
diff --git a/crates/ide/src/completion/complete_keyword.rs b/crates/ide/src/completion/complete_keyword.rs
deleted file mode 100644 (file)
index e597470..0000000
+++ /dev/null
@@ -1,568 +0,0 @@
-//! FIXME: write short doc here
-
-use syntax::{ast, SyntaxKind};
-use test_utils::mark;
-
-use crate::completion::{
-    CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions,
-};
-
-pub(super) fn complete_use_tree_keyword(acc: &mut Completions, ctx: &CompletionContext) {
-    // complete keyword "crate" in use stmt
-    let source_range = ctx.source_range();
-
-    if ctx.use_item_syntax.is_some() {
-        if ctx.path_qual.is_none() {
-            CompletionItem::new(CompletionKind::Keyword, source_range, "crate::")
-                .kind(CompletionItemKind::Keyword)
-                .insert_text("crate::")
-                .add_to(acc);
-        }
-        CompletionItem::new(CompletionKind::Keyword, source_range, "self")
-            .kind(CompletionItemKind::Keyword)
-            .add_to(acc);
-        CompletionItem::new(CompletionKind::Keyword, source_range, "super::")
-            .kind(CompletionItemKind::Keyword)
-            .insert_text("super::")
-            .add_to(acc);
-    }
-
-    // Suggest .await syntax for types that implement Future trait
-    if let Some(receiver) = &ctx.dot_receiver {
-        if let Some(ty) = ctx.sema.type_of_expr(receiver) {
-            if ty.impls_future(ctx.db) {
-                CompletionItem::new(CompletionKind::Keyword, ctx.source_range(), "await")
-                    .kind(CompletionItemKind::Keyword)
-                    .detail("expr.await")
-                    .insert_text("await")
-                    .add_to(acc);
-            }
-        };
-    }
-}
-
-pub(super) fn complete_expr_keyword(acc: &mut Completions, ctx: &CompletionContext) {
-    if ctx.token.kind() == SyntaxKind::COMMENT {
-        mark::hit!(no_keyword_completion_in_comments);
-        return;
-    }
-
-    let has_trait_or_impl_parent = ctx.has_impl_parent || ctx.has_trait_parent;
-    if ctx.trait_as_prev_sibling || ctx.impl_as_prev_sibling {
-        add_keyword(ctx, acc, "where", "where ");
-        return;
-    }
-    if ctx.unsafe_is_prev {
-        if ctx.has_item_list_or_source_file_parent || ctx.block_expr_parent {
-            add_keyword(ctx, acc, "fn", "fn $0() {}")
-        }
-
-        if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
-            add_keyword(ctx, acc, "trait", "trait $0 {}");
-            add_keyword(ctx, acc, "impl", "impl $0 {}");
-        }
-
-        return;
-    }
-    if ctx.has_item_list_or_source_file_parent || has_trait_or_impl_parent || ctx.block_expr_parent
-    {
-        add_keyword(ctx, acc, "fn", "fn $0() {}");
-    }
-    if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
-        add_keyword(ctx, acc, "use", "use ");
-        add_keyword(ctx, acc, "impl", "impl $0 {}");
-        add_keyword(ctx, acc, "trait", "trait $0 {}");
-    }
-
-    if ctx.has_item_list_or_source_file_parent {
-        add_keyword(ctx, acc, "enum", "enum $0 {}");
-        add_keyword(ctx, acc, "struct", "struct $0");
-        add_keyword(ctx, acc, "union", "union $0 {}");
-    }
-
-    if ctx.is_expr {
-        add_keyword(ctx, acc, "match", "match $0 {}");
-        add_keyword(ctx, acc, "while", "while $0 {}");
-        add_keyword(ctx, acc, "loop", "loop {$0}");
-        add_keyword(ctx, acc, "if", "if ");
-        add_keyword(ctx, acc, "if let", "if let ");
-    }
-
-    if ctx.if_is_prev || ctx.block_expr_parent {
-        add_keyword(ctx, acc, "let", "let ");
-    }
-
-    if ctx.after_if {
-        add_keyword(ctx, acc, "else", "else {$0}");
-        add_keyword(ctx, acc, "else if", "else if $0 {}");
-    }
-    if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
-        add_keyword(ctx, acc, "mod", "mod $0 {}");
-    }
-    if ctx.bind_pat_parent || ctx.ref_pat_parent {
-        add_keyword(ctx, acc, "mut", "mut ");
-    }
-    if ctx.has_item_list_or_source_file_parent || has_trait_or_impl_parent || ctx.block_expr_parent
-    {
-        add_keyword(ctx, acc, "const", "const ");
-        add_keyword(ctx, acc, "type", "type ");
-    }
-    if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
-        add_keyword(ctx, acc, "static", "static ");
-    };
-    if (ctx.has_item_list_or_source_file_parent) || ctx.block_expr_parent {
-        add_keyword(ctx, acc, "extern", "extern ");
-    }
-    if ctx.has_item_list_or_source_file_parent
-        || has_trait_or_impl_parent
-        || ctx.block_expr_parent
-        || ctx.is_match_arm
-    {
-        add_keyword(ctx, acc, "unsafe", "unsafe ");
-    }
-    if ctx.in_loop_body {
-        if ctx.can_be_stmt {
-            add_keyword(ctx, acc, "continue", "continue;");
-            add_keyword(ctx, acc, "break", "break;");
-        } else {
-            add_keyword(ctx, acc, "continue", "continue");
-            add_keyword(ctx, acc, "break", "break");
-        }
-    }
-    if ctx.has_item_list_or_source_file_parent || ctx.has_impl_parent | ctx.has_field_list_parent {
-        add_keyword(ctx, acc, "pub(crate)", "pub(crate) ");
-        add_keyword(ctx, acc, "pub", "pub ");
-    }
-
-    if !ctx.is_trivial_path {
-        return;
-    }
-    let fn_def = match &ctx.function_syntax {
-        Some(it) => it,
-        None => return,
-    };
-    acc.add_all(complete_return(ctx, &fn_def, ctx.can_be_stmt));
-}
-
-fn keyword(ctx: &CompletionContext, kw: &str, snippet: &str) -> CompletionItem {
-    let res = CompletionItem::new(CompletionKind::Keyword, ctx.source_range(), kw)
-        .kind(CompletionItemKind::Keyword);
-
-    match ctx.config.snippet_cap {
-        Some(cap) => res.insert_snippet(cap, snippet),
-        _ => res.insert_text(if snippet.contains('$') { kw } else { snippet }),
-    }
-    .build()
-}
-
-fn add_keyword(ctx: &CompletionContext, acc: &mut Completions, kw: &str, snippet: &str) {
-    acc.add(keyword(ctx, kw, snippet));
-}
-
-fn complete_return(
-    ctx: &CompletionContext,
-    fn_def: &ast::Fn,
-    can_be_stmt: bool,
-) -> Option<CompletionItem> {
-    let snip = match (can_be_stmt, fn_def.ret_type().is_some()) {
-        (true, true) => "return $0;",
-        (true, false) => "return;",
-        (false, true) => "return $0",
-        (false, false) => "return",
-    };
-    Some(keyword(ctx, "return", snip))
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{
-        test_utils::{check_edit, completion_list},
-        CompletionKind,
-    };
-    use test_utils::mark;
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Keyword);
-        expect.assert_eq(&actual)
-    }
-
-    #[test]
-    fn test_keywords_in_use_stmt() {
-        check(
-            r"use <|>",
-            expect![[r#"
-                kw crate::
-                kw self
-                kw super::
-            "#]],
-        );
-
-        check(
-            r"use a::<|>",
-            expect![[r#"
-                kw self
-                kw super::
-            "#]],
-        );
-
-        check(
-            r"use a::{b, <|>}",
-            expect![[r#"
-                kw self
-                kw super::
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_at_source_file_level() {
-        check(
-            r"m<|>",
-            expect![[r#"
-                kw const
-                kw enum
-                kw extern
-                kw fn
-                kw impl
-                kw mod
-                kw pub
-                kw pub(crate)
-                kw static
-                kw struct
-                kw trait
-                kw type
-                kw union
-                kw unsafe
-                kw use
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_in_function() {
-        check(
-            r"fn quux() { <|> }",
-            expect![[r#"
-                kw const
-                kw extern
-                kw fn
-                kw if
-                kw if let
-                kw impl
-                kw let
-                kw loop
-                kw match
-                kw mod
-                kw return
-                kw static
-                kw trait
-                kw type
-                kw unsafe
-                kw use
-                kw while
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_inside_block() {
-        check(
-            r"fn quux() { if true { <|> } }",
-            expect![[r#"
-                kw const
-                kw extern
-                kw fn
-                kw if
-                kw if let
-                kw impl
-                kw let
-                kw loop
-                kw match
-                kw mod
-                kw return
-                kw static
-                kw trait
-                kw type
-                kw unsafe
-                kw use
-                kw while
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_after_if() {
-        check(
-            r#"fn quux() { if true { () } <|> }"#,
-            expect![[r#"
-                kw const
-                kw else
-                kw else if
-                kw extern
-                kw fn
-                kw if
-                kw if let
-                kw impl
-                kw let
-                kw loop
-                kw match
-                kw mod
-                kw return
-                kw static
-                kw trait
-                kw type
-                kw unsafe
-                kw use
-                kw while
-            "#]],
-        );
-        check_edit(
-            "else",
-            r#"fn quux() { if true { () } <|> }"#,
-            r#"fn quux() { if true { () } else {$0} }"#,
-        );
-    }
-
-    #[test]
-    fn test_keywords_in_match_arm() {
-        check(
-            r#"
-fn quux() -> i32 {
-    match () { () => <|> }
-}
-"#,
-            expect![[r#"
-                kw if
-                kw if let
-                kw loop
-                kw match
-                kw return
-                kw unsafe
-                kw while
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_in_trait_def() {
-        check(
-            r"trait My { <|> }",
-            expect![[r#"
-                kw const
-                kw fn
-                kw type
-                kw unsafe
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_in_impl_def() {
-        check(
-            r"impl My { <|> }",
-            expect![[r#"
-                kw const
-                kw fn
-                kw pub
-                kw pub(crate)
-                kw type
-                kw unsafe
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_in_loop() {
-        check(
-            r"fn my() { loop { <|> } }",
-            expect![[r#"
-                kw break
-                kw const
-                kw continue
-                kw extern
-                kw fn
-                kw if
-                kw if let
-                kw impl
-                kw let
-                kw loop
-                kw match
-                kw mod
-                kw return
-                kw static
-                kw trait
-                kw type
-                kw unsafe
-                kw use
-                kw while
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_after_unsafe_in_item_list() {
-        check(
-            r"unsafe <|>",
-            expect![[r#"
-                kw fn
-                kw impl
-                kw trait
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_keywords_after_unsafe_in_block_expr() {
-        check(
-            r"fn my_fn() { unsafe <|> }",
-            expect![[r#"
-                kw fn
-                kw impl
-                kw trait
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_mut_in_ref_and_in_fn_parameters_list() {
-        check(
-            r"fn my_fn(&<|>) {}",
-            expect![[r#"
-                kw mut
-            "#]],
-        );
-        check(
-            r"fn my_fn(<|>) {}",
-            expect![[r#"
-                kw mut
-            "#]],
-        );
-        check(
-            r"fn my_fn() { let &<|> }",
-            expect![[r#"
-                kw mut
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_where_keyword() {
-        check(
-            r"trait A <|>",
-            expect![[r#"
-                kw where
-            "#]],
-        );
-        check(
-            r"impl A <|>",
-            expect![[r#"
-                kw where
-            "#]],
-        );
-    }
-
-    #[test]
-    fn no_keyword_completion_in_comments() {
-        mark::check!(no_keyword_completion_in_comments);
-        check(
-            r#"
-fn test() {
-    let x = 2; // A comment<|>
-}
-"#,
-            expect![[""]],
-        );
-        check(
-            r#"
-/*
-Some multi-line comment<|>
-*/
-"#,
-            expect![[""]],
-        );
-        check(
-            r#"
-/// Some doc comment
-/// let test<|> = 1
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn test_completion_await_impls_future() {
-        check(
-            r#"
-//- /main.rs crate:main deps:std
-use std::future::*;
-struct A {}
-impl Future for A {}
-fn foo(a: A) { a.<|> }
-
-//- /std/lib.rs crate:std
-pub mod future {
-    #[lang = "future_trait"]
-    pub trait Future {}
-}
-"#,
-            expect![[r#"
-                kw await expr.await
-            "#]],
-        );
-
-        check(
-            r#"
-//- /main.rs crate:main deps:std
-use std::future::*;
-fn foo() {
-    let a = async {};
-    a.<|>
-}
-
-//- /std/lib.rs crate:std
-pub mod future {
-    #[lang = "future_trait"]
-    pub trait Future {
-        type Output;
-    }
-}
-"#,
-            expect![[r#"
-                kw await expr.await
-            "#]],
-        )
-    }
-
-    #[test]
-    fn after_let() {
-        check(
-            r#"fn main() { let _ = <|> }"#,
-            expect![[r#"
-                kw if
-                kw if let
-                kw loop
-                kw match
-                kw return
-                kw while
-            "#]],
-        )
-    }
-
-    #[test]
-    fn before_field() {
-        check(
-            r#"
-struct Foo {
-    <|>
-    pub f: i32,
-}
-"#,
-            expect![[r#"
-                kw pub
-                kw pub(crate)
-            "#]],
-        )
-    }
-}
diff --git a/crates/ide/src/completion/complete_macro_in_item_position.rs b/crates/ide/src/completion/complete_macro_in_item_position.rs
deleted file mode 100644 (file)
index fc8625d..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-//! FIXME: write short doc here
-
-use crate::completion::{CompletionContext, Completions};
-
-pub(super) fn complete_macro_in_item_position(acc: &mut Completions, ctx: &CompletionContext) {
-    // Show only macros in top level.
-    if ctx.is_new_item {
-        ctx.scope.process_all_names(&mut |name, res| {
-            if let hir::ScopeDef::MacroDef(mac) = res {
-                acc.add_macro(ctx, Some(name.to_string()), mac);
-            }
-        })
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{test_utils::completion_list, CompletionKind};
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Reference);
-        expect.assert_eq(&actual)
-    }
-
-    #[test]
-    fn completes_macros_as_item() {
-        check(
-            r#"
-macro_rules! foo { () => {} }
-fn foo() {}
-
-<|>
-"#,
-            expect![[r#"
-                ma foo!(…) macro_rules! foo
-            "#]],
-        )
-    }
-}
diff --git a/crates/ide/src/completion/complete_mod.rs b/crates/ide/src/completion/complete_mod.rs
deleted file mode 100644 (file)
index c7a99bd..0000000
+++ /dev/null
@@ -1,324 +0,0 @@
-//! Completes mod declarations.
-
-use base_db::{SourceDatabaseExt, VfsPath};
-use hir::{Module, ModuleSource};
-use ide_db::RootDatabase;
-use rustc_hash::FxHashSet;
-
-use crate::{CompletionItem, CompletionItemKind};
-
-use super::{
-    completion_context::CompletionContext, completion_item::CompletionKind,
-    completion_item::Completions,
-};
-
-/// Complete mod declaration, i.e. `mod <|> ;`
-pub(super) fn complete_mod(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
-    let mod_under_caret = match &ctx.mod_declaration_under_caret {
-        Some(mod_under_caret) if mod_under_caret.item_list().is_some() => return None,
-        Some(mod_under_caret) => mod_under_caret,
-        None => return None,
-    };
-
-    let _p = profile::span("completion::complete_mod");
-
-    let current_module = ctx.scope.module()?;
-
-    let module_definition_file =
-        current_module.definition_source(ctx.db).file_id.original_file(ctx.db);
-    let source_root = ctx.db.source_root(ctx.db.file_source_root(module_definition_file));
-    let directory_to_look_for_submodules = directory_to_look_for_submodules(
-        current_module,
-        ctx.db,
-        source_root.path_for_file(&module_definition_file)?,
-    )?;
-
-    let existing_mod_declarations = current_module
-        .children(ctx.db)
-        .filter_map(|module| Some(module.name(ctx.db)?.to_string()))
-        .collect::<FxHashSet<_>>();
-
-    let module_declaration_file =
-        current_module.declaration_source(ctx.db).map(|module_declaration_source_file| {
-            module_declaration_source_file.file_id.original_file(ctx.db)
-        });
-
-    source_root
-        .iter()
-        .filter(|submodule_candidate_file| submodule_candidate_file != &module_definition_file)
-        .filter(|submodule_candidate_file| {
-            Some(submodule_candidate_file) != module_declaration_file.as_ref()
-        })
-        .filter_map(|submodule_file| {
-            let submodule_path = source_root.path_for_file(&submodule_file)?;
-            let directory_with_submodule = submodule_path.parent()?;
-            match submodule_path.name_and_extension()? {
-                ("lib", Some("rs")) | ("main", Some("rs")) => None,
-                ("mod", Some("rs")) => {
-                    if directory_with_submodule.parent()? == directory_to_look_for_submodules {
-                        match directory_with_submodule.name_and_extension()? {
-                            (directory_name, None) => Some(directory_name.to_owned()),
-                            _ => None,
-                        }
-                    } else {
-                        None
-                    }
-                }
-                (file_name, Some("rs"))
-                    if directory_with_submodule == directory_to_look_for_submodules =>
-                {
-                    Some(file_name.to_owned())
-                }
-                _ => None,
-            }
-        })
-        .filter(|name| !existing_mod_declarations.contains(name))
-        .for_each(|submodule_name| {
-            let mut label = submodule_name;
-            if mod_under_caret.semicolon_token().is_none() {
-                label.push(';')
-            }
-            acc.add(
-                CompletionItem::new(CompletionKind::Magic, ctx.source_range(), &label)
-                    .kind(CompletionItemKind::Module),
-            )
-        });
-
-    Some(())
-}
-
-fn directory_to_look_for_submodules(
-    module: Module,
-    db: &RootDatabase,
-    module_file_path: &VfsPath,
-) -> Option<VfsPath> {
-    let directory_with_module_path = module_file_path.parent()?;
-    let base_directory = match module_file_path.name_and_extension()? {
-        ("mod", Some("rs")) | ("lib", Some("rs")) | ("main", Some("rs")) => {
-            Some(directory_with_module_path)
-        }
-        (regular_rust_file_name, Some("rs")) => {
-            if matches!(
-                (
-                    directory_with_module_path
-                        .parent()
-                        .as_ref()
-                        .and_then(|path| path.name_and_extension()),
-                    directory_with_module_path.name_and_extension(),
-                ),
-                (Some(("src", None)), Some(("bin", None)))
-            ) {
-                // files in /src/bin/ can import each other directly
-                Some(directory_with_module_path)
-            } else {
-                directory_with_module_path.join(regular_rust_file_name)
-            }
-        }
-        _ => None,
-    }?;
-
-    let mut resulting_path = base_directory;
-    for module in module_chain_to_containing_module_file(module, db) {
-        if let Some(name) = module.name(db) {
-            resulting_path = resulting_path.join(&name.to_string())?;
-        }
-    }
-
-    Some(resulting_path)
-}
-
-fn module_chain_to_containing_module_file(
-    current_module: Module,
-    db: &RootDatabase,
-) -> Vec<Module> {
-    let mut path = Vec::new();
-
-    let mut current_module = Some(current_module);
-    while let Some(ModuleSource::Module(_)) =
-        current_module.map(|module| module.definition_source(db).value)
-    {
-        if let Some(module) = current_module {
-            path.insert(0, module);
-            current_module = module.parent(db);
-        } else {
-            current_module = None;
-        }
-    }
-
-    path
-}
-
-#[cfg(test)]
-mod tests {
-    use crate::completion::{test_utils::completion_list, CompletionKind};
-    use expect_test::{expect, Expect};
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Magic);
-        expect.assert_eq(&actual);
-    }
-
-    #[test]
-    fn lib_module_completion() {
-        check(
-            r#"
-            //- /lib.rs
-            mod <|>
-            //- /foo.rs
-            fn foo() {}
-            //- /foo/ignored_foo.rs
-            fn ignored_foo() {}
-            //- /bar/mod.rs
-            fn bar() {}
-            //- /bar/ignored_bar.rs
-            fn ignored_bar() {}
-        "#,
-            expect![[r#"
-                md bar;
-                md foo;
-            "#]],
-        );
-    }
-
-    #[test]
-    fn no_module_completion_with_module_body() {
-        check(
-            r#"
-            //- /lib.rs
-            mod <|> {
-
-            }
-            //- /foo.rs
-            fn foo() {}
-        "#,
-            expect![[r#""#]],
-        );
-    }
-
-    #[test]
-    fn main_module_completion() {
-        check(
-            r#"
-            //- /main.rs
-            mod <|>
-            //- /foo.rs
-            fn foo() {}
-            //- /foo/ignored_foo.rs
-            fn ignored_foo() {}
-            //- /bar/mod.rs
-            fn bar() {}
-            //- /bar/ignored_bar.rs
-            fn ignored_bar() {}
-        "#,
-            expect![[r#"
-                md bar;
-                md foo;
-            "#]],
-        );
-    }
-
-    #[test]
-    fn main_test_module_completion() {
-        check(
-            r#"
-            //- /main.rs
-            mod tests {
-                mod <|>;
-            }
-            //- /tests/foo.rs
-            fn foo() {}
-        "#,
-            expect![[r#"
-                md foo
-            "#]],
-        );
-    }
-
-    #[test]
-    fn directly_nested_module_completion() {
-        check(
-            r#"
-            //- /lib.rs
-            mod foo;
-            //- /foo.rs
-            mod <|>;
-            //- /foo/bar.rs
-            fn bar() {}
-            //- /foo/bar/ignored_bar.rs
-            fn ignored_bar() {}
-            //- /foo/baz/mod.rs
-            fn baz() {}
-            //- /foo/moar/ignored_moar.rs
-            fn ignored_moar() {}
-        "#,
-            expect![[r#"
-                md bar
-                md baz
-            "#]],
-        );
-    }
-
-    #[test]
-    fn nested_in_source_module_completion() {
-        check(
-            r#"
-            //- /lib.rs
-            mod foo;
-            //- /foo.rs
-            mod bar {
-                mod <|>
-            }
-            //- /foo/bar/baz.rs
-            fn baz() {}
-        "#,
-            expect![[r#"
-                md baz;
-            "#]],
-        );
-    }
-
-    // FIXME binary modules are not supported in tests properly
-    // Binary modules are a bit special, they allow importing the modules from `/src/bin`
-    // and that's why are good to test two things:
-    // * no cycles are allowed in mod declarations
-    // * no modules from the parent directory are proposed
-    // Unfortunately, binary modules support is in cargo not rustc,
-    // hence the test does not work now
-    //
-    // #[test]
-    // fn regular_bin_module_completion() {
-    //     check(
-    //         r#"
-    //         //- /src/bin.rs
-    //         fn main() {}
-    //         //- /src/bin/foo.rs
-    //         mod <|>
-    //         //- /src/bin/bar.rs
-    //         fn bar() {}
-    //         //- /src/bin/bar/bar_ignored.rs
-    //         fn bar_ignored() {}
-    //     "#,
-    //         expect![[r#"
-    //             md bar;
-    //         "#]],foo
-    //     );
-    // }
-
-    #[test]
-    fn already_declared_bin_module_completion_omitted() {
-        check(
-            r#"
-            //- /src/bin.rs crate:main
-            fn main() {}
-            //- /src/bin/foo.rs
-            mod <|>
-            //- /src/bin/bar.rs
-            mod foo;
-            fn bar() {}
-            //- /src/bin/bar/bar_ignored.rs
-            fn bar_ignored() {}
-        "#,
-            expect![[r#""#]],
-        );
-    }
-}
diff --git a/crates/ide/src/completion/complete_pattern.rs b/crates/ide/src/completion/complete_pattern.rs
deleted file mode 100644 (file)
index 5a13574..0000000
+++ /dev/null
@@ -1,88 +0,0 @@
-//! FIXME: write short doc here
-
-use crate::completion::{CompletionContext, Completions};
-
-/// Completes constats and paths in patterns.
-pub(super) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) {
-    if !ctx.is_pat_binding_or_const {
-        return;
-    }
-    if ctx.record_pat_syntax.is_some() {
-        return;
-    }
-
-    // FIXME: ideally, we should look at the type we are matching against and
-    // suggest variants + auto-imports
-    ctx.scope.process_all_names(&mut |name, res| {
-        match &res {
-            hir::ScopeDef::ModuleDef(def) => match def {
-                hir::ModuleDef::Adt(hir::Adt::Enum(..))
-                | hir::ModuleDef::Adt(hir::Adt::Struct(..))
-                | hir::ModuleDef::EnumVariant(..)
-                | hir::ModuleDef::Const(..)
-                | hir::ModuleDef::Module(..) => (),
-                _ => return,
-            },
-            hir::ScopeDef::MacroDef(_) => (),
-            _ => return,
-        };
-
-        acc.add_resolution(ctx, name.to_string(), &res)
-    });
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{test_utils::completion_list, CompletionKind};
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Reference);
-        expect.assert_eq(&actual)
-    }
-
-    #[test]
-    fn completes_enum_variants_and_modules() {
-        check(
-            r#"
-enum E { X }
-use self::E::X;
-const Z: E = E::X;
-mod m {}
-
-static FOO: E = E::X;
-struct Bar { f: u32 }
-
-fn foo() {
-   match E::X { <|> }
-}
-"#,
-            expect![[r#"
-                st Bar
-                en E
-                ev X   ()
-                ct Z
-                md m
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_in_simple_macro_call() {
-        check(
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-enum E { X }
-
-fn foo() {
-   m!(match E::X { <|> })
-}
-"#,
-            expect![[r#"
-                en E
-                ma m!(…) macro_rules! m
-            "#]],
-        );
-    }
-}
diff --git a/crates/ide/src/completion/complete_postfix.rs b/crates/ide/src/completion/complete_postfix.rs
deleted file mode 100644 (file)
index db53196..0000000
+++ /dev/null
@@ -1,454 +0,0 @@
-//! FIXME: write short doc here
-
-mod format_like;
-
-use assists::utils::TryEnum;
-use syntax::{
-    ast::{self, AstNode, AstToken},
-    TextRange, TextSize,
-};
-use text_edit::TextEdit;
-
-use self::format_like::add_format_like_completions;
-use crate::{
-    completion::{
-        completion_config::SnippetCap,
-        completion_context::CompletionContext,
-        completion_item::{Builder, CompletionKind, Completions},
-    },
-    CompletionItem, CompletionItemKind,
-};
-
-pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
-    if !ctx.config.enable_postfix_completions {
-        return;
-    }
-
-    let dot_receiver = match &ctx.dot_receiver {
-        Some(it) => it,
-        None => return,
-    };
-
-    let receiver_text =
-        get_receiver_text(dot_receiver, ctx.dot_receiver_is_ambiguous_float_literal);
-
-    let receiver_ty = match ctx.sema.type_of_expr(&dot_receiver) {
-        Some(it) => it,
-        None => return,
-    };
-
-    let cap = match ctx.config.snippet_cap {
-        Some(it) => it,
-        None => return,
-    };
-    let try_enum = TryEnum::from_ty(&ctx.sema, &receiver_ty);
-    if let Some(try_enum) = &try_enum {
-        match try_enum {
-            TryEnum::Result => {
-                postfix_snippet(
-                    ctx,
-                    cap,
-                    &dot_receiver,
-                    "ifl",
-                    "if let Ok {}",
-                    &format!("if let Ok($1) = {} {{\n    $0\n}}", receiver_text),
-                )
-                .add_to(acc);
-
-                postfix_snippet(
-                    ctx,
-                    cap,
-                    &dot_receiver,
-                    "while",
-                    "while let Ok {}",
-                    &format!("while let Ok($1) = {} {{\n    $0\n}}", receiver_text),
-                )
-                .add_to(acc);
-            }
-            TryEnum::Option => {
-                postfix_snippet(
-                    ctx,
-                    cap,
-                    &dot_receiver,
-                    "ifl",
-                    "if let Some {}",
-                    &format!("if let Some($1) = {} {{\n    $0\n}}", receiver_text),
-                )
-                .add_to(acc);
-
-                postfix_snippet(
-                    ctx,
-                    cap,
-                    &dot_receiver,
-                    "while",
-                    "while let Some {}",
-                    &format!("while let Some($1) = {} {{\n    $0\n}}", receiver_text),
-                )
-                .add_to(acc);
-            }
-        }
-    } else if receiver_ty.is_bool() || receiver_ty.is_unknown() {
-        postfix_snippet(
-            ctx,
-            cap,
-            &dot_receiver,
-            "if",
-            "if expr {}",
-            &format!("if {} {{\n    $0\n}}", receiver_text),
-        )
-        .add_to(acc);
-        postfix_snippet(
-            ctx,
-            cap,
-            &dot_receiver,
-            "while",
-            "while expr {}",
-            &format!("while {} {{\n    $0\n}}", receiver_text),
-        )
-        .add_to(acc);
-        postfix_snippet(ctx, cap, &dot_receiver, "not", "!expr", &format!("!{}", receiver_text))
-            .add_to(acc);
-    }
-
-    postfix_snippet(ctx, cap, &dot_receiver, "ref", "&expr", &format!("&{}", receiver_text))
-        .add_to(acc);
-    postfix_snippet(
-        ctx,
-        cap,
-        &dot_receiver,
-        "refm",
-        "&mut expr",
-        &format!("&mut {}", receiver_text),
-    )
-    .add_to(acc);
-
-    // The rest of the postfix completions create an expression that moves an argument,
-    // so it's better to consider references now to avoid breaking the compilation
-    let dot_receiver = include_references(dot_receiver);
-    let receiver_text =
-        get_receiver_text(&dot_receiver, ctx.dot_receiver_is_ambiguous_float_literal);
-
-    match try_enum {
-        Some(try_enum) => match try_enum {
-            TryEnum::Result => {
-                postfix_snippet(
-                    ctx,
-                    cap,
-                    &dot_receiver,
-                    "match",
-                    "match expr {}",
-                    &format!("match {} {{\n    Ok(${{1:_}}) => {{$2}},\n    Err(${{3:_}}) => {{$0}},\n}}", receiver_text),
-                )
-                .add_to(acc);
-            }
-            TryEnum::Option => {
-                postfix_snippet(
-                    ctx,
-                    cap,
-                    &dot_receiver,
-                    "match",
-                    "match expr {}",
-                    &format!(
-                        "match {} {{\n    Some(${{1:_}}) => {{$2}},\n    None => {{$0}},\n}}",
-                        receiver_text
-                    ),
-                )
-                .add_to(acc);
-            }
-        },
-        None => {
-            postfix_snippet(
-                ctx,
-                cap,
-                &dot_receiver,
-                "match",
-                "match expr {}",
-                &format!("match {} {{\n    ${{1:_}} => {{$0}},\n}}", receiver_text),
-            )
-            .add_to(acc);
-        }
-    }
-
-    postfix_snippet(
-        ctx,
-        cap,
-        &dot_receiver,
-        "box",
-        "Box::new(expr)",
-        &format!("Box::new({})", receiver_text),
-    )
-    .add_to(acc);
-
-    postfix_snippet(ctx, cap, &dot_receiver, "ok", "Ok(expr)", &format!("Ok({})", receiver_text))
-        .add_to(acc);
-
-    postfix_snippet(
-        ctx,
-        cap,
-        &dot_receiver,
-        "dbg",
-        "dbg!(expr)",
-        &format!("dbg!({})", receiver_text),
-    )
-    .add_to(acc);
-
-    postfix_snippet(
-        ctx,
-        cap,
-        &dot_receiver,
-        "dbgr",
-        "dbg!(&expr)",
-        &format!("dbg!(&{})", receiver_text),
-    )
-    .add_to(acc);
-
-    postfix_snippet(
-        ctx,
-        cap,
-        &dot_receiver,
-        "call",
-        "function(expr)",
-        &format!("${{1}}({})", receiver_text),
-    )
-    .add_to(acc);
-
-    if let ast::Expr::Literal(literal) = dot_receiver.clone() {
-        if let Some(literal_text) = ast::String::cast(literal.token()) {
-            add_format_like_completions(acc, ctx, &dot_receiver, cap, &literal_text);
-        }
-    }
-}
-
-fn get_receiver_text(receiver: &ast::Expr, receiver_is_ambiguous_float_literal: bool) -> String {
-    if receiver_is_ambiguous_float_literal {
-        let text = receiver.syntax().text();
-        let without_dot = ..text.len() - TextSize::of('.');
-        text.slice(without_dot).to_string()
-    } else {
-        receiver.to_string()
-    }
-}
-
-fn include_references(initial_element: &ast::Expr) -> ast::Expr {
-    let mut resulting_element = initial_element.clone();
-    while let Some(parent_ref_element) =
-        resulting_element.syntax().parent().and_then(ast::RefExpr::cast)
-    {
-        resulting_element = ast::Expr::from(parent_ref_element);
-    }
-    resulting_element
-}
-
-fn postfix_snippet(
-    ctx: &CompletionContext,
-    cap: SnippetCap,
-    receiver: &ast::Expr,
-    label: &str,
-    detail: &str,
-    snippet: &str,
-) -> Builder {
-    let edit = {
-        let receiver_syntax = receiver.syntax();
-        let receiver_range = ctx.sema.original_range(receiver_syntax).range;
-        let delete_range = TextRange::new(receiver_range.start(), ctx.source_range().end());
-        TextEdit::replace(delete_range, snippet.to_string())
-    };
-    CompletionItem::new(CompletionKind::Postfix, ctx.source_range(), label)
-        .detail(detail)
-        .kind(CompletionItemKind::Snippet)
-        .snippet_edit(cap, edit)
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{
-        test_utils::{check_edit, completion_list},
-        CompletionKind,
-    };
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Postfix);
-        expect.assert_eq(&actual)
-    }
-
-    #[test]
-    fn postfix_completion_works_for_trivial_path_expression() {
-        check(
-            r#"
-fn main() {
-    let bar = true;
-    bar.<|>
-}
-"#,
-            expect![[r#"
-                sn box   Box::new(expr)
-                sn call  function(expr)
-                sn dbg   dbg!(expr)
-                sn dbgr  dbg!(&expr)
-                sn if    if expr {}
-                sn match match expr {}
-                sn not   !expr
-                sn ok    Ok(expr)
-                sn ref   &expr
-                sn refm  &mut expr
-                sn while while expr {}
-            "#]],
-        );
-    }
-
-    #[test]
-    fn postfix_type_filtering() {
-        check(
-            r#"
-fn main() {
-    let bar: u8 = 12;
-    bar.<|>
-}
-"#,
-            expect![[r#"
-                sn box   Box::new(expr)
-                sn call  function(expr)
-                sn dbg   dbg!(expr)
-                sn dbgr  dbg!(&expr)
-                sn match match expr {}
-                sn ok    Ok(expr)
-                sn ref   &expr
-                sn refm  &mut expr
-            "#]],
-        )
-    }
-
-    #[test]
-    fn option_iflet() {
-        check_edit(
-            "ifl",
-            r#"
-enum Option<T> { Some(T), None }
-
-fn main() {
-    let bar = Option::Some(true);
-    bar.<|>
-}
-"#,
-            r#"
-enum Option<T> { Some(T), None }
-
-fn main() {
-    let bar = Option::Some(true);
-    if let Some($1) = bar {
-    $0
-}
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn result_match() {
-        check_edit(
-            "match",
-            r#"
-enum Result<T, E> { Ok(T), Err(E) }
-
-fn main() {
-    let bar = Result::Ok(true);
-    bar.<|>
-}
-"#,
-            r#"
-enum Result<T, E> { Ok(T), Err(E) }
-
-fn main() {
-    let bar = Result::Ok(true);
-    match bar {
-    Ok(${1:_}) => {$2},
-    Err(${3:_}) => {$0},
-}
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn postfix_completion_works_for_ambiguous_float_literal() {
-        check_edit("refm", r#"fn main() { 42.<|> }"#, r#"fn main() { &mut 42 }"#)
-    }
-
-    #[test]
-    fn works_in_simple_macro() {
-        check_edit(
-            "dbg",
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-fn main() {
-    let bar: u8 = 12;
-    m!(bar.d<|>)
-}
-"#,
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-fn main() {
-    let bar: u8 = 12;
-    m!(dbg!(bar))
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn postfix_completion_for_references() {
-        check_edit("dbg", r#"fn main() { &&42.<|> }"#, r#"fn main() { dbg!(&&42) }"#);
-        check_edit("refm", r#"fn main() { &&42.<|> }"#, r#"fn main() { &&&mut 42 }"#);
-    }
-
-    #[test]
-    fn postfix_completion_for_format_like_strings() {
-        check_edit(
-            "fmt",
-            r#"fn main() { "{some_var:?}".<|> }"#,
-            r#"fn main() { format!("{:?}", some_var) }"#,
-        );
-        check_edit(
-            "panic",
-            r#"fn main() { "Panic with {a}".<|> }"#,
-            r#"fn main() { panic!("Panic with {}", a) }"#,
-        );
-        check_edit(
-            "println",
-            r#"fn main() { "{ 2+2 } { SomeStruct { val: 1, other: 32 } :?}".<|> }"#,
-            r#"fn main() { println!("{} {:?}", 2+2, SomeStruct { val: 1, other: 32 }) }"#,
-        );
-        check_edit(
-            "loge",
-            r#"fn main() { "{2+2}".<|> }"#,
-            r#"fn main() { log::error!("{}", 2+2) }"#,
-        );
-        check_edit(
-            "logt",
-            r#"fn main() { "{2+2}".<|> }"#,
-            r#"fn main() { log::trace!("{}", 2+2) }"#,
-        );
-        check_edit(
-            "logd",
-            r#"fn main() { "{2+2}".<|> }"#,
-            r#"fn main() { log::debug!("{}", 2+2) }"#,
-        );
-        check_edit(
-            "logi",
-            r#"fn main() { "{2+2}".<|> }"#,
-            r#"fn main() { log::info!("{}", 2+2) }"#,
-        );
-        check_edit(
-            "logw",
-            r#"fn main() { "{2+2}".<|> }"#,
-            r#"fn main() { log::warn!("{}", 2+2) }"#,
-        );
-        check_edit(
-            "loge",
-            r#"fn main() { "{2+2}".<|> }"#,
-            r#"fn main() { log::error!("{}", 2+2) }"#,
-        );
-    }
-}
diff --git a/crates/ide/src/completion/complete_postfix/format_like.rs b/crates/ide/src/completion/complete_postfix/format_like.rs
deleted file mode 100644 (file)
index 50d1e5c..0000000
+++ /dev/null
@@ -1,279 +0,0 @@
-// Feature: Format String Completion.
-//
-// `"Result {result} is {2 + 2}"` is expanded to the `"Result {} is {}", result, 2 + 2`.
-//
-// The following postfix snippets are available:
-//
-// - `format` -> `format!(...)`
-// - `panic` -> `panic!(...)`
-// - `println` -> `println!(...)`
-// - `log`:
-//   + `logd` -> `log::debug!(...)`
-//   + `logt` -> `log::trace!(...)`
-//   + `logi` -> `log::info!(...)`
-//   + `logw` -> `log::warn!(...)`
-//   + `loge` -> `log::error!(...)`
-
-use crate::completion::{
-    complete_postfix::postfix_snippet, completion_config::SnippetCap,
-    completion_context::CompletionContext, completion_item::Completions,
-};
-use syntax::ast::{self, AstToken};
-
-/// Mapping ("postfix completion item" => "macro to use")
-static KINDS: &[(&str, &str)] = &[
-    ("fmt", "format!"),
-    ("panic", "panic!"),
-    ("println", "println!"),
-    ("eprintln", "eprintln!"),
-    ("logd", "log::debug!"),
-    ("logt", "log::trace!"),
-    ("logi", "log::info!"),
-    ("logw", "log::warn!"),
-    ("loge", "log::error!"),
-];
-
-pub(super) fn add_format_like_completions(
-    acc: &mut Completions,
-    ctx: &CompletionContext,
-    dot_receiver: &ast::Expr,
-    cap: SnippetCap,
-    receiver_text: &ast::String,
-) {
-    let input = match string_literal_contents(receiver_text) {
-        // It's not a string literal, do not parse input.
-        Some(input) => input,
-        None => return,
-    };
-
-    let mut parser = FormatStrParser::new(input);
-
-    if parser.parse().is_ok() {
-        for (label, macro_name) in KINDS {
-            let snippet = parser.into_suggestion(macro_name);
-
-            postfix_snippet(ctx, cap, &dot_receiver, label, macro_name, &snippet).add_to(acc);
-        }
-    }
-}
-
-/// Checks whether provided item is a string literal.
-fn string_literal_contents(item: &ast::String) -> Option<String> {
-    let item = item.text();
-    if item.len() >= 2 && item.starts_with("\"") && item.ends_with("\"") {
-        return Some(item[1..item.len() - 1].to_owned());
-    }
-
-    None
-}
-
-/// Parser for a format-like string. It is more allowing in terms of string contents,
-/// as we expect variable placeholders to be filled with expressions.
-#[derive(Debug)]
-pub struct FormatStrParser {
-    input: String,
-    output: String,
-    extracted_expressions: Vec<String>,
-    state: State,
-    parsed: bool,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq)]
-enum State {
-    NotExpr,
-    MaybeExpr,
-    Expr,
-    MaybeIncorrect,
-    FormatOpts,
-}
-
-impl FormatStrParser {
-    pub fn new(input: String) -> Self {
-        Self {
-            input: input.into(),
-            output: String::new(),
-            extracted_expressions: Vec::new(),
-            state: State::NotExpr,
-            parsed: false,
-        }
-    }
-
-    pub fn parse(&mut self) -> Result<(), ()> {
-        let mut current_expr = String::new();
-
-        let mut placeholder_id = 1;
-
-        // Count of open braces inside of an expression.
-        // We assume that user knows what they're doing, thus we treat it like a correct pattern, e.g.
-        // "{MyStruct { val_a: 0, val_b: 1 }}".
-        let mut inexpr_open_count = 0;
-
-        for chr in self.input.chars() {
-            match (self.state, chr) {
-                (State::NotExpr, '{') => {
-                    self.output.push(chr);
-                    self.state = State::MaybeExpr;
-                }
-                (State::NotExpr, '}') => {
-                    self.output.push(chr);
-                    self.state = State::MaybeIncorrect;
-                }
-                (State::NotExpr, _) => {
-                    self.output.push(chr);
-                }
-                (State::MaybeIncorrect, '}') => {
-                    // It's okay, we met "}}".
-                    self.output.push(chr);
-                    self.state = State::NotExpr;
-                }
-                (State::MaybeIncorrect, _) => {
-                    // Error in the string.
-                    return Err(());
-                }
-                (State::MaybeExpr, '{') => {
-                    self.output.push(chr);
-                    self.state = State::NotExpr;
-                }
-                (State::MaybeExpr, '}') => {
-                    // This is an empty sequence '{}'. Replace it with placeholder.
-                    self.output.push(chr);
-                    self.extracted_expressions.push(format!("${}", placeholder_id));
-                    placeholder_id += 1;
-                    self.state = State::NotExpr;
-                }
-                (State::MaybeExpr, _) => {
-                    current_expr.push(chr);
-                    self.state = State::Expr;
-                }
-                (State::Expr, '}') => {
-                    if inexpr_open_count == 0 {
-                        self.output.push(chr);
-                        self.extracted_expressions.push(current_expr.trim().into());
-                        current_expr = String::new();
-                        self.state = State::NotExpr;
-                    } else {
-                        // We're closing one brace met before inside of the expression.
-                        current_expr.push(chr);
-                        inexpr_open_count -= 1;
-                    }
-                }
-                (State::Expr, ':') => {
-                    if inexpr_open_count == 0 {
-                        // We're outside of braces, thus assume that it's a specifier, like "{Some(value):?}"
-                        self.output.push(chr);
-                        self.extracted_expressions.push(current_expr.trim().into());
-                        current_expr = String::new();
-                        self.state = State::FormatOpts;
-                    } else {
-                        // We're inside of braced expression, assume that it's a struct field name/value delimeter.
-                        current_expr.push(chr);
-                    }
-                }
-                (State::Expr, '{') => {
-                    current_expr.push(chr);
-                    inexpr_open_count += 1;
-                }
-                (State::Expr, _) => {
-                    current_expr.push(chr);
-                }
-                (State::FormatOpts, '}') => {
-                    self.output.push(chr);
-                    self.state = State::NotExpr;
-                }
-                (State::FormatOpts, _) => {
-                    self.output.push(chr);
-                }
-            }
-        }
-
-        if self.state != State::NotExpr {
-            return Err(());
-        }
-
-        self.parsed = true;
-        Ok(())
-    }
-
-    pub fn into_suggestion(&self, macro_name: &str) -> String {
-        assert!(self.parsed, "Attempt to get a suggestion from not parsed expression");
-
-        let expressions_as_string = self.extracted_expressions.join(", ");
-        format!(r#"{}("{}", {})"#, macro_name, self.output, expressions_as_string)
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use expect_test::{expect, Expect};
-
-    fn check(input: &str, expect: &Expect) {
-        let mut parser = FormatStrParser::new((*input).to_owned());
-        let outcome_repr = if parser.parse().is_ok() {
-            // Parsing should be OK, expected repr is "string; expr_1, expr_2".
-            if parser.extracted_expressions.is_empty() {
-                parser.output
-            } else {
-                format!("{}; {}", parser.output, parser.extracted_expressions.join(", "))
-            }
-        } else {
-            // Parsing should fail, expected repr is "-".
-            "-".to_owned()
-        };
-
-        expect.assert_eq(&outcome_repr);
-    }
-
-    #[test]
-    fn format_str_parser() {
-        let test_vector = &[
-            ("no expressions", expect![["no expressions"]]),
-            ("{expr} is {2 + 2}", expect![["{} is {}; expr, 2 + 2"]]),
-            ("{expr:?}", expect![["{:?}; expr"]]),
-            ("{malformed", expect![["-"]]),
-            ("malformed}", expect![["-"]]),
-            ("{{correct", expect![["{{correct"]]),
-            ("correct}}", expect![["correct}}"]]),
-            ("{correct}}}", expect![["{}}}; correct"]]),
-            ("{correct}}}}}", expect![["{}}}}}; correct"]]),
-            ("{incorrect}}", expect![["-"]]),
-            ("placeholders {} {}", expect![["placeholders {} {}; $1, $2"]]),
-            ("mixed {} {2 + 2} {}", expect![["mixed {} {} {}; $1, 2 + 2, $2"]]),
-            (
-                "{SomeStruct { val_a: 0, val_b: 1 }}",
-                expect![["{}; SomeStruct { val_a: 0, val_b: 1 }"]],
-            ),
-            ("{expr:?} is {2.32f64:.5}", expect![["{:?} is {:.5}; expr, 2.32f64"]]),
-            (
-                "{SomeStruct { val_a: 0, val_b: 1 }:?}",
-                expect![["{:?}; SomeStruct { val_a: 0, val_b: 1 }"]],
-            ),
-            ("{     2 + 2        }", expect![["{}; 2 + 2"]]),
-        ];
-
-        for (input, output) in test_vector {
-            check(input, output)
-        }
-    }
-
-    #[test]
-    fn test_into_suggestion() {
-        let test_vector = &[
-            ("println!", "{}", r#"println!("{}", $1)"#),
-            ("eprintln!", "{}", r#"eprintln!("{}", $1)"#),
-            (
-                "log::info!",
-                "{} {expr} {} {2 + 2}",
-                r#"log::info!("{} {} {} {}", $1, expr, $2, 2 + 2)"#,
-            ),
-            ("format!", "{expr:?}", r#"format!("{:?}", expr)"#),
-        ];
-
-        for (kind, input, output) in test_vector {
-            let mut parser = FormatStrParser::new((*input).to_owned());
-            parser.parse().expect("Parsing must succeed");
-
-            assert_eq!(&parser.into_suggestion(*kind), output);
-        }
-    }
-}
diff --git a/crates/ide/src/completion/complete_qualified_path.rs b/crates/ide/src/completion/complete_qualified_path.rs
deleted file mode 100644 (file)
index 2fafedd..0000000
+++ /dev/null
@@ -1,755 +0,0 @@
-//! Completion of paths, i.e. `some::prefix::<|>`.
-
-use hir::{Adt, HasVisibility, PathResolution, ScopeDef};
-use rustc_hash::FxHashSet;
-use syntax::AstNode;
-use test_utils::mark;
-
-use crate::completion::{CompletionContext, Completions};
-
-pub(super) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionContext) {
-    let path = match &ctx.path_qual {
-        Some(path) => path.clone(),
-        None => return,
-    };
-
-    if ctx.attribute_under_caret.is_some() || ctx.mod_declaration_under_caret.is_some() {
-        return;
-    }
-
-    let context_module = ctx.scope.module();
-
-    let resolution = match ctx.sema.resolve_path(&path) {
-        Some(res) => res,
-        None => return,
-    };
-
-    // Add associated types on type parameters and `Self`.
-    resolution.assoc_type_shorthand_candidates(ctx.db, |alias| {
-        acc.add_type_alias(ctx, alias);
-        None::<()>
-    });
-
-    match resolution {
-        PathResolution::Def(hir::ModuleDef::Module(module)) => {
-            let module_scope = module.scope(ctx.db, context_module);
-            for (name, def) in module_scope {
-                if ctx.use_item_syntax.is_some() {
-                    if let ScopeDef::Unknown = def {
-                        if let Some(name_ref) = ctx.name_ref_syntax.as_ref() {
-                            if name_ref.syntax().text() == name.to_string().as_str() {
-                                // for `use self::foo<|>`, don't suggest `foo` as a completion
-                                mark::hit!(dont_complete_current_use);
-                                continue;
-                            }
-                        }
-                    }
-                }
-
-                acc.add_resolution(ctx, name.to_string(), &def);
-            }
-        }
-        PathResolution::Def(def @ hir::ModuleDef::Adt(_))
-        | PathResolution::Def(def @ hir::ModuleDef::TypeAlias(_)) => {
-            if let hir::ModuleDef::Adt(Adt::Enum(e)) = def {
-                for variant in e.variants(ctx.db) {
-                    acc.add_enum_variant(ctx, variant, None);
-                }
-            }
-            let ty = match def {
-                hir::ModuleDef::Adt(adt) => adt.ty(ctx.db),
-                hir::ModuleDef::TypeAlias(a) => a.ty(ctx.db),
-                _ => unreachable!(),
-            };
-
-            // XXX: For parity with Rust bug #22519, this does not complete Ty::AssocType.
-            // (where AssocType is defined on a trait, not an inherent impl)
-
-            let krate = ctx.krate;
-            if let Some(krate) = krate {
-                let traits_in_scope = ctx.scope.traits_in_scope();
-                ty.iterate_path_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, item| {
-                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
-                        return None;
-                    }
-                    match item {
-                        hir::AssocItem::Function(func) => {
-                            acc.add_function(ctx, func, None);
-                        }
-                        hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
-                        hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
-                    }
-                    None::<()>
-                });
-
-                // Iterate assoc types separately
-                ty.iterate_assoc_items(ctx.db, krate, |item| {
-                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
-                        return None;
-                    }
-                    match item {
-                        hir::AssocItem::Function(_) | hir::AssocItem::Const(_) => {}
-                        hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
-                    }
-                    None::<()>
-                });
-            }
-        }
-        PathResolution::Def(hir::ModuleDef::Trait(t)) => {
-            // Handles `Trait::assoc` as well as `<Ty as Trait>::assoc`.
-            for item in t.items(ctx.db) {
-                if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
-                    continue;
-                }
-                match item {
-                    hir::AssocItem::Function(func) => {
-                        acc.add_function(ctx, func, None);
-                    }
-                    hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
-                    hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
-                }
-            }
-        }
-        PathResolution::TypeParam(_) | PathResolution::SelfType(_) => {
-            if let Some(krate) = ctx.krate {
-                let ty = match resolution {
-                    PathResolution::TypeParam(param) => param.ty(ctx.db),
-                    PathResolution::SelfType(impl_def) => impl_def.target_ty(ctx.db),
-                    _ => return,
-                };
-
-                let traits_in_scope = ctx.scope.traits_in_scope();
-                let mut seen = FxHashSet::default();
-                ty.iterate_path_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, item| {
-                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
-                        return None;
-                    }
-
-                    // We might iterate candidates of a trait multiple times here, so deduplicate
-                    // them.
-                    if seen.insert(item) {
-                        match item {
-                            hir::AssocItem::Function(func) => {
-                                acc.add_function(ctx, func, None);
-                            }
-                            hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
-                            hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
-                        }
-                    }
-                    None::<()>
-                });
-            }
-        }
-        _ => {}
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-    use test_utils::mark;
-
-    use crate::completion::{
-        test_utils::{check_edit, completion_list},
-        CompletionKind,
-    };
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Reference);
-        expect.assert_eq(&actual);
-    }
-
-    fn check_builtin(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::BuiltinType);
-        expect.assert_eq(&actual);
-    }
-
-    #[test]
-    fn dont_complete_current_use() {
-        mark::check!(dont_complete_current_use);
-        check(r#"use self::foo<|>;"#, expect![[""]]);
-    }
-
-    #[test]
-    fn dont_complete_current_use_in_braces_with_glob() {
-        check(
-            r#"
-mod foo { pub struct S; }
-use self::{foo::*, bar<|>};
-"#,
-            expect![[r#"
-                st S
-                md foo
-            "#]],
-        );
-    }
-
-    #[test]
-    fn dont_complete_primitive_in_use() {
-        check_builtin(r#"use self::<|>;"#, expect![[""]]);
-    }
-
-    #[test]
-    fn dont_complete_primitive_in_module_scope() {
-        check_builtin(r#"fn foo() { self::<|> }"#, expect![[""]]);
-    }
-
-    #[test]
-    fn completes_primitives() {
-        check_builtin(
-            r#"fn main() { let _: <|> = 92; }"#,
-            expect![[r#"
-                bt bool
-                bt char
-                bt f32
-                bt f64
-                bt i128
-                bt i16
-                bt i32
-                bt i64
-                bt i8
-                bt isize
-                bt str
-                bt u128
-                bt u16
-                bt u32
-                bt u64
-                bt u8
-                bt usize
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_mod_with_same_name_as_function() {
-        check(
-            r#"
-use self::my::<|>;
-
-mod my { pub struct Bar; }
-fn my() {}
-"#,
-            expect![[r#"
-                st Bar
-            "#]],
-        );
-    }
-
-    #[test]
-    fn filters_visibility() {
-        check(
-            r#"
-use self::my::<|>;
-
-mod my {
-    struct Bar;
-    pub struct Foo;
-    pub use Bar as PublicBar;
-}
-"#,
-            expect![[r#"
-                st Foo
-                st PublicBar
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_use_item_starting_with_self() {
-        check(
-            r#"
-use self::m::<|>;
-
-mod m { pub struct Bar; }
-"#,
-            expect![[r#"
-                st Bar
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_use_item_starting_with_crate() {
-        check(
-            r#"
-//- /lib.rs
-mod foo;
-struct Spam;
-//- /foo.rs
-use crate::Sp<|>
-"#,
-            expect![[r#"
-                st Spam
-                md foo
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_nested_use_tree() {
-        check(
-            r#"
-//- /lib.rs
-mod foo;
-struct Spam;
-//- /foo.rs
-use crate::{Sp<|>};
-"#,
-            expect![[r#"
-                st Spam
-                md foo
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_deeply_nested_use_tree() {
-        check(
-            r#"
-//- /lib.rs
-mod foo;
-pub mod bar {
-    pub mod baz {
-        pub struct Spam;
-    }
-}
-//- /foo.rs
-use crate::{bar::{baz::Sp<|>}};
-"#,
-            expect![[r#"
-                st Spam
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_enum_variant() {
-        check(
-            r#"
-enum E { Foo, Bar(i32) }
-fn foo() { let _ = E::<|> }
-"#,
-            expect![[r#"
-                ev Bar(…) (i32)
-                ev Foo    ()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_struct_associated_items() {
-        check(
-            r#"
-//- /lib.rs
-struct S;
-
-impl S {
-    fn a() {}
-    fn b(&self) {}
-    const C: i32 = 42;
-    type T = i32;
-}
-
-fn foo() { let _ = S::<|> }
-"#,
-            expect![[r#"
-                ct C   const C: i32 = 42;
-                ta T   type T = i32;
-                fn a() fn a()
-                me b() fn b(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn associated_item_visibility() {
-        check(
-            r#"
-struct S;
-
-mod m {
-    impl super::S {
-        pub(super) fn public_method() { }
-        fn private_method() { }
-        pub(super) type PublicType = u32;
-        type PrivateType = u32;
-        pub(super) const PUBLIC_CONST: u32 = 1;
-        const PRIVATE_CONST: u32 = 1;
-    }
-}
-
-fn foo() { let _ = S::<|> }
-"#,
-            expect![[r#"
-                ct PUBLIC_CONST    pub(super) const PUBLIC_CONST: u32 = 1;
-                ta PublicType      pub(super) type PublicType = u32;
-                fn public_method() pub(super) fn public_method()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_enum_associated_method() {
-        check(
-            r#"
-enum E {};
-impl E { fn m() { } }
-
-fn foo() { let _ = E::<|> }
-        "#,
-            expect![[r#"
-                fn m() fn m()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_union_associated_method() {
-        check(
-            r#"
-union U {};
-impl U { fn m() { } }
-
-fn foo() { let _ = U::<|> }
-"#,
-            expect![[r#"
-                fn m() fn m()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_use_paths_across_crates() {
-        check(
-            r#"
-//- /main.rs crate:main deps:foo
-use foo::<|>;
-
-//- /foo/lib.rs crate:foo
-pub mod bar { pub struct S; }
-"#,
-            expect![[r#"
-                md bar
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_trait_associated_method_1() {
-        check(
-            r#"
-trait Trait { fn m(); }
-
-fn foo() { let _ = Trait::<|> }
-"#,
-            expect![[r#"
-                fn m() fn m()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_trait_associated_method_2() {
-        check(
-            r#"
-trait Trait { fn m(); }
-
-struct S;
-impl Trait for S {}
-
-fn foo() { let _ = S::<|> }
-"#,
-            expect![[r#"
-                fn m() fn m()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_trait_associated_method_3() {
-        check(
-            r#"
-trait Trait { fn m(); }
-
-struct S;
-impl Trait for S {}
-
-fn foo() { let _ = <S as Trait>::<|> }
-"#,
-            expect![[r#"
-                fn m() fn m()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_ty_param_assoc_ty() {
-        check(
-            r#"
-trait Super {
-    type Ty;
-    const CONST: u8;
-    fn func() {}
-    fn method(&self) {}
-}
-
-trait Sub: Super {
-    type SubTy;
-    const C2: ();
-    fn subfunc() {}
-    fn submethod(&self) {}
-}
-
-fn foo<T: Sub>() { T::<|> }
-"#,
-            expect![[r#"
-                ct C2          const C2: ();
-                ct CONST       const CONST: u8;
-                ta SubTy       type SubTy;
-                ta Ty          type Ty;
-                fn func()      fn func()
-                me method()    fn method(&self)
-                fn subfunc()   fn subfunc()
-                me submethod() fn submethod(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_self_param_assoc_ty() {
-        check(
-            r#"
-trait Super {
-    type Ty;
-    const CONST: u8 = 0;
-    fn func() {}
-    fn method(&self) {}
-}
-
-trait Sub: Super {
-    type SubTy;
-    const C2: () = ();
-    fn subfunc() {}
-    fn submethod(&self) {}
-}
-
-struct Wrap<T>(T);
-impl<T> Super for Wrap<T> {}
-impl<T> Sub for Wrap<T> {
-    fn subfunc() {
-        // Should be able to assume `Self: Sub + Super`
-        Self::<|>
-    }
-}
-"#,
-            expect![[r#"
-                ct C2          const C2: () = ();
-                ct CONST       const CONST: u8 = 0;
-                ta SubTy       type SubTy;
-                ta Ty          type Ty;
-                fn func()      fn func()
-                me method()    fn method(&self)
-                fn subfunc()   fn subfunc()
-                me submethod() fn submethod(&self)
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_type_alias() {
-        check(
-            r#"
-struct S;
-impl S { fn foo() {} }
-type T = S;
-impl T { fn bar() {} }
-
-fn main() { T::<|>; }
-"#,
-            expect![[r#"
-                fn bar() fn bar()
-                fn foo() fn foo()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_qualified_macros() {
-        check(
-            r#"
-#[macro_export]
-macro_rules! foo { () => {} }
-
-fn main() { let _ = crate::<|> }
-        "#,
-            expect![[r##"
-                ma foo!(…) #[macro_export]
-                macro_rules! foo
-                fn main()  fn main()
-            "##]],
-        );
-    }
-
-    #[test]
-    fn test_super_super_completion() {
-        check(
-            r#"
-mod a {
-    const A: usize = 0;
-    mod b {
-        const B: usize = 0;
-        mod c { use super::super::<|> }
-    }
-}
-"#,
-            expect![[r#"
-                ct A
-                md b
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_reexported_items_under_correct_name() {
-        check(
-            r#"
-fn foo() { self::m::<|> }
-
-mod m {
-    pub use super::p::wrong_fn as right_fn;
-    pub use super::p::WRONG_CONST as RIGHT_CONST;
-    pub use super::p::WrongType as RightType;
-}
-mod p {
-    fn wrong_fn() {}
-    const WRONG_CONST: u32 = 1;
-    struct WrongType {};
-}
-"#,
-            expect![[r#"
-                ct RIGHT_CONST
-                st RightType
-                fn right_fn()  fn wrong_fn()
-            "#]],
-        );
-
-        check_edit(
-            "RightType",
-            r#"
-fn foo() { self::m::<|> }
-
-mod m {
-    pub use super::p::wrong_fn as right_fn;
-    pub use super::p::WRONG_CONST as RIGHT_CONST;
-    pub use super::p::WrongType as RightType;
-}
-mod p {
-    fn wrong_fn() {}
-    const WRONG_CONST: u32 = 1;
-    struct WrongType {};
-}
-"#,
-            r#"
-fn foo() { self::m::RightType }
-
-mod m {
-    pub use super::p::wrong_fn as right_fn;
-    pub use super::p::WRONG_CONST as RIGHT_CONST;
-    pub use super::p::WrongType as RightType;
-}
-mod p {
-    fn wrong_fn() {}
-    const WRONG_CONST: u32 = 1;
-    struct WrongType {};
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn completes_in_simple_macro_call() {
-        check(
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-fn main() { m!(self::f<|>); }
-fn foo() {}
-"#,
-            expect![[r#"
-                fn foo()  fn foo()
-                fn main() fn main()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn function_mod_share_name() {
-        check(
-            r#"
-fn foo() { self::m::<|> }
-
-mod m {
-    pub mod z {}
-    pub fn z() {}
-}
-"#,
-            expect![[r#"
-                md z
-                fn z() pub fn z()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_hashmap_new() {
-        check(
-            r#"
-struct RandomState;
-struct HashMap<K, V, S = RandomState> {}
-
-impl<K, V> HashMap<K, V, RandomState> {
-    pub fn new() -> HashMap<K, V, RandomState> { }
-}
-fn foo() {
-    HashMap::<|>
-}
-"#,
-            expect![[r#"
-                fn new() pub fn new() -> HashMap<K, V, RandomState>
-            "#]],
-        );
-    }
-
-    #[test]
-    fn dont_complete_attr() {
-        check(
-            r#"
-mod foo { pub struct Foo; }
-#[foo::<|>]
-fn f() {}
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn completes_function() {
-        check(
-            r#"
-fn foo(
-    a: i32,
-    b: i32
-) {
-
-}
-
-fn main() {
-    fo<|>
-}
-"#,
-            expect![[r#"
-                fn foo(…) fn foo(a: i32, b: i32)
-                fn main() fn main()
-            "#]],
-        );
-    }
-}
diff --git a/crates/ide/src/completion/complete_record.rs b/crates/ide/src/completion/complete_record.rs
deleted file mode 100644 (file)
index ceb8d16..0000000
+++ /dev/null
@@ -1,226 +0,0 @@
-//! Complete fields in record literals and patterns.
-use crate::completion::{CompletionContext, Completions};
-
-pub(super) fn complete_record(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
-    let missing_fields = match (ctx.record_pat_syntax.as_ref(), ctx.record_lit_syntax.as_ref()) {
-        (None, None) => return None,
-        (Some(_), Some(_)) => unreachable!("A record cannot be both a literal and a pattern"),
-        (Some(record_pat), _) => ctx.sema.record_pattern_missing_fields(record_pat),
-        (_, Some(record_lit)) => ctx.sema.record_literal_missing_fields(record_lit),
-    };
-
-    for (field, ty) in missing_fields {
-        acc.add_field(ctx, field, &ty)
-    }
-
-    Some(())
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{test_utils::completion_list, CompletionKind};
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Reference);
-        expect.assert_eq(&actual);
-    }
-
-    #[test]
-    fn test_record_pattern_field() {
-        check(
-            r#"
-struct S { foo: u32 }
-
-fn process(f: S) {
-    match f {
-        S { f<|>: 92 } => (),
-    }
-}
-"#,
-            expect![[r#"
-                fd foo u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_record_pattern_enum_variant() {
-        check(
-            r#"
-enum E { S { foo: u32, bar: () } }
-
-fn process(e: E) {
-    match e {
-        E::S { <|> } => (),
-    }
-}
-"#,
-            expect![[r#"
-                fd bar ()
-                fd foo u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_record_pattern_field_in_simple_macro() {
-        check(
-            r"
-macro_rules! m { ($e:expr) => { $e } }
-struct S { foo: u32 }
-
-fn process(f: S) {
-    m!(match f {
-        S { f<|>: 92 } => (),
-    })
-}
-",
-            expect![[r#"
-                fd foo u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn only_missing_fields_are_completed_in_destruct_pats() {
-        check(
-            r#"
-struct S {
-    foo1: u32, foo2: u32,
-    bar: u32, baz: u32,
-}
-
-fn main() {
-    let s = S {
-        foo1: 1, foo2: 2,
-        bar: 3, baz: 4,
-    };
-    if let S { foo1, foo2: a, <|> } = s {}
-}
-"#,
-            expect![[r#"
-                fd bar u32
-                fd baz u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_record_literal_field() {
-        check(
-            r#"
-struct A { the_field: u32 }
-fn foo() {
-   A { the<|> }
-}
-"#,
-            expect![[r#"
-                fd the_field u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_record_literal_enum_variant() {
-        check(
-            r#"
-enum E { A { a: u32 } }
-fn foo() {
-    let _ = E::A { <|> }
-}
-"#,
-            expect![[r#"
-                fd a u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_record_literal_two_structs() {
-        check(
-            r#"
-struct A { a: u32 }
-struct B { b: u32 }
-
-fn foo() {
-   let _: A = B { <|> }
-}
-"#,
-            expect![[r#"
-                fd b u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_record_literal_generic_struct() {
-        check(
-            r#"
-struct A<T> { a: T }
-
-fn foo() {
-   let _: A<u32> = A { <|> }
-}
-"#,
-            expect![[r#"
-                fd a u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn test_record_literal_field_in_simple_macro() {
-        check(
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-struct A { the_field: u32 }
-fn foo() {
-   m!(A { the<|> })
-}
-"#,
-            expect![[r#"
-                fd the_field u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn only_missing_fields_are_completed() {
-        check(
-            r#"
-struct S {
-    foo1: u32, foo2: u32,
-    bar: u32, baz: u32,
-}
-
-fn main() {
-    let foo1 = 1;
-    let s = S { foo1, foo2: 5, <|> }
-}
-"#,
-            expect![[r#"
-                fd bar u32
-                fd baz u32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_functional_update() {
-        check(
-            r#"
-struct S { foo1: u32, foo2: u32 }
-
-fn main() {
-    let foo1 = 1;
-    let s = S { foo1, <|> .. loop {} }
-}
-"#,
-            expect![[r#"
-                fd foo2 u32
-            "#]],
-        );
-    }
-}
diff --git a/crates/ide/src/completion/complete_snippet.rs b/crates/ide/src/completion/complete_snippet.rs
deleted file mode 100644 (file)
index 4837d29..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-//! FIXME: write short doc here
-
-use crate::completion::{
-    completion_config::SnippetCap, completion_item::Builder, CompletionContext, CompletionItem,
-    CompletionItemKind, CompletionKind, Completions,
-};
-
-fn snippet(ctx: &CompletionContext, cap: SnippetCap, label: &str, snippet: &str) -> Builder {
-    CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), label)
-        .insert_snippet(cap, snippet)
-        .kind(CompletionItemKind::Snippet)
-}
-
-pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) {
-    if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) {
-        return;
-    }
-    let cap = match ctx.config.snippet_cap {
-        Some(it) => it,
-        None => return,
-    };
-
-    snippet(ctx, cap, "pd", "eprintln!(\"$0 = {:?}\", $0);").add_to(acc);
-    snippet(ctx, cap, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc);
-}
-
-pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) {
-    if !ctx.is_new_item {
-        return;
-    }
-    let cap = match ctx.config.snippet_cap {
-        Some(it) => it,
-        None => return,
-    };
-
-    snippet(
-        ctx,
-        cap,
-        "tmod (Test module)",
-        "\
-#[cfg(test)]
-mod tests {
-    use super::*;
-
-    #[test]
-    fn ${1:test_name}() {
-        $0
-    }
-}",
-    )
-    .lookup_by("tmod")
-    .add_to(acc);
-
-    snippet(
-        ctx,
-        cap,
-        "tfn (Test function)",
-        "\
-#[test]
-fn ${1:feature}() {
-    $0
-}",
-    )
-    .lookup_by("tfn")
-    .add_to(acc);
-
-    snippet(ctx, cap, "macro_rules", "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}").add_to(acc);
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{test_utils::completion_list, CompletionKind};
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Snippet);
-        expect.assert_eq(&actual)
-    }
-
-    #[test]
-    fn completes_snippets_in_expressions() {
-        check(
-            r#"fn foo(x: i32) { <|> }"#,
-            expect![[r#"
-                sn pd
-                sn ppd
-            "#]],
-        );
-    }
-
-    #[test]
-    fn should_not_complete_snippets_in_path() {
-        check(r#"fn foo(x: i32) { ::foo<|> }"#, expect![[""]]);
-        check(r#"fn foo(x: i32) { ::<|> }"#, expect![[""]]);
-    }
-
-    #[test]
-    fn completes_snippets_in_items() {
-        check(
-            r#"
-#[cfg(test)]
-mod tests {
-    <|>
-}
-"#,
-            expect![[r#"
-                sn macro_rules
-                sn tfn (Test function)
-                sn tmod (Test module)
-            "#]],
-        )
-    }
-}
diff --git a/crates/ide/src/completion/complete_trait_impl.rs b/crates/ide/src/completion/complete_trait_impl.rs
deleted file mode 100644 (file)
index ff115df..0000000
+++ /dev/null
@@ -1,733 +0,0 @@
-//! Completion for associated items in a trait implementation.
-//!
-//! This module adds the completion items related to implementing associated
-//! items within a `impl Trait for Struct` block. The current context node
-//! must be within either a `FN`, `TYPE_ALIAS`, or `CONST` node
-//! and an direct child of an `IMPL`.
-//!
-//! # Examples
-//!
-//! Considering the following trait `impl`:
-//!
-//! ```ignore
-//! trait SomeTrait {
-//!     fn foo();
-//! }
-//!
-//! impl SomeTrait for () {
-//!     fn f<|>
-//! }
-//! ```
-//!
-//! may result in the completion of the following method:
-//!
-//! ```ignore
-//! # trait SomeTrait {
-//! #    fn foo();
-//! # }
-//!
-//! impl SomeTrait for () {
-//!     fn foo() {}<|>
-//! }
-//! ```
-
-use assists::utils::get_missing_assoc_items;
-use hir::{self, HasAttrs, HasSource};
-use syntax::{
-    ast::{self, edit, Impl},
-    AstNode, SyntaxKind, SyntaxNode, TextRange, T,
-};
-use text_edit::TextEdit;
-
-use crate::{
-    completion::{
-        CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, Completions,
-    },
-    display::function_declaration,
-};
-
-#[derive(Debug, PartialEq, Eq)]
-enum ImplCompletionKind {
-    All,
-    Fn,
-    TypeAlias,
-    Const,
-}
-
-pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext) {
-    if let Some((kind, trigger, impl_def)) = completion_match(ctx) {
-        get_missing_assoc_items(&ctx.sema, &impl_def).into_iter().for_each(|item| match item {
-            hir::AssocItem::Function(fn_item)
-                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Fn =>
-            {
-                add_function_impl(&trigger, acc, ctx, fn_item)
-            }
-            hir::AssocItem::TypeAlias(type_item)
-                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::TypeAlias =>
-            {
-                add_type_alias_impl(&trigger, acc, ctx, type_item)
-            }
-            hir::AssocItem::Const(const_item)
-                if kind == ImplCompletionKind::All || kind == ImplCompletionKind::Const =>
-            {
-                add_const_impl(&trigger, acc, ctx, const_item)
-            }
-            _ => {}
-        });
-    }
-}
-
-fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> {
-    let mut token = ctx.token.clone();
-    // For keywork without name like `impl .. { fn <|> }`, the current position is inside
-    // the whitespace token, which is outside `FN` syntax node.
-    // We need to follow the previous token in this case.
-    if token.kind() == SyntaxKind::WHITESPACE {
-        token = token.prev_token()?;
-    }
-
-    let impl_item_offset = match token.kind() {
-        // `impl .. { const <|> }`
-        // ERROR      0
-        //   CONST_KW <- *
-        SyntaxKind::CONST_KW => 0,
-        // `impl .. { fn/type <|> }`
-        // FN/TYPE_ALIAS  0
-        //   FN_KW        <- *
-        SyntaxKind::FN_KW | SyntaxKind::TYPE_KW => 0,
-        // `impl .. { fn/type/const foo<|> }`
-        // FN/TYPE_ALIAS/CONST  1
-        //  NAME                0
-        //    IDENT             <- *
-        SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1,
-        // `impl .. { foo<|> }`
-        // MACRO_CALL       3
-        //  PATH            2
-        //    PATH_SEGMENT  1
-        //      NAME_REF    0
-        //        IDENT     <- *
-        SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME_REF => 3,
-        _ => return None,
-    };
-
-    let impl_item = token.ancestors().nth(impl_item_offset)?;
-    // Must directly belong to an impl block.
-    // IMPL
-    //   ASSOC_ITEM_LIST
-    //     <item>
-    let impl_def = ast::Impl::cast(impl_item.parent()?.parent()?)?;
-    let kind = match impl_item.kind() {
-        // `impl ... { const <|> fn/type/const }`
-        _ if token.kind() == SyntaxKind::CONST_KW => ImplCompletionKind::Const,
-        SyntaxKind::CONST | SyntaxKind::ERROR => ImplCompletionKind::Const,
-        SyntaxKind::TYPE_ALIAS => ImplCompletionKind::TypeAlias,
-        SyntaxKind::FN => ImplCompletionKind::Fn,
-        SyntaxKind::MACRO_CALL => ImplCompletionKind::All,
-        _ => return None,
-    };
-    Some((kind, impl_item, impl_def))
-}
-
-fn add_function_impl(
-    fn_def_node: &SyntaxNode,
-    acc: &mut Completions,
-    ctx: &CompletionContext,
-    func: hir::Function,
-) {
-    let fn_name = func.name(ctx.db).to_string();
-
-    let label = if func.params(ctx.db).is_empty() {
-        format!("fn {}()", fn_name)
-    } else {
-        format!("fn {}(..)", fn_name)
-    };
-
-    let builder = CompletionItem::new(CompletionKind::Magic, ctx.source_range(), label)
-        .lookup_by(fn_name)
-        .set_documentation(func.docs(ctx.db));
-
-    let completion_kind = if func.self_param(ctx.db).is_some() {
-        CompletionItemKind::Method
-    } else {
-        CompletionItemKind::Function
-    };
-    let range = TextRange::new(fn_def_node.text_range().start(), ctx.source_range().end());
-
-    let function_decl = function_declaration(&func.source(ctx.db).value);
-    match ctx.config.snippet_cap {
-        Some(cap) => {
-            let snippet = format!("{} {{\n    $0\n}}", function_decl);
-            builder.snippet_edit(cap, TextEdit::replace(range, snippet))
-        }
-        None => {
-            let header = format!("{} {{", function_decl);
-            builder.text_edit(TextEdit::replace(range, header))
-        }
-    }
-    .kind(completion_kind)
-    .add_to(acc);
-}
-
-fn add_type_alias_impl(
-    type_def_node: &SyntaxNode,
-    acc: &mut Completions,
-    ctx: &CompletionContext,
-    type_alias: hir::TypeAlias,
-) {
-    let alias_name = type_alias.name(ctx.db).to_string();
-
-    let snippet = format!("type {} = ", alias_name);
-
-    let range = TextRange::new(type_def_node.text_range().start(), ctx.source_range().end());
-
-    CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
-        .text_edit(TextEdit::replace(range, snippet))
-        .lookup_by(alias_name)
-        .kind(CompletionItemKind::TypeAlias)
-        .set_documentation(type_alias.docs(ctx.db))
-        .add_to(acc);
-}
-
-fn add_const_impl(
-    const_def_node: &SyntaxNode,
-    acc: &mut Completions,
-    ctx: &CompletionContext,
-    const_: hir::Const,
-) {
-    let const_name = const_.name(ctx.db).map(|n| n.to_string());
-
-    if let Some(const_name) = const_name {
-        let snippet = make_const_compl_syntax(&const_.source(ctx.db).value);
-
-        let range = TextRange::new(const_def_node.text_range().start(), ctx.source_range().end());
-
-        CompletionItem::new(CompletionKind::Magic, ctx.source_range(), snippet.clone())
-            .text_edit(TextEdit::replace(range, snippet))
-            .lookup_by(const_name)
-            .kind(CompletionItemKind::Const)
-            .set_documentation(const_.docs(ctx.db))
-            .add_to(acc);
-    }
-}
-
-fn make_const_compl_syntax(const_: &ast::Const) -> String {
-    let const_ = edit::remove_attrs_and_docs(const_);
-
-    let const_start = const_.syntax().text_range().start();
-    let const_end = const_.syntax().text_range().end();
-
-    let start =
-        const_.syntax().first_child_or_token().map_or(const_start, |f| f.text_range().start());
-
-    let end = const_
-        .syntax()
-        .children_with_tokens()
-        .find(|s| s.kind() == T![;] || s.kind() == T![=])
-        .map_or(const_end, |f| f.text_range().start());
-
-    let len = end - start;
-    let range = TextRange::new(0.into(), len);
-
-    let syntax = const_.syntax().text().slice(range).to_string();
-
-    format!("{} = ", syntax.trim_end())
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-
-    use crate::completion::{
-        test_utils::{check_edit, completion_list},
-        CompletionKind,
-    };
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Magic);
-        expect.assert_eq(&actual)
-    }
-
-    #[test]
-    fn name_ref_function_type_const() {
-        check(
-            r#"
-trait Test {
-    type TestType;
-    const TEST_CONST: u16;
-    fn test();
-}
-struct T;
-
-impl Test for T {
-    t<|>
-}
-"#,
-            expect![["
-ct const TEST_CONST: u16 = \n\
-fn fn test()
-ta type TestType = \n\
-            "]],
-        );
-    }
-
-    #[test]
-    fn no_completion_inside_fn() {
-        check(
-            r"
-trait Test { fn test(); fn test2(); }
-struct T;
-
-impl Test for T {
-    fn test() {
-        t<|>
-    }
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { fn test(); fn test2(); }
-struct T;
-
-impl Test for T {
-    fn test() {
-        fn t<|>
-    }
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { fn test(); fn test2(); }
-struct T;
-
-impl Test for T {
-    fn test() {
-        fn <|>
-    }
-}
-",
-            expect![[""]],
-        );
-
-        // https://github.com/rust-analyzer/rust-analyzer/pull/5976#issuecomment-692332191
-        check(
-            r"
-trait Test { fn test(); fn test2(); }
-struct T;
-
-impl Test for T {
-    fn test() {
-        foo.<|>
-    }
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { fn test(_: i32); fn test2(); }
-struct T;
-
-impl Test for T {
-    fn test(t<|>)
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { fn test(_: fn()); fn test2(); }
-struct T;
-
-impl Test for T {
-    fn test(f: fn <|>)
-}
-",
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn no_completion_inside_const() {
-        check(
-            r"
-trait Test { const TEST: fn(); const TEST2: u32; type Test; fn test(); }
-struct T;
-
-impl Test for T {
-    const TEST: fn <|>
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
-struct T;
-
-impl Test for T {
-    const TEST: T<|>
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
-struct T;
-
-impl Test for T {
-    const TEST: u32 = f<|>
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
-struct T;
-
-impl Test for T {
-    const TEST: u32 = {
-        t<|>
-    };
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
-struct T;
-
-impl Test for T {
-    const TEST: u32 = {
-        fn <|>
-    };
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { const TEST: u32; const TEST2: u32; type Test; fn test(); }
-struct T;
-
-impl Test for T {
-    const TEST: u32 = {
-        fn t<|>
-    };
-}
-",
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn no_completion_inside_type() {
-        check(
-            r"
-trait Test { type Test; type Test2; fn test(); }
-struct T;
-
-impl Test for T {
-    type Test = T<|>;
-}
-",
-            expect![[""]],
-        );
-
-        check(
-            r"
-trait Test { type Test; type Test2; fn test(); }
-struct T;
-
-impl Test for T {
-    type Test = fn <|>;
-}
-",
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn name_ref_single_function() {
-        check_edit(
-            "test",
-            r#"
-trait Test {
-    fn test();
-}
-struct T;
-
-impl Test for T {
-    t<|>
-}
-"#,
-            r#"
-trait Test {
-    fn test();
-}
-struct T;
-
-impl Test for T {
-    fn test() {
-    $0
-}
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn single_function() {
-        check_edit(
-            "test",
-            r#"
-trait Test {
-    fn test();
-}
-struct T;
-
-impl Test for T {
-    fn t<|>
-}
-"#,
-            r#"
-trait Test {
-    fn test();
-}
-struct T;
-
-impl Test for T {
-    fn test() {
-    $0
-}
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn hide_implemented_fn() {
-        check(
-            r#"
-trait Test {
-    fn foo();
-    fn foo_bar();
-}
-struct T;
-
-impl Test for T {
-    fn foo() {}
-    fn f<|>
-}
-"#,
-            expect![[r#"
-                fn fn foo_bar()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn generic_fn() {
-        check_edit(
-            "foo",
-            r#"
-trait Test {
-    fn foo<T>();
-}
-struct T;
-
-impl Test for T {
-    fn f<|>
-}
-"#,
-            r#"
-trait Test {
-    fn foo<T>();
-}
-struct T;
-
-impl Test for T {
-    fn foo<T>() {
-    $0
-}
-}
-"#,
-        );
-        check_edit(
-            "foo",
-            r#"
-trait Test {
-    fn foo<T>() where T: Into<String>;
-}
-struct T;
-
-impl Test for T {
-    fn f<|>
-}
-"#,
-            r#"
-trait Test {
-    fn foo<T>() where T: Into<String>;
-}
-struct T;
-
-impl Test for T {
-    fn foo<T>()
-where T: Into<String> {
-    $0
-}
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn associated_type() {
-        check_edit(
-            "SomeType",
-            r#"
-trait Test {
-    type SomeType;
-}
-
-impl Test for () {
-    type S<|>
-}
-"#,
-            "
-trait Test {
-    type SomeType;
-}
-
-impl Test for () {
-    type SomeType = \n\
-}
-",
-        );
-    }
-
-    #[test]
-    fn associated_const() {
-        check_edit(
-            "SOME_CONST",
-            r#"
-trait Test {
-    const SOME_CONST: u16;
-}
-
-impl Test for () {
-    const S<|>
-}
-"#,
-            "
-trait Test {
-    const SOME_CONST: u16;
-}
-
-impl Test for () {
-    const SOME_CONST: u16 = \n\
-}
-",
-        );
-
-        check_edit(
-            "SOME_CONST",
-            r#"
-trait Test {
-    const SOME_CONST: u16 = 92;
-}
-
-impl Test for () {
-    const S<|>
-}
-"#,
-            "
-trait Test {
-    const SOME_CONST: u16 = 92;
-}
-
-impl Test for () {
-    const SOME_CONST: u16 = \n\
-}
-",
-        );
-    }
-
-    #[test]
-    fn complete_without_name() {
-        let test = |completion: &str, hint: &str, completed: &str, next_sibling: &str| {
-            println!(
-                "completion='{}', hint='{}', next_sibling='{}'",
-                completion, hint, next_sibling
-            );
-
-            check_edit(
-                completion,
-                &format!(
-                    r#"
-trait Test {{
-    type Foo;
-    const CONST: u16;
-    fn bar();
-}}
-struct T;
-
-impl Test for T {{
-    {}
-    {}
-}}
-"#,
-                    hint, next_sibling
-                ),
-                &format!(
-                    r#"
-trait Test {{
-    type Foo;
-    const CONST: u16;
-    fn bar();
-}}
-struct T;
-
-impl Test for T {{
-    {}
-    {}
-}}
-"#,
-                    completed, next_sibling
-                ),
-            )
-        };
-
-        // Enumerate some possible next siblings.
-        for next_sibling in &[
-            "",
-            "fn other_fn() {}", // `const <|> fn` -> `const fn`
-            "type OtherType = i32;",
-            "const OTHER_CONST: i32 = 0;",
-            "async fn other_fn() {}",
-            "unsafe fn other_fn() {}",
-            "default fn other_fn() {}",
-            "default type OtherType = i32;",
-            "default const OTHER_CONST: i32 = 0;",
-        ] {
-            test("bar", "fn <|>", "fn bar() {\n    $0\n}", next_sibling);
-            test("Foo", "type <|>", "type Foo = ", next_sibling);
-            test("CONST", "const <|>", "const CONST: u16 = ", next_sibling);
-        }
-    }
-}
diff --git a/crates/ide/src/completion/complete_unqualified_path.rs b/crates/ide/src/completion/complete_unqualified_path.rs
deleted file mode 100644 (file)
index 8b67571..0000000
+++ /dev/null
@@ -1,679 +0,0 @@
-//! Completion of names from the current scope, e.g. locals and imported items.
-
-use hir::{Adt, ModuleDef, ScopeDef, Type};
-use syntax::AstNode;
-use test_utils::mark;
-
-use crate::completion::{CompletionContext, Completions};
-
-pub(super) fn complete_unqualified_path(acc: &mut Completions, ctx: &CompletionContext) {
-    if !(ctx.is_trivial_path || ctx.is_pat_binding_or_const) {
-        return;
-    }
-    if ctx.record_lit_syntax.is_some()
-        || ctx.record_pat_syntax.is_some()
-        || ctx.attribute_under_caret.is_some()
-        || ctx.mod_declaration_under_caret.is_some()
-    {
-        return;
-    }
-
-    if let Some(ty) = &ctx.expected_type {
-        complete_enum_variants(acc, ctx, ty);
-    }
-
-    if ctx.is_pat_binding_or_const {
-        return;
-    }
-
-    ctx.scope.process_all_names(&mut |name, res| {
-        if ctx.use_item_syntax.is_some() {
-            if let (ScopeDef::Unknown, Some(name_ref)) = (&res, &ctx.name_ref_syntax) {
-                if name_ref.syntax().text() == name.to_string().as_str() {
-                    mark::hit!(self_fulfilling_completion);
-                    return;
-                }
-            }
-        }
-        acc.add_resolution(ctx, name.to_string(), &res)
-    });
-}
-
-fn complete_enum_variants(acc: &mut Completions, ctx: &CompletionContext, ty: &Type) {
-    if let Some(Adt::Enum(enum_data)) = ty.as_adt() {
-        let variants = enum_data.variants(ctx.db);
-
-        let module = if let Some(module) = ctx.scope.module() {
-            // Compute path from the completion site if available.
-            module
-        } else {
-            // Otherwise fall back to the enum's definition site.
-            enum_data.module(ctx.db)
-        };
-
-        for variant in variants {
-            if let Some(path) = module.find_use_path(ctx.db, ModuleDef::from(variant)) {
-                // Variants with trivial paths are already added by the existing completion logic,
-                // so we should avoid adding these twice
-                if path.segments.len() > 1 {
-                    acc.add_qualified_enum_variant(ctx, variant, path);
-                }
-            }
-        }
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use expect_test::{expect, Expect};
-    use test_utils::mark;
-
-    use crate::completion::{
-        test_utils::{check_edit, completion_list},
-        CompletionKind,
-    };
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = completion_list(ra_fixture, CompletionKind::Reference);
-        expect.assert_eq(&actual)
-    }
-
-    #[test]
-    fn self_fulfilling_completion() {
-        mark::check!(self_fulfilling_completion);
-        check(
-            r#"
-use foo<|>
-use std::collections;
-"#,
-            expect![[r#"
-                ?? collections
-            "#]],
-        );
-    }
-
-    #[test]
-    fn bind_pat_and_path_ignore_at() {
-        check(
-            r#"
-enum Enum { A, B }
-fn quux(x: Option<Enum>) {
-    match x {
-        None => (),
-        Some(en<|> @ Enum::A) => (),
-    }
-}
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn bind_pat_and_path_ignore_ref() {
-        check(
-            r#"
-enum Enum { A, B }
-fn quux(x: Option<Enum>) {
-    match x {
-        None => (),
-        Some(ref en<|>) => (),
-    }
-}
-"#,
-            expect![[""]],
-        );
-    }
-
-    #[test]
-    fn bind_pat_and_path() {
-        check(
-            r#"
-enum Enum { A, B }
-fn quux(x: Option<Enum>) {
-    match x {
-        None => (),
-        Some(En<|>) => (),
-    }
-}
-"#,
-            expect![[r#"
-                en Enum
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_bindings_from_let() {
-        check(
-            r#"
-fn quux(x: i32) {
-    let y = 92;
-    1 + <|>;
-    let z = ();
-}
-"#,
-            expect![[r#"
-                fn quux(…) fn quux(x: i32)
-                bn x       i32
-                bn y       i32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_bindings_from_if_let() {
-        check(
-            r#"
-fn quux() {
-    if let Some(x) = foo() {
-        let y = 92;
-    };
-    if let Some(a) = bar() {
-        let b = 62;
-        1 + <|>
-    }
-}
-"#,
-            expect![[r#"
-                bn a
-                bn b      i32
-                fn quux() fn quux()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_bindings_from_for() {
-        check(
-            r#"
-fn quux() {
-    for x in &[1, 2, 3] { <|> }
-}
-"#,
-            expect![[r#"
-                fn quux() fn quux()
-                bn x
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_if_prefix_is_keyword() {
-        mark::check!(completes_if_prefix_is_keyword);
-        check_edit(
-            "wherewolf",
-            r#"
-fn main() {
-    let wherewolf = 92;
-    drop(where<|>)
-}
-"#,
-            r#"
-fn main() {
-    let wherewolf = 92;
-    drop(wherewolf)
-}
-"#,
-        )
-    }
-
-    #[test]
-    fn completes_generic_params() {
-        check(
-            r#"fn quux<T>() { <|> }"#,
-            expect![[r#"
-                tp T
-                fn quux() fn quux<T>()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_generic_params_in_struct() {
-        check(
-            r#"struct S<T> { x: <|>}"#,
-            expect![[r#"
-                st S<…>
-                tp Self
-                tp T
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_self_in_enum() {
-        check(
-            r#"enum X { Y(<|>) }"#,
-            expect![[r#"
-                tp Self
-                en X
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_module_items() {
-        check(
-            r#"
-struct S;
-enum E {}
-fn quux() { <|> }
-"#,
-            expect![[r#"
-                en E
-                st S
-                fn quux() fn quux()
-            "#]],
-        );
-    }
-
-    /// Regression test for issue #6091.
-    #[test]
-    fn correctly_completes_module_items_prefixed_with_underscore() {
-        check_edit(
-            "_alpha",
-            r#"
-fn main() {
-    _<|>
-}
-fn _alpha() {}
-"#,
-            r#"
-fn main() {
-    _alpha()$0
-}
-fn _alpha() {}
-"#,
-        )
-    }
-
-    #[test]
-    fn completes_extern_prelude() {
-        check(
-            r#"
-//- /lib.rs crate:main deps:other_crate
-use <|>;
-
-//- /other_crate/lib.rs crate:other_crate
-// nothing here
-"#,
-            expect![[r#"
-                md other_crate
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_module_items_in_nested_modules() {
-        check(
-            r#"
-struct Foo;
-mod m {
-    struct Bar;
-    fn quux() { <|> }
-}
-"#,
-            expect![[r#"
-                st Bar
-                fn quux() fn quux()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_return_type() {
-        check(
-            r#"
-struct Foo;
-fn x() -> <|>
-"#,
-            expect![[r#"
-                st Foo
-                fn x() fn x()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn dont_show_both_completions_for_shadowing() {
-        check(
-            r#"
-fn foo() {
-    let bar = 92;
-    {
-        let bar = 62;
-        drop(<|>)
-    }
-}
-"#,
-            // FIXME: should be only one bar here
-            expect![[r#"
-                bn bar   i32
-                bn bar   i32
-                fn foo() fn foo()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_self_in_methods() {
-        check(
-            r#"impl S { fn foo(&self) { <|> } }"#,
-            expect![[r#"
-                tp Self
-                bn self &{unknown}
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_prelude() {
-        check(
-            r#"
-//- /main.rs crate:main deps:std
-fn foo() { let x: <|> }
-
-//- /std/lib.rs crate:std
-#[prelude_import]
-use prelude::*;
-
-mod prelude { struct Option; }
-"#,
-            expect![[r#"
-                st Option
-                fn foo()  fn foo()
-                md std
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_std_prelude_if_core_is_defined() {
-        check(
-            r#"
-//- /main.rs crate:main deps:core,std
-fn foo() { let x: <|> }
-
-//- /core/lib.rs crate:core
-#[prelude_import]
-use prelude::*;
-
-mod prelude { struct Option; }
-
-//- /std/lib.rs crate:std deps:core
-#[prelude_import]
-use prelude::*;
-
-mod prelude { struct String; }
-"#,
-            expect![[r#"
-                st String
-                md core
-                fn foo()  fn foo()
-                md std
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_macros_as_value() {
-        check(
-            r#"
-macro_rules! foo { () => {} }
-
-#[macro_use]
-mod m1 {
-    macro_rules! bar { () => {} }
-}
-
-mod m2 {
-    macro_rules! nope { () => {} }
-
-    #[macro_export]
-    macro_rules! baz { () => {} }
-}
-
-fn main() { let v = <|> }
-"#,
-            expect![[r##"
-                ma bar!(…) macro_rules! bar
-                ma baz!(…) #[macro_export]
-                macro_rules! baz
-                ma foo!(…) macro_rules! foo
-                md m1
-                md m2
-                fn main()  fn main()
-            "##]],
-        );
-    }
-
-    #[test]
-    fn completes_both_macro_and_value() {
-        check(
-            r#"
-macro_rules! foo { () => {} }
-fn foo() { <|> }
-"#,
-            expect![[r#"
-                ma foo!(…) macro_rules! foo
-                fn foo()   fn foo()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_macros_as_type() {
-        check(
-            r#"
-macro_rules! foo { () => {} }
-fn main() { let x: <|> }
-"#,
-            expect![[r#"
-                ma foo!(…) macro_rules! foo
-                fn main()  fn main()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_macros_as_stmt() {
-        check(
-            r#"
-macro_rules! foo { () => {} }
-fn main() { <|> }
-"#,
-            expect![[r#"
-                ma foo!(…) macro_rules! foo
-                fn main()  fn main()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_local_item() {
-        check(
-            r#"
-fn main() {
-    return f<|>;
-    fn frobnicate() {}
-}
-"#,
-            expect![[r#"
-                fn frobnicate() fn frobnicate()
-                fn main()       fn main()
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_in_simple_macro_1() {
-        check(
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-fn quux(x: i32) {
-    let y = 92;
-    m!(<|>);
-}
-"#,
-            expect![[r#"
-                ma m!(…)   macro_rules! m
-                fn quux(…) fn quux(x: i32)
-                bn x       i32
-                bn y       i32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_in_simple_macro_2() {
-        check(
-            r"
-macro_rules! m { ($e:expr) => { $e } }
-fn quux(x: i32) {
-    let y = 92;
-    m!(x<|>);
-}
-",
-            expect![[r#"
-                ma m!(…)   macro_rules! m
-                fn quux(…) fn quux(x: i32)
-                bn x       i32
-                bn y       i32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_in_simple_macro_without_closing_parens() {
-        check(
-            r#"
-macro_rules! m { ($e:expr) => { $e } }
-fn quux(x: i32) {
-    let y = 92;
-    m!(x<|>
-}
-"#,
-            expect![[r#"
-                ma m!(…)   macro_rules! m
-                fn quux(…) fn quux(x: i32)
-                bn x       i32
-                bn y       i32
-            "#]],
-        );
-    }
-
-    #[test]
-    fn completes_unresolved_uses() {
-        check(
-            r#"
-use spam::Quux;
-
-fn main() { <|> }
-"#,
-            expect![[r#"
-                ?? Quux
-                fn main() fn main()
-            "#]],
-        );
-    }
-    #[test]
-    fn completes_enum_variant_matcharm() {
-        check(
-            r#"
-enum Foo { Bar, Baz, Quux }
-
-fn main() {
-    let foo = Foo::Quux;
-    match foo { Qu<|> }
-}
-"#,
-            expect![[r#"
-                en Foo
-                ev Foo::Bar  ()
-                ev Foo::Baz  ()
-                ev Foo::Quux ()
-            "#]],
-        )
-    }
-
-    #[test]
-    fn completes_enum_variant_iflet() {
-        check(
-            r#"
-enum Foo { Bar, Baz, Quux }
-
-fn main() {
-    let foo = Foo::Quux;
-    if let Qu<|> = foo { }
-}
-"#,
-            expect![[r#"
-                en Foo
-                ev Foo::Bar  ()
-                ev Foo::Baz  ()
-                ev Foo::Quux ()
-            "#]],
-        )
-    }
-
-    #[test]
-    fn completes_enum_variant_basic_expr() {
-        check(
-            r#"
-enum Foo { Bar, Baz, Quux }
-fn main() { let foo: Foo = Q<|> }
-"#,
-            expect![[r#"
-                en Foo
-                ev Foo::Bar  ()
-                ev Foo::Baz  ()
-                ev Foo::Quux ()
-                fn main()    fn main()
-            "#]],
-        )
-    }
-
-    #[test]
-    fn completes_enum_variant_from_module() {
-        check(
-            r#"
-mod m { pub enum E { V } }
-fn f() -> m::E { V<|> }
-"#,
-            expect![[r#"
-                fn f()     fn f() -> m::E
-                md m
-                ev m::E::V ()
-            "#]],
-        )
-    }
-
-    #[test]
-    fn dont_complete_attr() {
-        check(
-            r#"
-struct Foo;
-#[<|>]
-fn f() {}
-"#,
-            expect![[""]],
-        )
-    }
-
-    #[test]
-    fn completes_type_or_trait_in_impl_block() {
-        check(
-            r#"
-trait MyTrait {}
-struct MyStruct {}
-
-impl My<|>
-"#,
-            expect![[r#"
-                st MyStruct
-                tt MyTrait
-                tp Self
-            "#]],
-        )
-    }
-}
diff --git a/crates/ide/src/completion/completion_config.rs b/crates/ide/src/completion/completion_config.rs
deleted file mode 100644 (file)
index 71b49ac..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-//! Settings for tweaking completion.
-//!
-//! The fun thing here is `SnippetCap` -- this type can only be created in this
-//! module, and we use to statically check that we only produce snippet
-//! completions if we are allowed to.
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct CompletionConfig {
-    pub enable_postfix_completions: bool,
-    pub add_call_parenthesis: bool,
-    pub add_call_argument_snippets: bool,
-    pub snippet_cap: Option<SnippetCap>,
-}
-
-impl CompletionConfig {
-    pub fn allow_snippets(&mut self, yes: bool) {
-        self.snippet_cap = if yes { Some(SnippetCap { _private: () }) } else { None }
-    }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct SnippetCap {
-    _private: (),
-}
-
-impl Default for CompletionConfig {
-    fn default() -> Self {
-        CompletionConfig {
-            enable_postfix_completions: true,
-            add_call_parenthesis: true,
-            add_call_argument_snippets: true,
-            snippet_cap: Some(SnippetCap { _private: () }),
-        }
-    }
-}
diff --git a/crates/ide/src/completion/completion_context.rs b/crates/ide/src/completion/completion_context.rs
deleted file mode 100644 (file)
index d9f9047..0000000
+++ /dev/null
@@ -1,523 +0,0 @@
-//! FIXME: write short doc here
-
-use base_db::SourceDatabase;
-use hir::{Local, ScopeDef, Semantics, SemanticsScope, Type};
-use ide_db::RootDatabase;
-use syntax::{
-    algo::{find_covering_element, find_node_at_offset},
-    ast, match_ast, AstNode, NodeOrToken,
-    SyntaxKind::*,
-    SyntaxNode, SyntaxToken, TextRange, TextSize,
-};
-use test_utils::mark;
-use text_edit::Indel;
-
-use crate::{
-    call_info::ActiveParameter,
-    completion::{
-        patterns::{
-            fn_is_prev, for_is_prev2, has_bind_pat_parent, has_block_expr_parent,
-            has_field_list_parent, has_impl_as_prev_sibling, has_impl_parent,
-            has_item_list_or_source_file_parent, has_ref_parent, has_trait_as_prev_sibling,
-            has_trait_parent, if_is_prev, inside_impl_trait_block, is_in_loop_body, is_match_arm,
-            unsafe_is_prev,
-        },
-        CompletionConfig,
-    },
-    FilePosition,
-};
-
-/// `CompletionContext` is created early during completion to figure out, where
-/// exactly is the cursor, syntax-wise.
-#[derive(Debug)]
-pub(crate) struct CompletionContext<'a> {
-    pub(super) sema: Semantics<'a, RootDatabase>,
-    pub(super) scope: SemanticsScope<'a>,
-    pub(super) db: &'a RootDatabase,
-    pub(super) config: &'a CompletionConfig,
-    pub(super) position: FilePosition,
-    /// The token before the cursor, in the original file.
-    pub(super) original_token: SyntaxToken,
-    /// The token before the cursor, in the macro-expanded file.
-    pub(super) token: SyntaxToken,
-    pub(super) krate: Option<hir::Crate>,
-    pub(super) expected_type: Option<Type>,
-    pub(super) name_ref_syntax: Option<ast::NameRef>,
-    pub(super) function_syntax: Option<ast::Fn>,
-    pub(super) use_item_syntax: Option<ast::Use>,
-    pub(super) record_lit_syntax: Option<ast::RecordExpr>,
-    pub(super) record_pat_syntax: Option<ast::RecordPat>,
-    pub(super) record_field_syntax: Option<ast::RecordExprField>,
-    pub(super) impl_def: Option<ast::Impl>,
-    /// FIXME: `ActiveParameter` is string-based, which is very very wrong
-    pub(super) active_parameter: Option<ActiveParameter>,
-    pub(super) is_param: bool,
-    /// If a name-binding or reference to a const in a pattern.
-    /// Irrefutable patterns (like let) are excluded.
-    pub(super) is_pat_binding_or_const: bool,
-    /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
-    pub(super) is_trivial_path: bool,
-    /// If not a trivial path, the prefix (qualifier).
-    pub(super) path_qual: Option<ast::Path>,
-    pub(super) after_if: bool,
-    /// `true` if we are a statement or a last expr in the block.
-    pub(super) can_be_stmt: bool,
-    /// `true` if we expect an expression at the cursor position.
-    pub(super) is_expr: bool,
-    /// Something is typed at the "top" level, in module or impl/trait.
-    pub(super) is_new_item: bool,
-    /// The receiver if this is a field or method access, i.e. writing something.<|>
-    pub(super) dot_receiver: Option<ast::Expr>,
-    pub(super) dot_receiver_is_ambiguous_float_literal: bool,
-    /// If this is a call (method or function) in particular, i.e. the () are already there.
-    pub(super) is_call: bool,
-    /// Like `is_call`, but for tuple patterns.
-    pub(super) is_pattern_call: bool,
-    /// If this is a macro call, i.e. the () are already there.
-    pub(super) is_macro_call: bool,
-    pub(super) is_path_type: bool,
-    pub(super) has_type_args: bool,
-    pub(super) attribute_under_caret: Option<ast::Attr>,
-    pub(super) mod_declaration_under_caret: Option<ast::Module>,
-    pub(super) unsafe_is_prev: bool,
-    pub(super) if_is_prev: bool,
-    pub(super) block_expr_parent: bool,
-    pub(super) bind_pat_parent: bool,
-    pub(super) ref_pat_parent: bool,
-    pub(super) in_loop_body: bool,
-    pub(super) has_trait_parent: bool,
-    pub(super) has_impl_parent: bool,
-    pub(super) inside_impl_trait_block: bool,
-    pub(super) has_field_list_parent: bool,
-    pub(super) trait_as_prev_sibling: bool,
-    pub(super) impl_as_prev_sibling: bool,
-    pub(super) is_match_arm: bool,
-    pub(super) has_item_list_or_source_file_parent: bool,
-    pub(super) for_is_prev2: bool,
-    pub(super) fn_is_prev: bool,
-    pub(super) locals: Vec<(String, Local)>,
-}
-
-impl<'a> CompletionContext<'a> {
-    pub(super) fn new(
-        db: &'a RootDatabase,
-        position: FilePosition,
-        config: &'a CompletionConfig,
-    ) -> Option<CompletionContext<'a>> {
-        let sema = Semantics::new(db);
-
-        let original_file = sema.parse(position.file_id);
-
-        // Insert a fake ident to get a valid parse tree. We will use this file
-        // to determine context, though the original_file will be used for
-        // actual completion.
-        let file_with_fake_ident = {
-            let parse = db.parse(position.file_id);
-            let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
-            parse.reparse(&edit).tree()
-        };
-        let fake_ident_token =
-            file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
-
-        let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
-        let original_token =
-            original_file.syntax().token_at_offset(position.offset).left_biased()?;
-        let token = sema.descend_into_macros(original_token.clone());
-        let scope = sema.scope_at_offset(&token.parent(), position.offset);
-        let mut locals = vec![];
-        scope.process_all_names(&mut |name, scope| {
-            if let ScopeDef::Local(local) = scope {
-                locals.push((name.to_string(), local));
-            }
-        });
-        let mut ctx = CompletionContext {
-            sema,
-            scope,
-            db,
-            config,
-            original_token,
-            token,
-            position,
-            krate,
-            expected_type: None,
-            name_ref_syntax: None,
-            function_syntax: None,
-            use_item_syntax: None,
-            record_lit_syntax: None,
-            record_pat_syntax: None,
-            record_field_syntax: None,
-            impl_def: None,
-            active_parameter: ActiveParameter::at(db, position),
-            is_param: false,
-            is_pat_binding_or_const: false,
-            is_trivial_path: false,
-            path_qual: None,
-            after_if: false,
-            can_be_stmt: false,
-            is_expr: false,
-            is_new_item: false,
-            dot_receiver: None,
-            is_call: false,
-            is_pattern_call: false,
-            is_macro_call: false,
-            is_path_type: false,
-            has_type_args: false,
-            dot_receiver_is_ambiguous_float_literal: false,
-            attribute_under_caret: None,
-            mod_declaration_under_caret: None,
-            unsafe_is_prev: false,
-            in_loop_body: false,
-            ref_pat_parent: false,
-            bind_pat_parent: false,
-            block_expr_parent: false,
-            has_trait_parent: false,
-            has_impl_parent: false,
-            inside_impl_trait_block: false,
-            has_field_list_parent: false,
-            trait_as_prev_sibling: false,
-            impl_as_prev_sibling: false,
-            if_is_prev: false,
-            is_match_arm: false,
-            has_item_list_or_source_file_parent: false,
-            for_is_prev2: false,
-            fn_is_prev: false,
-            locals,
-        };
-
-        let mut original_file = original_file.syntax().clone();
-        let mut hypothetical_file = file_with_fake_ident.syntax().clone();
-        let mut offset = position.offset;
-        let mut fake_ident_token = fake_ident_token;
-
-        // Are we inside a macro call?
-        while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
-            find_node_at_offset::<ast::MacroCall>(&original_file, offset),
-            find_node_at_offset::<ast::MacroCall>(&hypothetical_file, offset),
-        ) {
-            if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
-                != macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
-            {
-                break;
-            }
-            let hypothetical_args = match macro_call_with_fake_ident.token_tree() {
-                Some(tt) => tt,
-                None => break,
-            };
-            if let (Some(actual_expansion), Some(hypothetical_expansion)) = (
-                ctx.sema.expand(&actual_macro_call),
-                ctx.sema.speculative_expand(
-                    &actual_macro_call,
-                    &hypothetical_args,
-                    fake_ident_token,
-                ),
-            ) {
-                let new_offset = hypothetical_expansion.1.text_range().start();
-                if new_offset > actual_expansion.text_range().end() {
-                    break;
-                }
-                original_file = actual_expansion;
-                hypothetical_file = hypothetical_expansion.0;
-                fake_ident_token = hypothetical_expansion.1;
-                offset = new_offset;
-            } else {
-                break;
-            }
-        }
-        ctx.fill_keyword_patterns(&hypothetical_file, offset);
-        ctx.fill(&original_file, hypothetical_file, offset);
-        Some(ctx)
-    }
-
-    /// Checks whether completions in that particular case don't make much sense.
-    /// Examples:
-    /// - `fn <|>` -- we expect function name, it's unlikely that "hint" will be helpful.
-    ///   Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
-    /// - `for _ i<|>` -- obviously, it'll be "in" keyword.
-    pub(crate) fn no_completion_required(&self) -> bool {
-        (self.fn_is_prev && !self.inside_impl_trait_block) || self.for_is_prev2
-    }
-
-    /// The range of the identifier that is being completed.
-    pub(crate) fn source_range(&self) -> TextRange {
-        // check kind of macro-expanded token, but use range of original token
-        let kind = self.token.kind();
-        if kind == IDENT || kind == UNDERSCORE || kind.is_keyword() {
-            mark::hit!(completes_if_prefix_is_keyword);
-            self.original_token.text_range()
-        } else {
-            TextRange::empty(self.position.offset)
-        }
-    }
-
-    fn fill_keyword_patterns(&mut self, file_with_fake_ident: &SyntaxNode, offset: TextSize) {
-        let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
-        let syntax_element = NodeOrToken::Token(fake_ident_token);
-        self.block_expr_parent = has_block_expr_parent(syntax_element.clone());
-        self.unsafe_is_prev = unsafe_is_prev(syntax_element.clone());
-        self.if_is_prev = if_is_prev(syntax_element.clone());
-        self.bind_pat_parent = has_bind_pat_parent(syntax_element.clone());
-        self.ref_pat_parent = has_ref_parent(syntax_element.clone());
-        self.in_loop_body = is_in_loop_body(syntax_element.clone());
-        self.has_trait_parent = has_trait_parent(syntax_element.clone());
-        self.has_impl_parent = has_impl_parent(syntax_element.clone());
-        self.inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
-        self.has_field_list_parent = has_field_list_parent(syntax_element.clone());
-        self.impl_as_prev_sibling = has_impl_as_prev_sibling(syntax_element.clone());
-        self.trait_as_prev_sibling = has_trait_as_prev_sibling(syntax_element.clone());
-        self.is_match_arm = is_match_arm(syntax_element.clone());
-        self.has_item_list_or_source_file_parent =
-            has_item_list_or_source_file_parent(syntax_element.clone());
-        self.mod_declaration_under_caret =
-            find_node_at_offset::<ast::Module>(&file_with_fake_ident, offset)
-                .filter(|module| module.item_list().is_none());
-        self.for_is_prev2 = for_is_prev2(syntax_element.clone());
-        self.fn_is_prev = fn_is_prev(syntax_element.clone());
-    }
-
-    fn fill(
-        &mut self,
-        original_file: &SyntaxNode,
-        file_with_fake_ident: SyntaxNode,
-        offset: TextSize,
-    ) {
-        // FIXME: this is wrong in at least two cases:
-        //  * when there's no token `foo(<|>)`
-        //  * when there is a token, but it happens to have type of it's own
-        self.expected_type = self
-            .token
-            .ancestors()
-            .find_map(|node| {
-                let ty = match_ast! {
-                    match node {
-                        ast::Pat(it) => self.sema.type_of_pat(&it),
-                        ast::Expr(it) => self.sema.type_of_expr(&it),
-                        _ => return None,
-                    }
-                };
-                Some(ty)
-            })
-            .flatten();
-        self.attribute_under_caret = find_node_at_offset(&file_with_fake_ident, offset);
-
-        // First, let's try to complete a reference to some declaration.
-        if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(&file_with_fake_ident, offset) {
-            // Special case, `trait T { fn foo(i_am_a_name_ref) {} }`.
-            // See RFC#1685.
-            if is_node::<ast::Param>(name_ref.syntax()) {
-                self.is_param = true;
-                return;
-            }
-            // FIXME: remove this (V) duplication and make the check more precise
-            if name_ref.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
-                self.record_pat_syntax =
-                    self.sema.find_node_at_offset_with_macros(&original_file, offset);
-            }
-            self.classify_name_ref(original_file, name_ref, offset);
-        }
-
-        // Otherwise, see if this is a declaration. We can use heuristics to
-        // suggest declaration names, see `CompletionKind::Magic`.
-        if let Some(name) = find_node_at_offset::<ast::Name>(&file_with_fake_ident, offset) {
-            if let Some(bind_pat) = name.syntax().ancestors().find_map(ast::IdentPat::cast) {
-                self.is_pat_binding_or_const = true;
-                if bind_pat.at_token().is_some()
-                    || bind_pat.ref_token().is_some()
-                    || bind_pat.mut_token().is_some()
-                {
-                    self.is_pat_binding_or_const = false;
-                }
-                if bind_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast).is_some() {
-                    self.is_pat_binding_or_const = false;
-                }
-                if let Some(let_stmt) = bind_pat.syntax().ancestors().find_map(ast::LetStmt::cast) {
-                    if let Some(pat) = let_stmt.pat() {
-                        if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range())
-                        {
-                            self.is_pat_binding_or_const = false;
-                        }
-                    }
-                }
-            }
-            if is_node::<ast::Param>(name.syntax()) {
-                self.is_param = true;
-                return;
-            }
-            // FIXME: remove this (^) duplication and make the check more precise
-            if name.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
-                self.record_pat_syntax =
-                    self.sema.find_node_at_offset_with_macros(&original_file, offset);
-            }
-        }
-    }
-
-    fn classify_name_ref(
-        &mut self,
-        original_file: &SyntaxNode,
-        name_ref: ast::NameRef,
-        offset: TextSize,
-    ) {
-        self.name_ref_syntax =
-            find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
-        let name_range = name_ref.syntax().text_range();
-        if ast::RecordExprField::for_field_name(&name_ref).is_some() {
-            self.record_lit_syntax =
-                self.sema.find_node_at_offset_with_macros(&original_file, offset);
-        }
-
-        self.impl_def = self
-            .sema
-            .ancestors_with_macros(self.token.parent())
-            .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
-            .find_map(ast::Impl::cast);
-
-        let top_node = name_ref
-            .syntax()
-            .ancestors()
-            .take_while(|it| it.text_range() == name_range)
-            .last()
-            .unwrap();
-
-        match top_node.parent().map(|it| it.kind()) {
-            Some(SOURCE_FILE) | Some(ITEM_LIST) => {
-                self.is_new_item = true;
-                return;
-            }
-            _ => (),
-        }
-
-        self.use_item_syntax =
-            self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::Use::cast);
-
-        self.function_syntax = self
-            .sema
-            .ancestors_with_macros(self.token.parent())
-            .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
-            .find_map(ast::Fn::cast);
-
-        self.record_field_syntax = self
-            .sema
-            .ancestors_with_macros(self.token.parent())
-            .take_while(|it| {
-                it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR
-            })
-            .find_map(ast::RecordExprField::cast);
-
-        let parent = match name_ref.syntax().parent() {
-            Some(it) => it,
-            None => return,
-        };
-
-        if let Some(segment) = ast::PathSegment::cast(parent.clone()) {
-            let path = segment.parent_path();
-            self.is_call = path
-                .syntax()
-                .parent()
-                .and_then(ast::PathExpr::cast)
-                .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
-                .is_some();
-            self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some();
-            self.is_pattern_call =
-                path.syntax().parent().and_then(ast::TupleStructPat::cast).is_some();
-
-            self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some();
-            self.has_type_args = segment.generic_arg_list().is_some();
-
-            if let Some(path) = path_or_use_tree_qualifier(&path) {
-                self.path_qual = path
-                    .segment()
-                    .and_then(|it| {
-                        find_node_with_range::<ast::PathSegment>(
-                            original_file,
-                            it.syntax().text_range(),
-                        )
-                    })
-                    .map(|it| it.parent_path());
-                return;
-            }
-
-            if let Some(segment) = path.segment() {
-                if segment.coloncolon_token().is_some() {
-                    return;
-                }
-            }
-
-            self.is_trivial_path = true;
-
-            // Find either enclosing expr statement (thing with `;`) or a
-            // block. If block, check that we are the last expr.
-            self.can_be_stmt = name_ref
-                .syntax()
-                .ancestors()
-                .find_map(|node| {
-                    if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
-                        return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
-                    }
-                    if let Some(block) = ast::BlockExpr::cast(node) {
-                        return Some(
-                            block.expr().map(|e| e.syntax().text_range())
-                                == Some(name_ref.syntax().text_range()),
-                        );
-                    }
-                    None
-                })
-                .unwrap_or(false);
-            self.is_expr = path.syntax().parent().and_then(ast::PathExpr::cast).is_some();
-
-            if let Some(off) = name_ref.syntax().text_range().start().checked_sub(2.into()) {
-                if let Some(if_expr) =
-                    self.sema.find_node_at_offset_with_macros::<ast::IfExpr>(original_file, off)
-                {
-                    if if_expr.syntax().text_range().end() < name_ref.syntax().text_range().start()
-                    {
-                        self.after_if = true;
-                    }
-                }
-            }
-        }
-        if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
-            // The receiver comes before the point of insertion of the fake
-            // ident, so it should have the same range in the non-modified file
-            self.dot_receiver = field_expr
-                .expr()
-                .map(|e| e.syntax().text_range())
-                .and_then(|r| find_node_with_range(original_file, r));
-            self.dot_receiver_is_ambiguous_float_literal =
-                if let Some(ast::Expr::Literal(l)) = &self.dot_receiver {
-                    match l.kind() {
-                        ast::LiteralKind::FloatNumber { .. } => l.token().text().ends_with('.'),
-                        _ => false,
-                    }
-                } else {
-                    false
-                };
-        }
-        if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
-            // As above
-            self.dot_receiver = method_call_expr
-                .receiver()
-                .map(|e| e.syntax().text_range())
-                .and_then(|r| find_node_with_range(original_file, r));
-            self.is_call = true;
-        }
-    }
-}
-
-fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
-    find_covering_element(syntax, range).ancestors().find_map(N::cast)
-}
-
-fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
-    match node.ancestors().find_map(N::cast) {
-        None => false,
-        Some(n) => n.syntax().text_range() == node.text_range(),
-    }
-}
-
-fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<ast::Path> {
-    if let Some(qual) = path.qualifier() {
-        return Some(qual);
-    }
-    let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
-    let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
-    use_tree.path()
-}
diff --git a/crates/ide/src/completion/completion_item.rs b/crates/ide/src/completion/completion_item.rs
deleted file mode 100644 (file)
index 9377cdc..0000000
+++ /dev/null
@@ -1,384 +0,0 @@
-//! FIXME: write short doc here
-
-use std::fmt;
-
-use hir::Documentation;
-use syntax::TextRange;
-use text_edit::TextEdit;
-
-use crate::completion::completion_config::SnippetCap;
-
-/// `CompletionItem` describes a single completion variant in the editor pop-up.
-/// It is basically a POD with various properties. To construct a
-/// `CompletionItem`, use `new` method and the `Builder` struct.
-pub struct CompletionItem {
-    /// Used only internally in tests, to check only specific kind of
-    /// completion (postfix, keyword, reference, etc).
-    #[allow(unused)]
-    pub(crate) completion_kind: CompletionKind,
-    /// Label in the completion pop up which identifies completion.
-    label: String,
-    /// Range of identifier that is being completed.
-    ///
-    /// It should be used primarily for UI, but we also use this to convert
-    /// genetic TextEdit into LSP's completion edit (see conv.rs).
-    ///
-    /// `source_range` must contain the completion offset. `insert_text` should
-    /// start with what `source_range` points to, or VSCode will filter out the
-    /// completion silently.
-    source_range: TextRange,
-    /// What happens when user selects this item.
-    ///
-    /// Typically, replaces `source_range` with new identifier.
-    text_edit: TextEdit,
-    insert_text_format: InsertTextFormat,
-
-    /// What item (struct, function, etc) are we completing.
-    kind: Option<CompletionItemKind>,
-
-    /// Lookup is used to check if completion item indeed can complete current
-    /// ident.
-    ///
-    /// That is, in `foo.bar<|>` lookup of `abracadabra` will be accepted (it
-    /// contains `bar` sub sequence), and `quux` will rejected.
-    lookup: Option<String>,
-
-    /// Additional info to show in the UI pop up.
-    detail: Option<String>,
-    documentation: Option<Documentation>,
-
-    /// Whether this item is marked as deprecated
-    deprecated: bool,
-
-    /// If completing a function call, ask the editor to show parameter popup
-    /// after completion.
-    trigger_call_info: bool,
-
-    /// Score is useful to pre select or display in better order completion items
-    score: Option<CompletionScore>,
-}
-
-// We use custom debug for CompletionItem to make snapshot tests more readable.
-impl fmt::Debug for CompletionItem {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        let mut s = f.debug_struct("CompletionItem");
-        s.field("label", &self.label()).field("source_range", &self.source_range());
-        if self.text_edit().len() == 1 {
-            let atom = &self.text_edit().iter().next().unwrap();
-            s.field("delete", &atom.delete);
-            s.field("insert", &atom.insert);
-        } else {
-            s.field("text_edit", &self.text_edit);
-        }
-        if let Some(kind) = self.kind().as_ref() {
-            s.field("kind", kind);
-        }
-        if self.lookup() != self.label() {
-            s.field("lookup", &self.lookup());
-        }
-        if let Some(detail) = self.detail() {
-            s.field("detail", &detail);
-        }
-        if let Some(documentation) = self.documentation() {
-            s.field("documentation", &documentation);
-        }
-        if self.deprecated {
-            s.field("deprecated", &true);
-        }
-        if let Some(score) = &self.score {
-            s.field("score", score);
-        }
-        if self.trigger_call_info {
-            s.field("trigger_call_info", &true);
-        }
-        s.finish()
-    }
-}
-
-#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq)]
-pub enum CompletionScore {
-    /// If only type match
-    TypeMatch,
-    /// If type and name match
-    TypeAndNameMatch,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum CompletionItemKind {
-    Snippet,
-    Keyword,
-    Module,
-    Function,
-    BuiltinType,
-    Struct,
-    Enum,
-    EnumVariant,
-    Binding,
-    Field,
-    Static,
-    Const,
-    Trait,
-    TypeAlias,
-    Method,
-    TypeParam,
-    Macro,
-    Attribute,
-    UnresolvedReference,
-}
-
-impl CompletionItemKind {
-    #[cfg(test)]
-    pub(crate) fn tag(&self) -> &'static str {
-        match self {
-            CompletionItemKind::Attribute => "at",
-            CompletionItemKind::Binding => "bn",
-            CompletionItemKind::BuiltinType => "bt",
-            CompletionItemKind::Const => "ct",
-            CompletionItemKind::Enum => "en",
-            CompletionItemKind::EnumVariant => "ev",
-            CompletionItemKind::Field => "fd",
-            CompletionItemKind::Function => "fn",
-            CompletionItemKind::Keyword => "kw",
-            CompletionItemKind::Macro => "ma",
-            CompletionItemKind::Method => "me",
-            CompletionItemKind::Module => "md",
-            CompletionItemKind::Snippet => "sn",
-            CompletionItemKind::Static => "sc",
-            CompletionItemKind::Struct => "st",
-            CompletionItemKind::Trait => "tt",
-            CompletionItemKind::TypeAlias => "ta",
-            CompletionItemKind::TypeParam => "tp",
-            CompletionItemKind::UnresolvedReference => "??",
-        }
-    }
-}
-
-#[derive(Debug, PartialEq, Eq, Copy, Clone)]
-pub(crate) enum CompletionKind {
-    /// Parser-based keyword completion.
-    Keyword,
-    /// Your usual "complete all valid identifiers".
-    Reference,
-    /// "Secret sauce" completions.
-    Magic,
-    Snippet,
-    Postfix,
-    BuiltinType,
-    Attribute,
-}
-
-#[derive(Debug, PartialEq, Eq, Copy, Clone)]
-pub enum InsertTextFormat {
-    PlainText,
-    Snippet,
-}
-
-impl CompletionItem {
-    pub(crate) fn new(
-        completion_kind: CompletionKind,
-        source_range: TextRange,
-        label: impl Into<String>,
-    ) -> Builder {
-        let label = label.into();
-        Builder {
-            source_range,
-            completion_kind,
-            label,
-            insert_text: None,
-            insert_text_format: InsertTextFormat::PlainText,
-            detail: None,
-            documentation: None,
-            lookup: None,
-            kind: None,
-            text_edit: None,
-            deprecated: None,
-            trigger_call_info: None,
-            score: None,
-        }
-    }
-    /// What user sees in pop-up in the UI.
-    pub fn label(&self) -> &str {
-        &self.label
-    }
-    pub fn source_range(&self) -> TextRange {
-        self.source_range
-    }
-
-    pub fn insert_text_format(&self) -> InsertTextFormat {
-        self.insert_text_format
-    }
-
-    pub fn text_edit(&self) -> &TextEdit {
-        &self.text_edit
-    }
-
-    /// Short one-line additional information, like a type
-    pub fn detail(&self) -> Option<&str> {
-        self.detail.as_deref()
-    }
-    /// A doc-comment
-    pub fn documentation(&self) -> Option<Documentation> {
-        self.documentation.clone()
-    }
-    /// What string is used for filtering.
-    pub fn lookup(&self) -> &str {
-        self.lookup.as_deref().unwrap_or(&self.label)
-    }
-
-    pub fn kind(&self) -> Option<CompletionItemKind> {
-        self.kind
-    }
-
-    pub fn deprecated(&self) -> bool {
-        self.deprecated
-    }
-
-    pub fn score(&self) -> Option<CompletionScore> {
-        self.score
-    }
-
-    pub fn trigger_call_info(&self) -> bool {
-        self.trigger_call_info
-    }
-}
-
-/// A helper to make `CompletionItem`s.
-#[must_use]
-pub(crate) struct Builder {
-    source_range: TextRange,
-    completion_kind: CompletionKind,
-    label: String,
-    insert_text: Option<String>,
-    insert_text_format: InsertTextFormat,
-    detail: Option<String>,
-    documentation: Option<Documentation>,
-    lookup: Option<String>,
-    kind: Option<CompletionItemKind>,
-    text_edit: Option<TextEdit>,
-    deprecated: Option<bool>,
-    trigger_call_info: Option<bool>,
-    score: Option<CompletionScore>,
-}
-
-impl Builder {
-    pub(crate) fn add_to(self, acc: &mut Completions) {
-        acc.add(self.build())
-    }
-
-    pub(crate) fn build(self) -> CompletionItem {
-        let label = self.label;
-        let text_edit = match self.text_edit {
-            Some(it) => it,
-            None => TextEdit::replace(
-                self.source_range,
-                self.insert_text.unwrap_or_else(|| label.clone()),
-            ),
-        };
-
-        CompletionItem {
-            source_range: self.source_range,
-            label,
-            insert_text_format: self.insert_text_format,
-            text_edit,
-            detail: self.detail,
-            documentation: self.documentation,
-            lookup: self.lookup,
-            kind: self.kind,
-            completion_kind: self.completion_kind,
-            deprecated: self.deprecated.unwrap_or(false),
-            trigger_call_info: self.trigger_call_info.unwrap_or(false),
-            score: self.score,
-        }
-    }
-    pub(crate) fn lookup_by(mut self, lookup: impl Into<String>) -> Builder {
-        self.lookup = Some(lookup.into());
-        self
-    }
-    pub(crate) fn label(mut self, label: impl Into<String>) -> Builder {
-        self.label = label.into();
-        self
-    }
-    pub(crate) fn insert_text(mut self, insert_text: impl Into<String>) -> Builder {
-        self.insert_text = Some(insert_text.into());
-        self
-    }
-    pub(crate) fn insert_snippet(
-        mut self,
-        _cap: SnippetCap,
-        snippet: impl Into<String>,
-    ) -> Builder {
-        self.insert_text_format = InsertTextFormat::Snippet;
-        self.insert_text(snippet)
-    }
-    pub(crate) fn kind(mut self, kind: CompletionItemKind) -> Builder {
-        self.kind = Some(kind);
-        self
-    }
-    pub(crate) fn text_edit(mut self, edit: TextEdit) -> Builder {
-        self.text_edit = Some(edit);
-        self
-    }
-    pub(crate) fn snippet_edit(mut self, _cap: SnippetCap, edit: TextEdit) -> Builder {
-        self.insert_text_format = InsertTextFormat::Snippet;
-        self.text_edit(edit)
-    }
-    #[allow(unused)]
-    pub(crate) fn detail(self, detail: impl Into<String>) -> Builder {
-        self.set_detail(Some(detail))
-    }
-    pub(crate) fn set_detail(mut self, detail: Option<impl Into<String>>) -> Builder {
-        self.detail = detail.map(Into::into);
-        self
-    }
-    #[allow(unused)]
-    pub(crate) fn documentation(self, docs: Documentation) -> Builder {
-        self.set_documentation(Some(docs))
-    }
-    pub(crate) fn set_documentation(mut self, docs: Option<Documentation>) -> Builder {
-        self.documentation = docs.map(Into::into);
-        self
-    }
-    pub(crate) fn set_deprecated(mut self, deprecated: bool) -> Builder {
-        self.deprecated = Some(deprecated);
-        self
-    }
-    pub(crate) fn set_score(mut self, score: CompletionScore) -> Builder {
-        self.score = Some(score);
-        self
-    }
-    pub(crate) fn trigger_call_info(mut self) -> Builder {
-        self.trigger_call_info = Some(true);
-        self
-    }
-}
-
-impl<'a> Into<CompletionItem> for Builder {
-    fn into(self) -> CompletionItem {
-        self.build()
-    }
-}
-
-/// Represents an in-progress set of completions being built.
-#[derive(Debug, Default)]
-pub(crate) struct Completions {
-    buf: Vec<CompletionItem>,
-}
-
-impl Completions {
-    pub(crate) fn add(&mut self, item: impl Into<CompletionItem>) {
-        self.buf.push(item.into())
-    }
-    pub(crate) fn add_all<I>(&mut self, items: I)
-    where
-        I: IntoIterator,
-        I::Item: Into<CompletionItem>,
-    {
-        items.into_iter().for_each(|item| self.add(item.into()))
-    }
-}
-
-impl Into<Vec<CompletionItem>> for Completions {
-    fn into(self) -> Vec<CompletionItem> {
-        self.buf
-    }
-}
diff --git a/crates/ide/src/completion/generated_features.rs b/crates/ide/src/completion/generated_features.rs
deleted file mode 100644 (file)
index 24754a8..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-//! Generated file, do not edit by hand, see `xtask/src/codegen`
-
-use crate::completion::complete_attribute::LintCompletion;
-pub ( 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/completion/patterns.rs b/crates/ide/src/completion/patterns.rs
deleted file mode 100644 (file)
index cf6d594..0000000
+++ /dev/null
@@ -1,249 +0,0 @@
-//! Patterns telling us certain facts about current syntax element, they are used in completion context
-
-use syntax::{
-    algo::non_trivia_sibling,
-    ast::{self, LoopBodyOwner},
-    match_ast, AstNode, Direction, NodeOrToken, SyntaxElement,
-    SyntaxKind::*,
-    SyntaxNode, SyntaxToken,
-};
-
-#[cfg(test)]
-use crate::completion::test_utils::{check_pattern_is_applicable, check_pattern_is_not_applicable};
-
-pub(crate) fn has_trait_parent(element: SyntaxElement) -> bool {
-    not_same_range_ancestor(element)
-        .filter(|it| it.kind() == ASSOC_ITEM_LIST)
-        .and_then(|it| it.parent())
-        .filter(|it| it.kind() == TRAIT)
-        .is_some()
-}
-#[test]
-fn test_has_trait_parent() {
-    check_pattern_is_applicable(r"trait A { f<|> }", has_trait_parent);
-}
-
-pub(crate) fn has_impl_parent(element: SyntaxElement) -> bool {
-    not_same_range_ancestor(element)
-        .filter(|it| it.kind() == ASSOC_ITEM_LIST)
-        .and_then(|it| it.parent())
-        .filter(|it| it.kind() == IMPL)
-        .is_some()
-}
-#[test]
-fn test_has_impl_parent() {
-    check_pattern_is_applicable(r"impl A { f<|> }", has_impl_parent);
-}
-
-pub(crate) fn inside_impl_trait_block(element: SyntaxElement) -> bool {
-    // Here we search `impl` keyword up through the all ancestors, unlike in `has_impl_parent`,
-    // where we only check the first parent with different text range.
-    element
-        .ancestors()
-        .find(|it| it.kind() == IMPL)
-        .map(|it| ast::Impl::cast(it).unwrap())
-        .map(|it| it.trait_().is_some())
-        .unwrap_or(false)
-}
-#[test]
-fn test_inside_impl_trait_block() {
-    check_pattern_is_applicable(r"impl Foo for Bar { f<|> }", inside_impl_trait_block);
-    check_pattern_is_applicable(r"impl Foo for Bar { fn f<|> }", inside_impl_trait_block);
-    check_pattern_is_not_applicable(r"impl A { f<|> }", inside_impl_trait_block);
-    check_pattern_is_not_applicable(r"impl A { fn f<|> }", inside_impl_trait_block);
-}
-
-pub(crate) fn has_field_list_parent(element: SyntaxElement) -> bool {
-    not_same_range_ancestor(element).filter(|it| it.kind() == RECORD_FIELD_LIST).is_some()
-}
-#[test]
-fn test_has_field_list_parent() {
-    check_pattern_is_applicable(r"struct Foo { f<|> }", has_field_list_parent);
-    check_pattern_is_applicable(r"struct Foo { f<|> pub f: i32}", has_field_list_parent);
-}
-
-pub(crate) fn has_block_expr_parent(element: SyntaxElement) -> bool {
-    not_same_range_ancestor(element).filter(|it| it.kind() == BLOCK_EXPR).is_some()
-}
-#[test]
-fn test_has_block_expr_parent() {
-    check_pattern_is_applicable(r"fn my_fn() { let a = 2; f<|> }", has_block_expr_parent);
-}
-
-pub(crate) fn has_bind_pat_parent(element: SyntaxElement) -> bool {
-    element.ancestors().find(|it| it.kind() == IDENT_PAT).is_some()
-}
-#[test]
-fn test_has_bind_pat_parent() {
-    check_pattern_is_applicable(r"fn my_fn(m<|>) {}", has_bind_pat_parent);
-    check_pattern_is_applicable(r"fn my_fn() { let m<|> }", has_bind_pat_parent);
-}
-
-pub(crate) fn has_ref_parent(element: SyntaxElement) -> bool {
-    not_same_range_ancestor(element)
-        .filter(|it| it.kind() == REF_PAT || it.kind() == REF_EXPR)
-        .is_some()
-}
-#[test]
-fn test_has_ref_parent() {
-    check_pattern_is_applicable(r"fn my_fn(&m<|>) {}", has_ref_parent);
-    check_pattern_is_applicable(r"fn my() { let &m<|> }", has_ref_parent);
-}
-
-pub(crate) fn has_item_list_or_source_file_parent(element: SyntaxElement) -> bool {
-    let ancestor = not_same_range_ancestor(element);
-    if !ancestor.is_some() {
-        return true;
-    }
-    ancestor.filter(|it| it.kind() == SOURCE_FILE || it.kind() == ITEM_LIST).is_some()
-}
-#[test]
-fn test_has_item_list_or_source_file_parent() {
-    check_pattern_is_applicable(r"i<|>", has_item_list_or_source_file_parent);
-    check_pattern_is_applicable(r"mod foo { f<|> }", has_item_list_or_source_file_parent);
-}
-
-pub(crate) fn is_match_arm(element: SyntaxElement) -> bool {
-    not_same_range_ancestor(element.clone()).filter(|it| it.kind() == MATCH_ARM).is_some()
-        && previous_sibling_or_ancestor_sibling(element)
-            .and_then(|it| it.into_token())
-            .filter(|it| it.kind() == FAT_ARROW)
-            .is_some()
-}
-#[test]
-fn test_is_match_arm() {
-    check_pattern_is_applicable(r"fn my_fn() { match () { () => m<|> } }", is_match_arm);
-}
-
-pub(crate) fn unsafe_is_prev(element: SyntaxElement) -> bool {
-    element
-        .into_token()
-        .and_then(|it| previous_non_trivia_token(it))
-        .filter(|it| it.kind() == UNSAFE_KW)
-        .is_some()
-}
-#[test]
-fn test_unsafe_is_prev() {
-    check_pattern_is_applicable(r"unsafe i<|>", unsafe_is_prev);
-}
-
-pub(crate) fn if_is_prev(element: SyntaxElement) -> bool {
-    element
-        .into_token()
-        .and_then(|it| previous_non_trivia_token(it))
-        .filter(|it| it.kind() == IF_KW)
-        .is_some()
-}
-
-pub(crate) fn fn_is_prev(element: SyntaxElement) -> bool {
-    element
-        .into_token()
-        .and_then(|it| previous_non_trivia_token(it))
-        .filter(|it| it.kind() == FN_KW)
-        .is_some()
-}
-#[test]
-fn test_fn_is_prev() {
-    check_pattern_is_applicable(r"fn l<|>", fn_is_prev);
-}
-
-/// Check if the token previous to the previous one is `for`.
-/// For example, `for _ i<|>` => true.
-pub(crate) fn for_is_prev2(element: SyntaxElement) -> bool {
-    element
-        .into_token()
-        .and_then(|it| previous_non_trivia_token(it))
-        .and_then(|it| previous_non_trivia_token(it))
-        .filter(|it| it.kind() == FOR_KW)
-        .is_some()
-}
-#[test]
-fn test_for_is_prev2() {
-    check_pattern_is_applicable(r"for i i<|>", for_is_prev2);
-}
-
-#[test]
-fn test_if_is_prev() {
-    check_pattern_is_applicable(r"if l<|>", if_is_prev);
-}
-
-pub(crate) fn has_trait_as_prev_sibling(element: SyntaxElement) -> bool {
-    previous_sibling_or_ancestor_sibling(element).filter(|it| it.kind() == TRAIT).is_some()
-}
-#[test]
-fn test_has_trait_as_prev_sibling() {
-    check_pattern_is_applicable(r"trait A w<|> {}", has_trait_as_prev_sibling);
-}
-
-pub(crate) fn has_impl_as_prev_sibling(element: SyntaxElement) -> bool {
-    previous_sibling_or_ancestor_sibling(element).filter(|it| it.kind() == IMPL).is_some()
-}
-#[test]
-fn test_has_impl_as_prev_sibling() {
-    check_pattern_is_applicable(r"impl A w<|> {}", has_impl_as_prev_sibling);
-}
-
-pub(crate) fn is_in_loop_body(element: SyntaxElement) -> bool {
-    let leaf = match element {
-        NodeOrToken::Node(node) => node,
-        NodeOrToken::Token(token) => token.parent(),
-    };
-    for node in leaf.ancestors() {
-        if node.kind() == FN || node.kind() == CLOSURE_EXPR {
-            break;
-        }
-        let loop_body = match_ast! {
-            match node {
-                ast::ForExpr(it) => it.loop_body(),
-                ast::WhileExpr(it) => it.loop_body(),
-                ast::LoopExpr(it) => it.loop_body(),
-                _ => None,
-            }
-        };
-        if let Some(body) = loop_body {
-            if body.syntax().text_range().contains_range(leaf.text_range()) {
-                return true;
-            }
-        }
-    }
-    false
-}
-
-fn not_same_range_ancestor(element: SyntaxElement) -> Option<SyntaxNode> {
-    element
-        .ancestors()
-        .take_while(|it| it.text_range() == element.text_range())
-        .last()
-        .and_then(|it| it.parent())
-}
-
-fn previous_non_trivia_token(token: SyntaxToken) -> Option<SyntaxToken> {
-    let mut token = token.prev_token();
-    while let Some(inner) = token.clone() {
-        if !inner.kind().is_trivia() {
-            return Some(inner);
-        } else {
-            token = inner.prev_token();
-        }
-    }
-    None
-}
-
-fn previous_sibling_or_ancestor_sibling(element: SyntaxElement) -> Option<SyntaxElement> {
-    let token_sibling = non_trivia_sibling(element.clone(), Direction::Prev);
-    if let Some(sibling) = token_sibling {
-        Some(sibling)
-    } else {
-        // if not trying to find first ancestor which has such a sibling
-        let node = match element {
-            NodeOrToken::Node(node) => node,
-            NodeOrToken::Token(token) => token.parent(),
-        };
-        let range = node.text_range();
-        let top_node = node.ancestors().take_while(|it| it.text_range() == range).last()?;
-        let prev_sibling_node = top_node.ancestors().find(|it| {
-            non_trivia_sibling(NodeOrToken::Node(it.to_owned()), Direction::Prev).is_some()
-        })?;
-        non_trivia_sibling(NodeOrToken::Node(prev_sibling_node), Direction::Prev)
-    }
-}
diff --git a/crates/ide/src/completion/presentation.rs b/crates/ide/src/completion/presentation.rs
deleted file mode 100644 (file)
index a5172b8..0000000
+++ /dev/null
@@ -1,1346 +0,0 @@
-//! This modules takes care of rendering various definitions as completion items.
-//! It also handles scoring (sorting) completions.
-
-use hir::{HasAttrs, HasSource, HirDisplay, ModPath, ScopeDef, StructKind, Type};
-use itertools::Itertools;
-use syntax::ast::NameOwner;
-use test_utils::mark;
-
-use crate::{
-    completion::{
-        completion_item::Builder, CompletionContext, CompletionItem, CompletionItemKind,
-        CompletionKind, Completions,
-    },
-    display::{const_label, function_declaration, macro_label, type_label},
-    CompletionScore, RootDatabase,
-};
-
-impl Completions {
-    pub(crate) fn add_field(&mut self, ctx: &CompletionContext, field: hir::Field, ty: &Type) {
-        let is_deprecated = is_deprecated(field, ctx.db);
-        let name = field.name(ctx.db);
-        let mut completion_item =
-            CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.to_string())
-                .kind(CompletionItemKind::Field)
-                .detail(ty.display(ctx.db).to_string())
-                .set_documentation(field.docs(ctx.db))
-                .set_deprecated(is_deprecated);
-
-        if let Some(score) = compute_score(ctx, &ty, &name.to_string()) {
-            completion_item = completion_item.set_score(score);
-        }
-
-        completion_item.add_to(self);
-    }
-
-    pub(crate) fn add_tuple_field(&mut self, ctx: &CompletionContext, field: usize, ty: &Type) {
-        CompletionItem::new(CompletionKind::Reference, ctx.source_range(), field.to_string())
-            .kind(CompletionItemKind::Field)
-            .detail(ty.display(ctx.db).to_string())
-            .add_to(self);
-    }
-
-    pub(crate) fn add_resolution(
-        &mut self,
-        ctx: &CompletionContext,
-        local_name: String,
-        resolution: &ScopeDef,
-    ) {
-        use hir::ModuleDef::*;
-
-        let completion_kind = match resolution {
-            ScopeDef::ModuleDef(BuiltinType(..)) => CompletionKind::BuiltinType,
-            _ => CompletionKind::Reference,
-        };
-
-        let kind = match resolution {
-            ScopeDef::ModuleDef(Module(..)) => CompletionItemKind::Module,
-            ScopeDef::ModuleDef(Function(func)) => {
-                return self.add_function(ctx, *func, Some(local_name));
-            }
-            ScopeDef::ModuleDef(Adt(hir::Adt::Struct(_))) => CompletionItemKind::Struct,
-            // FIXME: add CompletionItemKind::Union
-            ScopeDef::ModuleDef(Adt(hir::Adt::Union(_))) => CompletionItemKind::Struct,
-            ScopeDef::ModuleDef(Adt(hir::Adt::Enum(_))) => CompletionItemKind::Enum,
-
-            ScopeDef::ModuleDef(EnumVariant(var)) => {
-                return self.add_enum_variant(ctx, *var, Some(local_name));
-            }
-            ScopeDef::ModuleDef(Const(..)) => CompletionItemKind::Const,
-            ScopeDef::ModuleDef(Static(..)) => CompletionItemKind::Static,
-            ScopeDef::ModuleDef(Trait(..)) => CompletionItemKind::Trait,
-            ScopeDef::ModuleDef(TypeAlias(..)) => CompletionItemKind::TypeAlias,
-            ScopeDef::ModuleDef(BuiltinType(..)) => CompletionItemKind::BuiltinType,
-            ScopeDef::GenericParam(..) => CompletionItemKind::TypeParam,
-            ScopeDef::Local(..) => CompletionItemKind::Binding,
-            // (does this need its own kind?)
-            ScopeDef::AdtSelfType(..) | ScopeDef::ImplSelfType(..) => CompletionItemKind::TypeParam,
-            ScopeDef::MacroDef(mac) => {
-                return self.add_macro(ctx, Some(local_name), *mac);
-            }
-            ScopeDef::Unknown => {
-                return self.add(
-                    CompletionItem::new(CompletionKind::Reference, ctx.source_range(), local_name)
-                        .kind(CompletionItemKind::UnresolvedReference),
-                );
-            }
-        };
-
-        let docs = match resolution {
-            ScopeDef::ModuleDef(Module(it)) => it.docs(ctx.db),
-            ScopeDef::ModuleDef(Adt(it)) => it.docs(ctx.db),
-            ScopeDef::ModuleDef(EnumVariant(it)) => it.docs(ctx.db),
-            ScopeDef::ModuleDef(Const(it)) => it.docs(ctx.db),
-            ScopeDef::ModuleDef(Static(it)) => it.docs(ctx.db),
-            ScopeDef::ModuleDef(Trait(it)) => it.docs(ctx.db),
-            ScopeDef::ModuleDef(TypeAlias(it)) => it.docs(ctx.db),
-            _ => None,
-        };
-
-        let mut completion_item =
-            CompletionItem::new(completion_kind, ctx.source_range(), local_name.clone());
-        if let ScopeDef::Local(local) = resolution {
-            let ty = local.ty(ctx.db);
-            if !ty.is_unknown() {
-                completion_item = completion_item.detail(ty.display(ctx.db).to_string());
-            }
-        };
-
-        if let ScopeDef::Local(local) = resolution {
-            if let Some(score) = compute_score(ctx, &local.ty(ctx.db), &local_name) {
-                completion_item = completion_item.set_score(score);
-            }
-        }
-
-        // Add `<>` for generic types
-        if ctx.is_path_type && !ctx.has_type_args && ctx.config.add_call_parenthesis {
-            if let Some(cap) = ctx.config.snippet_cap {
-                let has_non_default_type_params = match resolution {
-                    ScopeDef::ModuleDef(Adt(it)) => it.has_non_default_type_params(ctx.db),
-                    ScopeDef::ModuleDef(TypeAlias(it)) => it.has_non_default_type_params(ctx.db),
-                    _ => false,
-                };
-                if has_non_default_type_params {
-                    mark::hit!(inserts_angle_brackets_for_generics);
-                    completion_item = completion_item
-                        .lookup_by(local_name.clone())
-                        .label(format!("{}<…>", local_name))
-                        .insert_snippet(cap, format!("{}<$0>", local_name));
-                }
-            }
-        }
-
-        completion_item.kind(kind).set_documentation(docs).add_to(self)
-    }
-
-    pub(crate) fn add_macro(
-        &mut self,
-        ctx: &CompletionContext,
-        name: Option<String>,
-        macro_: hir::MacroDef,
-    ) {
-        // FIXME: Currently proc-macro do not have ast-node,
-        // such that it does not have source
-        if macro_.is_proc_macro() {
-            return;
-        }
-
-        let name = match name {
-            Some(it) => it,
-            None => return,
-        };
-
-        let ast_node = macro_.source(ctx.db).value;
-        let detail = macro_label(&ast_node);
-
-        let docs = macro_.docs(ctx.db);
-
-        let mut builder = CompletionItem::new(
-            CompletionKind::Reference,
-            ctx.source_range(),
-            &format!("{}!", name),
-        )
-        .kind(CompletionItemKind::Macro)
-        .set_documentation(docs.clone())
-        .set_deprecated(is_deprecated(macro_, ctx.db))
-        .detail(detail);
-
-        let needs_bang = ctx.use_item_syntax.is_none() && !ctx.is_macro_call;
-        builder = match ctx.config.snippet_cap {
-            Some(cap) if needs_bang => {
-                let docs = docs.as_ref().map_or("", |s| s.as_str());
-                let (bra, ket) = guess_macro_braces(&name, docs);
-                builder
-                    .insert_snippet(cap, format!("{}!{}$0{}", name, bra, ket))
-                    .label(format!("{}!{}…{}", name, bra, ket))
-                    .lookup_by(format!("{}!", name))
-            }
-            None if needs_bang => builder.insert_text(format!("{}!", name)),
-            _ => {
-                mark::hit!(dont_insert_macro_call_parens_unncessary);
-                builder.insert_text(name)
-            }
-        };
-
-        self.add(builder);
-    }
-
-    pub(crate) fn add_function(
-        &mut self,
-        ctx: &CompletionContext,
-        func: hir::Function,
-        local_name: Option<String>,
-    ) {
-        fn add_arg(arg: &str, ty: &Type, ctx: &CompletionContext) -> String {
-            if let Some(derefed_ty) = ty.remove_ref() {
-                for (name, local) in ctx.locals.iter() {
-                    if name == arg && local.ty(ctx.db) == derefed_ty {
-                        return (if ty.is_mutable_reference() { "&mut " } else { "&" }).to_string()
-                            + &arg.to_string();
-                    }
-                }
-            }
-            arg.to_string()
-        };
-        let name = local_name.unwrap_or_else(|| func.name(ctx.db).to_string());
-        let ast_node = func.source(ctx.db).value;
-
-        let mut builder =
-            CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.clone())
-                .kind(if func.self_param(ctx.db).is_some() {
-                    CompletionItemKind::Method
-                } else {
-                    CompletionItemKind::Function
-                })
-                .set_documentation(func.docs(ctx.db))
-                .set_deprecated(is_deprecated(func, ctx.db))
-                .detail(function_declaration(&ast_node));
-
-        let params_ty = func.params(ctx.db);
-        let params = ast_node
-            .param_list()
-            .into_iter()
-            .flat_map(|it| it.params())
-            .zip(params_ty)
-            .flat_map(|(it, param_ty)| {
-                if let Some(pat) = it.pat() {
-                    let name = pat.to_string();
-                    let arg = name.trim_start_matches("mut ").trim_start_matches('_');
-                    return Some(add_arg(arg, param_ty.ty(), ctx));
-                }
-                None
-            })
-            .collect();
-
-        builder = builder.add_call_parens(ctx, name, Params::Named(params));
-
-        self.add(builder)
-    }
-
-    pub(crate) fn add_const(&mut self, ctx: &CompletionContext, constant: hir::Const) {
-        let ast_node = constant.source(ctx.db).value;
-        let name = match ast_node.name() {
-            Some(name) => name,
-            _ => return,
-        };
-        let detail = const_label(&ast_node);
-
-        CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.text().to_string())
-            .kind(CompletionItemKind::Const)
-            .set_documentation(constant.docs(ctx.db))
-            .set_deprecated(is_deprecated(constant, ctx.db))
-            .detail(detail)
-            .add_to(self);
-    }
-
-    pub(crate) fn add_type_alias(&mut self, ctx: &CompletionContext, type_alias: hir::TypeAlias) {
-        let type_def = type_alias.source(ctx.db).value;
-        let name = match type_def.name() {
-            Some(name) => name,
-            _ => return,
-        };
-        let detail = type_label(&type_def);
-
-        CompletionItem::new(CompletionKind::Reference, ctx.source_range(), name.text().to_string())
-            .kind(CompletionItemKind::TypeAlias)
-            .set_documentation(type_alias.docs(ctx.db))
-            .set_deprecated(is_deprecated(type_alias, ctx.db))
-            .detail(detail)
-            .add_to(self);
-    }
-
-    pub(crate) fn add_qualified_enum_variant(
-        &mut self,
-        ctx: &CompletionContext,
-        variant: hir::EnumVariant,
-        path: ModPath,
-    ) {
-        self.add_enum_variant_impl(ctx, variant, None, Some(path))
-    }
-
-    pub(crate) fn add_enum_variant(
-        &mut self,
-        ctx: &CompletionContext,
-        variant: hir::EnumVariant,
-        local_name: Option<String>,
-    ) {
-        self.add_enum_variant_impl(ctx, variant, local_name, None)
-    }
-
-    fn add_enum_variant_impl(
-        &mut self,
-        ctx: &CompletionContext,
-        variant: hir::EnumVariant,
-        local_name: Option<String>,
-        path: Option<ModPath>,
-    ) {
-        let is_deprecated = is_deprecated(variant, ctx.db);
-        let name = local_name.unwrap_or_else(|| variant.name(ctx.db).to_string());
-        let qualified_name = match &path {
-            Some(it) => it.to_string(),
-            None => name.to_string(),
-        };
-        let detail_types = variant
-            .fields(ctx.db)
-            .into_iter()
-            .map(|field| (field.name(ctx.db), field.signature_ty(ctx.db)));
-        let variant_kind = variant.kind(ctx.db);
-        let detail = match variant_kind {
-            StructKind::Tuple | StructKind::Unit => format!(
-                "({})",
-                detail_types.map(|(_, t)| t.display(ctx.db).to_string()).format(", ")
-            ),
-            StructKind::Record => format!(
-                "{{ {} }}",
-                detail_types
-                    .map(|(n, t)| format!("{}: {}", n, t.display(ctx.db).to_string()))
-                    .format(", ")
-            ),
-        };
-        let mut res = CompletionItem::new(
-            CompletionKind::Reference,
-            ctx.source_range(),
-            qualified_name.clone(),
-        )
-        .kind(CompletionItemKind::EnumVariant)
-        .set_documentation(variant.docs(ctx.db))
-        .set_deprecated(is_deprecated)
-        .detail(detail);
-
-        if path.is_some() {
-            res = res.lookup_by(name);
-        }
-
-        if variant_kind == StructKind::Tuple {
-            mark::hit!(inserts_parens_for_tuple_enums);
-            let params = Params::Anonymous(variant.fields(ctx.db).len());
-            res = res.add_call_parens(ctx, qualified_name, params)
-        }
-
-        res.add_to(self);
-    }
-}
-
-pub(crate) fn compute_score(
-    ctx: &CompletionContext,
-    ty: &Type,
-    name: &str,
-) -> Option<CompletionScore> {
-    let (active_name, active_type) = if let Some(record_field) = &ctx.record_field_syntax {
-        mark::hit!(record_field_type_match);
-        let (struct_field, _local) = ctx.sema.resolve_record_field(record_field)?;
-        (struct_field.name(ctx.db).to_string(), struct_field.signature_ty(ctx.db))
-    } else if let Some(active_parameter) = &ctx.active_parameter {
-        mark::hit!(active_param_type_match);
-        (active_parameter.name.clone(), active_parameter.ty.clone())
-    } else {
-        return None;
-    };
-
-    // Compute score
-    // For the same type
-    if &active_type != ty {
-        return None;
-    }
-
-    let mut res = CompletionScore::TypeMatch;
-
-    // If same type + same name then go top position
-    if active_name == name {
-        res = CompletionScore::TypeAndNameMatch
-    }
-
-    Some(res)
-}
-
-enum Params {
-    Named(Vec<String>),
-    Anonymous(usize),
-}
-
-impl Params {
-    fn len(&self) -> usize {
-        match self {
-            Params::Named(xs) => xs.len(),
-            Params::Anonymous(len) => *len,
-        }
-    }
-
-    fn is_empty(&self) -> bool {
-        self.len() == 0
-    }
-}
-
-impl Builder {
-    fn add_call_parens(mut self, ctx: &CompletionContext, name: String, params: Params) -> Builder {
-        if !ctx.config.add_call_parenthesis {
-            return self;
-        }
-        if ctx.use_item_syntax.is_some() {
-            mark::hit!(no_parens_in_use_item);
-            return self;
-        }
-        if ctx.is_pattern_call {
-            mark::hit!(dont_duplicate_pattern_parens);
-            return self;
-        }
-        if ctx.is_call {
-            return self;
-        }
-
-        // Don't add parentheses if the expected type is some function reference.
-        if let Some(ty) = &ctx.expected_type {
-            if ty.is_fn() {
-                mark::hit!(no_call_parens_if_fn_ptr_needed);
-                return self;
-            }
-        }
-
-        let cap = match ctx.config.snippet_cap {
-            Some(it) => it,
-            None => return self,
-        };
-        // If not an import, add parenthesis automatically.
-        mark::hit!(inserts_parens_for_function_calls);
-
-        let (snippet, label) = if params.is_empty() {
-            (format!("{}()$0", name), format!("{}()", name))
-        } else {
-            self = self.trigger_call_info();
-            let snippet = match (ctx.config.add_call_argument_snippets, params) {
-                (true, Params::Named(params)) => {
-                    let function_params_snippet =
-                        params.iter().enumerate().format_with(", ", |(index, param_name), f| {
-                            f(&format_args!("${{{}:{}}}", index + 1, param_name))
-                        });
-                    format!("{}({})$0", name, function_params_snippet)
-                }
-                _ => {
-                    mark::hit!(suppress_arg_snippets);
-                    format!("{}($0)", name)
-                }
-            };
-
-            (snippet, format!("{}(…)", name))
-        };
-        self.lookup_by(name).label(label).insert_snippet(cap, snippet)
-    }
-}
-
-fn is_deprecated(node: impl HasAttrs, db: &RootDatabase) -> bool {
-    node.attrs(db).by_key("deprecated").exists()
-}
-
-fn guess_macro_braces(macro_name: &str, docs: &str) -> (&'static str, &'static str) {
-    let mut votes = [0, 0, 0];
-    for (idx, s) in docs.match_indices(&macro_name) {
-        let (before, after) = (&docs[..idx], &docs[idx + s.len()..]);
-        // Ensure to match the full word
-        if after.starts_with('!')
-            && !before.ends_with(|c: char| c == '_' || c.is_ascii_alphanumeric())
-        {
-            // It may have spaces before the braces like `foo! {}`
-            match after[1..].chars().find(|&c| !c.is_whitespace()) {
-                Some('{') => votes[0] += 1,
-                Some('[') => votes[1] += 1,
-                Some('(') => votes[2] += 1,
-                _ => {}
-            }
-        }
-    }
-
-    // Insert a space before `{}`.
-    // We prefer the last one when some votes equal.
-    let (_vote, (bra, ket)) = votes
-        .iter()
-        .zip(&[(" {", "}"), ("[", "]"), ("(", ")")])
-        .max_by_key(|&(&vote, _)| vote)
-        .unwrap();
-    (*bra, *ket)
-}
-
-#[cfg(test)]
-mod tests {
-    use std::cmp::Reverse;
-
-    use expect_test::{expect, Expect};
-    use test_utils::mark;
-
-    use crate::{
-        completion::{
-            test_utils::{
-                check_edit, check_edit_with_config, do_completion, get_all_completion_items,
-            },
-            CompletionConfig, CompletionKind,
-        },
-        CompletionScore,
-    };
-
-    fn check(ra_fixture: &str, expect: Expect) {
-        let actual = do_completion(ra_fixture, CompletionKind::Reference);
-        expect.assert_debug_eq(&actual);
-    }
-
-    fn check_scores(ra_fixture: &str, expect: Expect) {
-        fn display_score(score: Option<CompletionScore>) -> &'static str {
-            match score {
-                Some(CompletionScore::TypeMatch) => "[type]",
-                Some(CompletionScore::TypeAndNameMatch) => "[type+name]",
-                None => "[]".into(),
-            }
-        }
-
-        let mut completions = get_all_completion_items(CompletionConfig::default(), ra_fixture);
-        completions.sort_by_key(|it| (Reverse(it.score()), it.label().to_string()));
-        let actual = completions
-            .into_iter()
-            .filter(|it| it.completion_kind == CompletionKind::Reference)
-            .map(|it| {
-                let tag = it.kind().unwrap().tag();
-                let score = display_score(it.score());
-                format!("{} {} {}\n", tag, it.label(), score)
-            })
-            .collect::<String>();
-        expect.assert_eq(&actual);
-    }
-
-    #[test]
-    fn enum_detail_includes_record_fields() {
-        check(
-            r#"
-enum Foo { Foo { x: i32, y: i32 } }
-
-fn main() { Foo::Fo<|> }
-"#,
-            expect![[r#"
-                [
-                    CompletionItem {
-                        label: "Foo",
-                        source_range: 54..56,
-                        delete: 54..56,
-                        insert: "Foo",
-                        kind: EnumVariant,
-                        detail: "{ x: i32, y: i32 }",
-                    },
-                ]
-            "#]],
-        );
-    }
-
-    #[test]
-    fn enum_detail_doesnt_include_tuple_fields() {
-        check(
-            r#"
-enum Foo { Foo (i32, i32) }
-
-fn main() { Foo::Fo<|> }
-"#,
-            expect![[r#"
-                [
-                    CompletionItem {
-                        label: "Foo(…)",
-                        source_range: 46..48,
-                        delete: 46..48,
-                        insert: "Foo($0)",
-                        kind: EnumVariant,
-                        lookup: "Foo",
-                        detail: "(i32, i32)",
-                        trigger_call_info: true,
-                    },
-                ]
-            "#]],
-        );
-    }
-
-    #[test]
-    fn enum_detail_just_parentheses_for_unit() {
-        check(
-            r#"
-enum Foo { Foo }
-
-fn main() { Foo::Fo<|> }
-"#,
-            expect![[r#"
-                [
-                    CompletionItem {
-                        label: "Foo",
-                        source_range: 35..37,
-                        delete: 35..37,
-                        insert: "Foo",
-                        kind: EnumVariant,
-                        detail: "()",
-                    },
-                ]
-            "#]],
-        );
-    }
-
-    #[test]
-    fn sets_deprecated_flag_in_completion_items() {
-        check(
-            r#"
-#[deprecated]
-fn something_deprecated() {}
-#[deprecated(since = "1.0.0")]
-fn something_else_deprecated() {}
-
-fn main() { som<|> }
-"#,
-            expect![[r#"
-                [
-                    CompletionItem {
-                        label: "main()",
-                        source_range: 121..124,
-                        delete: 121..124,
-                        insert: "main()$0",
-                        kind: Function,
-                        lookup: "main",
-                        detail: "fn main()",
-                    },
-                    CompletionItem {
-                        label: "something_deprecated()",
-                        source_range: 121..124,
-                        delete: 121..124,
-                        insert: "something_deprecated()$0",
-                        kind: Function,
-                        lookup: "something_deprecated",
-                        detail: "fn something_deprecated()",
-                        deprecated: true,
-                    },
-                    CompletionItem {
-                        label: "something_else_deprecated()",
-                        source_range: 121..124,
-                        delete: 121..124,
-                        insert: "something_else_deprecated()$0",
-                        kind: Function,
-                        lookup: "something_else_deprecated",
-                        detail: "fn something_else_deprecated()",
-                        deprecated: true,
-                    },
-                ]
-            "#]],
-        );
-
-        check(
-            r#"
-struct A { #[deprecated] the_field: u32 }
-fn foo() { A { the<|> } }
-"#,
-            expect![[r#"
-                [
-                    CompletionItem {
-                        label: "the_field",
-                        source_range: 57..60,
-                        delete: 57..60,
-                        insert: "the_field",
-                        kind: Field,
-                        detail: "u32",
-                        deprecated: true,
-                    },
-                ]
-            "#]],
-        );
-    }
-
-    #[test]
-    fn renders_docs() {
-        check(
-            r#"
-struct S {
-    /// Field docs
-    foo:
-}
-impl S {
-    /// Method docs
-    fn bar(self) { self.<|> }
-}"#,
-            expect![[r#"
-                [
-                    CompletionItem {
-                        label: "bar()",
-                        source_range: 94..94,
-                        delete: 94..94,
-                        insert: "bar()$0",
-                        kind: Method,
-                        lookup: "bar",
-                        detail: "fn bar(self)",
-                        documentation: Documentation(
-                            "Method docs",
-                        ),
-                    },
-                    CompletionItem {
-                        label: "foo",
-                        source_range: 94..94,
-                        delete: 94..94,
-                        insert: "foo",
-                        kind: Field,
-                        detail: "{unknown}",
-                        documentation: Documentation(
-                            "Field docs",
-                        ),
-                    },
-                ]
-            "#]],
-        );
-
-        check(
-            r#"
-use self::my<|>;
-
-/// mod docs
-mod my { }
-
-/// enum docs
-enum E {
-    /// variant docs
-    V
-}
-use self::E::*;
-"#,
-            expect![[r#"
-                [
-                    CompletionItem {
-                        label: "E",
-                        source_range: 10..12,
-                        delete: 10..12,
-                        insert: "E",
-                        kind: Enum,
-                        documentation: Documentation(
-                            "enum docs",
-                        ),
-                    },
-                    CompletionItem {
-                        label: "V",
-                        source_range: 10..12,
-                        delete: 10..12,
-                        insert: "V",
-                        kind: EnumVariant,
-                        detail: "()",
-                        documentation: Documentation(
-                            "variant docs",
-                        ),
-                    },
-                    CompletionItem {
-                        label: "my",
-                        source_range: 10..12,
-                        delete: 10..12,
-                        insert: "my",
-                        kind: Module,
-                        documentation: Documentation(
-                            "mod docs",
-                        ),
-                    },
-                ]
-            "#]],
-        )
-    }
-
-    #[test]
-    fn dont_render_attrs() {
-        check(
-            r#"
-struct S;
-impl S {
-    #[inline]
-    fn the_method(&self) { }
-}
-fn foo(s: S) { s.<|> }
-"#,
-            expect![[r#"
-                [
-                    CompletionItem {
-                        label: "the_method()",
-                        source_range: 81..81,
-                        delete: 81..81,
-                        insert: "the_method()$0",
-                        kind: Method,
-                        lookup: "the_method",
-                        detail: "fn the_method(&self)",
-                    },
-                ]
-            "#]],
-        )
-    }
-
-    #[test]
-    fn inserts_parens_for_function_calls() {
-        mark::check!(inserts_parens_for_function_calls);
-        check_edit(
-            "no_args",
-            r#"
-fn no_args() {}
-fn main() { no_<|> }
-"#,
-            r#"
-fn no_args() {}
-fn main() { no_args()$0 }
-"#,
-        );
-
-        check_edit(
-            "with_args",
-            r#"
-fn with_args(x: i32, y: String) {}
-fn main() { with_<|> }
-"#,
-            r#"
-fn with_args(x: i32, y: String) {}
-fn main() { with_args(${1:x}, ${2:y})$0 }
-"#,
-        );
-
-        check_edit(
-            "foo",
-            r#"
-struct S;
-impl S {
-    fn foo(&self) {}
-}
-fn bar(s: &S) { s.f<|> }
-"#,
-            r#"
-struct S;
-impl S {
-    fn foo(&self) {}
-}
-fn bar(s: &S) { s.foo()$0 }
-"#,
-        );
-
-        check_edit(
-            "foo",
-            r#"
-struct S {}
-impl S {
-    fn foo(&self, x: i32) {}
-}
-fn bar(s: &S) {
-    s.f<|>
-}
-"#,
-            r#"
-struct S {}
-impl S {
-    fn foo(&self, x: i32) {}
-}
-fn bar(s: &S) {
-    s.foo(${1:x})$0
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn suppress_arg_snippets() {
-        mark::check!(suppress_arg_snippets);
-        check_edit_with_config(
-            CompletionConfig { add_call_argument_snippets: false, ..CompletionConfig::default() },
-            "with_args",
-            r#"
-fn with_args(x: i32, y: String) {}
-fn main() { with_<|> }
-"#,
-            r#"
-fn with_args(x: i32, y: String) {}
-fn main() { with_args($0) }
-"#,
-        );
-    }
-
-    #[test]
-    fn strips_underscores_from_args() {
-        check_edit(
-            "foo",
-            r#"
-fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
-fn main() { f<|> }
-"#,
-            r#"
-fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {}
-fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 }
-"#,
-        );
-    }
-
-    #[test]
-    fn insert_ref_when_matching_local_in_scope() {
-        check_edit(
-            "ref_arg",
-            r#"
-struct Foo {}
-fn ref_arg(x: &Foo) {}
-fn main() {
-    let x = Foo {};
-    ref_ar<|>
-}
-"#,
-            r#"
-struct Foo {}
-fn ref_arg(x: &Foo) {}
-fn main() {
-    let x = Foo {};
-    ref_arg(${1:&x})$0
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn insert_mut_ref_when_matching_local_in_scope() {
-        check_edit(
-            "ref_arg",
-            r#"
-struct Foo {}
-fn ref_arg(x: &mut Foo) {}
-fn main() {
-    let x = Foo {};
-    ref_ar<|>
-}
-"#,
-            r#"
-struct Foo {}
-fn ref_arg(x: &mut Foo) {}
-fn main() {
-    let x = Foo {};
-    ref_arg(${1:&mut x})$0
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn insert_ref_when_matching_local_in_scope_for_method() {
-        check_edit(
-            "apply_foo",
-            r#"
-struct Foo {}
-struct Bar {}
-impl Bar {
-    fn apply_foo(&self, x: &Foo) {}
-}
-
-fn main() {
-    let x = Foo {};
-    let y = Bar {};
-    y.<|>
-}
-"#,
-            r#"
-struct Foo {}
-struct Bar {}
-impl Bar {
-    fn apply_foo(&self, x: &Foo) {}
-}
-
-fn main() {
-    let x = Foo {};
-    let y = Bar {};
-    y.apply_foo(${1:&x})$0
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn trim_mut_keyword_in_func_completion() {
-        check_edit(
-            "take_mutably",
-            r#"
-fn take_mutably(mut x: &i32) {}
-
-fn main() {
-    take_m<|>
-}
-"#,
-            r#"
-fn take_mutably(mut x: &i32) {}
-
-fn main() {
-    take_mutably(${1:x})$0
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn inserts_parens_for_tuple_enums() {
-        mark::check!(inserts_parens_for_tuple_enums);
-        check_edit(
-            "Some",
-            r#"
-enum Option<T> { Some(T), None }
-use Option::*;
-fn main() -> Option<i32> {
-    Som<|>
-}
-"#,
-            r#"
-enum Option<T> { Some(T), None }
-use Option::*;
-fn main() -> Option<i32> {
-    Some($0)
-}
-"#,
-        );
-        check_edit(
-            "Some",
-            r#"
-enum Option<T> { Some(T), None }
-use Option::*;
-fn main(value: Option<i32>) {
-    match value {
-        Som<|>
-    }
-}
-"#,
-            r#"
-enum Option<T> { Some(T), None }
-use Option::*;
-fn main(value: Option<i32>) {
-    match value {
-        Some($0)
-    }
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn dont_duplicate_pattern_parens() {
-        mark::check!(dont_duplicate_pattern_parens);
-        check_edit(
-            "Var",
-            r#"
-enum E { Var(i32) }
-fn main() {
-    match E::Var(92) {
-        E::<|>(92) => (),
-    }
-}
-"#,
-            r#"
-enum E { Var(i32) }
-fn main() {
-    match E::Var(92) {
-        E::Var(92) => (),
-    }
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn no_call_parens_if_fn_ptr_needed() {
-        mark::check!(no_call_parens_if_fn_ptr_needed);
-        check_edit(
-            "foo",
-            r#"
-fn foo(foo: u8, bar: u8) {}
-struct ManualVtable { f: fn(u8, u8) }
-
-fn main() -> ManualVtable {
-    ManualVtable { f: f<|> }
-}
-"#,
-            r#"
-fn foo(foo: u8, bar: u8) {}
-struct ManualVtable { f: fn(u8, u8) }
-
-fn main() -> ManualVtable {
-    ManualVtable { f: foo }
-}
-"#,
-        );
-    }
-
-    #[test]
-    fn no_parens_in_use_item() {
-        mark::check!(no_parens_in_use_item);
-        check_edit(
-            "foo",
-            r#"
-mod m { pub fn foo() {} }
-use crate::m::f<|>;
-"#,
-            r#"
-mod m { pub fn foo() {} }
-use crate::m::foo;
-"#,
-        );
-    }
-
-    #[test]
-    fn no_parens_in_call() {
-        check_edit(
-            "foo",
-            r#"
-fn foo(x: i32) {}
-fn main() { f<|>(); }
-"#,
-            r#"
-fn foo(x: i32) {}
-fn main() { foo(); }
-"#,
-        );
-        check_edit(
-            "foo",
-            r#"
-struct Foo;
-impl Foo { fn foo(&self){} }
-fn f(foo: &Foo) { foo.f<|>(); }
-"#,
-            r#"
-struct Foo;
-impl Foo { fn foo(&self){} }
-fn f(foo: &Foo) { foo.foo(); }
-"#,
-        );
-    }
-
-    #[test]
-    fn inserts_angle_brackets_for_generics() {
-        mark::check!(inserts_angle_brackets_for_generics);
-        check_edit(
-            "Vec",
-            r#"
-struct Vec<T> {}
-fn foo(xs: Ve<|>)
-"#,
-            r#"
-struct Vec<T> {}
-fn foo(xs: Vec<$0>)
-"#,
-        );
-        check_edit(
-            "Vec",
-            r#"
-type Vec<T> = (T,);
-fn foo(xs: Ve<|>)
-"#,
-            r#"
-type Vec<T> = (T,);
-fn foo(xs: Vec<$0>)
-"#,
-        );
-        check_edit(
-            "Vec",
-            r#"
-struct Vec<T = i128> {}
-fn foo(xs: Ve<|>)
-"#,
-            r#"
-struct Vec<T = i128> {}
-fn foo(xs: Vec)
-"#,
-        );
-        check_edit(
-            "Vec",
-            r#"
-struct Vec<T> {}
-fn foo(xs: Ve<|><i128>)
-"#,
-            r#"
-struct Vec<T> {}
-fn foo(xs: Vec<i128>)
-"#,
-        );
-    }
-
-    #[test]
-    fn dont_insert_macro_call_parens_unncessary() {
-        mark::check!(dont_insert_macro_call_parens_unncessary);
-        check_edit(
-            "frobnicate!",
-            r#"
-//- /main.rs crate:main deps:foo
-use foo::<|>;
-//- /foo/lib.rs crate:foo
-#[macro_export]
-macro_rules frobnicate { () => () }
-"#,
-            r#"
-use foo::frobnicate;
-"#,
-        );
-
-        check_edit(
-            "frobnicate!",
-            r#"
-macro_rules frobnicate { () => () }
-fn main() { frob<|>!(); }
-"#,
-            r#"
-macro_rules frobnicate { () => () }
-fn main() { frobnicate!(); }
-"#,
-        );
-    }
-
-    #[test]
-    fn active_param_score() {
-        mark::check!(active_param_type_match);
-        check_scores(
-            r#"
-struct S { foo: i64, bar: u32, baz: u32 }
-fn test(bar: u32) { }
-fn foo(s: S) { test(s.<|>) }
-"#,
-            expect![[r#"
-                fd bar [type+name]
-                fd baz [type]
-                fd foo []
-            "#]],
-        );
-    }
-
-    #[test]
-    fn record_field_scores() {
-        mark::check!(record_field_type_match);
-        check_scores(
-            r#"
-struct A { foo: i64, bar: u32, baz: u32 }
-struct B { x: (), y: f32, bar: u32 }
-fn foo(a: A) { B { bar: a.<|> }; }
-"#,
-            expect![[r#"
-                fd bar [type+name]
-                fd baz [type]
-                fd foo []
-            "#]],
-        )
-    }
-
-    #[test]
-    fn record_field_and_call_scores() {
-        check_scores(
-            r#"
-struct A { foo: i64, bar: u32, baz: u32 }
-struct B { x: (), y: f32, bar: u32 }
-fn f(foo: i64) {  }
-fn foo(a: A) { B { bar: f(a.<|>) }; }
-"#,
-            expect![[r#"
-                fd foo [type+name]
-                fd bar []
-                fd baz []
-            "#]],
-        );
-        check_scores(
-            r#"
-struct A { foo: i64, bar: u32, baz: u32 }
-struct B { x: (), y: f32, bar: u32 }
-fn f(foo: i64) {  }
-fn foo(a: A) { f(B { bar: a.<|> }); }
-"#,
-            expect![[r#"
-                fd bar [type+name]
-                fd baz [type]
-                fd foo []
-            "#]],
-        );
-    }
-
-    #[test]
-    fn prioritize_exact_ref_match() {
-        check_scores(
-            r#"
-struct WorldSnapshot { _f: () };
-fn go(world: &WorldSnapshot) { go(w<|>) }
-"#,
-            expect![[r#"
-                bn world [type+name]
-                st WorldSnapshot []
-                fn go(…) []
-            "#]],
-        );
-    }
-
-    #[test]
-    fn too_many_arguments() {
-        mark::check!(too_many_arguments);
-        check_scores(
-            r#"
-struct Foo;
-fn f(foo: &Foo) { f(foo, w<|>) }
-"#,
-            expect![[r#"
-                st Foo []
-                fn f(…) []
-                bn foo []
-            "#]],
-        );
-    }
-
-    #[test]
-    fn guesses_macro_braces() {
-        check_edit(
-            "vec!",
-            r#"
-/// Creates a [`Vec`] containing the arguments.
-///
-/// ```
-/// let v = vec![1, 2, 3];
-/// assert_eq!(v[0], 1);
-/// assert_eq!(v[1], 2);
-/// assert_eq!(v[2], 3);
-/// ```
-macro_rules! vec { () => {} }
-
-fn fn main() { v<|> }
-"#,
-            r#"
-/// Creates a [`Vec`] containing the arguments.
-///
-/// ```
-/// let v = vec![1, 2, 3];
-/// assert_eq!(v[0], 1);
-/// assert_eq!(v[1], 2);
-/// assert_eq!(v[2], 3);
-/// ```
-macro_rules! vec { () => {} }
-
-fn fn main() { vec![$0] }
-"#,
-        );
-
-        check_edit(
-            "foo!",
-            r#"
-/// Foo
-///
-/// Don't call `fooo!()` `fooo!()`, or `_foo![]` `_foo![]`,
-/// call as `let _=foo!  { hello world };`
-macro_rules! foo { () => {} }
-fn main() { <|> }
-"#,
-            r#"
-/// Foo
-///
-/// Don't call `fooo!()` `fooo!()`, or `_foo![]` `_foo![]`,
-/// call as `let _=foo!  { hello world };`
-macro_rules! foo { () => {} }
-fn main() { foo! {$0} }
-"#,
-        )
-    }
-}
diff --git a/crates/ide/src/completion/test_utils.rs b/crates/ide/src/completion/test_utils.rs
deleted file mode 100644 (file)
index dabbef8..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-//! Runs completion for testing purposes.
-
-use hir::Semantics;
-use itertools::Itertools;
-use stdx::{format_to, trim_indent};
-use syntax::{AstNode, NodeOrToken, SyntaxElement};
-use test_utils::assert_eq_text;
-
-use crate::{
-    completion::{completion_item::CompletionKind, CompletionConfig},
-    fixture, CompletionItem,
-};
-
-pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
-    do_completion_with_config(CompletionConfig::default(), code, kind)
-}
-
-pub(crate) fn do_completion_with_config(
-    config: CompletionConfig,
-    code: &str,
-    kind: CompletionKind,
-) -> Vec<CompletionItem> {
-    let mut kind_completions: Vec<CompletionItem> = get_all_completion_items(config, code)
-        .into_iter()
-        .filter(|c| c.completion_kind == kind)
-        .collect();
-    kind_completions.sort_by(|l, r| l.label().cmp(r.label()));
-    kind_completions
-}
-
-pub(crate) fn completion_list(code: &str, kind: CompletionKind) -> String {
-    completion_list_with_config(CompletionConfig::default(), code, kind)
-}
-
-pub(crate) fn completion_list_with_config(
-    config: CompletionConfig,
-    code: &str,
-    kind: CompletionKind,
-) -> String {
-    let mut kind_completions: Vec<CompletionItem> = get_all_completion_items(config, code)
-        .into_iter()
-        .filter(|c| c.completion_kind == kind)
-        .collect();
-    kind_completions.sort_by_key(|c| c.label().to_owned());
-    let label_width = kind_completions
-        .iter()
-        .map(|it| monospace_width(it.label()))
-        .max()
-        .unwrap_or_default()
-        .min(16);
-    kind_completions
-        .into_iter()
-        .map(|it| {
-            let tag = it.kind().unwrap().tag();
-            let var_name = format!("{} {}", tag, it.label());
-            let mut buf = var_name;
-            if let Some(detail) = it.detail() {
-                let width = label_width.saturating_sub(monospace_width(it.label()));
-                format_to!(buf, "{:width$} {}", "", detail, width = width);
-            }
-            format_to!(buf, "\n");
-            buf
-        })
-        .collect()
-}
-
-fn monospace_width(s: &str) -> usize {
-    s.chars().count()
-}
-
-pub(crate) fn check_edit(what: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
-    check_edit_with_config(CompletionConfig::default(), what, ra_fixture_before, ra_fixture_after)
-}
-
-pub(crate) fn check_edit_with_config(
-    config: CompletionConfig,
-    what: &str,
-    ra_fixture_before: &str,
-    ra_fixture_after: &str,
-) {
-    let ra_fixture_after = trim_indent(ra_fixture_after);
-    let (analysis, position) = fixture::position(ra_fixture_before);
-    let completions: Vec<CompletionItem> =
-        analysis.completions(&config, position).unwrap().unwrap().into();
-    let (completion,) = completions
-        .iter()
-        .filter(|it| it.lookup() == what)
-        .collect_tuple()
-        .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions));
-    let mut actual = analysis.file_text(position.file_id).unwrap().to_string();
-    completion.text_edit().apply(&mut actual);
-    assert_eq_text!(&ra_fixture_after, &actual)
-}
-
-pub(crate) fn check_pattern_is_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
-    let (analysis, pos) = fixture::position(code);
-    analysis
-        .with_db(|db| {
-            let sema = Semantics::new(db);
-            let original_file = sema.parse(pos.file_id);
-            let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
-            assert!(check(NodeOrToken::Token(token)));
-        })
-        .unwrap();
-}
-
-pub(crate) fn check_pattern_is_not_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
-    let (analysis, pos) = fixture::position(code);
-    analysis
-        .with_db(|db| {
-            let sema = Semantics::new(db);
-            let original_file = sema.parse(pos.file_id);
-            let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
-            assert!(!check(NodeOrToken::Token(token)));
-        })
-        .unwrap();
-}
-
-pub(crate) fn get_all_completion_items(
-    config: CompletionConfig,
-    code: &str,
-) -> Vec<CompletionItem> {
-    let (analysis, position) = fixture::position(code);
-    analysis.completions(&config, position).unwrap().unwrap().into()
-}
index 2484dbbf12bc745ee3f87f3508e7f19f7232f9e5..0650915c531450960cc0ef3479efcdf494fc8edc 100644 (file)
@@ -4,87 +4,8 @@
 mod navigation_target;
 mod short_label;
 
-use syntax::{
-    ast::{self, AstNode, AttrsOwner, GenericParamsOwner, NameOwner},
-    SyntaxKind::{ATTR, COMMENT},
-};
-
-use ast::VisibilityOwner;
-use stdx::format_to;
-
 pub use navigation_target::NavigationTarget;
 pub(crate) use navigation_target::{ToNav, TryToNav};
 pub(crate) use short_label::ShortLabel;
 
-pub(crate) fn function_declaration(node: &ast::Fn) -> String {
-    let mut buf = String::new();
-    if let Some(vis) = node.visibility() {
-        format_to!(buf, "{} ", vis);
-    }
-    if node.async_token().is_some() {
-        format_to!(buf, "async ");
-    }
-    if node.const_token().is_some() {
-        format_to!(buf, "const ");
-    }
-    if node.unsafe_token().is_some() {
-        format_to!(buf, "unsafe ");
-    }
-    if let Some(abi) = node.abi() {
-        // Keyword `extern` is included in the string.
-        format_to!(buf, "{} ", abi);
-    }
-    if let Some(name) = node.name() {
-        format_to!(buf, "fn {}", name)
-    }
-    if let Some(type_params) = node.generic_param_list() {
-        format_to!(buf, "{}", type_params);
-    }
-    if let Some(param_list) = node.param_list() {
-        let params: Vec<String> = param_list
-            .self_param()
-            .into_iter()
-            .map(|self_param| self_param.to_string())
-            .chain(param_list.params().map(|param| param.to_string()))
-            .collect();
-        // Useful to inline parameters
-        format_to!(buf, "({})", params.join(", "));
-    }
-    if let Some(ret_type) = node.ret_type() {
-        if ret_type.ty().is_some() {
-            format_to!(buf, " {}", ret_type);
-        }
-    }
-    if let Some(where_clause) = node.where_clause() {
-        format_to!(buf, "\n{}", where_clause);
-    }
-    buf
-}
-
-pub(crate) fn const_label(node: &ast::Const) -> String {
-    let label: String = node
-        .syntax()
-        .children_with_tokens()
-        .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR))
-        .map(|node| node.to_string())
-        .collect();
-
-    label.trim().to_owned()
-}
-
-pub(crate) fn type_label(node: &ast::TypeAlias) -> String {
-    let label: String = node
-        .syntax()
-        .children_with_tokens()
-        .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR))
-        .map(|node| node.to_string())
-        .collect();
-
-    label.trim().to_owned()
-}
-
-pub(crate) fn macro_label(node: &ast::MacroCall) -> String {
-    let name = node.name().map(|name| name.syntax().text().to_string()).unwrap_or_default();
-    let vis = if node.has_atom_attr("macro_export") { "#[macro_export]\n" } else { "" };
-    format!("{}macro_rules! {}", vis, name)
-}
+pub(crate) use syntax::display::{function_declaration, macro_label};
index aaf9b3b4b7dc16ad24fefb7593aa4b0b0dd6961c..cecfae4c7018eb41c2e82a768ab8fd8043af7c72 100644 (file)
@@ -23,8 +23,6 @@ macro_rules! eprintln {
 mod display;
 
 mod call_hierarchy;
-mod call_info;
-mod completion;
 mod diagnostics;
 mod expand_macro;
 mod extend_selection;
@@ -65,10 +63,6 @@ macro_rules! eprintln {
 
 pub use crate::{
     call_hierarchy::CallItem,
-    call_info::CallInfo,
-    completion::{
-        CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat,
-    },
     diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
     display::NavigationTarget,
     expand_macro::ExpandedMacro,
@@ -86,6 +80,10 @@ macro_rules! eprintln {
         Highlight, HighlightModifier, HighlightModifiers, HighlightTag, HighlightedRange,
     },
 };
+pub use call_info::CallInfo;
+pub use completion::{
+    CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat,
+};
 
 pub use assists::{
     utils::MergeBehaviour, Assist, AssistConfig, AssistId, AssistKind, ResolvedAssist,
index 43f4e6feab309290af0ff95039f250de81f3b9fb..acd91b26c0705b6cd576045d52e7f0401ff536a6 100644 (file)
@@ -3,14 +3,12 @@
 use std::{collections::BTreeMap, convert::TryFrom};
 
 use ast::{HasQuotes, HasStringValue};
+use call_info::ActiveParameter;
 use hir::Semantics;
 use itertools::Itertools;
 use syntax::{ast, AstToken, SyntaxNode, SyntaxToken, TextRange, TextSize};
 
-use crate::{
-    call_info::ActiveParameter, Analysis, Highlight, HighlightModifier, HighlightTag,
-    HighlightedRange, RootDatabase,
-};
+use crate::{Analysis, Highlight, HighlightModifier, HighlightTag, HighlightedRange, RootDatabase};
 
 use super::HighlightedRangeStack;
 
diff --git a/crates/syntax/src/display.rs b/crates/syntax/src/display.rs
new file mode 100644 (file)
index 0000000..8d2c7ea
--- /dev/null
@@ -0,0 +1,83 @@
+//! This module contains utilities for turning SyntaxNodes and HIR types
+//! into types that may be used to render in a UI.
+
+use crate::{
+    ast::{self, AstNode, AttrsOwner, GenericParamsOwner, NameOwner},
+    SyntaxKind::{ATTR, COMMENT},
+};
+
+use ast::VisibilityOwner;
+use stdx::format_to;
+
+pub fn function_declaration(node: &ast::Fn) -> String {
+    let mut buf = String::new();
+    if let Some(vis) = node.visibility() {
+        format_to!(buf, "{} ", vis);
+    }
+    if node.async_token().is_some() {
+        format_to!(buf, "async ");
+    }
+    if node.const_token().is_some() {
+        format_to!(buf, "const ");
+    }
+    if node.unsafe_token().is_some() {
+        format_to!(buf, "unsafe ");
+    }
+    if let Some(abi) = node.abi() {
+        // Keyword `extern` is included in the string.
+        format_to!(buf, "{} ", abi);
+    }
+    if let Some(name) = node.name() {
+        format_to!(buf, "fn {}", name)
+    }
+    if let Some(type_params) = node.generic_param_list() {
+        format_to!(buf, "{}", type_params);
+    }
+    if let Some(param_list) = node.param_list() {
+        let params: Vec<String> = param_list
+            .self_param()
+            .into_iter()
+            .map(|self_param| self_param.to_string())
+            .chain(param_list.params().map(|param| param.to_string()))
+            .collect();
+        // Useful to inline parameters
+        format_to!(buf, "({})", params.join(", "));
+    }
+    if let Some(ret_type) = node.ret_type() {
+        if ret_type.ty().is_some() {
+            format_to!(buf, " {}", ret_type);
+        }
+    }
+    if let Some(where_clause) = node.where_clause() {
+        format_to!(buf, "\n{}", where_clause);
+    }
+    buf
+}
+
+pub fn const_label(node: &ast::Const) -> String {
+    let label: String = node
+        .syntax()
+        .children_with_tokens()
+        .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR))
+        .map(|node| node.to_string())
+        .collect();
+
+    label.trim().to_owned()
+}
+
+pub fn type_label(node: &ast::TypeAlias) -> String {
+    let label: String = node
+        .syntax()
+        .children_with_tokens()
+        .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR))
+        .map(|node| node.to_string())
+        .collect();
+
+    label.trim().to_owned()
+}
+
+pub fn macro_label(node: &ast::MacroCall) -> String {
+    let name = node.name().map(|name| name.syntax().text().to_string()).unwrap_or_default();
+    let vis = if node.has_atom_attr("macro_export") { "#[macro_export]\n" } else { "" };
+    format!("{}macro_rules! {}", vis, name)
+}
index 7f8da66af072dc98dc8f73c2b1f2d54efa336fcb..849a1cdd6358e3b81878b816ea347c7c3e6083a7 100644 (file)
@@ -32,6 +32,7 @@ macro_rules! eprintln {
 #[cfg(test)]
 mod tests;
 
+pub mod display;
 pub mod algo;
 pub mod ast;
 #[doc(hidden)]
index d335adb72b3ff45085c4e51bf77eb2213dffe620..46006940746155fdc3c505d9206bc7d752a21462 100644 (file)
@@ -213,7 +213,7 @@ fn check_todo(path: &Path, text: &str) {
         // `ast::make`.
         "ast/make.rs",
         // The documentation in string literals may contain anything for its own purposes
-        "completion/generated_features.rs",
+        "completion/src/generated_features.rs",
     ];
     if need_todo.iter().any(|p| path.ends_with(p)) {
         return;