From bdb734b63ad83b0e96520daa7ce70137b442ecd0 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 5 Sep 2024 13:19:02 +0200 Subject: [PATCH] Support more IDE features for asm operands --- .../rust-analyzer/crates/hir-def/src/body.rs | 13 ++++- .../crates/hir-def/src/body/lower/asm.rs | 14 ++++-- .../crates/hir/src/has_source.rs | 27 ++++++++++- src/tools/rust-analyzer/crates/hir/src/lib.rs | 16 +++++++ .../rust-analyzer/crates/hir/src/semantics.rs | 2 +- .../crates/hir/src/source_analyzer.rs | 6 +-- .../rust-analyzer/crates/ide-db/src/defs.rs | 7 +-- .../rust-analyzer/crates/ide-db/src/rename.rs | 3 +- .../rust-analyzer/crates/ide-db/src/search.rs | 18 ++++++- .../crates/ide/src/navigation_target.rs | 30 ++++++++++-- .../rust-analyzer/crates/ide/src/rename.rs | 48 +++++++++++++++++++ .../test_data/highlight_asm.html | 32 ++++++------- .../test_data/highlight_strings.html | 4 +- 13 files changed, 180 insertions(+), 40 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body.rs b/src/tools/rust-analyzer/crates/hir-def/src/body.rs index 03507189fb9..af972c92469 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body.rs @@ -105,7 +105,7 @@ pub struct BodySourceMap { // format_args! FxHashMap>, // asm! - FxHashMap>, + FxHashMap)>>, )>, >, @@ -439,7 +439,7 @@ pub fn implicit_format_args( pub fn asm_template_args( &self, node: InFile<&ast::AsmExpr>, - ) -> Option<(ExprId, &[(syntax::TextRange, usize)])> { + ) -> Option<(ExprId, &[(syntax::TextRange, usize, Option)])> { let src = node.map(AstPtr::new).map(AstPtr::upcast::); let expr = self.expr_map.get(&src)?; Some(*expr).zip(self.template_map.as_ref()?.1.get(expr).map(std::ops::Deref::deref)) @@ -482,4 +482,13 @@ fn shrink_to_fit(&mut self) { diagnostics.shrink_to_fit(); binding_definitions.shrink_to_fit(); } + + pub fn template_map( + &self, + ) -> Option<&( + FxHashMap, Vec<(tt::TextRange, Name)>>, + FxHashMap, Vec<(tt::TextRange, usize, Option)>>, + )> { + self.template_map.as_deref() + } } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/body/lower/asm.rs b/src/tools/rust-analyzer/crates/hir-def/src/body/lower/asm.rs index 59b348b77db..8d2c0b3926f 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/body/lower/asm.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/body/lower/asm.rs @@ -1,3 +1,4 @@ +use hir_expand::name::Name; use intern::Symbol; use rustc_hash::{FxHashMap, FxHashSet}; use syntax::{ @@ -202,27 +203,30 @@ pub(super) fn lower_inline_asm( rustc_parse_format::Piece::NextArgument(arg) => { // let span = arg_spans.next(); - let operand_idx = match arg.position { + let (operand_idx, name) = match arg.position { rustc_parse_format::ArgumentIs(idx) | rustc_parse_format::ArgumentImplicitlyIs(idx) => { if idx >= operands.len() || named_pos.contains_key(&idx) || reg_args.contains(&idx) { - None + (None, None) } else { - Some(idx) + (Some(idx), None) } } rustc_parse_format::ArgumentNamed(name) => { let name = Symbol::intern(name); - named_args.get(&name).copied() + ( + named_args.get(&name).copied(), + Some(Name::new_symbol_root(name)), + ) } }; if let Some(operand_idx) = operand_idx { if let Some(position_span) = to_span(arg.position_span) { - mappings.push((position_span, operand_idx)); + mappings.push((position_span, operand_idx, name)); } } } diff --git a/src/tools/rust-analyzer/crates/hir/src/has_source.rs b/src/tools/rust-analyzer/crates/hir/src/has_source.rs index 7d52a28b91e..82c90ac3010 100644 --- a/src/tools/rust-analyzer/crates/hir/src/has_source.rs +++ b/src/tools/rust-analyzer/crates/hir/src/has_source.rs @@ -14,8 +14,8 @@ use crate::{ db::HirDatabase, Adt, Callee, Const, Enum, ExternCrateDecl, Field, FieldSource, Function, Impl, - Label, LifetimeParam, LocalSource, Macro, Module, Param, SelfParam, Static, Struct, Trait, - TraitAlias, TypeAlias, TypeOrConstParam, Union, Variant, + InlineAsmOperand, Label, LifetimeParam, LocalSource, Macro, Module, Param, SelfParam, Static, + Struct, Trait, TraitAlias, TypeAlias, TypeOrConstParam, Union, Variant, }; pub trait HasSource { @@ -292,3 +292,26 @@ fn source(self, db: &dyn HirDatabase) -> Option> { Some(self.id.lookup(db.upcast()).source(db.upcast())) } } + +impl HasSource for InlineAsmOperand { + type Ast = ast::AsmOperandNamed; + fn source(self, db: &dyn HirDatabase) -> Option> { + let (_body, source_map) = db.body_with_source_map(self.owner); + if let Ok(src) = source_map.expr_syntax(self.expr) { + let root = src.file_syntax(db.upcast()); + return src + .map(|ast| match ast.to_node(&root) { + ast::Expr::AsmExpr(asm) => asm + .asm_pieces() + .filter_map(|it| match it { + ast::AsmPiece::AsmOperandNamed(it) => Some(it), + _ => None, + }) + .nth(self.index), + _ => None, + }) + .transpose(); + } + None + } +} diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index c8b227123f1..75969bd8994 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -5253,6 +5253,22 @@ pub struct InlineAsmOperand { index: usize, } +impl InlineAsmOperand { + pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody { + self.owner.into() + } + + pub fn name(&self, db: &dyn HirDatabase) -> Option { + db.body_with_source_map(self.owner) + .1 + .template_map()? + .1 + .get(&self.expr)? + .get(self.index) + .and_then(|(_, _, name)| name.clone()) + } +} + // FIXME: Document this #[derive(Debug)] pub struct Callable { diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs index 0ba0e446578..543f2fc089f 100644 --- a/src/tools/rust-analyzer/crates/hir/src/semantics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs @@ -576,7 +576,7 @@ pub fn as_format_args_parts( let (owner, (expr, asm_parts)) = source_analyzer.as_asm_parts(asm.as_ref())?; let res = asm_parts .iter() - .map(|&(range, index)| { + .map(|&(range, index, _)| { ( range + quote.end(), Some(Either::Right(InlineAsmOperand { owner, expr, index })), diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index f6f1da1b7d6..4baf9079a05 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -913,8 +913,8 @@ pub(crate) fn resolve_offset_in_asm_template( let (expr, args) = body_source_map.asm_template_args(asm)?; Some(*def).zip( args.iter() - .find(|(range, _)| range.contains_inclusive(offset)) - .map(|(range, idx)| (expr, *range, *idx)), + .find(|(range, _, _)| range.contains_inclusive(offset)) + .map(|(range, idx, _)| (expr, *range, *idx)), ) } @@ -944,7 +944,7 @@ pub(crate) fn as_format_args_parts<'a>( pub(crate) fn as_asm_parts( &self, asm: InFile<&ast::AsmExpr>, - ) -> Option<(DefWithBodyId, (ExprId, &[(TextRange, usize)]))> { + ) -> Option<(DefWithBodyId, (ExprId, &[(TextRange, usize, Option)]))> { let (def, _, body_source_map) = self.def.as_ref()?; Some(*def).zip(body_source_map.asm_template_args(asm)) } diff --git a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs index c134c9f6725..099f26eba78 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/defs.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/defs.rs @@ -85,13 +85,13 @@ pub fn module(&self, db: &RootDatabase) -> Option { Definition::Label(it) => it.module(db), Definition::ExternCrateDecl(it) => it.module(db), Definition::DeriveHelper(it) => it.derive().module(db), + Definition::InlineAsmOperand(it) => it.parent(db).module(db), Definition::BuiltinAttr(_) | Definition::BuiltinType(_) | Definition::BuiltinLifetime(_) | Definition::TupleField(_) | Definition::ToolModule(_) - | Definition::InlineAsmRegOrRegClass(_) - | Definition::InlineAsmOperand(_) => return None, + | Definition::InlineAsmRegOrRegClass(_) => return None, }; Some(module) } @@ -156,7 +156,8 @@ pub fn name(&self, db: &RootDatabase) -> Option { Definition::ToolModule(_) => return None, // FIXME Definition::DeriveHelper(it) => it.name(db), Definition::ExternCrateDecl(it) => return it.alias_or_name(db), - Definition::InlineAsmRegOrRegClass(_) | Definition::InlineAsmOperand(_) => return None, // FIXME + Definition::InlineAsmRegOrRegClass(_) => return None, + Definition::InlineAsmOperand(op) => return op.name(db), }; Some(name) } diff --git a/src/tools/rust-analyzer/crates/ide-db/src/rename.rs b/src/tools/rust-analyzer/crates/ide-db/src/rename.rs index 0435b2f0c6f..f1404ed9f22 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/rename.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/rename.rs @@ -200,6 +200,7 @@ pub fn range_for_rename(self, sema: &Semantics<'_, RootDatabase>) -> Option name_range(it, sema).and_then(syn_ctx_is_root), Definition::BuiltinType(_) | Definition::BuiltinLifetime(_) | Definition::BuiltinAttr(_) @@ -207,8 +208,6 @@ pub fn range_for_rename(self, sema: &Semantics<'_, RootDatabase>) -> Option return None, - // FIXME: - Definition::InlineAsmOperand(_) => return None, // FIXME: This should be doable in theory Definition::DeriveHelper(_) => return None, }; diff --git a/src/tools/rust-analyzer/crates/ide-db/src/search.rs b/src/tools/rust-analyzer/crates/ide-db/src/search.rs index 4d0668ffea8..ad30c624c41 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/search.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/search.rs @@ -319,6 +319,23 @@ fn search_scope(&self, db: &RootDatabase) -> SearchScope { }; } + if let Definition::InlineAsmOperand(op) = self { + let def = match op.parent(db) { + DefWithBody::Function(f) => f.source(db).map(|src| src.syntax().cloned()), + DefWithBody::Const(c) => c.source(db).map(|src| src.syntax().cloned()), + DefWithBody::Static(s) => s.source(db).map(|src| src.syntax().cloned()), + DefWithBody::Variant(v) => v.source(db).map(|src| src.syntax().cloned()), + // FIXME: implement + DefWithBody::InTypeConst(_) => return SearchScope::empty(), + }; + return match def { + Some(def) => SearchScope::file_range( + def.as_ref().original_file_range_with_macro_call_body(db), + ), + None => SearchScope::single_file(file_id), + }; + } + if let Definition::SelfType(impl_) = self { return match impl_.source(db).map(|src| src.syntax().cloned()) { Some(def) => SearchScope::file_range( @@ -909,7 +926,6 @@ pub fn search(&self, sink: &mut dyn FnMut(EditionedFileId, FileReference) -> boo let finder = &Finder::new(name); let include_self_kw_refs = self.include_self_kw_refs.as_ref().map(|ty| (ty, Finder::new("Self"))); - for (text, file_id, search_range) in Self::scope_files(sema.db, &search_scope) { self.sema.db.unwind_if_cancelled(); let tree = LazyCell::new(move || sema.parse(file_id).syntax().clone()); diff --git a/src/tools/rust-analyzer/crates/ide/src/navigation_target.rs b/src/tools/rust-analyzer/crates/ide/src/navigation_target.rs index 68039ef309d..9bc7bf411f0 100644 --- a/src/tools/rust-analyzer/crates/ide/src/navigation_target.rs +++ b/src/tools/rust-analyzer/crates/ide/src/navigation_target.rs @@ -237,15 +237,14 @@ fn try_to_nav(&self, db: &RootDatabase) -> Option it.try_to_nav(db), Definition::TraitAlias(it) => it.try_to_nav(db), Definition::TypeAlias(it) => it.try_to_nav(db), - Definition::ExternCrateDecl(it) => Some(it.try_to_nav(db)?), + Definition::ExternCrateDecl(it) => it.try_to_nav(db), + Definition::InlineAsmOperand(it) => it.try_to_nav(db), Definition::BuiltinLifetime(_) | Definition::BuiltinType(_) | Definition::TupleField(_) | Definition::ToolModule(_) | Definition::InlineAsmRegOrRegClass(_) | Definition::BuiltinAttr(_) => None, - // FIXME - Definition::InlineAsmOperand(_) => None, // FIXME: The focus range should be set to the helper declaration Definition::DeriveHelper(it) => it.derive().try_to_nav(db), } @@ -696,6 +695,31 @@ fn try_to_nav(&self, db: &RootDatabase) -> Option Option> { + let InFile { file_id, value } = &self.source(db)?; + let file_id = *file_id; + Some(orig_range_with_focus(db, file_id, value.syntax(), value.name()).map( + |(FileRange { file_id, range: full_range }, focus_range)| { + let edition = self.parent(db).module(db).krate().edition(db); + NavigationTarget { + file_id, + name: self + .name(db) + .map_or_else(|| "_".into(), |it| it.display(db, edition).to_smolstr()), + alias: None, + kind: Some(SymbolKind::Local), + full_range, + focus_range, + container_name: None, + description: None, + docs: None, + } + }, + )) + } +} + #[derive(Debug)] pub struct UpmappingResult { /// The macro call site. diff --git a/src/tools/rust-analyzer/crates/ide/src/rename.rs b/src/tools/rust-analyzer/crates/ide/src/rename.rs index 42b7472c645..9b9344e98cd 100644 --- a/src/tools/rust-analyzer/crates/ide/src/rename.rs +++ b/src/tools/rust-analyzer/crates/ide/src/rename.rs @@ -2975,6 +2975,54 @@ fn test() { ); } + #[test] + fn asm_operand() { + check( + "bose", + r#" +//- minicore: asm +fn test() { + core::arch::asm!( + "push {base}", + base$0 = const 0 + ); +} +"#, + r#" +fn test() { + core::arch::asm!( + "push {bose}", + bose = const 0 + ); +} +"#, + ); + } + + #[test] + fn asm_operand2() { + check( + "bose", + r#" +//- minicore: asm +fn test() { + core::arch::asm!( + "push {base$0}", + base = const 0 + ); +} +"#, + r#" +fn test() { + core::arch::asm!( + "push {bose}", + bose = const 0 + ); +} +"#, + ); + } + #[test] fn rename_path_inside_use_tree() { check( diff --git a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_asm.html b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_asm.html index d322a374b34..d830a388721 100644 --- a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_asm.html +++ b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_asm.html @@ -50,17 +50,17 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd let foo = 1; let mut o = 0; core::arch::asm!( - "%input = OpLoad _ {0}", + "%input = OpLoad _ {0}", concat!("%result = ", "bar", " _ %input"), - "OpStore {1} %result", + "OpStore {1} %result", in(reg) &foo, in(reg) &mut o, ); let thread_id: usize; core::arch::asm!(" - mov {0}, gs:[0x30] - mov {0}, [{0}+0x48] + mov {0}, gs:[0x30] + mov {0}, [{0}+0x48] ", out(reg) thread_id, options(pure, readonly, nostack)); static UNMAP_BASE: usize; @@ -69,28 +69,28 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd const OffPtr: usize; const OffFn: usize; core::arch::asm!(" - push {free_type} - push {free_size} - push {base} + push {free_type} + push {free_size} + push {base} mov eax, fs:[30h] mov eax, [eax+8h] - add eax, {off_fn} - mov [eax-{off_fn}+{off_ptr}], eax + add eax, {off_fn} + mov [eax-{off_fn}+{off_ptr}], eax push eax - jmp {virtual_free} + jmp {virtual_free} ", - off_ptr = const OffPtr, - off_fn = const OffFn, + off_ptr = const OffPtr, + off_fn = const OffFn, - free_size = const 0, - free_type = const MEM_RELEASE, + free_size = const 0, + free_type = const MEM_RELEASE, - virtual_free = sym VirtualFree, + virtual_free = sym VirtualFree, - base = sym UNMAP_BASE, + base = sym UNMAP_BASE, options(noreturn), ); } diff --git a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html index 37bbc1e1ee2..d5b9fc0e2c4 100644 --- a/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html +++ b/src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html @@ -166,8 +166,8 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd let i: u64 = 3; let o: u64; core::arch::asm!( - "mov {0}, {1}", - "add {0}, 5", + "mov {0}, {1}", + "add {0}, 5", out(reg) o, in(reg) i, );