Summary

Add a frontmatter syntax to Rust as a way for cargo to have manifests embedded in source code:

#!/usr/bin/env cargo
---
[dependencies]
clap = { version = "4.2", features = ["derive"] }
---

use clap::Parser;

#[derive(Parser, Debug)]
#[clap(version)]
struct Args {
    #[clap(short, long, help = "Path to config")]
    config: Option<std::path::PathBuf>,
}

fn main() {
    let args = Args::parse();
    println!("{:?}", args);
}

Motivation

“cargo script” is in need of a syntax for embedding manifests in source. See that RFC for its motivations.

Guide-level explanation

Static site generators use a frontmatter syntax to embed metadata in markdown files:

---
name: My Blog Post
---

## Stuff happened

Hello world!

We are carrying this concept over to Rust while merging some lessons from commonmark’s fenced code blocks:

#!/usr/bin/env cargo
---
[dependencies]
clap = { version = "4.2", features = ["derive"] }
---

use clap::Parser;

#[derive(Parser, Debug)]
#[clap(version)]
struct Args {
    #[clap(short, long, help = "Path to config")]
    config: Option<std::path::PathBuf>,
}

fn main() {
    let args = Args::parse();
    println!("{:?}", args);
}

Like with commonmark code fences, an info-string is allowed after the opening --- for use by the command interpreting the block to identify the contents of the block.

Reference-level explanation

When parsing Rust source, after stripping the shebang (#!), rustc will strip the frontmatter:

This applies anywhere shebang stripping is performed. For example, if include! strips shebangs, then it will also frontmatter.

As cargo will be the first step in the process to parse this, the responsibility for high quality error messages will largely fall on cargo.

Drawbacks

Rationale and alternatives

Within this solution, we considered starting with only allowing this in the root mod (e.g. main.rs) but decided to allow it in any file mostly for ease of implementation. Like with Python, this allows any file in a package (with the correct deps and mods) to be executed, allowing easier interacting experiences in verifying behavior.

Required vs Optional Shebang

We could require the shebang to be present for all cargo-scripts. This would most negatively impact Windows users as the shebang is a no-op. We still care about Windows because cargo-scripts can still be used for exploration and prototyping, even if they can’t directly be used as drop-in utilities.

The main reason to require a shebang is to positively identify the associated “interpreter”. However, statically analyzing a shebang is complicated and we are wanting to avoid it in the core workflow. This isn’t to say that tools like rust-analyzer might choose to require it to help their workflow.

Blank lines

Originally, the proposal viewed the block as being “part of” the shebang and didn’t allow them to be separated by blank lines. However, the shebang is optional and users are likely to assume they can use blanklines (see https://www.youtube.com/watch?v=S8MLYZv_54w).

This could cause ordering confusion (doc comments vs attributes vs frontmatter)

Infostring

The main question on infostrings is whether they are tool-defined or rustc-defined. At one time, we proposed requiring the infostring and requiring it be cargo as a way to defer this decision.

As the design requirements are catered to processing by external tools, as opposed to rustc, we are instead reserving this syntax for external tools by making the infostrings tool-defined. The Rust toolchain (rustc, clippy, rustdoc, etc) already have access to attributes for user-provided content. If they need a more ergonomic way of specifying content, we should solve that more generally for attributes.

With that decision made, the infostring can be optional. Can it also be deferred out? Possibly, but we are leaving them in for unpredictable exception cases and in case users want to make the syntax explicit for their editor (especially if its not cargo which more trivial editor implementations will likely assume). We may at least defer stabilization of infostrings.

The infostring syntax was selected to allow file names (e.g. Cargo.lock). Additional attributes are left to a future possibility.

Syntax

RFC 3502 lays out some design principles, including

This led us to wanting to re-use the existing manifest format inside of Rust code. The question is what that syntax for embedding should be.

When choosing the syntax, our care-abouts are

Why add to Rust syntax, rather than letting Cargo handle it

The most naive way for cargo to handle this is for cargo to strip the manifest, write the Rust file to a temporary file, and compile that. This is what has traditionally been done with various iterations of “cargo script”.

This provides a second-class experience which runs counter to one of the design goals

A key part in there is “plan to support”. We’d need to build up buy-in for tools to be supporting a Cargo-only syntax. This becomes more difficult when the tool in question tries to be Cargo-agnostic. By having Cargo-agnostic external tool syntax in Rust, this mostly becomes transparent.

We could build a special relationship with rustc to support this. For example, rustdoc passes code to rustc on stdin and sets UNSTABLE_RUSTDOC_TEST_PATH and UNSTABLE_RUSTDOC_TEST_LINE to control how errors are rendered. We could then also special case the messages inside of cargo. This both adds a major support burden to keep this house of lies standing but still falls short when it comes to tooling support. Now every tool that wants to support the Cargo-only syntax has to build their own house of lies.

Frontmatter

This proposed syntax builds off of the precedence of Rust having syntax specialized for an external tool (doc-comments for rustdoc). However, a new syntax is used instead of extending the comment syntax:

The difference between this syntax and comments is comments are generally geared towards people, even if a subset (doc-comments) are also able to be somewhat processed by a program, while this is geared mostly towards machine processing.

This proposal mirrors the location of YAML frontmatter (absolutely first). As we learn more of its uses and problems people run into in practice, we can evaluate if we want to loosen any of the rules.

Differences with YAML frontmatter include:

Besides characters, differences with commonmark code fences include:

Benefits:

Downsides:

Alternative 1: Vary the opening/closing character

Instead of dashes, we could do another character, like

In practice (with infostrings):

#!/usr/bin/env cargo
```cargo
[package]
edition = "2018"
```

fn main() {
}
#!/usr/bin/env cargo
~~~cargo
[package]
edition = "2018"
~~~

fn main() {
}
#!/usr/bin/env cargo
+++cargo
[package]
edition = "2018"
+++

fn main() {
}
#!/usr/bin/env cargo
===cargo
[package]
edition = "2018"
===

fn main() {
}
#!/usr/bin/env cargo
>>>cargo
[package]
edition = "2018"
<<<

fn main() {
}
#!/usr/bin/env cargo
<<<cargo
[package]
edition = "2018"
>>>

fn main() {
}

Downsides

Note:

Alternative 2: Extended Shebang

#!/usr/bin/env cargo

fn main() {}

This is a variation on other options that ties itself closer to the shebang syntax. The hope would be that we could get buy-in from other languages.

Syntactically, this avoids confusion with attributes by being stripped before lexing. We could make this less ambiguous by using a double hash.

#!/usr/bin/env cargo
# ```cargo
# [dependencies]
# foo = "1.2.3"
# ```

fn main() {}

Benefits

Downsides

If we dropped future possibilities for additional content, we could remove the opening/closing syntax, greatly reducing the minimum syntax needed in some cases.

#!/usr/bin/env cargo
# package.edition = "2018"

fn main() {}

Alternative 3: Doc-comment

#!/usr/bin/env cargo

//! ```cargo
//! [package]
//! edition = "2018"
//! ```

fn main() {
}

Benefits

Downsides:

Alternative 4: Attribute

#!/usr/bin/env cargo

#![cargo(manifest = r#"
[package]
edition = "2018"
"#)]

fn main() {
}

Benefits

Downsides

Alternative 5: Regular Comment

Simple header:

#!/usr/bin/env cargo
/* Cargo.toml:
[package]
edition = "2018"
*/

fn main() {
}

HEREDOC:

#!/usr/bin/env cargo
/* Cargo.toml >>>
[package]
edition = "2018"
<<<
*/

fn main() {
}

The manifest can be a regular comment with a header. If we were to support multiple types of content (manifest, lockfile), we could either use multiple comments or HEREDOC. This does not prescribe the exact syntax used or supported comments

Benefits

Downsides

Alternative 6: Macro

#!/usr/bin/env cargo

cargo! {
[package]
edition = "2018"
}

fn main() {
}

Benefits

Downsides

Bazel has an import proc-macro but its more for simplifying the writing of extern crate.

Alternative 7: Presentation Streams

#!/usr/bin/env cargo

fn main() {
}

---Cargo.toml
[package]
edition = "2018"

YAML allows several documents to be concatenated together variant presentation streams which might seem familiar as this is frequently used in static-site generators for adding frontmatter to pages. What if we extended Rust’s syntax to allow something similar?

Benefits

Downsides

Prior art

See also Single-file scripts that download their dependencies which enumerates the syntax used by different tools.

cargo-script family

There are several forks of cargo script.

doc-comments

#!/usr/bin/env run-cargo-script
//! This is a regular crate doc comment, but it also contains a partial
//! Cargo manifest.  Note the use of a *fenced* code block, and the
//! `cargo` "language".
//!
//! ```cargo
//! [dependencies]
//! time = "0.1.25"
//! ```
extern crate time;
fn main() {
    println!("{}", time::now().rfc822z());
}

short-hand

// cargo-deps: time="0.1.25"
// You can also leave off the version number, in which case, it's assumed
// to be "*".  Also, the `cargo-deps` comment *must* be a single-line
// comment, and it *must* be the first thing in the file, after the
// hashbang.
extern crate time;
fn main() {
    println!("{}", time::now().rfc822z());
}

RustExplorer

Rust Explorer uses a comment syntax for specifying dependencies

Example:

/*
[dependencies]
actix-web = "*"
ureq = "*"
tokio = { version = "*", features = ["full"] }
*/

use actix_web::App;
use actix_web::get;
use actix_web::HttpResponse;
use actix_web::HttpServer;
use actix_web::post;
use actix_web::Responder;
use actix_web::web;
use tokio::spawn;
use tokio::sync::oneshot;
use tokio::task::spawn_blocking;

PL/Rust

Example:

CREATE OR REPLACE FUNCTION randint() RETURNS bigint LANGUAGE plrust AS $$
[dependencies]
rand = "0.8"

[code]
use rand::Rng; 
Ok(Some(rand::thread_rng().gen())) 
$$;

See External Dependencies

YAML frontmatter

As a specialization of YAML presentation streams, static site generators use frontmatter to embed YAML at the top of files. Other systems have extended this for non-YAML use, like zola using +++ for TOML.

Proposed Python syntax

Currently the draft PEP 723 proposes allowing begin/end markers inside of regular comments:

# /// pyproject
# [run]
# requires-python = ">=3.11"
# dependencies = [
#   "requests<3",
#   "rich",
# ]
# ///

import requests
from rich.pretty import pprint

resp = requests.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:10])

Unresolved questions

Future possibilities

Multiple frontmatters

At least for cargo’s use cases, the only other file that we would consider supporting is Cargo.lock and we have other avenues we want to explore as future possibilities before we even consider the idea of multiple frontmatters.

So if we decide we need to embed additional metadata, we have a couple of options for extending frontmatter support.

Distinct blocks, maybe with newlines

---Cargo.toml
---

---Cargo.lock
---

Continuous blocks

---Cargo.toml
---Cargo.lock
---

Distinct blocks is more like the source inspiration, markdown, though has more noise, places to get things wrong, and syntax questions (newlines).