Skip to content

Commit b829e7c

Browse files
bors[bot]liushuyu
andauthored
Merge #1080
1080: macros: add compile_error! macro r=CohenArthur a=liushuyu - Added `compile_error` macro Co-authored-by: liushuyu <[email protected]>
2 parents 779de32 + 35570ae commit b829e7c

File tree

4 files changed

+32
-0
lines changed

4 files changed

+32
-0
lines changed

gcc/rust/expand/rust-macro-builtins.cc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,4 +236,20 @@ MacroBuiltin::include_str (Location invoc_locus, AST::MacroInvocData &invoc)
236236
return AST::ASTFragment ({node});
237237
}
238238

239+
/* Expand builtin macro compile_error!("error"), which forces a compile error
240+
during the compile time. */
241+
AST::ASTFragment
242+
MacroBuiltin::compile_error (Location invoc_locus, AST::MacroInvocData &invoc)
243+
{
244+
auto lit_expr
245+
= parse_single_string_literal (invoc.get_delim_tok_tree (), invoc_locus);
246+
if (lit_expr == nullptr)
247+
return AST::ASTFragment::create_error ();
248+
249+
std::string error_string = lit_expr->as_string ();
250+
rust_error_at (invoc_locus, "%s", error_string.c_str ());
251+
252+
return AST::ASTFragment::create_error ();
253+
}
254+
239255
} // namespace Rust

gcc/rust/expand/rust-macro-builtins.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ class MacroBuiltin
7777

7878
static AST::ASTFragment include_str (Location invoc_locus,
7979
AST::MacroInvocData &invoc);
80+
81+
static AST::ASTFragment compile_error (Location invoc_locus,
82+
AST::MacroInvocData &invoc);
8083
};
8184
} // namespace Rust
8285

gcc/rust/util/rust-hir-map.cc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,7 @@ Mappings::insert_macro_def (AST::MacroRulesDefinition *macro)
753753
{"column", MacroBuiltin::column},
754754
{"include_bytes", MacroBuiltin::include_bytes},
755755
{"include_str", MacroBuiltin::include_str},
756+
{"compile_error", MacroBuiltin::compile_error},
756757
};
757758

758759
auto builtin = builtin_macros.find (macro->get_rule_name ());
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
macro_rules! compile_error {
2+
() => {{}};
3+
}
4+
5+
fn main () {
6+
let message = "error message";
7+
compile_error! (message); // { dg-error "argument must be a string literal" "" }
8+
compile_error! (); // { dg-error "macro takes 1 argument" "" }
9+
compile_error! ("a", "b"); // { dg-error "macro takes 1 argument" "" }
10+
compile_error! ("expected error message"); // { dg-error "expected error message" }
11+
compile_error! ("expected error message",); // { dg-error "expected error message" }
12+
}

0 commit comments

Comments
 (0)