1

I'm looking for the right method to statically register structures at compile time.

The origin of this requirement is to have a bunch of applets with dedicated tasks so that if I run myprog foo, it will call the foo applet.

So I started by defining an Applet structure:

struct Applet {
    name: &str,
    call: fn(),
}

Then I can define my foo applet this way:

fn foo_call() {
    println!("Foo");
}
let foo_applet = Applet { name: "foo", call: foo_call };

Now I would like to register this applet so that my main function can call it if available:

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();

    match AppletRegistry.get(args[1]) {
        Some(x) => x.call(),
        _ => (),
    }
}

The whole deal is about how AppletRegistry should be implemented so that I can list all the available applets preferably at compile time.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Spack
  • 464
  • 4
  • 22

3 Answers3

7

You can't.

One of the conscious design choices with Rust is "no code before main", thus there is no support for this sort of thing. Fundamentally, you need to have code somewhere that you explicitly call that registers the applets.

Rust programs that need to do something like this will just list all the possible implementations explicitly and construct a single, static array of them. Something like this:

pub const APPLETS: &'static [Applet] = [
    Applet { name: "foo", call: ::applets::foo::foo_call },
    Applet { name: "bar", call: ::applets::bar::bar_call },
];

(Sometimes, the repetitive elements can be simplified with macros, i.e. in this example, you could change it so that the name is only mentioned once.)

Theoretically, you could do it by doing what languages like D do behind the scenes, but would be platform-specific and probably require messing with linker scripts and/or modifying the compiler.

Aside: What about #[test]? #[test] is magic and handled by the compiler. The short version is: it does the job of finding all the tests in a crate and building said giant list, which is then used by the test runner which effectively replaces your main function. No, there's no way you can do anything similar.

DK.
  • 55,277
  • 5
  • 189
  • 162
  • 2
    *have a macro somewhere* — I don't see a macro in your example, and I can't figure out how one would play in here. Could you expand that bit a little more? Also, what about concepts like `#[test]`, which you annotate a function with and then it gets magically run from the test main. Would it be possible to do something similar as a user? – Shepmaster Sep 20 '15 at 19:26
  • _No there's no way you can do something similar._ - Using [compiler plugins](https://doc.rust-lang.org/stable/book/compiler-plugins.html), but it's not yet stable if I understood correctly. – Spack Sep 21 '15 at 06:29
6

You can.

You need to use the inventory crate. This is limited to Linux, macOS, iOS, FreeBSD, Android, and Windows at the moment.

You need to use inventory::submit to add it to a global registry, inventory::collect to build the registry, and inventory::iter to iterate over the registry:

use inventory; // 0.1.9
use std::{collections::BTreeMap, env};

struct Applet {
    name: &'static str,
    call: fn(),
}

// Add something to the registry

fn foo_call() {
    println!("Foo");
}
inventory::submit!(Applet {
    name: "foo",
    call: foo_call
});

// Build the registry

inventory::collect!(Applet);

fn main() {
    let args: Vec<String> = env::args().collect();

    let mut registry = BTreeMap::new();

    // Access the registry
    for applet in inventory::iter::<Applet> {
        registry.insert(applet.name, applet);
    }

    if let Some(applet) = registry.get(&args[1].as_ref()) {
        (applet.call)();
    }
}

Running it shows how it works:

$ cargo run foo
Foo

$ cargo run bar
chub500
  • 712
  • 6
  • 18
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Could this be done in a default trait function implementation so that library end users don't have to worry about registering something themselves and can just rely on implementing a certain trait? – Pop Flamingo Oct 31 '22 at 15:22
  • @PopFlamingo no idea — try it and let me know! – Shepmaster Nov 01 '22 at 18:19
3

This is not a direct answer to your question but just FYI... For ELF binaries, I could achieve something similar to GCC's __attribute__((constructor)) with

fn init() { ... }
#[link_section = ".init_array"]
static INIT: fn() = init;

This is obviously a deviation from Rust's design philosophies. (Portability and what @DK calls "no code before main" principle.)

INIT can also be an Rust array. You might need to pay more attention to alignments.

nodakai
  • 7,773
  • 3
  • 30
  • 60
  • 1
    I *knew* there was a linker section for this, but damned if I could find what it was called. Of course, as you say, this is *horribly* non-portable... – DK. Sep 20 '15 at 12:52