Skip to content

Pass the crate environment to proc macros #6820

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions crates/base_db/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
//! actual IO. See `vfs` and `project_model` in the `rust-analyzer` crate for how
//! actual IO is done and lowered to input.

use std::{fmt, iter::FromIterator, ops, str::FromStr, sync::Arc};
use std::{fmt, iter::FromIterator, ops, panic::RefUnwindSafe, str::FromStr, sync::Arc};

use cfg::CfgOptions;
use rustc_hash::{FxHashMap, FxHashSet};
use syntax::SmolStr;
use tt::TokenExpander;
use tt::{ExpansionError, Subtree};
use vfs::{file_set::FileSet, FileId, VfsPath};

/// Files are grouped into source roots. A source root is a directory on the
Expand Down Expand Up @@ -150,11 +150,20 @@ pub enum ProcMacroKind {
Attr,
}

pub trait ProcMacroExpander: fmt::Debug + Send + Sync + RefUnwindSafe {
fn expand(
&self,
subtree: &Subtree,
attrs: Option<&Subtree>,
env: &Env,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, yeah, I think this makes sense -- proc macro can observe compile-time env variables.

) -> Result<Subtree, ExpansionError>;
}

#[derive(Debug, Clone)]
pub struct ProcMacro {
pub name: SmolStr,
pub kind: ProcMacroKind,
pub expander: Arc<dyn TokenExpander>,
pub expander: Arc<dyn ProcMacroExpander>,
}

impl Eq for ProcMacro {}
Expand Down Expand Up @@ -413,6 +422,10 @@ impl Env {
pub fn get(&self, env: &str) -> Option<String> {
self.entries.get(env).cloned()
}

pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.entries.iter().map(|(k, v)| (k.as_str(), v.as_str()))
}
}

#[derive(Debug)]
Expand Down
2 changes: 1 addition & 1 deletion crates/base_db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub use crate::{
change::Change,
input::{
CrateData, CrateDisplayName, CrateGraph, CrateId, CrateName, Dependency, Edition, Env,
ProcMacro, ProcMacroId, ProcMacroKind, SourceRoot, SourceRootId,
ProcMacro, ProcMacroExpander, ProcMacroId, ProcMacroKind, SourceRoot, SourceRootId,
},
};
pub use salsa;
Expand Down
2 changes: 1 addition & 1 deletion crates/hir_expand/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ fn expand_proc_macro(
_ => unreachable!(),
};

expander.expand(db, lazy_id, &macro_arg.0)
expander.expand(db, loc.krate, &macro_arg.0)
}

fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
Expand Down
9 changes: 6 additions & 3 deletions crates/hir_expand/src/proc_macro.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Proc Macro Expander stub

use crate::{db::AstDatabase, LazyMacroId};
use crate::db::AstDatabase;
use base_db::{CrateId, ProcMacroId};
use tt::buffer::{Cursor, TokenBuffer};

Expand Down Expand Up @@ -32,7 +32,7 @@ impl ProcMacroExpander {
pub fn expand(
self,
db: &dyn AstDatabase,
_id: LazyMacroId,
calling_crate: CrateId,
tt: &tt::Subtree,
) -> Result<tt::Subtree, mbe::ExpandError> {
match self.proc_macro_id {
Expand All @@ -47,7 +47,10 @@ impl ProcMacroExpander {
let tt = remove_derive_attrs(tt)
.ok_or_else(|| err!("Fail to remove derive for custom derive"))?;

proc_macro.expander.expand(&tt, None).map_err(mbe::ExpandError::from)
// Proc macros have access to the environment variables of the invoking crate.
let env = &krate_graph[calling_crate].env;

proc_macro.expander.expand(&tt, None, &env).map_err(mbe::ExpandError::from)
}
None => Err(mbe::ExpandError::UnresolvedProcMacro),
}
Expand Down
8 changes: 5 additions & 3 deletions crates/proc_macro_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use std::{
sync::Arc,
};

use base_db::ProcMacro;
use base_db::{Env, ProcMacro};
use tt::{SmolStr, Subtree};

use crate::process::{ProcMacroProcessSrv, ProcMacroProcessThread};
Expand All @@ -39,17 +39,19 @@ impl PartialEq for ProcMacroProcessExpander {
}
}

impl tt::TokenExpander for ProcMacroProcessExpander {
impl base_db::ProcMacroExpander for ProcMacroProcessExpander {
fn expand(
&self,
subtree: &Subtree,
attr: Option<&Subtree>,
env: &Env,
) -> Result<Subtree, tt::ExpansionError> {
let task = ExpansionTask {
macro_body: subtree.clone(),
macro_name: self.name.to_string(),
attributes: attr.cloned(),
lib: self.dylib_path.to_path_buf(),
env: env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
};

let result: ExpansionResult = self.process.send_task(msg::Request::ExpansionMacro(task))?;
Expand Down Expand Up @@ -90,7 +92,7 @@ impl ProcMacroClient {
ProcMacroKind::FuncLike => base_db::ProcMacroKind::FuncLike,
ProcMacroKind::Attr => base_db::ProcMacroKind::Attr,
};
let expander: Arc<dyn tt::TokenExpander> = Arc::new(ProcMacroProcessExpander {
let expander = Arc::new(ProcMacroProcessExpander {
process: self.process.clone(),
name: name.clone(),
dylib_path: dylib_path.into(),
Expand Down
4 changes: 4 additions & 0 deletions crates/proc_macro_api/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ pub struct ExpansionTask {
pub attributes: Option<Subtree>,

pub lib: PathBuf,

/// Environment variables to set during macro expansion.
pub env: Vec<(String, String)>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would OsString be a better fit here semantic-wise?

In analysis, we need to use Strings, because only that's compatible with env!.

Here, the consumre is external process, so OsString might be better?

But mostly, this is irrelevant.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that's true. But they come from Env, so we won't see non-UTF-8 variables.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, in similar cases I generally prefer to shape the interface to the shape of the external world, rather than to the shape of an internal impl.

It's less confusing to have some explicit glue code, than for two things share identical inteface by accident.

}

#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]
Expand Down Expand Up @@ -251,6 +254,7 @@ mod tests {
macro_name: Default::default(),
attributes: None,
lib: Default::default(),
env: Default::default(),
};

let json = serde_json::to_string(&task).unwrap();
Expand Down
20 changes: 18 additions & 2 deletions crates/proc_macro_srv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use proc_macro::bridge::client::TokenStream;
use proc_macro_api::{ExpansionResult, ExpansionTask, ListMacrosResult, ListMacrosTask};
use std::{
collections::{hash_map::Entry, HashMap},
fs,
env, fs,
path::{Path, PathBuf},
time::SystemTime,
};
Expand All @@ -37,7 +37,23 @@ pub(crate) struct ProcMacroSrv {
impl ProcMacroSrv {
pub fn expand(&mut self, task: &ExpansionTask) -> Result<ExpansionResult, String> {
let expander = self.expander(&task.lib)?;
match expander.expand(&task.macro_name, &task.macro_body, task.attributes.as_ref()) {

let mut prev_env = HashMap::new();
for (k, v) in &task.env {
prev_env.insert(k.as_str(), env::var_os(k));
env::set_var(k, v);
}

let result = expander.expand(&task.macro_name, &task.macro_body, task.attributes.as_ref());

for (k, _) in &task.env {
match &prev_env[k.as_str()] {
Some(v) => env::set_var(k, v),
None => env::remove_var(k),
}
}

match result {
Ok(expansion) => Ok(ExpansionResult { expansion }),
Err(msg) => {
let msg = msg.as_str().unwrap_or("<unknown error>");
Expand Down
7 changes: 1 addition & 6 deletions crates/tt/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! `tt` crate defines a `TokenTree` data structure: this is the interface (both
//! input and output) of macros. It closely mirrors `proc_macro` crate's
//! `TokenTree`.
use std::{fmt, panic::RefUnwindSafe};
use std::fmt;

use stdx::impl_from;

Expand Down Expand Up @@ -247,8 +247,3 @@ impl fmt::Display for ExpansionError {
}
}
}

pub trait TokenExpander: fmt::Debug + Send + Sync + RefUnwindSafe {
fn expand(&self, subtree: &Subtree, attrs: Option<&Subtree>)
-> Result<Subtree, ExpansionError>;
}