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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#![feature(proc_macro_diagnostic)]

extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro::{ Diagnostic, Level };
use proc_macro2::TokenStream as TokenStream2;
use syn::Result;
use syn::parse::{ Parse, ParseStream };
use quote::quote;
use std::env;
use std::io::prelude::*;
use std::fs::File;
use std::rc::Rc;

struct Args {
    key: syn::LitStr,
}

impl Parse for Args {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(Args {
            key: input.parse()?,
        })
    }
}

/// Macro for accessing data from the `package.metadata` section of the Cargo manifest
///
/// # Arguments
/// * `key` - A string slice of a dot-separated path to the TOML key of interest
///
/// # Example
/// Given the following `Cargo.toml`:
/// ```no_run
/// [package]
/// name = "MyApp"
/// version = "0.1.0"
///
/// [package.metadata]
/// copyright = "Copyright (c) 2019 ACME Inc."
/// ```
///
/// And the following `main.rs`:
/// ```no_run
/// #![feature(proc_macro_hygiene)]
///
/// use std::env;
/// use cargo_meta::package_metadata;
///
/// pub fn main() {
///     println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
///     println!("{}", package_metadata!("copyright"));
/// }
/// ```
///
/// Invoking `cargo run` will produce:
/// ```no_run
/// MyApp 0.1.0
/// Copyright (c) 2019 ACME Inc.
/// ```
///
/// ## TOML Support
/// This macro only supports static data:
/// * Integers
/// * Floating-point numbers
/// * Booleans
/// * Keys of tables nested below the `package.metadata` section of the manifest (if the
///   value is a supported type)
/// * Entire TOML arrays
///
/// ## Array Example
/// Given the following Cargo manifest:
/// ```no_run
/// [package.metadata.arrays]
/// some_array = [ 1, 2, 3 ]
/// ```
///
/// This is legal:
/// ```no_run
/// static ARR: [3; i64] = package_metadata!("arrays.some_array");
/// ```
///
/// It does *not* currently support accessing TOML array elements directly, though this
/// is possible.  TOML tables will not be possible without a statically keyed hashmap such
/// as the one provided by the `phf` crate.  Support *may* be added if/when Rust can
/// support static hashmaps with compile-time key errors.
#[proc_macro]
pub fn metadata(tokens: TokenStream) -> TokenStream {
    let args = syn::parse_macro_input!(tokens as Args);
    let manifest = load_manifest();

    let metadata = {
        use toml::value::Table;

        if let Some(package) = manifest.get("package") {
            if let Some(metadata) = package.get("metadata") {
                if let Some(tbl) = metadata.as_table() {
                    tbl.clone()
                } else {
                    let msg = "TOML property has an incorrect type";
                    Diagnostic::new(Level::Error, msg)
                        .note(format!("key `package.metadata`"))
                        .note(format!("expected type `Table`"))
                        .note(format!("actual type `{}`", toml_typename(metadata)))
                        .emit();
                    panic!(msg)
                }
            } else {
                Table::new()
            }
        } else {
            Table::new()
        }
    };

    let key = &args.key.value();
    if let Some(value) = toml_get(&metadata, key) {
        toml_codegen(&value).into()
    } else {
        let msg = "key not present in the Cargo manifest";
        Diagnostic::new(Level::Error, msg)
            .note(format!("key `package.metadata.{}`", key))
            .emit();
        panic!(msg)
    }
}

fn load_manifest() -> toml::value::Value {
    let path = format!("{}/Cargo.toml", env::var("CARGO_MANIFEST_DIR").unwrap());
    let path = Rc::new(path);

    let mut file = {
        let path = Rc::clone(&path);
        File::open(&*path)
            .unwrap_or_else(move |err| {
                let msg = "error occurred opening Cargo manifest";
                Diagnostic::new(Level::Error, msg)
                    .note(format!("{}", err))
                    .note(format!("at `{}`", *path))
                    .emit();
                panic!(msg)
            })
    };

    let mut contents = String::new();
    {
        let path = Rc::clone(&path);
        file.read_to_string(&mut contents)
            .unwrap_or_else(|err| {
                let msg = "error occurred reading Cargo manifest";
                Diagnostic::new(Level::Error, msg)
                    .note(format!("{}", err))
                    .note(format!("at `{}`", *path))
                    .emit();
                panic!(msg)
            });
    }

    toml::from_str(&contents)
        .unwrap_or_else(|err| {
            let msg = "failed to parse Cargo manifest";
            Diagnostic::new(Level::Error, msg)
                .note(format!("{}", err))
                .note(format!("at `{}`", *path))
                .emit();
            panic!(msg)
        })
}

fn toml_get(mut tbl: &toml::value::Table, key: &str) -> Option<toml::value::Value> {
    use toml::value::Value;

    let key_parts: Vec<_> = key.split(".").collect();
    let mut ret = Value::Table(tbl.clone());

    for key in key_parts.iter() {
        match tbl.get(key.clone())? {
            Value::Table(tbl2) => {
                tbl = tbl2;
            },

            value => {
                ret = value.clone();
            },
        }
    }

    Some(ret)
}

fn toml_codegen(value: &toml::value::Value) -> TokenStream2 {
    use toml::value::Value;
    use Value::*;
    match value {
        String(s) => quote! {{
            cargo_meta::id::<&str>(#s)
        }},

        Integer(i) => quote! {{
            cargo_meta::id::<i64>(#i)
        }},

        Float(f) => quote! {{
            cargo_meta::id::<f64>(#f)
        }},

        Boolean(b) => quote! {{
            cargo_meta::id::<bool>(#b)
        }},

        Array(a) => toml_array_codegen(a),

        Table(_t) => {
            let msg = "TOML tables are not supported";
            Diagnostic::new(Level::Error, msg)
                .note(format!("this would require statically keyed hash tables"))
                .emit();
            panic!(msg)
        },

        Datetime(d) => {
            let msg = "TOML dates are emitted as `&'static str`";
            Diagnostic::new(Level::Warning, msg)
                .note(format!("there are no const constructors for `Datetime`"))
                .emit();

            let date_str = toml::ser::to_string(d).unwrap();
            quote! {{
                #date_str
            }}
        },
    }
}

fn toml_typename(value: &toml::value::Value) -> &'static str {
    use toml::value::Value::*;
    match value {
        String(_)   => "String",
        Integer(_)  => "Integer",
        Float(_)    => "Float",
        Boolean(_)  => "Boolean",
        Datetime(_) => "Datetime",
        Array(_)    => "Array",
        Table(_)    => "Table",
    }
}

fn toml_array_codegen(arr: &toml::value::Array) -> TokenStream2 {
    let statements = emit_array_items(arr);
    let emit = quote! {{
        [
            #statements
        ]
    }};

    emit.into()
}

fn emit_array_items(arr: &toml::value::Array) -> TokenStream2 {
    arr.iter().flat_map(|val| {
        let val = toml_codegen(val);
        quote! {
            #val,
        }
    }).collect()
}