Crate macro_gpt

source ·
Expand description

Crates.io docs.rs MIT License

This crate is half-meme, half serious.

gpt!

The gpt! macro is a funny proof of concept that lets you do things like this:

use macro_gpt::*;

struct MyStruct;
gpt!("implement PartialEq for an existing struct called MyStruct");

fn main() {
    assert!(MyStruct {} == MyStruct {});
}

And GPT4 will try its best to expand the gpt! macro to something that compiles based solely on your prompt. This macro has no idea about the contents of your file other than what you tell it about in your prompt. The generated source code is printed to the console at compile-time, and this is the only way you can retrieve it since it is quite possible it will be different the next time you compile.

gpt_inject!

The gpt_inject! macro, on the other hand, is actually useful. It is invoked quite similarly to the gpt! macro, in that you pass a string literal prompt to a proc macro called gpt_inject!. From here the similarities start to vanish.

Namely, gpt_inject!:

  • Has access to your entire Rust file and provides this as context information to GPT4
  • Tasks GPT4 with coming up with Rust code that could replace your macro invocation in a way that will compile correctly and fulfill the requirements laid out in your prompt.

When you compile, your gpt_inject! macro invocation will be replaced with the code GPT4 generates, and a line comment will be provided (which you can uncomment and tweak further, if desired) containing the original prompt you used to generate the current expansion.

Here is an example:

use macro_gpt::*;

struct Something;
gpt_inject!("Make a trait defining a method called `foo` that prints hello world to the console and have `Something` implement it");

When you compile this, the file will re-write itself to look something like this, directly in your editor:

use macro_gpt::*;

struct Something;

// generated by: gpt_inject!("Make a trait defining a method called `foo` that prints hello world to the console and have `Something` implement it")
trait HelloWorld {
    fn foo(&self);
}

impl HelloWorld for Something {
    fn foo(&self) {
        println!("Hello, world!");
    }
}
// end of generated code

Requirements

For either macro to work, you must have a valid OPENAI_API_KEY environment variable set and accessible to cargo/rustc when you are compiling.

Macros

  • (Meme) Uses the supplied (string literal) prompt to generate valid Rust code from GPT4 based on the prompt at compile-time, and expands to the code that GPT4 generates.
  • Allows you to write a prompt to GPT4 as a string literal argument to the macro. When the macro is compiled, the macro will find the file in which it was invoked and replace the macro call with the code generated by GPT4, along with a comment allowing you to further tweak the prompt.