#proc-macro #gpt #chatgpt #generate #macro #ai

macro macro-gpt

A simple proc macro that uses ChatGPT to generate rust code at compile-time based on a prompt, and a less simple one that can inject the results of prompts directly into your editor!

2 releases

0.1.2 Jul 24, 2023
0.1.0 Jul 23, 2023

#1686 in Procedural macros

MIT license

237 lines

Macro GPT: GPT in Rust Proc Macros

Crates.io docs.rs MIT License

This crate is half-meme, half serious.


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.


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


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.


~337K SLoC