Skip to main content

aoc_core_macros/
lib.rs

1#![warn(missing_docs)]
2
3//! Implementation details of the `bin_setup` procedural macro for my Advent of Code `aoc-core` library crate.
4//!
5//! You probably don't want to use this crate directly,
6//! although it can be useful if you use your own library.
7
8use proc_macro::TokenStream;
9
10use quote::quote;
11use syn::{ItemFn, parse_macro_input};
12
13mod input;
14
15use input::BinSetupInput;
16
17/// This macro can be used to generate my standard approach to Advent of Code binaries.
18///
19/// It can only be attached to `fn main()`.\
20/// Required arguments:
21/// - `puzzles_count`, number of puzzles in the binary
22/// - `resources_directory`, path to inputs and answers files, relative to `src`
23/// - `input_extension`, input files extension
24/// - `answers_file`, file containing the puzzle answers for checking execution
25///
26/// A simple `pretty_solution_2` macro is provided to:
27/// - embed input strings
28/// - execute solutions
29/// - measure execution time
30/// - verify output against provided answers
31///
32/// This macro takes day number, puzzle title, puzzle file name,
33/// first solution function, second solution function (optional).
34///
35/// The generated main function provides `args` handling to execute only specific days, e.g. `$ executable 1 3 5`
36///
37/// Example usage:
38/// ```
39/// use aoc_core_macros::bin_setup;
40///
41/// #[bin_setup(5, "../resources", ".in", "Answers.out")]
42/// fn main() {
43///     pretty_solution_2!(5, "Puzzle X", "PuzzleX", solution1, solution2);
44/// }
45///
46/// fn solution1(input: &str) -> u8 {
47///     input.lines().map(|n| n.parse::<u8>().unwrap()).sum()
48/// }
49///
50/// fn solution2(input: &str) -> u8 {
51///     input.lines().map(|n| n.parse::<u8>().unwrap()).product()
52/// }
53///
54/// // ../resources/PuzzleX.in
55/// // 2
56/// // 3
57///
58/// // ../resources/Answers.out
59/// // PuzzleX 5 6
60/// ```
61///
62/// Generated code looks like this:
63/// ```
64/// #[allow(clippy::items_after_statements)]
65/// fn main() {
66///     let puzzle_answers: rustc_hash::FxHashMap<&'static str, [&'static str; 2]> =
67///         include_str!(concat!("../resources", "/", "Answers.out"))
68///             .lines()
69///             .map(|line| {
70///                 let parts: Vec<_> = line.split_ascii_whitespace().collect();
71///
72///                 (parts[0], [parts[1], parts[2]])
73///             })
74///             .collect();
75///
76///     let selected_puzzles: [bool; 5] = {
77///         let args: Vec<_> = std::env::args().collect();
78///
79///         if args.len() == 1 {
80///             [true; 5]
81///         } else {
82///             std::array::from_fn(|day| args.contains(&(day + 1).to_string()))
83///         }
84///     };
85///
86///     #[inline]
87///     fn pretty_solution<R>(
88///         puzzle: &str,
89///         part: usize,
90///         solution: fn(&str) -> R,
91///         input: &str,
92///         answer: &str,
93///     ) where
94///         R: std::fmt::Display + PartialEq,
95///     {
96///         let now = std::time::Instant::now();
97///         let solution = solution(input);
98///         let microseconds = now.elapsed().as_micros();
99///
100///         assert!(
101///             solution.to_string() == answer,
102///             "Wrong solution for {puzzle} part {part}: expected {answer}, but got {solution}"
103///         );
104///
105///         println!("{part} -> {answer} ({microseconds}μs)");
106///     }
107///
108///     macro_rules! pretty_solution_2 {
109///         ($day:literal, $title: literal, $puzzle: literal, $solution1:ident $(,$solution2:ident)?) => {
110///             if selected_puzzles[$day - 1] {
111///                 println!("Day {}: {}", $day, $title);
112///
113///                 const INPUT: &str =
114///                     include_str!(concat!("../resources", "/", $puzzle, ".in"));
115///                 let answers = puzzle_answers.get($puzzle).expect("Puzzle answer not found");
116///
117///                 pretty_solution($puzzle, 1, $solution1, INPUT, answers[0]);
118///
119///                 $(pretty_solution($puzzle, 2, $solution2, INPUT, answers[1]);)?
120///
121///                 println!();
122///             }
123///         };
124///     }
125///
126///     pretty_solution_2!(5, "Puzzle X", "PuzzleX", solution1, solution2);
127/// }
128///
129/// # fn solution1(input: &str) -> u8 {
130/// #     input.lines().map(|n| n.parse::<u8>().unwrap()).sum()
131/// # }
132/// #
133/// # fn solution2(input: &str) -> u8 {
134/// #     input.lines().map(|n| n.parse::<u8>().unwrap()).product()
135/// # }
136/// ```
137#[proc_macro_attribute]
138pub fn bin_setup(attr: TokenStream, item: TokenStream) -> TokenStream {
139    let BinSetupInput {
140        puzzles_count,
141        resources_directory,
142        input_extension,
143        answers_file,
144    } = parse_macro_input!(attr as BinSetupInput);
145
146    let input_fn = parse_macro_input!(item as ItemFn);
147
148    if input_fn.sig.ident != "main" {
149        return syn::Error::new_spanned(
150            &input_fn.sig.ident,
151            format!(
152                "#[{}] can only be applied to `fn main()`",
153                stringify!(bin_setup)
154            ),
155        )
156        .into_compile_error()
157        .into();
158    }
159
160    let input_fn = input_fn.block;
161
162    quote! {
163        #[allow(clippy::items_after_statements)]
164        fn main() {
165            let puzzle_answers: rustc_hash::FxHashMap<&'static str, [&'static str; 2]> =
166                include_str!(concat!(#resources_directory, "/", #answers_file))
167                    .lines()
168                    .map(|line| {
169                        let parts: Vec<_> = line.split_ascii_whitespace().collect();
170
171                        (parts[0], [parts[1], parts[2]])
172                    })
173                    .collect();
174
175            let selected_puzzles: [bool; #puzzles_count] = {
176                let args: Vec<_> = std::env::args().collect();
177
178                if args.len() == 1 {
179                    [true; #puzzles_count]
180                } else {
181                    std::array::from_fn(|day| args.contains(&(day + 1).to_string()))
182                }
183            };
184
185            #[inline]
186            fn pretty_solution<R>(
187                puzzle: &str,
188                part: usize,
189                solution: fn(&str) -> R,
190                input: &str,
191                answer: &str,
192            ) where
193                R: std::fmt::Display + PartialEq,
194            {
195                let now = std::time::Instant::now();
196                let solution = solution(input);
197                let microseconds = now.elapsed().as_micros();
198
199                assert!(
200                    solution.to_string() == answer,
201                    "Wrong solution for {puzzle} part {part}: expected {answer}, but got {solution}"
202                );
203
204                println!("{part} -> {answer} ({microseconds}μs)");
205            }
206
207            macro_rules! pretty_solution_2 {
208                ($day:literal, $title: literal, $puzzle: literal, $solution1:ident $(,$solution2:ident)?) => {
209                    if selected_puzzles[$day - 1] {
210                        println!("Day {}: {}", $day, $title);
211
212                        const INPUT: &str =
213                            include_str!(concat!(#resources_directory, "/", $puzzle, #input_extension));
214                        let answers = puzzle_answers.get($puzzle).expect("Puzzle answer not found");
215
216                        pretty_solution($puzzle, 1, $solution1, INPUT, answers[0]);
217
218                        $(pretty_solution($puzzle, 2, $solution2, INPUT, answers[1]);)?
219
220                        println!();
221                    }
222                };
223            }
224
225            #input_fn
226        }
227    }
228    .into()
229}