Skip to content

Commit

Permalink
macros: add compile_error! macro
Browse files Browse the repository at this point in the history
addresses Rust-GCC#927

Signed-off-by: Zixing Liu <[email protected]>
  • Loading branch information
liushuyu committed Apr 3, 2022
1 parent 9011184 commit 35570ae
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
16 changes: 16 additions & 0 deletions gcc/rust/expand/rust-macro-builtins.cc
Original file line number Diff line number Diff line change
Expand Up @@ -236,4 +236,20 @@ MacroBuiltin::include_str (Location invoc_locus, AST::MacroInvocData &invoc)
return AST::ASTFragment ({node});
}

/* Expand builtin macro compile_error!("error"), which forces a compile error
during the compile time. */
AST::ASTFragment
MacroBuiltin::compile_error (Location invoc_locus, AST::MacroInvocData &invoc)
{
auto lit_expr
= parse_single_string_literal (invoc.get_delim_tok_tree (), invoc_locus);
if (lit_expr == nullptr)
return AST::ASTFragment::create_error ();

std::string error_string = lit_expr->as_string ();
rust_error_at (invoc_locus, "%s", error_string.c_str ());

return AST::ASTFragment::create_error ();
}

} // namespace Rust
3 changes: 3 additions & 0 deletions gcc/rust/expand/rust-macro-builtins.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ class MacroBuiltin

static AST::ASTFragment include_str (Location invoc_locus,
AST::MacroInvocData &invoc);

static AST::ASTFragment compile_error (Location invoc_locus,
AST::MacroInvocData &invoc);
};
} // namespace Rust

Expand Down
1 change: 1 addition & 0 deletions gcc/rust/util/rust-hir-map.cc
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,7 @@ Mappings::insert_macro_def (AST::MacroRulesDefinition *macro)
{"column", MacroBuiltin::column},
{"include_bytes", MacroBuiltin::include_bytes},
{"include_str", MacroBuiltin::include_str},
{"compile_error", MacroBuiltin::compile_error},
};

auto builtin = builtin_macros.find (macro->get_rule_name ());
Expand Down
12 changes: 12 additions & 0 deletions gcc/testsuite/rust/compile/builtin_macro_compile_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
macro_rules! compile_error {
() => {{}};
}

fn main () {
let message = "error message";
compile_error! (message); // { dg-error "argument must be a string literal" "" }
compile_error! (); // { dg-error "macro takes 1 argument" "" }
compile_error! ("a", "b"); // { dg-error "macro takes 1 argument" "" }
compile_error! ("expected error message"); // { dg-error "expected error message" }
compile_error! ("expected error message",); // { dg-error "expected error message" }
}

0 comments on commit 35570ae

Please sign in to comment.