Skip to content

Commit 7087742

Browse files
Pass crate environment to proc macros
1 parent 798968e commit 7087742

File tree

6 files changed

+42
-9
lines changed

6 files changed

+42
-9
lines changed

crates/base_db/src/input.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,12 @@ pub enum ProcMacroKind {
151151
}
152152

153153
pub trait ProcMacroExpander: fmt::Debug + Send + Sync + RefUnwindSafe {
154-
fn expand(&self, subtree: &Subtree, attrs: Option<&Subtree>)
155-
-> Result<Subtree, ExpansionError>;
154+
fn expand(
155+
&self,
156+
subtree: &Subtree,
157+
attrs: Option<&Subtree>,
158+
env: &Env,
159+
) -> Result<Subtree, ExpansionError>;
156160
}
157161

158162
#[derive(Debug, Clone)]
@@ -418,6 +422,10 @@ impl Env {
418422
pub fn get(&self, env: &str) -> Option<String> {
419423
self.entries.get(env).cloned()
420424
}
425+
426+
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
427+
self.entries.iter().map(|(k, v)| (k.as_str(), v.as_str()))
428+
}
421429
}
422430

423431
#[derive(Debug)]

crates/hir_expand/src/db.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ fn expand_proc_macro(
271271
_ => unreachable!(),
272272
};
273273

274-
expander.expand(db, lazy_id, &macro_arg.0)
274+
expander.expand(db, loc.krate, &macro_arg.0)
275275
}
276276

277277
fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {

crates/hir_expand/src/proc_macro.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Proc Macro Expander stub
22
3-
use crate::{db::AstDatabase, LazyMacroId};
3+
use crate::db::AstDatabase;
44
use base_db::{CrateId, ProcMacroId};
55
use tt::buffer::{Cursor, TokenBuffer};
66

@@ -32,7 +32,7 @@ impl ProcMacroExpander {
3232
pub fn expand(
3333
self,
3434
db: &dyn AstDatabase,
35-
_id: LazyMacroId,
35+
calling_crate: CrateId,
3636
tt: &tt::Subtree,
3737
) -> Result<tt::Subtree, mbe::ExpandError> {
3838
match self.proc_macro_id {
@@ -47,7 +47,10 @@ impl ProcMacroExpander {
4747
let tt = remove_derive_attrs(tt)
4848
.ok_or_else(|| err!("Fail to remove derive for custom derive"))?;
4949

50-
proc_macro.expander.expand(&tt, None).map_err(mbe::ExpandError::from)
50+
// Proc macros have access to the environment variables of the invoking crate.
51+
let env = &krate_graph[calling_crate].env;
52+
53+
proc_macro.expander.expand(&tt, None, &env).map_err(mbe::ExpandError::from)
5154
}
5255
None => Err(mbe::ExpandError::UnresolvedProcMacro),
5356
}

crates/proc_macro_api/src/lib.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use std::{
1616
sync::Arc,
1717
};
1818

19-
use base_db::ProcMacro;
19+
use base_db::{Env, ProcMacro};
2020
use tt::{SmolStr, Subtree};
2121

2222
use crate::process::{ProcMacroProcessSrv, ProcMacroProcessThread};
@@ -44,12 +44,14 @@ impl base_db::ProcMacroExpander for ProcMacroProcessExpander {
4444
&self,
4545
subtree: &Subtree,
4646
attr: Option<&Subtree>,
47+
env: &Env,
4748
) -> Result<Subtree, tt::ExpansionError> {
4849
let task = ExpansionTask {
4950
macro_body: subtree.clone(),
5051
macro_name: self.name.to_string(),
5152
attributes: attr.cloned(),
5253
lib: self.dylib_path.to_path_buf(),
54+
env: env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
5355
};
5456

5557
let result: ExpansionResult = self.process.send_task(msg::Request::ExpansionMacro(task))?;

crates/proc_macro_api/src/rpc.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ pub struct ExpansionTask {
5151
pub attributes: Option<Subtree>,
5252

5353
pub lib: PathBuf,
54+
55+
/// Environment variables to set during macro expansion.
56+
pub env: Vec<(String, String)>,
5457
}
5558

5659
#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]
@@ -251,6 +254,7 @@ mod tests {
251254
macro_name: Default::default(),
252255
attributes: None,
253256
lib: Default::default(),
257+
env: Default::default(),
254258
};
255259

256260
let json = serde_json::to_string(&task).unwrap();

crates/proc_macro_srv/src/lib.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use proc_macro::bridge::client::TokenStream;
2424
use proc_macro_api::{ExpansionResult, ExpansionTask, ListMacrosResult, ListMacrosTask};
2525
use std::{
2626
collections::{hash_map::Entry, HashMap},
27-
fs,
27+
env, fs,
2828
path::{Path, PathBuf},
2929
time::SystemTime,
3030
};
@@ -37,7 +37,23 @@ pub(crate) struct ProcMacroSrv {
3737
impl ProcMacroSrv {
3838
pub fn expand(&mut self, task: &ExpansionTask) -> Result<ExpansionResult, String> {
3939
let expander = self.expander(&task.lib)?;
40-
match expander.expand(&task.macro_name, &task.macro_body, task.attributes.as_ref()) {
40+
41+
let mut prev_env = HashMap::new();
42+
for (k, v) in &task.env {
43+
prev_env.insert(k.as_str(), env::var_os(k));
44+
env::set_var(k, v);
45+
}
46+
47+
let result = expander.expand(&task.macro_name, &task.macro_body, task.attributes.as_ref());
48+
49+
for (k, _) in &task.env {
50+
match &prev_env[k.as_str()] {
51+
Some(v) => env::set_var(k, v),
52+
None => env::remove_var(k),
53+
}
54+
}
55+
56+
match result {
4157
Ok(expansion) => Ok(ExpansionResult { expansion }),
4258
Err(msg) => {
4359
let msg = msg.as_str().unwrap_or("<unknown error>");

0 commit comments

Comments
 (0)