obsidian-execute-code
obsidian-execute-code copied to clipboard
Rust library or binary
In a lot of code blocks in Rust, the main function is omitted for brevity, or because it is not needed.
Is it possible to make cargo-eval compile (or just check) these blocks as a library instead?
This would make them actually compile instead of giving a main function not found in crate
.
I confess that I'm not that familiar with Rust: what do you mean by "as a library"?
It is (relatively) easy for us to add a main function if none is detected (turning println!("Hi!");
into fn main() { println!("Hi!"); }
), but cargo-eval is intended to evaluate scripts. I quickly scanned through the readme
& maybe the templates feature can help too?
I'm not completely sure I understand your request, sorry! If I misunderstand, please feel free to correct me and I'll do my best to help :)
Cargo basically has two ways to compile a crate, a binary, which has a main function defined, or a library, which does not.
It seems like more of an "issue" with cargo-eval, so I will go with adding a main function for now.
Thanks for your really swift answer :)
I understand, thanks!
Would a feature to automatically add the main
function help? We currently do something like that for C++. I would want to help make your workflow as frictionless as possible :)
When I removed the need to have a main function in C++, I didn't go with wrapping everything in a main function because it's really hard to do, since there's a lot you can't put inside a function so you'd have to parse the whole code yourself and transform it, and trying to parse C++ ourselves is a bad idea. Instead the implementation just passes the code directly to cling without first putting it in a file. It looks like cargo-eval might support this with https://lib.rs/crates/cargo-eval#readme-expressions, in which case an executor similar to the C++ one could be made, I'm just not sure about external dependencies via the --dep
arg, there might be some parsing needed to automatically extract the deps from a code block if cargo-eval doesn't already do this.
It seems like cargo-eval doesn't import the external dependency automatically:
PS C:\Users\chlohal> cargo eval --expr 'extern crate time; time::now().rfc822z().to_string()'
Compiling expr v0.1.0 (C:\Users\chlohal\AppData\Local\cargo-eval\scripts\expr-e7ce8f561d23c233)
error[E0463]: can't find crate for `time`
--> expr.rs:18:12
|
18 | match {extern crate time; time::now().rfc822z().to_string()} {
| ^^^^^^^^^^^^^^^^^^ can't find crate
For more information about this error, try `rustc --explain E0463`.
error: could not compile `expr` due to previous error
internal error: cargo failed with status 101
We can use a regex to search for extern crate [\w-]+
and import it, but that seems brittle. This also only supports expressions-- does rust support nested functions?