Use macro for all the things

This commit is contained in:
Edwin Cheng 2019-11-23 22:48:34 +08:00
parent 6940ae9eab
commit 16854e28ef

View File

@ -8,37 +8,11 @@ use crate::{
use crate::quote; use crate::quote;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltinFnLikeExpander {
Column,
File,
Line,
Stringify,
}
struct BuiltInMacroInfo {
name: name::Name,
kind: BuiltinFnLikeExpander,
expand: fn(
db: &dyn AstDatabase,
id: MacroCallId,
_tt: &tt::Subtree,
) -> Result<tt::Subtree, mbe::ExpandError>,
}
macro_rules! register_builtin { macro_rules! register_builtin {
( $(($name:ident, $kind: ident) => $expand:ident),* ) => { ( $(($name:ident, $kind: ident) => $expand:ident),* ) => {
const BUILTIN_MACROS: &[BuiltInMacroInfo] = &[ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
$(BuiltInMacroInfo { name: name::$name, kind: BuiltinFnLikeExpander::$kind, expand: $expand }),* pub enum BuiltinFnLikeExpander {
]; $($kind),*
};
}
register_builtin! {
(COLUMN_MACRO, Column) => column_expand,
(FILE_MACRO, File) => file_expand,
(LINE_MACRO, Line) => line_expand,
(STRINGIFY_MACRO, Stringify) => stringify_expand
} }
impl BuiltinFnLikeExpander { impl BuiltinFnLikeExpander {
@ -48,12 +22,9 @@ impl BuiltinFnLikeExpander {
id: MacroCallId, id: MacroCallId,
tt: &tt::Subtree, tt: &tt::Subtree,
) -> Result<tt::Subtree, mbe::ExpandError> { ) -> Result<tt::Subtree, mbe::ExpandError> {
let expander = BUILTIN_MACROS let expander = match *self {
.iter() $( BuiltinFnLikeExpander::$kind => $expand, )*
.find(|it| *self == it.kind) };
.map(|it| it.expand)
.ok_or_else(|| mbe::ExpandError::ConversionError)?;
expander(db, id, tt) expander(db, id, tt)
} }
} }
@ -63,10 +34,22 @@ pub fn find_builtin_macro(
krate: CrateId, krate: CrateId,
ast_id: AstId<ast::MacroCall>, ast_id: AstId<ast::MacroCall>,
) -> Option<MacroDefId> { ) -> Option<MacroDefId> {
let kind = BUILTIN_MACROS.iter().find(|it| *ident == it.name).map(|it| it.kind)?; let kind = match ident {
$( id if id == &name::$name => BuiltinFnLikeExpander::$kind, )*
_ => return None,
};
Some(MacroDefId { krate, ast_id, kind: MacroDefKind::BuiltIn(kind) }) Some(MacroDefId { krate, ast_id, kind: MacroDefKind::BuiltIn(kind) })
} }
};
}
register_builtin! {
(COLUMN_MACRO, Column) => column_expand,
(FILE_MACRO, File) => file_expand,
(LINE_MACRO, Line) => line_expand,
(STRINGIFY_MACRO, Stringify) => stringify_expand
}
fn to_line_number(db: &dyn AstDatabase, file: HirFileId, pos: TextUnit) -> usize { fn to_line_number(db: &dyn AstDatabase, file: HirFileId, pos: TextUnit) -> usize {
// FIXME: Use expansion info // FIXME: Use expansion info