mirror of
https://github.com/rust-lang/rust-analyzer.git
synced 2025-09-29 13:25:09 +00:00
Internal: Cleanup proc-macro error handling
This commit is contained in:
parent
df15b6f668
commit
7beac14cba
39 changed files with 380 additions and 522 deletions
14
crates/hir-expand/src/builtin.rs
Normal file
14
crates/hir-expand/src/builtin.rs
Normal file
|
@ -0,0 +1,14 @@
|
|||
#[macro_use]
|
||||
mod quote;
|
||||
|
||||
mod attr_macro;
|
||||
mod derive_macro;
|
||||
mod fn_macro;
|
||||
|
||||
pub use self::{
|
||||
attr_macro::{find_builtin_attr, pseudo_derive_attr_expansion, BuiltinAttrExpander},
|
||||
derive_macro::{find_builtin_derive, BuiltinDeriveExpander},
|
||||
fn_macro::{
|
||||
find_builtin_macro, include_input_to_file_id, BuiltinFnLikeExpander, EagerExpander,
|
||||
},
|
||||
};
|
|
@ -9,18 +9,18 @@ use stdx::never;
|
|||
use tracing::debug;
|
||||
|
||||
use crate::{
|
||||
builtin::quote::{dollar_crate, quote},
|
||||
db::ExpandDatabase,
|
||||
hygiene::span_with_def_site_ctxt,
|
||||
name,
|
||||
name::{AsName, Name},
|
||||
quote::dollar_crate,
|
||||
span_map::ExpansionSpanMap,
|
||||
tt,
|
||||
tt, ExpandError, ExpandResult,
|
||||
};
|
||||
use syntax::ast::{
|
||||
self, AstNode, FieldList, HasAttrs, HasGenericParams, HasModuleItem, HasName, HasTypeBounds,
|
||||
};
|
||||
|
||||
use crate::{db::ExpandDatabase, name, quote, ExpandError, ExpandResult};
|
||||
|
||||
macro_rules! register_builtin {
|
||||
( $($trait:ident => $expand:ident),* ) => {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
@ -13,10 +13,10 @@ use syntax::{
|
|||
};
|
||||
|
||||
use crate::{
|
||||
builtin::quote::{dollar_crate, quote},
|
||||
db::ExpandDatabase,
|
||||
hygiene::{span_with_call_site_ctxt, span_with_def_site_ctxt},
|
||||
name, quote,
|
||||
quote::dollar_crate,
|
||||
name,
|
||||
tt::{self, DelimSpan},
|
||||
ExpandError, ExpandResult, HirFileIdExt, Lookup as _, MacroCallId,
|
||||
};
|
||||
|
@ -145,7 +145,7 @@ register_builtin! {
|
|||
}
|
||||
|
||||
fn mk_pound(span: Span) -> tt::Subtree {
|
||||
crate::quote::IntoTt::to_subtree(
|
||||
crate::builtin::quote::IntoTt::to_subtree(
|
||||
vec![crate::tt::Leaf::Punct(crate::tt::Punct {
|
||||
char: '#',
|
||||
spacing: crate::tt::Spacing::Alone,
|
|
@ -17,22 +17,21 @@ pub(crate) fn dollar_crate(span: Span) -> tt::Ident<Span> {
|
|||
// 2. #()* pattern repetition not supported now
|
||||
// * But we can do it manually, see `test_quote_derive_copy_hack`
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! __quote {
|
||||
macro_rules! quote_impl__ {
|
||||
($span:ident) => {
|
||||
Vec::<$crate::tt::TokenTree>::new()
|
||||
};
|
||||
|
||||
( @SUBTREE($span:ident) $delim:ident $($tt:tt)* ) => {
|
||||
{
|
||||
let children = $crate::__quote!($span $($tt)*);
|
||||
let children = $crate::builtin::quote::__quote!($span $($tt)*);
|
||||
$crate::tt::Subtree {
|
||||
delimiter: crate::tt::Delimiter {
|
||||
kind: crate::tt::DelimiterKind::$delim,
|
||||
open: $span,
|
||||
close: $span,
|
||||
},
|
||||
token_trees: $crate::quote::IntoTt::to_tokens(children).into_boxed_slice(),
|
||||
token_trees: $crate::builtin::quote::IntoTt::to_tokens(children).into_boxed_slice(),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -69,9 +68,9 @@ macro_rules! __quote {
|
|||
// hash variable
|
||||
($span:ident # $first:ident $($tail:tt)* ) => {
|
||||
{
|
||||
let token = $crate::quote::ToTokenTree::to_token($first, $span);
|
||||
let token = $crate::builtin::quote::ToTokenTree::to_token($first, $span);
|
||||
let mut tokens = vec![token.into()];
|
||||
let mut tail_tokens = $crate::quote::IntoTt::to_tokens($crate::__quote!($span $($tail)*));
|
||||
let mut tail_tokens = $crate::builtin::quote::IntoTt::to_tokens($crate::builtin::quote::__quote!($span $($tail)*));
|
||||
tokens.append(&mut tail_tokens);
|
||||
tokens
|
||||
}
|
||||
|
@ -79,22 +78,22 @@ macro_rules! __quote {
|
|||
|
||||
($span:ident ## $first:ident $($tail:tt)* ) => {
|
||||
{
|
||||
let mut tokens = $first.into_iter().map(|it| $crate::quote::ToTokenTree::to_token(it, $span)).collect::<Vec<crate::tt::TokenTree>>();
|
||||
let mut tail_tokens = $crate::quote::IntoTt::to_tokens($crate::__quote!($span $($tail)*));
|
||||
let mut tokens = $first.into_iter().map(|it| $crate::builtin::quote::ToTokenTree::to_token(it, $span)).collect::<Vec<crate::tt::TokenTree>>();
|
||||
let mut tail_tokens = $crate::builtin::quote::IntoTt::to_tokens($crate::builtin::quote::__quote!($span $($tail)*));
|
||||
tokens.append(&mut tail_tokens);
|
||||
tokens
|
||||
}
|
||||
};
|
||||
|
||||
// Brace
|
||||
($span:ident { $($tt:tt)* } ) => { $crate::__quote!(@SUBTREE($span) Brace $($tt)*) };
|
||||
($span:ident { $($tt:tt)* } ) => { $crate::builtin::quote::__quote!(@SUBTREE($span) Brace $($tt)*) };
|
||||
// Bracket
|
||||
($span:ident [ $($tt:tt)* ] ) => { $crate::__quote!(@SUBTREE($span) Bracket $($tt)*) };
|
||||
($span:ident [ $($tt:tt)* ] ) => { $crate::builtin::quote::__quote!(@SUBTREE($span) Bracket $($tt)*) };
|
||||
// Parenthesis
|
||||
($span:ident ( $($tt:tt)* ) ) => { $crate::__quote!(@SUBTREE($span) Parenthesis $($tt)*) };
|
||||
($span:ident ( $($tt:tt)* ) ) => { $crate::builtin::quote::__quote!(@SUBTREE($span) Parenthesis $($tt)*) };
|
||||
|
||||
// Literal
|
||||
($span:ident $tt:literal ) => { vec![$crate::quote::ToTokenTree::to_token($tt, $span).into()] };
|
||||
($span:ident $tt:literal ) => { vec![$crate::builtin::quote::ToTokenTree::to_token($tt, $span).into()] };
|
||||
// Ident
|
||||
($span:ident $tt:ident ) => {
|
||||
vec![ {
|
||||
|
@ -108,36 +107,37 @@ macro_rules! __quote {
|
|||
|
||||
// Puncts
|
||||
// FIXME: Not all puncts are handled
|
||||
($span:ident -> ) => {$crate::__quote!(@PUNCT($span) '-', '>')};
|
||||
($span:ident & ) => {$crate::__quote!(@PUNCT($span) '&')};
|
||||
($span:ident , ) => {$crate::__quote!(@PUNCT($span) ',')};
|
||||
($span:ident : ) => {$crate::__quote!(@PUNCT($span) ':')};
|
||||
($span:ident ; ) => {$crate::__quote!(@PUNCT($span) ';')};
|
||||
($span:ident :: ) => {$crate::__quote!(@PUNCT($span) ':', ':')};
|
||||
($span:ident . ) => {$crate::__quote!(@PUNCT($span) '.')};
|
||||
($span:ident < ) => {$crate::__quote!(@PUNCT($span) '<')};
|
||||
($span:ident > ) => {$crate::__quote!(@PUNCT($span) '>')};
|
||||
($span:ident ! ) => {$crate::__quote!(@PUNCT($span) '!')};
|
||||
($span:ident -> ) => {$crate::builtin::quote::__quote!(@PUNCT($span) '-', '>')};
|
||||
($span:ident & ) => {$crate::builtin::quote::__quote!(@PUNCT($span) '&')};
|
||||
($span:ident , ) => {$crate::builtin::quote::__quote!(@PUNCT($span) ',')};
|
||||
($span:ident : ) => {$crate::builtin::quote::__quote!(@PUNCT($span) ':')};
|
||||
($span:ident ; ) => {$crate::builtin::quote::__quote!(@PUNCT($span) ';')};
|
||||
($span:ident :: ) => {$crate::builtin::quote::__quote!(@PUNCT($span) ':', ':')};
|
||||
($span:ident . ) => {$crate::builtin::quote::__quote!(@PUNCT($span) '.')};
|
||||
($span:ident < ) => {$crate::builtin::quote::__quote!(@PUNCT($span) '<')};
|
||||
($span:ident > ) => {$crate::builtin::quote::__quote!(@PUNCT($span) '>')};
|
||||
($span:ident ! ) => {$crate::builtin::quote::__quote!(@PUNCT($span) '!')};
|
||||
|
||||
($span:ident $first:tt $($tail:tt)+ ) => {
|
||||
{
|
||||
let mut tokens = $crate::quote::IntoTt::to_tokens($crate::__quote!($span $first ));
|
||||
let mut tail_tokens = $crate::quote::IntoTt::to_tokens($crate::__quote!($span $($tail)*));
|
||||
let mut tokens = $crate::builtin::quote::IntoTt::to_tokens($crate::builtin::quote::__quote!($span $first ));
|
||||
let mut tail_tokens = $crate::builtin::quote::IntoTt::to_tokens($crate::builtin::quote::__quote!($span $($tail)*));
|
||||
|
||||
tokens.append(&mut tail_tokens);
|
||||
tokens
|
||||
}
|
||||
};
|
||||
}
|
||||
pub(super) use quote_impl__ as __quote;
|
||||
|
||||
/// FIXME:
|
||||
/// It probably should implement in proc-macro
|
||||
#[macro_export]
|
||||
macro_rules! quote {
|
||||
macro_rules! quote_impl {
|
||||
($span:ident=> $($tt:tt)* ) => {
|
||||
$crate::quote::IntoTt::to_subtree($crate::__quote!($span $($tt)*), $span)
|
||||
$crate::builtin::quote::IntoTt::to_subtree($crate::builtin::quote::__quote!($span $($tt)*), $span)
|
||||
}
|
||||
}
|
||||
pub(super) use quote_impl as quote;
|
||||
|
||||
pub(crate) trait IntoTt {
|
||||
fn to_subtree(self, span: Span) -> crate::tt::Subtree;
|
||||
|
@ -232,6 +232,8 @@ mod tests {
|
|||
use span::{SpanAnchor, SyntaxContextId, ROOT_ERASED_FILE_AST_ID};
|
||||
use syntax::{TextRange, TextSize};
|
||||
|
||||
use super::quote;
|
||||
|
||||
const DUMMY: tt::Span = tt::Span {
|
||||
range: TextRange::empty(TextSize::new(0)),
|
||||
anchor: SpanAnchor {
|
|
@ -25,8 +25,7 @@ impl ChangeWithProcMacros {
|
|||
|
||||
pub fn apply(self, db: &mut (impl ExpandDatabase + SourceDatabaseExt)) {
|
||||
self.source_change.apply(db);
|
||||
if let Some(mut proc_macros) = self.proc_macros {
|
||||
proc_macros.shrink_to_fit();
|
||||
if let Some(proc_macros) = self.proc_macros {
|
||||
db.set_proc_macros_with_durability(Arc::new(proc_macros), Durability::HIGH);
|
||||
}
|
||||
if let Some(target_data_layouts) = self.target_data_layouts {
|
||||
|
|
|
@ -11,8 +11,7 @@ use triomphe::Arc;
|
|||
|
||||
use crate::{
|
||||
attrs::{collect_attrs, AttrId},
|
||||
builtin_attr_macro::pseudo_derive_attr_expansion,
|
||||
builtin_fn_macro::EagerExpander,
|
||||
builtin::pseudo_derive_attr_expansion,
|
||||
cfg_process,
|
||||
declarative::DeclarativeMacroExpander,
|
||||
fixup::{self, SyntaxFixupUndoInfo},
|
||||
|
@ -20,9 +19,9 @@ use crate::{
|
|||
proc_macro::ProcMacros,
|
||||
span_map::{RealSpanMap, SpanMap, SpanMapRef},
|
||||
tt, AstId, BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander,
|
||||
CustomProcMacroExpander, EagerCallInfo, ExpandError, ExpandResult, ExpandTo, ExpansionSpanMap,
|
||||
HirFileId, HirFileIdRepr, Lookup, MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId,
|
||||
MacroDefKind, MacroFileId,
|
||||
CustomProcMacroExpander, EagerCallInfo, EagerExpander, ExpandError, ExpandResult, ExpandTo,
|
||||
ExpansionSpanMap, HirFileId, HirFileIdRepr, Lookup, MacroCallId, MacroCallKind, MacroCallLoc,
|
||||
MacroDefId, MacroDefKind, MacroFileId,
|
||||
};
|
||||
/// This is just to ensure the types of smart_macro_arg and macro_arg are the same
|
||||
type MacroArgResult = (Arc<tt::Subtree>, SyntaxFixupUndoInfo, Span);
|
||||
|
|
|
@ -6,9 +6,7 @@
|
|||
#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
|
||||
|
||||
pub mod attrs;
|
||||
pub mod builtin_attr_macro;
|
||||
pub mod builtin_derive_macro;
|
||||
pub mod builtin_fn_macro;
|
||||
pub mod builtin;
|
||||
pub mod change;
|
||||
pub mod db;
|
||||
pub mod declarative;
|
||||
|
@ -19,7 +17,6 @@ pub mod inert_attr_macro;
|
|||
pub mod mod_path;
|
||||
pub mod name;
|
||||
pub mod proc_macro;
|
||||
pub mod quote;
|
||||
pub mod span_map;
|
||||
|
||||
mod cfg_process;
|
||||
|
@ -29,7 +26,7 @@ use attrs::collect_attrs;
|
|||
use rustc_hash::FxHashMap;
|
||||
use triomphe::Arc;
|
||||
|
||||
use std::{fmt, hash::Hash};
|
||||
use std::hash::Hash;
|
||||
|
||||
use base_db::{salsa::InternValueTrivial, CrateId};
|
||||
use either::Either;
|
||||
|
@ -44,9 +41,10 @@ use syntax::{
|
|||
|
||||
use crate::{
|
||||
attrs::AttrId,
|
||||
builtin_attr_macro::BuiltinAttrExpander,
|
||||
builtin_derive_macro::BuiltinDeriveExpander,
|
||||
builtin_fn_macro::{BuiltinFnLikeExpander, EagerExpander},
|
||||
builtin::{
|
||||
include_input_to_file_id, BuiltinAttrExpander, BuiltinDeriveExpander,
|
||||
BuiltinFnLikeExpander, EagerExpander,
|
||||
},
|
||||
db::ExpandDatabase,
|
||||
mod_path::ModPath,
|
||||
proc_macro::{CustomProcMacroExpander, ProcMacroKind},
|
||||
|
@ -127,7 +125,8 @@ pub type ExpandResult<T> = ValueResult<T, ExpandError>;
|
|||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
|
||||
pub enum ExpandError {
|
||||
UnresolvedProcMacro(CrateId),
|
||||
ProcMacroAttrExpansionDisabled,
|
||||
MissingProcMacroExpander(CrateId),
|
||||
/// The macro expansion is disabled.
|
||||
MacroDisabled,
|
||||
MacroDefinition,
|
||||
|
@ -141,6 +140,26 @@ impl ExpandError {
|
|||
pub fn other(msg: impl Into<Box<str>>) -> Self {
|
||||
ExpandError::Other(Arc::new(msg.into()))
|
||||
}
|
||||
|
||||
pub fn render_to_string(&self, db: &dyn ExpandDatabase) -> (String, bool) {
|
||||
match self {
|
||||
Self::ProcMacroAttrExpansionDisabled => {
|
||||
("procedural attribute macro expansion is disabled".to_owned(), false)
|
||||
}
|
||||
Self::MacroDisabled => ("proc-macro is explicitly disabled".to_owned(), false),
|
||||
&Self::MissingProcMacroExpander(def_crate) => {
|
||||
match db.proc_macros().get_error_for_crate(def_crate) {
|
||||
Some((e, hard_err)) => (e.to_owned(), hard_err),
|
||||
None => ("missing expander".to_owned(), true),
|
||||
}
|
||||
}
|
||||
Self::MacroDefinition => ("macro definition has parse errors".to_owned(), true),
|
||||
Self::Mbe(e) => (e.to_string(), true),
|
||||
Self::RecursionOverflow => ("overflow expanding the original macro".to_owned(), true),
|
||||
Self::Other(e) => ((***e).to_owned(), true),
|
||||
Self::ProcMacroPanic(e) => ((***e).to_owned(), true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<mbe::ExpandError> for ExpandError {
|
||||
|
@ -148,24 +167,6 @@ impl From<mbe::ExpandError> for ExpandError {
|
|||
Self::Mbe(mbe)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ExpandError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ExpandError::UnresolvedProcMacro(_) => f.write_str("unresolved proc-macro"),
|
||||
ExpandError::Mbe(it) => it.fmt(f),
|
||||
ExpandError::RecursionOverflow => f.write_str("overflow expanding the original macro"),
|
||||
ExpandError::ProcMacroPanic(it) => {
|
||||
f.write_str("proc-macro panicked: ")?;
|
||||
f.write_str(it)
|
||||
}
|
||||
ExpandError::Other(it) => f.write_str(it),
|
||||
ExpandError::MacroDisabled => f.write_str("macro disabled"),
|
||||
ExpandError::MacroDefinition => f.write_str("macro definition has parse errors"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct MacroCallLoc {
|
||||
pub def: MacroDefId,
|
||||
|
@ -277,11 +278,9 @@ impl HirFileIdExt for HirFileId {
|
|||
let loc = db.lookup_intern_macro_call(file.macro_call_id);
|
||||
if loc.def.is_include() {
|
||||
if let MacroCallKind::FnLike { eager: Some(eager), .. } = &loc.kind {
|
||||
if let Ok(it) = builtin_fn_macro::include_input_to_file_id(
|
||||
db,
|
||||
file.macro_call_id,
|
||||
&eager.arg,
|
||||
) {
|
||||
if let Ok(it) =
|
||||
include_input_to_file_id(db, file.macro_call_id, &eager.arg)
|
||||
{
|
||||
break it;
|
||||
}
|
||||
}
|
||||
|
@ -572,9 +571,7 @@ impl MacroCallLoc {
|
|||
) -> Option<EditionedFileId> {
|
||||
if self.def.is_include() {
|
||||
if let MacroCallKind::FnLike { eager: Some(eager), .. } = &self.kind {
|
||||
if let Ok(it) =
|
||||
builtin_fn_macro::include_input_to_file_id(db, macro_call_id, &eager.arg)
|
||||
{
|
||||
if let Ok(it) = include_input_to_file_id(db, macro_call_id, &eager.arg) {
|
||||
return Some(it);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,20 +7,10 @@ use base_db::{CrateId, Env};
|
|||
use intern::Symbol;
|
||||
use rustc_hash::FxHashMap;
|
||||
use span::Span;
|
||||
use stdx::never;
|
||||
use triomphe::Arc;
|
||||
|
||||
use crate::{db::ExpandDatabase, tt, ExpandError, ExpandResult};
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct ProcMacroId(u32);
|
||||
|
||||
impl ProcMacroId {
|
||||
pub fn new(u32: u32) -> Self {
|
||||
ProcMacroId(u32)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
|
||||
pub enum ProcMacroKind {
|
||||
CustomDerive,
|
||||
|
@ -28,7 +18,10 @@ pub enum ProcMacroKind {
|
|||
Attr,
|
||||
}
|
||||
|
||||
/// A proc-macro expander implementation.
|
||||
pub trait ProcMacroExpander: fmt::Debug + Send + Sync + RefUnwindSafe {
|
||||
/// Run the expander with the given input subtree, optional attribute input subtree (for
|
||||
/// [`ProcMacroKind::Attr`]), environment variables, and span information.
|
||||
fn expand(
|
||||
&self,
|
||||
subtree: &tt::Subtree,
|
||||
|
@ -42,57 +35,162 @@ pub trait ProcMacroExpander: fmt::Debug + Send + Sync + RefUnwindSafe {
|
|||
|
||||
#[derive(Debug)]
|
||||
pub enum ProcMacroExpansionError {
|
||||
/// The proc-macro panicked.
|
||||
Panic(String),
|
||||
/// Things like "proc macro server was killed by OOM".
|
||||
/// The server itself errored out.
|
||||
System(String),
|
||||
}
|
||||
|
||||
pub type ProcMacroLoadResult = Result<Vec<ProcMacro>, String>;
|
||||
pub type ProcMacroLoadResult = Result<Vec<ProcMacro>, (String, bool)>;
|
||||
type StoredProcMacroLoadResult = Result<Box<[ProcMacro]>, (Box<str>, bool)>;
|
||||
|
||||
pub type ProcMacros = FxHashMap<CrateId, ProcMacroLoadResult>;
|
||||
#[derive(Default, Debug)]
|
||||
pub struct ProcMacrosBuilder(FxHashMap<CrateId, StoredProcMacroLoadResult>);
|
||||
impl ProcMacrosBuilder {
|
||||
pub fn insert(&mut self, proc_macros_crate: CrateId, proc_macro: ProcMacroLoadResult) {
|
||||
self.0.insert(
|
||||
proc_macros_crate,
|
||||
match proc_macro {
|
||||
Ok(it) => Ok(it.into_boxed_slice()),
|
||||
Err((e, hard_err)) => Err((e.into_boxed_str(), hard_err)),
|
||||
},
|
||||
);
|
||||
}
|
||||
pub fn build(mut self) -> ProcMacros {
|
||||
self.0.shrink_to_fit();
|
||||
ProcMacros(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct ProcMacros(FxHashMap<CrateId, StoredProcMacroLoadResult>);
|
||||
|
||||
impl FromIterator<(CrateId, ProcMacroLoadResult)> for ProcMacros {
|
||||
fn from_iter<T: IntoIterator<Item = (CrateId, ProcMacroLoadResult)>>(iter: T) -> Self {
|
||||
let mut builder = ProcMacrosBuilder::default();
|
||||
for (k, v) in iter {
|
||||
builder.insert(k, v);
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
impl ProcMacros {
|
||||
fn get(&self, krate: CrateId, idx: u32) -> Result<&ProcMacro, ExpandError> {
|
||||
let proc_macros = match self.0.get(&krate) {
|
||||
Some(Ok(proc_macros)) => proc_macros,
|
||||
Some(Err(_)) | None => {
|
||||
return Err(ExpandError::other("internal error: no proc macros for crate"));
|
||||
}
|
||||
};
|
||||
proc_macros.get(idx as usize).ok_or_else(|| {
|
||||
ExpandError::other(
|
||||
format!(
|
||||
"internal error: proc-macro index out of bounds: the length is {} but the index is {}",
|
||||
proc_macros.len(),
|
||||
idx
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
pub fn get_error_for_crate(&self, krate: CrateId) -> Option<(&str, bool)> {
|
||||
self.0.get(&krate).and_then(|it| it.as_ref().err()).map(|(e, hard_err)| (&**e, *hard_err))
|
||||
}
|
||||
|
||||
/// Fetch the [`CustomProcMacroExpander`]s and their corresponding names for the given crate.
|
||||
pub fn for_crate(
|
||||
&self,
|
||||
krate: CrateId,
|
||||
def_site_ctx: span::SyntaxContextId,
|
||||
) -> Option<Box<[(crate::name::Name, CustomProcMacroExpander, bool)]>> {
|
||||
match self.0.get(&krate) {
|
||||
Some(Ok(proc_macros)) => Some({
|
||||
proc_macros
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, it)| {
|
||||
let name = crate::name::Name::new_symbol(it.name.clone(), def_site_ctx);
|
||||
(name, CustomProcMacroExpander::new(idx as u32), it.disabled)
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded proc-macro.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProcMacro {
|
||||
/// The name of the proc macro.
|
||||
pub name: Symbol,
|
||||
pub kind: ProcMacroKind,
|
||||
/// The expander handle for this proc macro.
|
||||
pub expander: sync::Arc<dyn ProcMacroExpander>,
|
||||
/// Whether this proc-macro is disabled for early name resolution. Notably, the
|
||||
/// [`Self::expander`] is still usable.
|
||||
pub disabled: bool,
|
||||
}
|
||||
|
||||
/// A custom proc-macro expander handle. This handle together with its crate resolves to a [`ProcMacro`]
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
|
||||
pub struct CustomProcMacroExpander {
|
||||
proc_macro_id: ProcMacroId,
|
||||
proc_macro_id: u32,
|
||||
}
|
||||
|
||||
impl CustomProcMacroExpander {
|
||||
const DUMMY_ID: u32 = !0;
|
||||
const MISSING_EXPANDER: u32 = !0;
|
||||
const DISABLED_ID: u32 = !1;
|
||||
const PROC_MACRO_ATTR_DISABLED: u32 = !2;
|
||||
|
||||
pub fn new(proc_macro_id: ProcMacroId) -> Self {
|
||||
assert_ne!(proc_macro_id.0, Self::DUMMY_ID);
|
||||
assert_ne!(proc_macro_id.0, Self::DISABLED_ID);
|
||||
pub fn new(proc_macro_id: u32) -> Self {
|
||||
assert_ne!(proc_macro_id, Self::MISSING_EXPANDER);
|
||||
assert_ne!(proc_macro_id, Self::DISABLED_ID);
|
||||
assert_ne!(proc_macro_id, Self::PROC_MACRO_ATTR_DISABLED);
|
||||
Self { proc_macro_id }
|
||||
}
|
||||
|
||||
/// A dummy expander that always errors. This is used for proc-macros that are missing, usually
|
||||
/// due to them not being built yet.
|
||||
pub const fn dummy() -> Self {
|
||||
Self { proc_macro_id: ProcMacroId(Self::DUMMY_ID) }
|
||||
}
|
||||
|
||||
/// The macro was not yet resolved.
|
||||
pub const fn is_dummy(&self) -> bool {
|
||||
self.proc_macro_id.0 == Self::DUMMY_ID
|
||||
/// An expander that always errors due to the actual proc-macro expander missing.
|
||||
pub const fn missing_expander() -> Self {
|
||||
Self { proc_macro_id: Self::MISSING_EXPANDER }
|
||||
}
|
||||
|
||||
/// A dummy expander that always errors. This expander is used for macros that have been disabled.
|
||||
pub const fn disabled() -> Self {
|
||||
Self { proc_macro_id: ProcMacroId(Self::DISABLED_ID) }
|
||||
Self { proc_macro_id: Self::DISABLED_ID }
|
||||
}
|
||||
|
||||
/// A dummy expander that always errors. This expander is used for attribute macros when
|
||||
/// proc-macro attribute expansion is disabled.
|
||||
pub const fn disabled_proc_attr() -> Self {
|
||||
Self { proc_macro_id: Self::PROC_MACRO_ATTR_DISABLED }
|
||||
}
|
||||
|
||||
/// The macro-expander is missing or has yet to be build.
|
||||
pub const fn is_missing(&self) -> bool {
|
||||
self.proc_macro_id == Self::MISSING_EXPANDER
|
||||
}
|
||||
|
||||
/// The macro is explicitly disabled and cannot be expanded.
|
||||
pub const fn is_disabled(&self) -> bool {
|
||||
self.proc_macro_id.0 == Self::DISABLED_ID
|
||||
self.proc_macro_id == Self::DISABLED_ID
|
||||
}
|
||||
|
||||
/// The macro is explicitly disabled due to proc-macro attribute expansion being disabled.
|
||||
pub const fn is_disabled_proc_attr(&self) -> bool {
|
||||
self.proc_macro_id == Self::PROC_MACRO_ATTR_DISABLED
|
||||
}
|
||||
|
||||
/// The macro is explicitly disabled due to proc-macro attribute expansion being disabled.
|
||||
pub const fn as_expand_error(&self, def_crate: CrateId) -> Option<ExpandError> {
|
||||
match self.proc_macro_id {
|
||||
Self::PROC_MACRO_ATTR_DISABLED => Some(ExpandError::ProcMacroAttrExpansionDisabled),
|
||||
Self::DISABLED_ID => Some(ExpandError::MacroDisabled),
|
||||
Self::MISSING_EXPANDER => Some(ExpandError::MissingProcMacroExpander(def_crate)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expand(
|
||||
|
@ -107,38 +205,27 @@ impl CustomProcMacroExpander {
|
|||
mixed_site: Span,
|
||||
) -> ExpandResult<tt::Subtree> {
|
||||
match self.proc_macro_id {
|
||||
ProcMacroId(Self::DUMMY_ID) => ExpandResult::new(
|
||||
Self::PROC_MACRO_ATTR_DISABLED => ExpandResult::new(
|
||||
tt::Subtree::empty(tt::DelimSpan { open: call_site, close: call_site }),
|
||||
ExpandError::UnresolvedProcMacro(def_crate),
|
||||
ExpandError::ProcMacroAttrExpansionDisabled,
|
||||
),
|
||||
ProcMacroId(Self::DISABLED_ID) => ExpandResult::new(
|
||||
Self::MISSING_EXPANDER => ExpandResult::new(
|
||||
tt::Subtree::empty(tt::DelimSpan { open: call_site, close: call_site }),
|
||||
ExpandError::MissingProcMacroExpander(def_crate),
|
||||
),
|
||||
Self::DISABLED_ID => ExpandResult::new(
|
||||
tt::Subtree::empty(tt::DelimSpan { open: call_site, close: call_site }),
|
||||
ExpandError::MacroDisabled,
|
||||
),
|
||||
ProcMacroId(id) => {
|
||||
id => {
|
||||
let proc_macros = db.proc_macros();
|
||||
let proc_macros = match proc_macros.get(&def_crate) {
|
||||
Some(Ok(proc_macros)) => proc_macros,
|
||||
Some(Err(_)) | None => {
|
||||
never!("Non-dummy expander even though there are no proc macros");
|
||||
let proc_macro = match proc_macros.get(def_crate, id) {
|
||||
Ok(proc_macro) => proc_macro,
|
||||
Err(e) => {
|
||||
return ExpandResult::new(
|
||||
tt::Subtree::empty(tt::DelimSpan { open: call_site, close: call_site }),
|
||||
ExpandError::other("Internal error"),
|
||||
);
|
||||
}
|
||||
};
|
||||
let proc_macro = match proc_macros.get(id as usize) {
|
||||
Some(proc_macro) => proc_macro,
|
||||
None => {
|
||||
never!(
|
||||
"Proc macro index out of bounds: the length is {} but the index is {}",
|
||||
proc_macros.len(),
|
||||
id
|
||||
);
|
||||
return ExpandResult::new(
|
||||
tt::Subtree::empty(tt::DelimSpan { open: call_site, close: call_site }),
|
||||
ExpandError::other("Internal error: proc-macro index out of bounds"),
|
||||
);
|
||||
e,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue