minor: improve readability

naming, layout & comments help!
This commit is contained in:
Aleksey Kladov 2021-08-31 15:44:43 +03:00
parent f1222e8085
commit 722a2a4690
4 changed files with 75 additions and 69 deletions

View File

@ -26,58 +26,10 @@
}; };
pub use version::{read_dylib_info, RustCInfo}; pub use version::{read_dylib_info, RustCInfo};
#[derive(Debug, Clone)] /// A handle to an external process which load dylibs with macros (.so or .dll)
pub struct ProcMacroProcessExpander { /// and runs actual macro expansion functions.
process: Arc<Mutex<ProcMacroProcessSrv>>,
dylib_path: AbsPathBuf,
name: SmolStr,
kind: ProcMacroKind,
}
impl Eq for ProcMacroProcessExpander {}
impl PartialEq for ProcMacroProcessExpander {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.kind == other.kind
&& self.dylib_path == other.dylib_path
&& Arc::ptr_eq(&self.process, &other.process)
}
}
impl ProcMacroProcessExpander {
pub fn name(&self) -> &str {
&self.name
}
pub fn kind(&self) -> ProcMacroKind {
self.kind
}
pub fn expand(
&self,
subtree: &Subtree,
attr: Option<&Subtree>,
env: Vec<(String, String)>,
) -> Result<Subtree, tt::ExpansionError> {
let task = ExpansionTask {
macro_body: FlatTree::new(subtree),
macro_name: self.name.to_string(),
attributes: attr.map(FlatTree::new),
lib: self.dylib_path.to_path_buf().into(),
env,
};
let result: ExpansionResult = self
.process
.lock()
.unwrap_or_else(|e| e.into_inner())
.send_task(msg::Request::ExpansionMacro(task))?;
Ok(result.expansion.to_subtree())
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct ProcMacroClient { pub struct ProcMacroServer {
/// Currently, the proc macro process expands all procedural macros sequentially. /// Currently, the proc macro process expands all procedural macros sequentially.
/// ///
/// That means that concurrent salsa requests may block each other when expanding proc macros, /// That means that concurrent salsa requests may block each other when expanding proc macros,
@ -87,17 +39,39 @@ pub struct ProcMacroClient {
process: Arc<Mutex<ProcMacroProcessSrv>>, process: Arc<Mutex<ProcMacroProcessSrv>>,
} }
impl ProcMacroClient { /// A handle to a specific macro (a `#[proc_macro]` annotated function).
///
/// It exists withing a context of a specific [`ProcMacroProcess`] -- currently
/// we share a single expander process for all macros.
#[derive(Debug, Clone)]
pub struct ProcMacro {
process: Arc<Mutex<ProcMacroProcessSrv>>,
dylib_path: AbsPathBuf,
name: SmolStr,
kind: ProcMacroKind,
}
impl Eq for ProcMacro {}
impl PartialEq for ProcMacro {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.kind == other.kind
&& self.dylib_path == other.dylib_path
&& Arc::ptr_eq(&self.process, &other.process)
}
}
impl ProcMacroServer {
/// Spawns an external process as the proc macro server and returns a client connected to it. /// Spawns an external process as the proc macro server and returns a client connected to it.
pub fn extern_process( pub fn spawn(
process_path: AbsPathBuf, process_path: AbsPathBuf,
args: impl IntoIterator<Item = impl AsRef<OsStr>>, args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> io::Result<ProcMacroClient> { ) -> io::Result<ProcMacroServer> {
let process = ProcMacroProcessSrv::run(process_path, args)?; let process = ProcMacroProcessSrv::run(process_path, args)?;
Ok(ProcMacroClient { process: Arc::new(Mutex::new(process)) }) Ok(ProcMacroServer { process: Arc::new(Mutex::new(process)) })
} }
pub fn by_dylib_path(&self, dylib_path: &AbsPath) -> Vec<ProcMacroProcessExpander> { pub fn load_dylib(&self, dylib_path: &AbsPath) -> Vec<ProcMacro> {
let _p = profile::span("ProcMacroClient::by_dylib_path"); let _p = profile::span("ProcMacroClient::by_dylib_path");
match version::read_dylib_info(dylib_path) { match version::read_dylib_info(dylib_path) {
Ok(info) => { Ok(info) => {
@ -129,7 +103,7 @@ pub fn by_dylib_path(&self, dylib_path: &AbsPath) -> Vec<ProcMacroProcessExpande
macros macros
.into_iter() .into_iter()
.map(|(name, kind)| ProcMacroProcessExpander { .map(|(name, kind)| ProcMacro {
process: self.process.clone(), process: self.process.clone(),
name: name.into(), name: name.into(),
kind, kind,
@ -138,3 +112,35 @@ pub fn by_dylib_path(&self, dylib_path: &AbsPath) -> Vec<ProcMacroProcessExpande
.collect() .collect()
} }
} }
impl ProcMacro {
pub fn name(&self) -> &str {
&self.name
}
pub fn kind(&self) -> ProcMacroKind {
self.kind
}
pub fn expand(
&self,
subtree: &Subtree,
attr: Option<&Subtree>,
env: Vec<(String, String)>,
) -> Result<Subtree, tt::ExpansionError> {
let task = ExpansionTask {
macro_body: FlatTree::new(subtree),
macro_name: self.name.to_string(),
attributes: attr.map(FlatTree::new),
lib: self.dylib_path.to_path_buf().into(),
env,
};
let result: ExpansionResult = self
.process
.lock()
.unwrap_or_else(|e| e.into_inner())
.send_task(msg::Request::ExpansionMacro(task))?;
Ok(result.expansion.to_subtree())
}
}

View File

@ -7,7 +7,7 @@
use hir::db::DefDatabase; use hir::db::DefDatabase;
use ide::{AnalysisHost, Change}; use ide::{AnalysisHost, Change};
use ide_db::base_db::CrateGraph; use ide_db::base_db::CrateGraph;
use proc_macro_api::ProcMacroClient; use proc_macro_api::ProcMacroServer;
use project_model::{CargoConfig, ProjectManifest, ProjectWorkspace}; use project_model::{CargoConfig, ProjectManifest, ProjectWorkspace};
use vfs::{loader::Handle, AbsPath, AbsPathBuf}; use vfs::{loader::Handle, AbsPath, AbsPathBuf};
@ -28,7 +28,7 @@ pub fn load_workspace_at(
cargo_config: &CargoConfig, cargo_config: &CargoConfig,
load_config: &LoadCargoConfig, load_config: &LoadCargoConfig,
progress: &dyn Fn(String), progress: &dyn Fn(String),
) -> Result<(AnalysisHost, vfs::Vfs, Option<ProcMacroClient>)> { ) -> Result<(AnalysisHost, vfs::Vfs, Option<ProcMacroServer>)> {
let root = AbsPathBuf::assert(std::env::current_dir()?.join(root)); let root = AbsPathBuf::assert(std::env::current_dir()?.join(root));
let root = ProjectManifest::discover_single(&root)?; let root = ProjectManifest::discover_single(&root)?;
let mut workspace = ProjectWorkspace::load(root, cargo_config, progress)?; let mut workspace = ProjectWorkspace::load(root, cargo_config, progress)?;
@ -49,7 +49,7 @@ pub fn load_workspace_at(
pub fn load_workspace( pub fn load_workspace(
ws: ProjectWorkspace, ws: ProjectWorkspace,
load_config: &LoadCargoConfig, load_config: &LoadCargoConfig,
) -> Result<(AnalysisHost, vfs::Vfs, Option<ProcMacroClient>)> { ) -> Result<(AnalysisHost, vfs::Vfs, Option<ProcMacroServer>)> {
let (sender, receiver) = unbounded(); let (sender, receiver) = unbounded();
let mut vfs = vfs::Vfs::default(); let mut vfs = vfs::Vfs::default();
let mut loader = { let mut loader = {
@ -60,7 +60,7 @@ pub fn load_workspace(
let proc_macro_client = if load_config.with_proc_macro { let proc_macro_client = if load_config.with_proc_macro {
let path = AbsPathBuf::assert(std::env::current_exe()?); let path = AbsPathBuf::assert(std::env::current_exe()?);
Some(ProcMacroClient::extern_process(path, &["proc-macro"]).unwrap()) Some(ProcMacroServer::spawn(path, &["proc-macro"]).unwrap())
} else { } else {
None None
}; };

View File

@ -11,7 +11,7 @@
use ide_db::base_db::CrateId; use ide_db::base_db::CrateId;
use lsp_types::{SemanticTokens, Url}; use lsp_types::{SemanticTokens, Url};
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use proc_macro_api::ProcMacroClient; use proc_macro_api::ProcMacroServer;
use project_model::{CargoWorkspace, ProjectWorkspace, Target, WorkspaceBuildScripts}; use project_model::{CargoWorkspace, ProjectWorkspace, Target, WorkspaceBuildScripts};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use vfs::AnchoredPathBuf; use vfs::AnchoredPathBuf;
@ -60,7 +60,7 @@ pub(crate) struct GlobalState {
pub(crate) shutdown_requested: bool, pub(crate) shutdown_requested: bool,
pub(crate) last_reported_status: Option<lsp_ext::ServerStatusParams>, pub(crate) last_reported_status: Option<lsp_ext::ServerStatusParams>,
pub(crate) source_root_config: SourceRootConfig, pub(crate) source_root_config: SourceRootConfig,
pub(crate) proc_macro_client: Option<ProcMacroClient>, pub(crate) proc_macro_client: Option<ProcMacroServer>,
pub(crate) flycheck: Vec<FlycheckHandle>, pub(crate) flycheck: Vec<FlycheckHandle>,
pub(crate) flycheck_sender: Sender<flycheck::Message>, pub(crate) flycheck_sender: Sender<flycheck::Message>,

View File

@ -7,7 +7,7 @@
use ide_db::base_db::{ use ide_db::base_db::{
CrateGraph, Env, ProcMacro, ProcMacroExpander, ProcMacroKind, SourceRoot, VfsPath, CrateGraph, Env, ProcMacro, ProcMacroExpander, ProcMacroKind, SourceRoot, VfsPath,
}; };
use proc_macro_api::ProcMacroClient; use proc_macro_api::ProcMacroServer;
use project_model::{ProjectWorkspace, WorkspaceBuildScripts}; use project_model::{ProjectWorkspace, WorkspaceBuildScripts};
use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind}; use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
@ -329,7 +329,7 @@ fn eq_ignore_build_data<'a>(
if self.proc_macro_client.is_none() { if self.proc_macro_client.is_none() {
self.proc_macro_client = match self.config.proc_macro_srv() { self.proc_macro_client = match self.config.proc_macro_srv() {
None => None, None => None,
Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) { Some((path, args)) => match ProcMacroServer::spawn(path.clone(), args) {
Ok(it) => Some(it), Ok(it) => Some(it),
Err(err) => { Err(err) => {
tracing::error!( tracing::error!(
@ -556,15 +556,15 @@ pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
} }
} }
pub(crate) fn load_proc_macro(client: Option<&ProcMacroClient>, path: &AbsPath) -> Vec<ProcMacro> { pub(crate) fn load_proc_macro(client: Option<&ProcMacroServer>, path: &AbsPath) -> Vec<ProcMacro> {
return client return client
.map(|it| it.by_dylib_path(path)) .map(|it| it.load_dylib(path))
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.map(expander_to_proc_macro) .map(expander_to_proc_macro)
.collect(); .collect();
fn expander_to_proc_macro(expander: proc_macro_api::ProcMacroProcessExpander) -> ProcMacro { fn expander_to_proc_macro(expander: proc_macro_api::ProcMacro) -> ProcMacro {
let name = expander.name().into(); let name = expander.name().into();
let kind = match expander.kind() { let kind = match expander.kind() {
proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive, proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
@ -576,7 +576,7 @@ fn expander_to_proc_macro(expander: proc_macro_api::ProcMacroProcessExpander) ->
} }
#[derive(Debug)] #[derive(Debug)]
struct Expander(proc_macro_api::ProcMacroProcessExpander); struct Expander(proc_macro_api::ProcMacro);
impl ProcMacroExpander for Expander { impl ProcMacroExpander for Expander {
fn expand( fn expand(