Repository: rust-analyzer/rust-analyzer
Pull request #7068 (2020-12-28 18:36:06)

Add VSCode command to view the hir of a function body
Will fix https://github.com/rust-analyzer/rust-analyzer/issues/7061. Very rough initial version just to work out where I needed to wire everything up.

@matklad would you be happy merging a hir visualiser of some kind? If so, do you have any thoughts on what you'd like it show, and how?

I've spent very little time on this thus far, so I'm fine with throwing away the contents of this PR, but I want to avoid taking the time to make this more polished/interactive/useful only to discover that no-one else has any interest in this functionality.

![image](https://user-images.githubusercontent.com/1974256/103236081-bb58f700-493b-11eb-9d12-55ae1b870f8f.png)



Patch:
diff --git a/crates/hir/src/code_model.rs b/crates/hir/src/code_model.rs
index b7ded34788..804cdb143f 100644
--- a/crates/hir/src/code_model.rs
+++ b/crates/hir/src/code_model.rs
@@ -39,7 +39,7 @@ use hir_ty::{
     TyDefId, TyKind, TypeCtor,
 };
 use rustc_hash::FxHashSet;
-use stdx::impl_from;
+use stdx::{format_to, impl_from};
 use syntax::{
     ast::{self, AttrsOwner, NameOwner},
     AstNode, SmolStr,
@@ -797,6 +797,19 @@ impl Function {
     pub fn has_body(self, db: &dyn HirDatabase) -> bool {
         db.function_data(self.id).has_body
     }
+
+    /// A textual representation of the HIR of this function for debugging purposes.
+    pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
+        let body = db.body(self.id.into());
+
+        let mut result = String::new();
+        format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
+        for (id, expr) in body.exprs.iter() {
+            format_to!(result, "{:?}: {:?}\n", id, expr);
+        }
+
+        result
+    }
 }
 
 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs
index 41eb139d16..25c2047ca6 100644
--- a/crates/ide/src/lib.rs
+++ b/crates/ide/src/lib.rs
@@ -31,6 +31,7 @@ mod folding_ranges;
 mod goto_definition;
 mod goto_implementation;
 mod goto_type_definition;
+mod view_hir;
 mod hover;
 mod inlay_hints;
 mod join_lines;
@@ -271,6 +272,10 @@ impl Analysis {
         self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
     }
 
+    pub fn view_hir(&self, position: FilePosition) -> Cancelable<String> {
+        self.with_db(|db| view_hir::view_hir(&db, position))
+    }
+
     pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
         self.with_db(|db| expand_macro::expand_macro(db, position))
     }
diff --git a/crates/ide/src/view_hir.rs b/crates/ide/src/view_hir.rs
new file mode 100644
index 0000000000..cfcfb7cfbc
--- /dev/null
+++ b/crates/ide/src/view_hir.rs
@@ -0,0 +1,25 @@
+use hir::{Function, Semantics};
+use ide_db::base_db::FilePosition;
+use ide_db::RootDatabase;
+use syntax::{algo::find_node_at_offset, ast, AstNode};
+
+// Feature: View Hir
+//
+// |===
+// | Editor  | Action Name
+//
+// | VS Code | **Rust Analyzer: View Hir**
+// |===
+pub(crate) fn view_hir(db: &RootDatabase, position: FilePosition) -> String {
+    body_hir(db, position).unwrap_or("Not inside a function body".to_string())
+}
+
+fn body_hir(db: &RootDatabase, position: FilePosition) -> Option<String> {
+    let sema = Semantics::new(db);
+    let source_file = sema.parse(position.file_id);
+
+    let function = find_node_at_offset::<ast::Fn>(source_file.syntax(), position.offset)?;
+
+    let function: Function = sema.to_def(&function)?;
+    Some(function.debug_hir(db))
+}
diff --git a/crates/mbe/src/parser.rs b/crates/mbe/src/parser.rs
index d681905f57..c3fdd40404 100644
--- a/crates/mbe/src/parser.rs
+++ b/crates/mbe/src/parser.rs
@@ -101,15 +101,8 @@ fn next_op<'a>(
                     Op::Repeat { subtree, separator, kind }
                 }
                 tt::TokenTree::Leaf(leaf) => match leaf {
-                    tt::Leaf::Punct(punct) => {
-                        static UNDERSCORE: SmolStr = SmolStr::new_inline("_");
-
-                        if punct.char != '_' {
-                            return Err(ExpandError::UnexpectedToken);
-                        }
-                        let name = &UNDERSCORE;
-                        let kind = eat_fragment_kind(src, mode)?;
-                        Op::Var { name, kind }
+                    tt::Leaf::Punct(_) => {
+                        return Err(ExpandError::UnexpectedToken);
                     }
                     tt::Leaf::Ident(ident) => {
                         let name = &ident.text;
diff --git a/crates/mbe/src/syntax_bridge.rs b/crates/mbe/src/syntax_bridge.rs
index 265c0d63d8..2bec7fd495 100644
--- a/crates/mbe/src/syntax_bridge.rs
+++ b/crates/mbe/src/syntax_bridge.rs
@@ -313,7 +313,7 @@ trait TokenConvertor {
             return;
         }
 
-        result.push(if k.is_punct() {
+        result.push(if k.is_punct() && k != UNDERSCORE {
             assert_eq!(range.len(), TextSize::of('.'));
             let delim = match k {
                 T!['('] => Some((tt::DelimiterKind::Parenthesis, T![')'])),
@@ -378,6 +378,7 @@ trait TokenConvertor {
             let leaf: tt::Leaf = match k {
                 T![true] | T![false] => make_leaf!(Ident),
                 IDENT => make_leaf!(Ident),
+                UNDERSCORE => make_leaf!(Ident),
                 k if k.is_keyword() => make_leaf!(Ident),
                 k if k.is_literal() => make_leaf!(Literal),
                 LIFETIME_IDENT => {
diff --git a/crates/parser/src/grammar.rs b/crates/parser/src/grammar.rs
index 63cc900272..f08c8bab74 100644
--- a/crates/parser/src/grammar.rs
+++ b/crates/parser/src/grammar.rs
@@ -59,7 +59,7 @@ pub(crate) mod fragments {
     };
 
     pub(crate) fn expr(p: &mut Parser) {
-        let _ = expressions::expr_with_attrs(p);
+        let _ = expressions::expr(p);
     }
 
     pub(crate) fn stmt(p: &mut Parser) {
diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs
index 374fb5302b..85f1f81ad7 100644
--- a/crates/rust-analyzer/src/handlers.rs
+++ b/crates/rust-analyzer/src/handlers.rs
@@ -104,6 +104,16 @@ pub(crate) fn handle_syntax_tree(
     Ok(res)
 }
 
+pub(crate) fn handle_view_hir(
+    snap: GlobalStateSnapshot,
+    params: lsp_types::TextDocumentPositionParams,
+) -> Result<String> {
+    let _p = profile::span("handle_view_hir");
+    let position = from_proto::file_position(&snap, params)?;
+    let res = snap.analysis.view_hir(position)?;
+    Ok(res)
+}
+
 pub(crate) fn handle_expand_macro(
     snap: GlobalStateSnapshot,
     params: lsp_ext::ExpandMacroParams,
diff --git a/crates/rust-analyzer/src/lsp_ext.rs b/crates/rust-analyzer/src/lsp_ext.rs
index 93ac45415f..a85978737b 100644
--- a/crates/rust-analyzer/src/lsp_ext.rs
+++ b/crates/rust-analyzer/src/lsp_ext.rs
@@ -53,6 +53,14 @@ pub struct SyntaxTreeParams {
     pub range: Option<Range>,
 }
 
+pub enum ViewHir {}
+
+impl Request for ViewHir {
+    type Params = lsp_types::TextDocumentPositionParams;
+    type Result = String;
+    const METHOD: &'static str = "rust-analyzer/viewHir";
+}
+
 pub enum ExpandMacro {}
 
 impl Request for ExpandMacro {
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs
index 5d55dc96e2..8eca79f7ee 100644
--- a/crates/rust-analyzer/src/main_loop.rs
+++ b/crates/rust-analyzer/src/main_loop.rs
@@ -443,6 +443,7 @@ impl GlobalState {
             .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
             .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
             .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
+            .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
             .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
             .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
             .on::<lsp_ext::Runnables>(handlers::handle_runnables)
diff --git a/docs/dev/README.md b/docs/dev/README.md
index 4a2f9feb36..55527bab0a 100644
--- a/docs/dev/README.md
+++ b/docs/dev/README.md
@@ -227,6 +227,8 @@ There are also two VS Code commands which might be of interest:
 
 * `Rust Analyzer: Syntax Tree` shows syntax tree of the current file/selection.
 
+* `Rust Analyzer: View Hir` shows the HIR expressions within the function containing the cursor.
+
   You can hover over syntax nodes in the opened text file to see the appropriate
   rust code that it refers to and the rust editor will also highlight the proper
   text range.
diff --git a/docs/dev/lsp-extensions.md b/docs/dev/lsp-extensions.md
index 8c01db07c8..78d86f060a 100644
--- a/docs/dev/lsp-extensions.md
+++ b/docs/dev/lsp-extensions.md
@@ -1,5 +1,5 @@
 <!---
-lsp_ext.rs hash: 203fdf79b21b5987
+lsp_ext.rs hash: 91f2c62457e0a20f
 
 If you need to change the above hash to make the test pass, please check if you
 need to adjust this doc as well and ping this  issue:
@@ -449,6 +449,17 @@ interface SyntaxTeeParams {
 Returns textual representation of a parse tree for the file/selected region.
 Primarily for debugging, but very useful for all people working on rust-analyzer itself.
 
+## View Hir
+
+**Method:** `rust-analyzer/viewHir`
+
+**Request:** `TextDocumentPositionParams`
+
+**Response:** `string`
+
+Returns a textual representation of the HIR of the function containing the cursor.
+For debugging or when working on rust-analyzer itself.
+
 ## Expand Macro
 
 **Method:** `rust-analyzer/expandMacro`
diff --git a/docs/dev/style.md b/docs/dev/style.md
index 58b3093798..13c6a2a167 100644
--- a/docs/dev/style.md
+++ b/docs/dev/style.md
@@ -63,18 +63,6 @@ After you are happy with the state of the code, please use [interactive rebase](
 Avoid @mentioning people in commit messages and pull request descriptions(they are added to commit message by bors).
 Such messages create a lot of duplicate notification traffic during rebases.
 
-If possible, write commit messages from user's perspective:
-
-```
-# Good
-Goto definition works inside macros
-
-# Not as good
-Use original span for FileId
-```
-
-This makes it easier to prepare a changelog.
-
 ## Clippy
 
 We don't enforce Clippy.
diff --git a/editors/code/package.json b/editors/code/package.json
index 13749a0849..4bae5d647b 100644
--- a/editors/code/package.json
+++ b/editors/code/package.json
@@ -103,6 +103,11 @@
                 "title": "Show Syntax Tree",
                 "category": "Rust Analyzer"
             },
+            {
+                "command": "rust-analyzer.viewHir",
+                "title": "View Hir",
+                "category": "Rust Analyzer"
+            },
             {
                 "command": "rust-analyzer.expandMacro",
                 "title": "Expand macro recursively",
@@ -998,6 +1003,10 @@
                     "command": "rust-analyzer.syntaxTree",
                     "when": "inRustProject"
                 },
+                {
+                    "command": "rust-analyzer.viewHir",
+                    "when": "inRustProject"
+                },
                 {
                     "command": "rust-analyzer.expandMacro",
                     "when": "inRustProject"
diff --git a/editors/code/src/commands.ts b/editors/code/src/commands.ts
index 9d4823a34d..2911bccd5e 100644
--- a/editors/code/src/commands.ts
+++ b/editors/code/src/commands.ts
@@ -340,6 +340,61 @@ export function syntaxTree(ctx: Ctx): Cmd {
     };
 }
 
+// Opens the virtual file that will show the HIR of the function containing the cursor position
+//
+// The contents of the file come from the `TextDocumentContentProvider`
+export function viewHir(ctx: Ctx): Cmd {
+    const tdcp = new class implements vscode.TextDocumentContentProvider {
+        readonly uri = vscode.Uri.parse('rust-analyzer://viewHir/hir.txt');
+        readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>();
+        constructor() {
+            vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions);
+            vscode.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor, this, ctx.subscriptions);
+        }
+
+        private onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent) {
+            if (isRustDocument(event.document)) {
+                // We need to order this after language server updates, but there's no API for that.
+                // Hence, good old sleep().
+                void sleep(10).then(() => this.eventEmitter.fire(this.uri));
+            }
+        }
+        private onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined) {
+            if (editor && isRustEditor(editor)) {
+                this.eventEmitter.fire(this.uri);
+            }
+        }
+
+        provideTextDocumentContent(_uri: vscode.Uri, ct: vscode.CancellationToken): vscode.ProviderResult<string> {
+            const rustEditor = ctx.activeRustEditor;
+            const client = ctx.client;
+            if (!rustEditor || !client) return '';
+
+            const params = {
+                textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(rustEditor.document),
+                position: client.code2ProtocolConverter.asPosition(
+                    rustEditor.selection.active,
+                ),
+            };
+            return client.sendRequest(ra.viewHir, params, ct);
+        }
+
+        get onDidChange(): vscode.Event<vscode.Uri> {
+            return this.eventEmitter.event;
+        }
+    };
+
+    ctx.pushCleanup(vscode.workspace.registerTextDocumentContentProvider('rust-analyzer', tdcp));
+
+    return async () => {
+        const document = await vscode.workspace.openTextDocument(tdcp.uri);
+        tdcp.eventEmitter.fire(tdcp.uri);
+        void await vscode.window.showTextDocument(document, {
+            viewColumn: vscode.ViewColumn.Two,
+            preserveFocus: true
+        });
+    };
+}
 
 // Opens the virtual file that will show the syntax tree
 //
diff --git a/editors/code/src/lsp_ext.ts b/editors/code/src/lsp_ext.ts
index 5e877ce651..d21a3db862 100644
--- a/editors/code/src/lsp_ext.ts
+++ b/editors/code/src/lsp_ext.ts
@@ -24,6 +24,7 @@ export interface SyntaxTreeParams {
 }
 export const syntaxTree = new lc.RequestType<SyntaxTreeParams, string, void>("rust-analyzer/syntaxTree");
 
+export const viewHir = new lc.RequestType<lc.TextDocumentPositionParams, string, void>("rust-analyzer/viewHir");
 
 export interface ExpandMacroParams {
     textDocument: lc.TextDocumentIdentifier;
diff --git a/editors/code/src/main.ts b/editors/code/src/main.ts
index 282240d845..60907dfd40 100644
--- a/editors/code/src/main.ts
+++ b/editors/code/src/main.ts
@@ -105,6 +105,7 @@ async function tryActivate(context: vscode.ExtensionContext) {
     ctx.registerCommand('joinLines', commands.joinLines);
     ctx.registerCommand('parentModule', commands.parentModule);
     ctx.registerCommand('syntaxTree', commands.syntaxTree);
+    ctx.registerCommand('viewHir', commands.viewHir);
     ctx.registerCommand('expandMacro', commands.expandMacro);
     ctx.registerCommand('run', commands.run);
     ctx.registerCommand('debug', commands.debug);


Test patch:
diff --git a/crates/hir_def/src/nameres/tests/macros.rs b/crates/hir_def/src/nameres/tests/macros.rs
index e5e9e8ca16..f9bf5bc725 100644
--- a/crates/hir_def/src/nameres/tests/macros.rs
+++ b/crates/hir_def/src/nameres/tests/macros.rs
@@ -677,7 +677,7 @@ fn macro_expansion_overflow() {
         r#"
 macro_rules! a {
     ($e:expr; $($t:tt)*) => {
-        b!(static = (); $($t)*);
+        b!($($t)*);
     };
     () => {};
 }
@@ -689,7 +689,7 @@ macro_rules! b {
     () => {};
 }
 
-b! { static = #[] ();}
+b! { static = #[] (); }
 "#,
         expect![[r#"
             crate
diff --git a/crates/mbe/src/tests.rs b/crates/mbe/src/tests.rs
index 1d9afb4fb8..6cd0ed2053 100644
--- a/crates/mbe/src/tests.rs
+++ b/crates/mbe/src/tests.rs
@@ -760,18 +760,6 @@ fn test_last_expr() {
     );
 }
 
-#[test]
-fn test_expr_with_attr() {
-    parse_macro(
-        r#"
-macro_rules! m {
-    ($a:expr) => {0}
-}
-"#,
-    )
-    .assert_expand_items("m!(#[allow(a)]())", "0");
-}
-
 #[test]
 fn test_ty() {
     parse_macro(
@@ -1031,42 +1019,6 @@ fn test_underscore() {
     .assert_expand_items(r#"foo! { => }"#, r#"0"#);
 }
 
-#[test]
-fn test_underscore_not_greedily() {
-    parse_macro(
-        r#"
-macro_rules! q {
-    ($($a:ident)* _) => {0};
-}
-"#,
-    )
-    // `_` overlaps with `$a:ident` but rustc matches it under the `_` token
-    .assert_expand_items(r#"q![a b c d _]"#, r#"0"#);
-
-    parse_macro(
-        r#"
-macro_rules! q {
-    ($($a:expr => $b:ident)* _ => $c:expr) => {0};
-}
-"#,
-    )
-    // `_ => ou` overlaps with `$a:expr => $b:ident` but rustc matches it under `_ => $c:expr`
-    .assert_expand_items(r#"q![a => b c => d _ => ou]"#, r#"0"#);
-}
-
-#[test]
-fn test_underscore_as_type() {
-    parse_macro(
-        r#"
-macro_rules! q {
-    ($a:ty) => {0};
-}
-"#,
-    )
-    // Underscore is a type
-    .assert_expand_items(r#"q![_]"#, r#"0"#);
-}
-
 #[test]
 fn test_vertical_bar_with_pat() {
     parse_macro(