aoc_toolbox_derive/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use std::cell::RefCell;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::collections::HashSet;

use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::{parse_macro_input, AttributeArgs, ItemFn, Lit, NestedMeta};

use inflector::Inflector;

thread_local! {
    static AOC_SOLVERS: RefCell<HashMap<String, HashSet<String>>> = RefCell::new(HashMap::new());
}

fn format_trait(day: &String, part: &String) -> Ident {
    format_ident!("{}{}", day.to_title_case(), part.to_title_case())
}

fn format_module(day: &String, part: &String) -> Ident {
    format_ident!("Mod{}{}", day.to_title_case(), part.to_title_case())
}

#[proc_macro_attribute]
pub fn aoc_solver(
    input: proc_macro::TokenStream,
    annotated_item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let attributes = parse_macro_input!(input as AttributeArgs);
    let attributes: Vec<String> = attributes
        .iter()
        .map(|a| match a {
            NestedMeta::Lit(Lit::Str(s)) => s.value(),
            _ => panic!("Attribute is not a string"),
        })
        .collect();
    if attributes.len() != 2 {
        panic!("Number of attributes must be two");
    }
    let day = attributes[0].clone();
    let part = attributes[1].clone();

    let trait_name = format_trait(&day, &part);
    let module_name = format_module(&day, &part);
    let func = parse_macro_input!(annotated_item as ItemFn);
    let function = format_ident!("{}", func.sig.ident.to_string());
    let solve_impl = quote! {
        mod #module_name {
            use super::*;
            use crate::#trait_name;

            impl<'a> #trait_name for aoc_toolbox::Aoc<'a> {
                fn solve() -> String {
                    #function(aoc_toolbox::utils::load_input(#day))
                }
            }
        }
    };

    AOC_SOLVERS.with(|solvers| {
        match solvers.borrow_mut().entry(day) {
            Entry::Occupied(mut e) => {
                if e.get().contains(&part) {
                    panic!("Part \"{}\" for day \"{}\" exists already", part, e.key());
                }
                e.get_mut().insert(part);
            }
            Entry::Vacant(e) => {
                e.insert(HashSet::new()).insert(part);
            }
        };
    });

    quote! {
        #func

        #solve_impl
    }
    .into_token_stream()
    .into()
}

#[proc_macro]
pub fn aoc_main(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let year = parse_macro_input!(input as Lit);

    AOC_SOLVERS.with(|solvers| {
        let traits: Vec<TokenStream> = solvers
            .borrow_mut()
            .iter()
            .flat_map(|(day, parts)| {
                let ret: Vec<TokenStream> = parts
                    .iter()
                    .map(|part| {
                        let trait_name = format_trait(day, part);

                        quote! {
                            trait #trait_name {
                                fn solve() -> String;
                            }
                        }
                    })
                    .collect();
                ret
            })
            .collect();

        let adders: Vec<TokenStream> = solvers
            .borrow_mut()
            .iter()
            .flat_map(|(day, parts)| {
                let ret: Vec<TokenStream> = parts
                    .iter()
                    .map(|part| {
                        let trait_name = format_trait(day, part);

                        quote! {
                            aoc.add_solver(#day, #part, <aoc_toolbox::Aoc as #trait_name>::solve);
                        }
                    })
                    .collect();
                ret
            })
            .collect();

        quote! {
            #( #traits )*

            fn main() -> Result<(), Box<dyn std::error::Error>> {
                use aoc_toolbox::{clap, Parser};

                #[derive(aoc_toolbox::Parser, Debug)]
                #[clap(about, long_about = None)]
                struct Args {
                    /// Name of the solver to run
                    #[clap(index = 1, value_parser, default_value = "all")]
                    solver: String,

                    /// List all available solvers
                    #[clap(short, long, value_parser, exclusive = true)]
                    list: bool,

                    /// List all available solvers
                    #[clap(short = 'd', long, value_parser)]
                    with_duration: bool,
                }

                let args = Args::parse();

                let mut aoc = aoc_toolbox::Aoc::new( #year , args.with_duration);
                #( #adders )*

                if args.list {
                    aoc.list();
                    return Ok(());
                }

                aoc.run(args.solver)?;
                Ok(())
            }
        }
        .into()
    })
}