rust-lang/discord-mods-bot

Add a way to run code that requires neither an explicit `main` nor the printing of a final expression

Kimundi opened this issue · 1 comments

While giving support on the discord channel, I've noticed over time that there are some recurring scenarios where you might want to show how some code runs via the bot, but neither ?play or ?eval are the ideal solutions.

For example, lets say I want to show the output of this code:

println!("{}", std::mem::size_of<u16>());
println!("{}", std::mem::size_of<u128>());

Currently I have two options:

  • ?play
     fn main() {
         println!("{}", std::mem::size_of<u16>());
         println!("{}", std::mem::size_of<u128>());
     }
    2
    16
    
  • ?eval
     println!("{}", std::mem::size_of<u16>());
     println!("{}", std::mem::size_of<u128>());
    2
    16
    ()
    

The ?play variant has the desired compact output, but takes more effort to write up due to needing to wrap the code in a main. Depending on the target audience of such an demonstration (ie, very early beginners), it might also be confusing that a function definition got involved.

The ?eval variant is easier to type and more compact, which can make it clearer what is being demonstrated, but it has the disadvantage that it prints the final () if its actually just used for side-effects.

Ideally there would be a simple way to do a mixture of both: Automatically wrap the code in a block and run it, but without unconditionally printing an expression:

  • ?run
     println!("{}", std::mem::size_of<u16>());
     println!("{}", std::mem::size_of<u128>());
    2
    16
    

I can imagine multiple ways to expose this functionality:

  • As an extra command like ?run
  • As an modifier for ?play (to automatically add a main)
  • As an modifier for ?eval (to suppress the trailing expression)
  • As an automatic fallback mode of ?play that tries to detect if there is no fn main, and adds one automatically. (This would be similar to how doc tests get compiled)

I think the best way for this would be flags for whether to print the stdout and whether to print the overall expression. If we wanted to go the extra mile, a command that explains what happens at each statement may be possible, but it would involve more than syntactic appraisal.