mdBook icon indicating copy to clipboard operation
mdBook copied to clipboard

Playground code with no `main` fails to compile

Open micouy opened this issue 2 years ago • 4 comments

The paragraph on Rust Playground says:

If there is no main function, then the code is automatically wrapped inside one.

However, my code doesn't compile without it. I've also replicated it in the editor chapter by removing the main function.

Code:

let number = 5;
print!("{}", number);

Error:

   Compiling playground v0.0.1 (/playground)
error: expected item, found keyword `let`
 --> src/main.rs:1:1
  |
1 | let number = 5;
  | ^^^ expected item

error: could not compile `playground` due to previous error

micouy avatar Mar 11 '22 20:03 micouy

This only happens when combined with editable, as the code editor does not support hidden lines. The javascript side could potentially wrap it in fn main, though it would be a bit unfortunate to need to duplicate that logic.

ehuss avatar Mar 11 '22 21:03 ehuss

Thanks for the info. Is this the intended behavior? If yes, I think it would be useful to include a note in the docs.

micouy avatar Mar 11 '22 21:03 micouy

This only happens when combined with editable, as the code editor does not support hidden lines.

As a user, my expectation was that a code block would work the same with and without the editable attribute.

The javascript side could potentially wrap it in fn main, though it would be a bit unfortunate to need to duplicate that logic.

I guess there is already functionality for this to make "plain" code blocks runnable on the playground? My mental model would be that the same logic should kick in when I want to execute an editable code block.

Hidden lines are of course complicated... perhaps a solution would be to show them when the editor receives focus? That way the code can start small, and if the user wants to edit the code, the user gets to edit the full thing.

mgeisler avatar May 02 '22 12:05 mgeisler

It's not just editable blocks. See the code fragment in https://rust-lang.github.io/mdBook/format/theme/syntax-highlighting.html#hiding-code-lines. If you keep the lines hidden, it fails to compile saying that the first variable should be const because it doesn't see it's in a fn. But if you show hidden lines, it compiles fine.

If the goal, similar to rustdoc examples, is to allow snippets to compile, it seems the hidden lines should always be part of the jsonified body posted to the runner. As a very naive example, could the fully body without anything hidden be defined as a hidden div or something that is always sent to the runner? E.g.,

<pre class="playground">
<pre style="display: none" id="code">
fn main() {
  let a = 1;
  let b = 2;
  assert_ne!(a, b);
}
</pre>
<code class="language-rust edition2018 hljs hide-boring">
<!-- the code rendered as it is now -->
</code>
</pre>

heaths avatar Dec 02 '22 22:12 heaths