How to make the following code to pass the compilation?
Rules:
You cannot modify the function, you are only allowed to add code surrounding it.
You can use macros, but the expanded code must obey all of other rules. Which means it's not allowed to use #[cfg(...)], stringify! or macro_rules! to hide or disrupt that function.
You cannot put it inside comments (/* */) or string literals (" ").
There is at least one solution exists, maybe more.
Are attribute maxros that add code to the function when expanded allowed? Technically speaking all the original code will still exist after the expansion.
Assuming we want the String to remain a std::string::String, and depending on how lenient we're willing to get with the definition of words “modify” and “exist”:
Option #1
fn foo() -> String {
use foo::*;
mod foo {
#![no_implicit_prelude]
type String = &'static str;
trait ToString { fn to_string(&self) -> &Self { &self } }
impl ToString for &'static str {}
// -->
pub fn foo() -> String {
let a: String = "a".to_string();
let b = a;
let c = a;
a
}
// <--
}
foo().into()
}
Option #2
macro_rules! skip {
(fn $fn_name:ident() -> $ret:ty {
$first:stmt;
$skip_1:stmt;
$skip_2:stmt;
$last:stmt
}) => {
fn $fn_name() -> $ret {
$first
$last
}
};
}
// same result = same function,
// didn't "modify" a thing
skip! {
fn foo() -> String {
let a: String = "a".to_string();
let b = a;
let c = a;
a
}
}
Option #3
macro_rules! put_that_back {
(fn $fn_name:ident() -> $ret:ty {
$first:stmt;
$(let $to:ident = $from:ident;)+
$last:expr
}) => {
fn $fn_name() -> $ret {
$first
$(let $to = $from; let $from = $to;)*
$last
}
};
}
// all "the code", and therefore,
// all the initial statements
// "must exist", you said?
put_that_back! {
fn foo() -> String {
let a: String = "a".to_string();
let b = a;
//+ let a = b;
let c = a;
//+ let a = c;
a
}
nice try but unfortunately only option1 is correct. because when all macros expanded the function has been restructured, and the function is not allowed to be modify.
I'm not saying that as long as token is there will be ok, but the whole function must be there and not modified.
maybe i didn't express the rule rigorous enough. I'm gonna improve the game description