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
#![doc = include_str!("../README.md")]
#![warn(clippy::pedantic)]
#![warn(unused_crate_dependencies)]

use proc_macro::TokenStream;
use quote::quote;
use std::path::PathBuf;
use syn::parse::{Parse, ParseStream};
use syn::parse_macro_input;
use syn::Token;

/// Compiles the given regex using the `fancy_regex` crate and tries to match the given value. If
/// the value matches the regex, the macro will expand to the first expression. Otherwise it will
/// expand to the second expression.
///
/// It is designed to be used within other macros to produce compile time errors when the regex
/// doesn't match but it might work for other use-cases as well.
///
/// ```
/// libcnb_proc_macros::verify_regex!(
///     "^A-Z+$",
///     "foobar",
///     println!("It did match!"),
///     println!("It did not match!")
/// );
/// ```
#[proc_macro]
pub fn verify_regex(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as VerifyRegexInput);

    let token_stream = match fancy_regex::Regex::new(&input.regex.value()) {
        Ok(regex) => {
            let regex_matches = regex.is_match(&input.value.value()).unwrap_or(false);

            let expression = if regex_matches {
                input.expression_when_matched
            } else {
                input.expression_when_unmatched
            };

            quote! { #expression }
        }
        Err(err) => syn::Error::new(
            input.regex.span(),
            format!("Could not compile regular expression: {err}"),
        )
        .to_compile_error(),
    };

    token_stream.into()
}

struct VerifyRegexInput {
    regex: syn::LitStr,
    value: syn::LitStr,
    expression_when_matched: syn::Expr,
    expression_when_unmatched: syn::Expr,
}

impl Parse for VerifyRegexInput {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let regex: syn::LitStr = input.parse()?;
        input.parse::<Token![,]>()?;
        let value: syn::LitStr = input.parse()?;
        input.parse::<Token![,]>()?;
        let expression_when_matched: syn::Expr = input.parse()?;
        input.parse::<Token![,]>()?;
        let expression_when_unmatched: syn::Expr = input.parse()?;

        Ok(Self {
            regex,
            value,
            expression_when_matched,
            expression_when_unmatched,
        })
    }
}

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

    let cargo_metadata = std::env::var("CARGO_MANIFEST_DIR")
        .map(PathBuf::from)
        .ok()
        .map(|cargo_manifest_dir| {
            cargo_metadata::MetadataCommand::new()
                .manifest_path(cargo_manifest_dir.join("Cargo.toml"))
                .exec()
        })
        .transpose();

    let token_stream = if let Ok(Some(cargo_metadata)) = cargo_metadata {
        if let Some(root_package) = cargo_metadata.root_package() {
            let valid_target = root_package
                .targets
                .iter()
                .any(|target| target.name == input.target_name.value());

            let expression = if valid_target {
                input.expression_when_matched
            } else {
                input.expression_when_unmatched
            };

            quote! {
                #expression
            }
        } else {
            quote! {
                compile_error!("Cannot read root package for this crate!")
            }
        }
    } else {
        quote! {
            compile_error!("Cannot read Cargo metadata!")
        }
    };

    token_stream.into()
}

struct VerifyBinTargetExistsInput {
    target_name: syn::LitStr,
    expression_when_matched: syn::Expr,
    expression_when_unmatched: syn::Expr,
}

impl Parse for VerifyBinTargetExistsInput {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let target_name: syn::LitStr = input.parse()?;
        input.parse::<Token![,]>()?;
        let expression_when_matched: syn::Expr = input.parse()?;
        input.parse::<Token![,]>()?;
        let expression_when_unmatched: syn::Expr = input.parse()?;

        Ok(Self {
            target_name,
            expression_when_matched,
            expression_when_unmatched,
        })
    }
}