Skip to content

Commit e00e655

Browse files
bors[bot]kjeremy
andauthored
Merge #2362
2362: Expand compile_error! r=edwin0cheng a=kjeremy Does not validate that the input is a string literal. I thought that I could `match_ast!` against the `macro_args` but that did not work. Even if it had I am not sure which error would be appropriate. Co-authored-by: Jeremy Kolb <[email protected]>
2 parents a888441 + 67d3600 commit e00e655

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

crates/ra_hir_expand/src/builtin_macro.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ macro_rules! register_builtin {
4646

4747
register_builtin! {
4848
(COLUMN_MACRO, Column) => column_expand,
49+
(COMPILE_ERROR_MACRO, CompileError) => compile_error_expand,
4950
(FILE_MACRO, File) => file_expand,
5051
(LINE_MACRO, Line) => line_expand,
5152
(STRINGIFY_MACRO, Stringify) => stringify_expand
@@ -183,6 +184,26 @@ fn file_expand(
183184
Ok(expanded)
184185
}
185186

187+
fn compile_error_expand(
188+
_db: &dyn AstDatabase,
189+
_id: MacroCallId,
190+
tt: &tt::Subtree,
191+
) -> Result<tt::Subtree, mbe::ExpandError> {
192+
if tt.count() == 1 {
193+
match &tt.token_trees[0] {
194+
tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => {
195+
let s = it.text.as_str();
196+
if s.contains(r#"""#) {
197+
return Ok(quote! { loop { #it }});
198+
}
199+
}
200+
_ => {}
201+
};
202+
}
203+
204+
Err(mbe::ExpandError::BindingError("Must be a string".into()))
205+
}
206+
186207
#[cfg(test)]
187208
mod tests {
188209
use super::*;
@@ -270,4 +291,21 @@ mod tests {
270291

271292
assert_eq!(expanded, "\"\"");
272293
}
294+
295+
#[test]
296+
fn test_compile_error_expand() {
297+
let expanded = expand_builtin_macro(
298+
r#"
299+
#[rustc_builtin_macro]
300+
macro_rules! compile_error {
301+
($msg:expr) => ({ /* compiler built-in */ });
302+
($msg:expr,) => ({ /* compiler built-in */ })
303+
}
304+
compile_error!("error!");
305+
"#,
306+
BuiltinFnLikeExpander::CompileError,
307+
);
308+
309+
assert_eq!(expanded, r#"loop{"error!"}"#);
310+
}
273311
}

crates/ra_hir_expand/src/name.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,5 +144,6 @@ pub const BOX_TYPE: Name = Name::new_inline_ascii(3, b"Box");
144144
// Builtin Macros
145145
pub const FILE_MACRO: Name = Name::new_inline_ascii(4, b"file");
146146
pub const COLUMN_MACRO: Name = Name::new_inline_ascii(6, b"column");
147+
pub const COMPILE_ERROR_MACRO: Name = Name::new_inline_ascii(13, b"compile_error");
147148
pub const LINE_MACRO: Name = Name::new_inline_ascii(4, b"line");
148149
pub const STRINGIFY_MACRO: Name = Name::new_inline_ascii(9, b"stringify");

0 commit comments

Comments
 (0)