Repository: rust-analyzer/rust-analyzer
Pull request #2069 (2019-10-25 11:49:49)

auto-generate assists docs and tests


Patch:
diff --git a/Cargo.lock b/Cargo.lock
index 382eb92e4c..c902caeb4d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -126,9 +126,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 [[package]]
 name = "chalk-engine"
 version = "0.9.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9#13303bb0067c6ed0572322080ae367ee38f9e7c9"
+source = "git+https://github.com/rust-lang/chalk.git#13303bb0067c6ed0572322080ae367ee38f9e7c9"
 dependencies = [
- "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
+ "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)",
  "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "stacker 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
@@ -136,17 +136,17 @@ dependencies = [
 [[package]]
 name = "chalk-ir"
 version = "0.1.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9#13303bb0067c6ed0572322080ae367ee38f9e7c9"
+source = "git+https://github.com/rust-lang/chalk.git#13303bb0067c6ed0572322080ae367ee38f9e7c9"
 dependencies = [
- "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
- "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
+ "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git)",
+ "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)",
  "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "chalk-macros"
 version = "0.1.1"
-source = "git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9#13303bb0067c6ed0572322080ae367ee38f9e7c9"
+source = "git+https://github.com/rust-lang/chalk.git#13303bb0067c6ed0572322080ae367ee38f9e7c9"
 dependencies = [
  "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
@@ -154,22 +154,22 @@ dependencies = [
 [[package]]
 name = "chalk-rust-ir"
 version = "0.1.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9#13303bb0067c6ed0572322080ae367ee38f9e7c9"
+source = "git+https://github.com/rust-lang/chalk.git#13303bb0067c6ed0572322080ae367ee38f9e7c9"
 dependencies = [
- "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
- "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
- "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
+ "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git)",
+ "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)",
+ "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)",
 ]
 
 [[package]]
 name = "chalk-solve"
 version = "0.1.0"
-source = "git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9#13303bb0067c6ed0572322080ae367ee38f9e7c9"
+source = "git+https://github.com/rust-lang/chalk.git#13303bb0067c6ed0572322080ae367ee38f9e7c9"
 dependencies = [
- "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
- "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
- "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
- "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
+ "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git)",
+ "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)",
+ "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)",
+ "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)",
  "ena 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -979,9 +979,9 @@ name = "ra_hir"
 version = "0.1.0"
 dependencies = [
  "arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
- "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
- "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
- "chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)",
+ "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)",
+ "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)",
+ "chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git)",
  "ena 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "insta 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -1794,11 +1794,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 "checksum cargo_metadata 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8d2d1617e838936c0d2323a65cc151e03ae19a7678dd24f72bccf27119b90a5d"
 "checksum cc 1.0.46 (registry+https://github.com/rust-lang/crates.io-index)" = "0213d356d3c4ea2c18c40b037c3be23cd639825c18f25ee670ac7813beeef99c"
 "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
-"checksum chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)" = "<none>"
-"checksum chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)" = "<none>"
-"checksum chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)" = "<none>"
-"checksum chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)" = "<none>"
-"checksum chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git?rev=13303bb0067c6ed0572322080ae367ee38f9e7c9)" = "<none>"
+"checksum chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git)" = "<none>"
+"checksum chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)" = "<none>"
+"checksum chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)" = "<none>"
+"checksum chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)" = "<none>"
+"checksum chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git)" = "<none>"
 "checksum chrono 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)" = "e8493056968583b0193c1bb04d6f7684586f3726992d6c573261941a895dbd68"
 "checksum clicolors-control 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "90082ee5dcdd64dc4e9e0d37fbf3ee325419e39c0092191e0393df65518f741e"
 "checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f"
diff --git a/crates/ra_assists/src/assists/early_return.rs b/crates/ra_assists/src/assists/early_return.rs
index f7d7e12e73..b3d0253406 100644
--- a/crates/ra_assists/src/assists/early_return.rs
+++ b/crates/ra_assists/src/assists/early_return.rs
@@ -1,26 +1,3 @@
-//! Assist: `convert_to_guarded_return`
-//!
-//! Replace a large conditional with a guarded return.
-//!
-//! ```text
-//! fn <|>main() {
-//!     if cond {
-//!         foo();
-//!         bar();
-//!     }
-//! }
-//! ```
-//! ->
-//! ```text
-//! fn main() {
-//!     if !cond {
-//!         return;
-//!     }
-//!     foo();
-//!     bar();
-//! }
-//! ```
-
 use std::ops::RangeInclusive;
 
 use hir::db::HirDatabase;
@@ -36,6 +13,26 @@ use crate::{
     AssistId,
 };
 
+// Assist: convert_to_guarded_return
+// Replace a large conditional with a guarded return.
+// ```
+// fn main() {
+//     <|>if cond {
+//         foo();
+//         bar();
+//     }
+// }
+// ```
+// ->
+// ```
+// fn main() {
+//     if !cond {
+//         return;
+//     }
+//     foo();
+//     bar();
+// }
+// ```
 pub(crate) fn convert_to_guarded_return(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
     let if_expr: ast::IfExpr = ctx.node_at_offset()?;
     let expr = if_expr.condition()?.expr()?;
diff --git a/crates/ra_assists/src/lib.rs b/crates/ra_assists/src/lib.rs
index ab77b46a99..de576324fb 100644
--- a/crates/ra_assists/src/lib.rs
+++ b/crates/ra_assists/src/lib.rs
@@ -7,6 +7,8 @@
 
 mod assist_ctx;
 mod marks;
+#[cfg(test)]
+mod doc_tests;
 
 use hir::db::HirDatabase;
 use itertools::Itertools;
@@ -36,7 +38,7 @@ pub struct AssistAction {
     pub target: Option<TextRange>,
 }
 
-/// Return all the assists eapplicable at the given position.
+/// Return all the assists applicable at the given position.
 ///
 /// Assists are returned in the "unresolved" state, that is only labels are
 /// returned, without actual edits.
diff --git a/crates/ra_hir/Cargo.toml b/crates/ra_hir/Cargo.toml
index dce897d301..54c09788aa 100644
--- a/crates/ra_hir/Cargo.toml
+++ b/crates/ra_hir/Cargo.toml
@@ -22,9 +22,9 @@ tt = { path = "../ra_tt", package = "ra_tt" }
 test_utils = { path = "../test_utils" }
 ra_prof = { path = "../ra_prof" }
 
-chalk-solve = { git = "https://github.com/rust-lang/chalk.git", rev = "13303bb0067c6ed0572322080ae367ee38f9e7c9" }
-chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "13303bb0067c6ed0572322080ae367ee38f9e7c9" }
-chalk-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "13303bb0067c6ed0572322080ae367ee38f9e7c9" }
+chalk-solve = { git = "https://github.com/rust-lang/chalk.git" }
+chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git" }
+chalk-ir = { git = "https://github.com/rust-lang/chalk.git" }
 lalrpop-intern = "0.15.1"
 
 [dev-dependencies]
diff --git a/crates/ra_ide_api/src/lib.rs b/crates/ra_ide_api/src/lib.rs
index d0188da449..0832229fd1 100644
--- a/crates/ra_ide_api/src/lib.rs
+++ b/crates/ra_ide_api/src/lib.rs
@@ -14,7 +14,6 @@ mod db;
 pub mod mock_analysis;
 mod symbol_index;
 mod change;
-mod source_change;
 mod feature_flags;
 
 mod status;
@@ -55,6 +54,8 @@ use ra_db::{
     CheckCanceled, FileLoader, SourceDatabase,
 };
 use ra_syntax::{SourceFile, TextRange, TextUnit};
+use ra_text_edit::TextEdit;
+use relative_path::RelativePathBuf;
 
 use crate::{db::LineIndexDatabase, symbol_index::FileSymbol};
 
@@ -72,7 +73,6 @@ pub use crate::{
     line_index_utils::translate_offset_with_edit,
     references::{ReferenceSearchResult, SearchScope},
     runnables::{Runnable, RunnableKind},
-    source_change::{FileSystemEdit, SourceChange, SourceFileEdit},
     syntax_highlighting::HighlightedRange,
 };
 
@@ -83,6 +83,99 @@ pub use ra_db::{
 
 pub type Cancelable<T> = Result<T, Canceled>;
 
+#[derive(Debug)]
+pub struct SourceChange {
+    pub label: String,
+    pub source_file_edits: Vec<SourceFileEdit>,
+    pub file_system_edits: Vec<FileSystemEdit>,
+    pub cursor_position: Option<FilePosition>,
+}
+
+impl SourceChange {
+    /// Creates a new SourceChange with the given label
+    /// from the edits.
+    pub(crate) fn from_edits<L: Into<String>>(
+        label: L,
+        source_file_edits: Vec<SourceFileEdit>,
+        file_system_edits: Vec<FileSystemEdit>,
+    ) -> Self {
+        SourceChange {
+            label: label.into(),
+            source_file_edits,
+            file_system_edits,
+            cursor_position: None,
+        }
+    }
+
+    /// Creates a new SourceChange with the given label,
+    /// containing only the given `SourceFileEdits`.
+    pub(crate) fn source_file_edits<L: Into<String>>(label: L, edits: Vec<SourceFileEdit>) -> Self {
+        SourceChange {
+            label: label.into(),
+            source_file_edits: edits,
+            file_system_edits: vec![],
+            cursor_position: None,
+        }
+    }
+
+    /// Creates a new SourceChange with the given label,
+    /// containing only the given `FileSystemEdits`.
+    pub(crate) fn file_system_edits<L: Into<String>>(label: L, edits: Vec<FileSystemEdit>) -> Self {
+        SourceChange {
+            label: label.into(),
+            source_file_edits: vec![],
+            file_system_edits: edits,
+            cursor_position: None,
+        }
+    }
+
+    /// Creates a new SourceChange with the given label,
+    /// containing only a single `SourceFileEdit`.
+    pub(crate) fn source_file_edit<L: Into<String>>(label: L, edit: SourceFileEdit) -> Self {
+        SourceChange::source_file_edits(label, vec![edit])
+    }
+
+    /// Creates a new SourceChange with the given label
+    /// from the given `FileId` and `TextEdit`
+    pub(crate) fn source_file_edit_from<L: Into<String>>(
+        label: L,
+        file_id: FileId,
+        edit: TextEdit,
+    ) -> Self {
+        SourceChange::source_file_edit(label, SourceFileEdit { file_id, edit })
+    }
+
+    /// Creates a new SourceChange with the given label
+    /// from the given `FileId` and `TextEdit`
+    pub(crate) fn file_system_edit<L: Into<String>>(label: L, edit: FileSystemEdit) -> Self {
+        SourceChange::file_system_edits(label, vec![edit])
+    }
+
+    /// Sets the cursor position to the given `FilePosition`
+    pub(crate) fn with_cursor(mut self, cursor_position: FilePosition) -> Self {
+        self.cursor_position = Some(cursor_position);
+        self
+    }
+
+    /// Sets the cursor position to the given `FilePosition`
+    pub(crate) fn with_cursor_opt(mut self, cursor_position: Option<FilePosition>) -> Self {
+        self.cursor_position = cursor_position;
+        self
+    }
+}
+
+#[derive(Debug)]
+pub struct SourceFileEdit {
+    pub file_id: FileId,
+    pub edit: TextEdit,
+}
+
+#[derive(Debug)]
+pub enum FileSystemEdit {
+    CreateFile { source_root: SourceRootId, path: RelativePathBuf },
+    MoveFile { src: FileId, dst_source_root: SourceRootId, dst_path: RelativePathBuf },
+}
+
 #[derive(Debug)]
 pub struct Diagnostic {
     pub message: String,
@@ -314,20 +407,24 @@ impl Analysis {
         self.with_db(|db| typing::on_enter(&db, position))
     }
 
-    /// Returns an edit which should be applied after a character was typed.
-    ///
-    /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
-    /// automatically.
-    pub fn on_char_typed(
-        &self,
-        position: FilePosition,
-        char_typed: char,
-    ) -> Cancelable<Option<SourceChange>> {
-        // Fast path to not even parse the file.
-        if !typing::TRIGGER_CHARS.contains(char_typed) {
-            return Ok(None);
-        }
-        self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
+    /// Returns an edit which should be applied after `=` was typed. Primarily,
+    /// this works when adding `let =`.
+    // FIXME: use a snippet completion instead of this hack here.
+    pub fn on_eq_typed(&self, position: FilePosition) -> Cancelable<Option<SourceChange>> {
+        self.with_db(|db| {
+            let parse = db.parse(position.file_id);
+            let file = parse.tree();
+            let edit = typing::on_eq_typed(&file, position.offset)?;
+            Some(SourceChange::source_file_edit(
+                "add semicolon",
+                SourceFileEdit { edit, file_id: position.file_id },
+            ))
+        })
+    }
+
+    /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
+    pub fn on_dot_typed(&self, position: FilePosition) -> Cancelable<Option<SourceChange>> {
+        self.with_db(|db| typing::on_dot_typed(&db, position))
     }
 
     /// Returns a tree representation of symbols in the file. Useful to draw a
diff --git a/crates/ra_ide_api/src/source_change.rs b/crates/ra_ide_api/src/source_change.rs
deleted file mode 100644
index 4e63bbf6f0..0000000000
--- a/crates/ra_ide_api/src/source_change.rs
+++ /dev/null
@@ -1,119 +0,0 @@
-//! This modules defines type to represent changes to the source code, that flow
-//! from the server to the client.
-//!
-//! It can be viewed as a dual for `AnalysisChange`.
-
-use ra_text_edit::TextEdit;
-use relative_path::RelativePathBuf;
-
-use crate::{FileId, FilePosition, SourceRootId, TextUnit};
-
-#[derive(Debug)]
-pub struct SourceChange {
-    pub label: String,
-    pub source_file_edits: Vec<SourceFileEdit>,
-    pub file_system_edits: Vec<FileSystemEdit>,
-    pub cursor_position: Option<FilePosition>,
-}
-
-impl SourceChange {
-    /// Creates a new SourceChange with the given label
-    /// from the edits.
-    pub(crate) fn from_edits<L: Into<String>>(
-        label: L,
-        source_file_edits: Vec<SourceFileEdit>,
-        file_system_edits: Vec<FileSystemEdit>,
-    ) -> Self {
-        SourceChange {
-            label: label.into(),
-            source_file_edits,
-            file_system_edits,
-            cursor_position: None,
-        }
-    }
-
-    /// Creates a new SourceChange with the given label,
-    /// containing only the given `SourceFileEdits`.
-    pub(crate) fn source_file_edits<L: Into<String>>(label: L, edits: Vec<SourceFileEdit>) -> Self {
-        SourceChange {
-            label: label.into(),
-            source_file_edits: edits,
-            file_system_edits: vec![],
-            cursor_position: None,
-        }
-    }
-
-    /// Creates a new SourceChange with the given label,
-    /// containing only the given `FileSystemEdits`.
-    pub(crate) fn file_system_edits<L: Into<String>>(label: L, edits: Vec<FileSystemEdit>) -> Self {
-        SourceChange {
-            label: label.into(),
-            source_file_edits: vec![],
-            file_system_edits: edits,
-            cursor_position: None,
-        }
-    }
-
-    /// Creates a new SourceChange with the given label,
-    /// containing only a single `SourceFileEdit`.
-    pub(crate) fn source_file_edit<L: Into<String>>(label: L, edit: SourceFileEdit) -> Self {
-        SourceChange::source_file_edits(label, vec![edit])
-    }
-
-    /// Creates a new SourceChange with the given label
-    /// from the given `FileId` and `TextEdit`
-    pub(crate) fn source_file_edit_from<L: Into<String>>(
-        label: L,
-        file_id: FileId,
-        edit: TextEdit,
-    ) -> Self {
-        SourceChange::source_file_edit(label, SourceFileEdit { file_id, edit })
-    }
-
-    /// Creates a new SourceChange with the given label
-    /// from the given `FileId` and `TextEdit`
-    pub(crate) fn file_system_edit<L: Into<String>>(label: L, edit: FileSystemEdit) -> Self {
-        SourceChange::file_system_edits(label, vec![edit])
-    }
-
-    /// Sets the cursor position to the given `FilePosition`
-    pub(crate) fn with_cursor(mut self, cursor_position: FilePosition) -> Self {
-        self.cursor_position = Some(cursor_position);
-        self
-    }
-
-    /// Sets the cursor position to the given `FilePosition`
-    pub(crate) fn with_cursor_opt(mut self, cursor_position: Option<FilePosition>) -> Self {
-        self.cursor_position = cursor_position;
-        self
-    }
-}
-
-#[derive(Debug)]
-pub struct SourceFileEdit {
-    pub file_id: FileId,
-    pub edit: TextEdit,
-}
-
-#[derive(Debug)]
-pub enum FileSystemEdit {
-    CreateFile { source_root: SourceRootId, path: RelativePathBuf },
-    MoveFile { src: FileId, dst_source_root: SourceRootId, dst_path: RelativePathBuf },
-}
-
-pub(crate) struct SingleFileChange {
-    pub label: String,
-    pub edit: TextEdit,
-    pub cursor_position: Option<TextUnit>,
-}
-
-impl SingleFileChange {
-    pub(crate) fn into_source_change(self, file_id: FileId) -> SourceChange {
-        SourceChange {
-            label: self.label,
-            source_file_edits: vec![SourceFileEdit { file_id, edit: self.edit }],
-            file_system_edits: Vec::new(),
-            cursor_position: self.cursor_position.map(|offset| FilePosition { file_id, offset }),
-        }
-    }
-}
diff --git a/crates/ra_ide_api/src/typing.rs b/crates/ra_ide_api/src/typing.rs
index 26a3111fd8..2f5782012b 100644
--- a/crates/ra_ide_api/src/typing.rs
+++ b/crates/ra_ide_api/src/typing.rs
@@ -1,17 +1,4 @@
-//! This module handles auto-magic editing actions applied together with users
-//! edits. For example, if the user typed
-//!
-//! ```text
-//!     foo
-//!         .bar()
-//!         .baz()
-//!     |   // <- cursor is here
-//! ```
-//!
-//! and types `.` next, we want to indent the dot.
-//!
-//! Language server executes such typing assists synchronously. That is, they
-//! block user's typing and should be pretty fast for this reason!
+//! FIXME: write short doc here
 
 use ra_db::{FilePosition, SourceDatabase};
 use ra_fmt::leading_indent;
@@ -24,7 +11,7 @@ use ra_syntax::{
 };
 use ra_text_edit::{TextEdit, TextEditBuilder};
 
-use crate::{db::RootDatabase, source_change::SingleFileChange, SourceChange, SourceFileEdit};
+use crate::{db::RootDatabase, SourceChange, SourceFileEdit};
 
 pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> {
     let parse = db.parse(position.file_id);
@@ -81,67 +68,39 @@ fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
     Some(text[pos..].into())
 }
 
-pub(crate) const TRIGGER_CHARS: &str = ".=>";
-
-pub(crate) fn on_char_typed(
-    db: &RootDatabase,
-    position: FilePosition,
-    char_typed: char,
-) -> Option<SourceChange> {
-    assert!(TRIGGER_CHARS.contains(char_typed));
-    let file = &db.parse(position.file_id).tree();
-    assert_eq!(file.syntax().text().char_at(position.offset), Some(char_typed));
-    let single_file_change = on_char_typed_inner(file, position.offset, char_typed)?;
-    Some(single_file_change.into_source_change(position.file_id))
-}
-
-fn on_char_typed_inner(
-    file: &SourceFile,
-    offset: TextUnit,
-    char_typed: char,
-) -> Option<SingleFileChange> {
-    assert!(TRIGGER_CHARS.contains(char_typed));
-    match char_typed {
-        '.' => on_dot_typed(file, offset),
-        '=' => on_eq_typed(file, offset),
-        '>' => on_arrow_typed(file, offset),
-        _ => unreachable!(),
-    }
-}
-
-/// Returns an edit which should be applied after `=` was typed. Primarily,
-/// this works when adding `let =`.
-// FIXME: use a snippet completion instead of this hack here.
-fn on_eq_typed(file: &SourceFile, offset: TextUnit) -> Option<SingleFileChange> {
-    assert_eq!(file.syntax().text().char_at(offset), Some('='));
-    let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
+pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<TextEdit> {
+    assert_eq!(file.syntax().text().char_at(eq_offset), Some('='));
+    let let_stmt: ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?;
     if let_stmt.has_semi() {
         return None;
     }
     if let Some(expr) = let_stmt.initializer() {
         let expr_range = expr.syntax().text_range();
-        if expr_range.contains(offset) && offset != expr_range.start() {
+        if expr_range.contains(eq_offset) && eq_offset != expr_range.start() {
             return None;
         }
-        if file.syntax().text().slice(offset..expr_range.start()).contains_char('\n') {
+        if file.syntax().text().slice(eq_offset..expr_range.start()).contains_char('\n') {
             return None;
         }
     } else {
         return None;
     }
     let offset = let_stmt.syntax().text_range().end();
-    Some(SingleFileChange {
-        label: "add semicolon".to_string(),
-        edit: TextEdit::insert(offset, ";".to_string()),
-        cursor_position: None,
-    })
+    let mut edit = TextEditBuilder::default();
+    edit.insert(offset, ";".to_string());
+    Some(edit.finish())
 }
 
-/// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
-fn on_dot_typed(file: &SourceFile, offset: TextUnit) -> Option<SingleFileChange> {
-    assert_eq!(file.syntax().text().char_at(offset), Some('.'));
-    let whitespace =
-        file.syntax().token_at_offset(offset).left_biased().and_then(ast::Whitespace::cast)?;
+pub(crate) fn on_dot_typed(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> {
+    let parse = db.parse(position.file_id);
+    assert_eq!(parse.tree().syntax().text().char_at(position.offset), Some('.'));
+
+    let whitespace = parse
+        .tree()
+        .syntax()
+        .token_at_offset(position.offset)
+        .left_biased()
+        .and_then(ast::Whitespace::cast)?;
 
     let current_indent = {
         let text = whitespace.text();
@@ -158,36 +117,20 @@ fn on_dot_typed(file: &SourceFile, offset: TextUnit) -> Option<SingleFileChange>
     if current_indent_len == target_indent_len {
         return None;
     }
-
-    Some(SingleFileChange {
-        label: "reindent dot".to_string(),
-        edit: TextEdit::replace(
-            TextRange::from_to(offset - current_indent_len, offset),
-            target_indent,
-        ),
-        cursor_position: Some(
-            offset + target_indent_len - current_indent_len + TextUnit::of_char('.'),
-        ),
-    })
-}
-
-/// Adds a space after an arrow when `fn foo() { ... }` is turned into `fn foo() -> { ... }`
-fn on_arrow_typed(file: &SourceFile, offset: TextUnit) -> Option<SingleFileChange> {
-    let file_text = file.syntax().text();
-    assert_eq!(file_text.char_at(offset), Some('>'));
-    let after_arrow = offset + TextUnit::of_char('>');
-    if file_text.char_at(after_arrow) != Some('{') {
-        return None;
-    }
-    if find_node_at_offset::<ast::RetType>(file.syntax(), offset).is_none() {
-        return None;
-    }
-
-    Some(SingleFileChange {
-        label: "add space after return type".to_string(),
-        edit: TextEdit::insert(after_arrow, " ".to_string()),
-        cursor_position: Some(after_arrow),
-    })
+    let mut edit = TextEditBuilder::default();
+    edit.replace(
+        TextRange::from_to(position.offset - current_indent_len, position.offset),
+        target_indent,
+    );
+
+    let res = SourceChange::source_file_edit_from("reindent dot", position.file_id, edit.finish())
+        .with_cursor(FilePosition {
+            offset: position.offset + target_indent_len - current_indent_len
+                + TextUnit::of_char('.'),
+            file_id: position.file_id,
+        });
+
+    Some(res)
 }
 
 #[cfg(test)]
@@ -199,87 +142,21 @@ mod tests {
     use super::*;
 
     #[test]
-    fn test_on_enter() {
-        fn apply_on_enter(before: &str) -> Option<String> {
+    fn test_on_eq_typed() {
+        fn type_eq(before: &str, after: &str) {
             let (offset, before) = extract_offset(before);
-            let (analysis, file_id) = single_file(&before);
-            let result = analysis.on_enter(FilePosition { offset, file_id }).unwrap()?;
-
-            assert_eq!(result.source_file_edits.len(), 1);
-            let actual = result.source_file_edits[0].edit.apply(&before);
-            let actual = add_cursor(&actual, result.cursor_position.unwrap().offset);
-            Some(actual)
-        }
-
-        fn do_check(before: &str, after: &str) {
-            let actual = apply_on_enter(before).unwrap();
-            assert_eq_text!(after, &actual);
-        }
-
-        fn do_check_noop(text: &str) {
-            assert!(apply_on_enter(text).is_none())
-        }
-
-        do_check(
-            r"
-/// Some docs<|>
-fn foo() {
-}
-",
-            r"
-/// Some docs
-/// <|>
-fn foo() {
-}
-",
-        );
-        do_check(
-            r"
-impl S {
-    /// Some<|> docs.
-    fn foo() {}
-}
-",
-            r"
-impl S {
-    /// Some
-    /// <|> docs.
-    fn foo() {}
-}
-",
-        );
-        do_check_noop(r"<|>//! docz");
-    }
-
-    fn do_type_char(char_typed: char, before: &str) -> Option<(String, SingleFileChange)> {
-        let (offset, before) = extract_offset(before);
-        let edit = TextEdit::insert(offset, char_typed.to_string());
-        let before = edit.apply(&before);
-        let parse = SourceFile::parse(&before);
-        on_char_typed_inner(&parse.tree(), offset, char_typed)
-            .map(|it| (it.edit.apply(&before), it))
-    }
-
-    fn type_char(char_typed: char, before: &str, after: &str) {
-        let (actual, file_change) = do_type_char(char_typed, before)
-            .expect(&format!("typing `{}` did nothing", char_typed));
-
-        if after.contains("<|>") {
-            let (offset, after) = extract_offset(after);
-            assert_eq_text!(&after, &actual);
-            assert_eq!(file_change.cursor_position, Some(offset))
-        } else {
-            assert_eq_text!(after, &actual);
+            let mut edit = TextEditBuilder::default();
+            edit.insert(offset, "=".to_string());
+            let before = edit.finish().apply(&before);
+            let parse = SourceFile::parse(&before);
+            if let Some(result) = on_eq_typed(&parse.tree(), offset) {
+                let actual = result.apply(&before);
+                assert_eq_text!(after, &actual);
+            } else {
+                assert_eq_text!(&before, after)
+            };
         }
-    }
 
-    fn type_char_noop(char_typed: char, before: &str) {
-        let file_change = do_type_char(char_typed, before);
-        assert!(file_change.is_none())
-    }
-
-    #[test]
-    fn test_on_eq_typed() {
         //     do_check(r"
         // fn foo() {
         //     let foo =<|>
@@ -289,8 +166,7 @@ impl S {
         //     let foo =;
         // }
         // ");
-        type_char(
-            '=',
+        type_eq(
             r"
 fn foo() {
     let foo <|> 1 + 1
@@ -315,10 +191,24 @@ fn foo() {
         // ");
     }
 
+    fn type_dot(before: &str, after: &str) {
+        let (offset, before) = extract_offset(before);
+        let mut edit = TextEditBuilder::default();
+        edit.insert(offset, ".".to_string());
+        let before = edit.finish().apply(&before);
+        let (analysis, file_id) = single_file(&before);
+        if let Some(result) = analysis.on_dot_typed(FilePosition { offset, file_id }).unwrap() {
+            assert_eq!(result.source_file_edits.len(), 1);
+            let actual = result.source_file_edits[0].edit.apply(&before);
+            assert_eq_text!(after, &actual);
+        } else {
+            assert_eq_text!(&before, after)
+        };
+    }
+
     #[test]
     fn indents_new_chain_call() {
-        type_char(
-            '.',
+        type_dot(
             r"
             pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
                 self.child_impl(db, name)
@@ -332,21 +222,25 @@ fn foo() {
             }
             ",
         );
-        type_char_noop(
-            '.',
+        type_dot(
             r"
             pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
                 self.child_impl(db, name)
                     <|>
             }
             ",
+            r"
+            pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
+                self.child_impl(db, name)
+                    .
+            }
+            ",
         )
     }
 
     #[test]
     fn indents_new_chain_call_with_semi() {
-        type_char(
-            '.',
+        type_dot(
             r"
             pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
                 self.child_impl(db, name)
@@ -360,21 +254,25 @@ fn foo() {
             }
             ",
         );
-        type_char_noop(
-            '.',
+        type_dot(
             r"
             pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
                 self.child_impl(db, name)
                     <|>;
             }
             ",
+            r"
+            pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
+                self.child_impl(db, name)
+                    .;
+            }
+            ",
         )
     }
 
     #[test]
     fn indents_continued_chain_call() {
-        type_char(
-            '.',
+        type_dot(
             r"
             pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
                 self.child_impl(db, name)
@@ -390,8 +288,7 @@ fn foo() {
             }
             ",
         );
-        type_char_noop(
-            '.',
+        type_dot(
             r"
             pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
                 self.child_impl(db, name)
@@ -399,13 +296,19 @@ fn foo() {
                     <|>
             }
             ",
+            r"
+            pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
+                self.child_impl(db, name)
+                    .first()
+                    .
+            }
+            ",
         );
     }
 
     #[test]
     fn indents_middle_of_chain_call() {
-        type_char(
-            '.',
+        type_dot(
             r"
             fn source_impl() {
                 let var = enum_defvariant_list().unwrap()
@@ -423,8 +326,7 @@ fn foo() {
             }
             ",
         );
-        type_char_noop(
-            '.',
+        type_dot(
             r"
             fn source_impl() {
                 let var = enum_defvariant_list().unwrap()
@@ -433,31 +335,95 @@ fn foo() {
                     .unwrap();
             }
             ",
+            r"
+            fn source_impl() {
+                let var = enum_defvariant_list().unwrap()
+                    .
+                    .nth(92)
+                    .unwrap();
+            }
+            ",
         );
     }
 
     #[test]
     fn dont_indent_freestanding_dot() {
-        type_char_noop(
-            '.',
+        type_dot(
             r"
             pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
                 <|>
             }
             ",
+            r"
+            pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
+                .
+            }
+            ",
         );
-        type_char_noop(
-            '.',
+        type_dot(
             r"
             pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
             <|>
             }
             ",
+            r"
+            pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
+            .
+            }
+            ",
         );
     }
 
     #[test]
-    fn adds_space_after_return_type() {
-        type_char('>', "fn foo() -<|>{ 92 }", "fn foo() -><|> { 92 }")
+    fn test_on_enter() {
+        fn apply_on_enter(before: &str) -> Option<String> {
+            let (offset, before) = extract_offset(before);
+            let (analysis, file_id) = single_file(&before);
+            let result = analysis.on_enter(FilePosition { offset, file_id }).unwrap()?;
+
+            assert_eq!(result.source_file_edits.len(), 1);
+            let actual = result.source_file_edits[0].edit.apply(&before);
+            let actual = add_cursor(&actual, result.cursor_position.unwrap().offset);
+            Some(actual)
+        }
+
+        fn do_check(before: &str, after: &str) {
+            let actual = apply_on_enter(before).unwrap();
+            assert_eq_text!(after, &actual);
+        }
+
+        fn do_check_noop(text: &str) {
+            assert!(apply_on_enter(text).is_none())
+        }
+
+        do_check(
+            r"
+/// Some docs<|>
+fn foo() {
+}
+",
+            r"
+/// Some docs
+/// <|>
+fn foo() {
+}
+",
+        );
+        do_check(
+            r"
+impl S {
+    /// Some<|> docs.
+    fn foo() {}
+}
+",
+            r"
+impl S {
+    /// Some
+    /// <|> docs.
+    fn foo() {}
+}
+",
+        );
+        do_check_noop(r"<|>//! docz");
     }
 }
diff --git a/crates/ra_lsp_server/src/caps.rs b/crates/ra_lsp_server/src/caps.rs
index eea0965edb..30bcbd7a82 100644
--- a/crates/ra_lsp_server/src/caps.rs
+++ b/crates/ra_lsp_server/src/caps.rs
@@ -38,7 +38,7 @@ pub fn server_capabilities() -> ServerCapabilities {
         document_range_formatting_provider: None,
         document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions {
             first_trigger_character: "=".to_string(),
-            more_trigger_character: Some(vec![".".to_string(), ">".to_string()]),
+            more_trigger_character: Some(vec![".".to_string()]),
         }),
         selection_range_provider: Some(GenericCapability::default()),
         folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
diff --git a/crates/ra_lsp_server/src/main_loop/handlers.rs b/crates/ra_lsp_server/src/main_loop/handlers.rs
index 16fb072660..a29971d107 100644
--- a/crates/ra_lsp_server/src/main_loop/handlers.rs
+++ b/crates/ra_lsp_server/src/main_loop/handlers.rs
@@ -132,7 +132,6 @@ pub fn handle_on_enter(
     }
 }
 
-// Don't forget to add new trigger characters to `ServerCapabilities` in `caps.rs`.
 pub fn handle_on_type_formatting(
     world: WorldSnapshot,
     params: req::DocumentOnTypeFormattingParams,
@@ -145,17 +144,12 @@ pub fn handle_on_type_formatting(
     // in `ra_ide_api`, the `on_type` invariant is that
     // `text.char_at(position) == typed_char`.
     position.offset = position.offset - TextUnit::of_char('.');
-    let char_typed = params.ch.chars().next().unwrap_or('\0');
 
-    // We have an assist that inserts ` ` after typing `->` in `fn foo() ->{`,
-    // but it requires precise cursor positioning to work, and one can't
-    // position the cursor with on_type formatting. So, let's just toggle this
-    // feature off here, hoping that we'll enable it one day, 😿.
-    if char_typed == '>' {
-        return Ok(None);
-    }
-
-    let edit = world.analysis().on_char_typed(position, char_typed)?;
+    let edit = match params.ch.as_str() {
+        "=" => world.analysis().on_eq_typed(position),
+        "." => world.analysis().on_dot_typed(position),
+        _ => return Ok(None),
+    }?;
     let mut edit = match edit {
         Some(it) => it,
         None => return Ok(None),
diff --git a/crates/ra_text_edit/src/text_edit.rs b/crates/ra_text_edit/src/text_edit.rs
index 413c7d782e..0381ea0008 100644
--- a/crates/ra_text_edit/src/text_edit.rs
+++ b/crates/ra_text_edit/src/text_edit.rs
@@ -32,24 +32,6 @@ impl TextEditBuilder {
 }
 
 impl TextEdit {
-    pub fn insert(offset: TextUnit, text: String) -> TextEdit {
-        let mut builder = TextEditBuilder::default();
-        builder.insert(offset, text);
-        builder.finish()
-    }
-
-    pub fn delete(range: TextRange) -> TextEdit {
-        let mut builder = TextEditBuilder::default();
-        builder.delete(range);
-        builder.finish()
-    }
-
-    pub fn replace(range: TextRange, replace_with: String) -> TextEdit {
-        let mut builder = TextEditBuilder::default();
-        builder.replace(range, replace_with);
-        builder.finish()
-    }
-
     pub(crate) fn from_atoms(mut atoms: Vec<AtomTextEdit>) -> TextEdit {
         atoms.sort_by_key(|a| (a.delete.start(), a.delete.end()));
         for (a1, a2) in atoms.iter().zip(atoms.iter().skip(1)) {
diff --git a/docs/user/assists.md b/docs/user/assists.md
new file mode 100644
index 0000000000..cb4b0b9fb8
--- /dev/null
+++ b/docs/user/assists.md
@@ -0,0 +1,24 @@
+# Assists
+
+## `convert_to_guarded_return`
+
+Replace a large conditional with a guarded return.
+
+```rust
+// BEFORE
+fn main() {
+    <|>if cond {
+        foo();
+        bar();
+    }
+}
+
+// AFTER
+fn main() {
+    if !cond {
+        return;
+    }
+    foo();
+    bar();
+}
+```
diff --git a/docs/user/features.md b/docs/user/features.md
index 8b7a8d7fc1..a94b65ad4d 100644
--- a/docs/user/features.md
+++ b/docs/user/features.md
@@ -97,11 +97,13 @@ Start `cargo watch` for live error highlighting. Will prompt to install if it's
 
 Stop `cargo watch`
 
-### Code Actions (Assists)
+### Assists (Code Actions)
 
 These are triggered in a particular context via light bulb. We use custom code on
 the VS Code side to be able to position cursor. `<|>` signifies cursor
 
+See [assists.md](./assists.md)
+
 - Add `#[derive]`
 
 ```rust
diff --git a/xtask/src/codegen.rs b/xtask/src/codegen.rs
index bf3a901195..44729cd57a 100644
--- a/xtask/src/codegen.rs
+++ b/xtask/src/codegen.rs
@@ -7,12 +7,22 @@
 
 mod gen_syntax;
 mod gen_parser_tests;
+mod gen_assists_docs;
 
-use std::{fs, mem, path::Path};
+use std::{
+    fs,
+    io::Write,
+    mem,
+    path::Path,
+    process::{Command, Stdio},
+};
 
-use crate::Result;
+use crate::{project_root, Result};
 
-pub use self::{gen_parser_tests::generate_parser_tests, gen_syntax::generate_syntax};
+pub use self::{
+    gen_assists_docs::generate_assists_docs, gen_parser_tests::generate_parser_tests,
+    gen_syntax::generate_syntax,
+};
 
 pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
 const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar";
@@ -22,6 +32,10 @@ const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/err
 pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs";
 pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs";
 
+const ASSISTS_DIR: &str = "crates/ra_assists/src/assists";
+const ASSISTS_TESTS: &str = "crates/ra_assists/src/doc_tests/generated.rs";
+const ASSISTS_DOCS: &str = "docs/user/assists.md";
+
 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
 pub enum Mode {
     Overwrite,
@@ -30,7 +44,7 @@ pub enum Mode {
 
 /// A helper to update file on disk if it has changed.
 /// With verify = false,
-pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
+fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
     match fs::read_to_string(path) {
         Ok(ref old_contents) if old_contents == contents => {
             return Ok(());
@@ -45,6 +59,20 @@ pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
     Ok(())
 }
 
+fn reformat(text: impl std::fmt::Display) -> Result<String> {
+    let mut rustfmt = Command::new("rustfmt")
+        .arg("--config-path")
+        .arg(project_root().join("rustfmt.toml"))
+        .stdin(Stdio::piped())
+        .stdout(Stdio::piped())
+        .spawn()?;
+    write!(rustfmt.stdin.take().unwrap(), "{}", text)?;
+    let output = rustfmt.wait_with_output()?;
+    let stdout = String::from_utf8(output.stdout)?;
+    let preamble = "Generated file, do not edit by hand, see `crate/ra_tools/src/codegen`";
+    Ok(format!("//! {}\n\n{}", preamble, stdout))
+}
+
 fn extract_comment_blocks(text: &str) -> Vec<Vec<String>> {
     let mut res = Vec::new();
 
diff --git a/xtask/src/codegen/gen_assists_docs.rs b/xtask/src/codegen/gen_assists_docs.rs
new file mode 100644
index 0000000000..654ae09d66
--- /dev/null
+++ b/xtask/src/codegen/gen_assists_docs.rs
@@ -0,0 +1,123 @@
+use std::{fs, path::Path};
+
+use crate::{
+    codegen::{self, extract_comment_blocks, Mode},
+    project_root, Result,
+};
+
+pub fn generate_assists_docs(mode: Mode) -> Result<()> {
+    let assists = collect_assists()?;
+    generate_tests(&assists, mode)?;
+    generate_docs(&assists, mode)?;
+    Ok(())
+}
+
+#[derive(Debug)]
+struct Assist {
+    id: String,
+    doc: String,
+    before: String,
+    after: String,
+}
+
+fn collect_assists() -> Result<Vec<Assist>> {
+    let mut res = Vec::new();
+    for entry in fs::read_dir(project_root().join(codegen::ASSISTS_DIR))? {
+        let entry = entry?;
+        let path = entry.path();
+        if path.is_file() {
+            collect_file(&mut res, path.as_path())?;
+        }
+    }
+    res.sort_by(|lhs, rhs| lhs.id.cmp(&rhs.id));
+    return Ok(res);
+
+    fn collect_file(acc: &mut Vec<Assist>, path: &Path) -> Result<()> {
+        let text = fs::read_to_string(path)?;
+        let comment_blocks = extract_comment_blocks(&text);
+
+        for block in comment_blocks {
+            // FIXME: doesn't support blank lines yet, need to tweak
+            // `extract_comment_blocks` for that.
+            let mut lines = block.iter();
+            let first_line = lines.next().unwrap();
+            if !first_line.starts_with("Assist: ") {
+                continue;
+            }
+            let id = first_line["Assist: ".len()..].to_string();
+            assert!(id.chars().all(|it| it.is_ascii_lowercase() || it == '_'));
+
+            let doc = take_until(lines.by_ref(), "```");
+            let before = take_until(lines.by_ref(), "```");
+
+            assert_eq!(lines.next().unwrap().as_str(), "->");
+            assert_eq!(lines.next().unwrap().as_str(), "```");
+            let after = take_until(lines.by_ref(), "```");
+            acc.push(Assist { id, doc, before, after })
+        }
+
+        fn take_until<'a>(lines: impl Iterator<Item = &'a String>, marker: &str) -> String {
+            let mut buf = Vec::new();
+            for line in lines {
+                if line == marker {
+                    break;
+                }
+                buf.push(line.clone());
+            }
+            buf.join("\n")
+        }
+        Ok(())
+    }
+}
+
+fn generate_tests(assists: &[Assist], mode: Mode) -> Result<()> {
+    let mut buf = String::from("use super::check;\n");
+
+    for assist in assists.iter() {
+        let test = format!(
+            r######"
+#[test]
+fn doctest_{}() {{
+    check(
+        "{}",
+r#####"
+{}
+"#####, r#####"
+{}
+"#####)
+}}
+"######,
+            assist.id, assist.id, assist.before, assist.after
+        );
+
+        buf.push_str(&test)
+    }
+    let buf = codegen::reformat(buf)?;
+    codegen::update(&project_root().join(codegen::ASSISTS_TESTS), &buf, mode)
+}
+
+fn generate_docs(assists: &[Assist], mode: Mode) -> Result<()> {
+    let mut buf = String::from("# Assists\n");
+
+    for assist in assists {
+        let docs = format!(
+            "
+## `{}`
+
+{}
+
+```rust
+// BEFORE
+{}
+
+// AFTER
+{}
+```
+",
+            assist.id, assist.doc, assist.before, assist.after
+        );
+        buf.push_str(&docs);
+    }
+
+    codegen::update(&project_root().join(codegen::ASSISTS_DOCS), &buf, mode)
+}
diff --git a/xtask/src/codegen/gen_syntax.rs b/xtask/src/codegen/gen_syntax.rs
index 6a81c0e4df..88f2ac0e35 100644
--- a/xtask/src/codegen/gen_syntax.rs
+++ b/xtask/src/codegen/gen_syntax.rs
@@ -3,12 +3,7 @@
 //! Specifically, it generates the `SyntaxKind` enum and a number of newtype
 //! wrappers around `SyntaxNode` which implement `ra_syntax::AstNode`.
 
-use std::{
-    collections::BTreeMap,
-    fs,
-    io::Write,
-    process::{Command, Stdio},
-};
+use std::{collections::BTreeMap, fs};
 
 use proc_macro2::{Punct, Spacing};
 use quote::{format_ident, quote};
@@ -163,7 +158,7 @@ fn generate_ast(grammar: &Grammar) -> Result<String> {
         #(#nodes)*
     };
 
-    let pretty = reformat(ast)?;
+    let pretty = codegen::reformat(ast)?;
     Ok(pretty)
 }
 
@@ -276,21 +271,7 @@ fn generate_syntax_kinds(grammar: &Grammar) -> Result<String> {
         }
     };
 
-    reformat(ast)
-}
-
-fn reformat(text: impl std::fmt::Display) -> Result<String> {
-    let mut rustfmt = Command::new("rustfmt")
-        .arg("--config-path")
-        .arg(project_root().join("rustfmt.toml"))
-        .stdin(Stdio::piped())
-        .stdout(Stdio::piped())
-        .spawn()?;
-    write!(rustfmt.stdin.take().unwrap(), "{}", text)?;
-    let output = rustfmt.wait_with_output()?;
-    let stdout = String::from_utf8(output.stdout)?;
-    let preamble = "Generated file, do not edit by hand, see `crate/ra_tools/src/codegen`";
-    Ok(format!("//! {}\n\n{}", preamble, stdout))
+    codegen::reformat(ast)
 }
 
 #[derive(Deserialize, Debug)]
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index db901ced26..06aa3c8eca 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -64,6 +64,7 @@ fn main() -> Result<()> {
             }
             codegen::generate_syntax(Mode::Overwrite)?;
             codegen::generate_parser_tests(Mode::Overwrite)?;
+            codegen::generate_assists_docs(Mode::Overwrite)?;
         }
         "format" => {
             if matches.contains(["-h", "--help"]) {


Test patch:
diff --git a/crates/ra_assists/src/doc_tests.rs b/crates/ra_assists/src/doc_tests.rs
new file mode 100644
index 0000000000..88e901517c
--- /dev/null
+++ b/crates/ra_assists/src/doc_tests.rs
@@ -0,0 +1,23 @@
+//! Each assist definition has a special comment, which specifies docs and
+//! example.
+//!
+//! We collect all the example and write the as tests in this module.
+
+mod generated;
+
+use hir::mock::MockDatabase;
+use ra_db::FileRange;
+use ra_syntax::TextRange;
+use test_utils::{assert_eq_text, extract_offset};
+
+fn check(assist_id: &str, before: &str, after: &str) {
+    let (before_cursor_pos, before) = extract_offset(before);
+    let (db, _source_root, file_id) = MockDatabase::with_single_file(&before);
+    let frange = FileRange { file_id, range: TextRange::offset_len(before_cursor_pos, 0.into()) };
+
+    let (_assist_id, action) =
+        crate::assists(&db, frange).into_iter().find(|(id, _)| id.id.0 == assist_id).unwrap();
+
+    let actual = action.edit.apply(&before);
+    assert_eq_text!(after, &actual);
+}
diff --git a/crates/ra_assists/src/doc_tests/generated.rs b/crates/ra_assists/src/doc_tests/generated.rs
new file mode 100644
index 0000000000..e5f6910f11
--- /dev/null
+++ b/crates/ra_assists/src/doc_tests/generated.rs
@@ -0,0 +1,27 @@
+//! Generated file, do not edit by hand, see `crate/ra_tools/src/codegen`
+
+use super::check;
+
+#[test]
+fn doctest_convert_to_guarded_return() {
+    check(
+        "convert_to_guarded_return",
+        r#####"
+fn main() {
+    <|>if cond {
+        foo();
+        bar();
+    }
+}
+"#####,
+        r#####"
+fn main() {
+    if !cond {
+        return;
+    }
+    foo();
+    bar();
+}
+"#####,
+    )
+}
diff --git a/xtask/tests/tidy-tests/cli.rs b/xtask/tests/tidy-tests/cli.rs
index 543c7d7c45..573ffadbf8 100644
--- a/xtask/tests/tidy-tests/cli.rs
+++ b/xtask/tests/tidy-tests/cli.rs
@@ -18,6 +18,13 @@ fn generated_tests_are_fresh() {
     }
 }
 
+#[test]
+fn generated_assists_are_fresh() {
+    if let Err(error) = codegen::generate_assists_docs(Mode::Verify) {
+        panic!("{}. Please update assists by running `cargo xtask codegen`", error);
+    }
+}
+
 #[test]
 fn check_code_formatting() {
     if let Err(error) = run_rustfmt(Mode::Verify) {
diff --git a/xtask/tests/tidy-tests/docs.rs b/xtask/tests/tidy-tests/docs.rs
index fe5852bc62..b766aeff16 100644
--- a/xtask/tests/tidy-tests/docs.rs
+++ b/xtask/tests/tidy-tests/docs.rs
@@ -8,7 +8,9 @@ use walkdir::{DirEntry, WalkDir};
 use xtask::project_root;
 
 fn is_exclude_dir(p: &Path) -> bool {
-    let exclude_dirs = ["tests", "test_data"];
+    // Test hopefully don't really need comments, and for assists we already
+    // have special comments which are source of doc tests and user docs.
+    let exclude_dirs = ["tests", "test_data", "assists"];
     let mut cur_path = p;
     while let Some(path) = cur_path.parent() {
         if exclude_dirs.iter().any(|dir| path.ends_with(dir)) {