compile-time-macros 0.3.2

Macros for getting compile time information.
Documentation
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! This crate provides macros for getting compile time information.
//!
//! This crate should not be used directly; use [`compile-time`](https://docs.rs/compile-time) instead.

extern crate proc_macro;

use proc_macro::TokenStream;
use quote::{format_ident, quote, ToTokens};

mod command;
#[cfg(feature = "time")]
mod datetime;
#[cfg(feature = "version")]
mod version;

/// Returns the compile date as [`time::Date`].
///
/// By default, the returned date is in UTC, call `date!(local)`
/// to return the local date.
///
/// # Example
///
/// Get the UTC date:
///
/// ```
/// const COMPILE_DATE: time::Date = compile_time::date!();
///
/// let year = COMPILE_DATE.year();
/// let month = COMPILE_DATE.month();
/// let day = COMPILE_DATE.day();
/// println!("Compiled on {month} {day}, {year}.");
/// ```
///
/// Get the date for the local time zone:
///
/// ```
/// const COMPILE_DATE: time::Date = compile_time::date!(local);
///
/// let year = COMPILE_DATE.year();
/// let month = COMPILE_DATE.month();
/// let day = COMPILE_DATE.day();
/// println!("Compiled on {month} {day}, {year}.");
/// ```
#[cfg(feature = "time")]
#[proc_macro]
pub fn date(input: TokenStream) -> TokenStream {
  use syn::parse_macro_input;

  use datetime::TimeInput;

  let input = parse_macro_input!(input as TimeInput);
  let now = match input.now() {
    Ok(now) => now,
    Err(err) => return err.into_compile_error().into(),
  };

  let date = now.date();

  let year = date.year();
  let month = format_ident!("{}", format!("{:?}", date.month()));
  let day = date.day();

  let time_prefix = quote! { ::compile_time::__re_exports::time };
  quote! {
    const {
      match #time_prefix::Date::from_calendar_date(#year, #time_prefix::Month::#month, #day) {
        Ok(date) => date,
        _ => ::core::unreachable!(),
      }
    }
  }
  .into()
}

/// Returns the compile date as `&'static str` in `yyyy-MM-dd` format.
///
/// By default, the returned date is in UTC, call `date_str!(local)`
/// to return the local date.
///
/// # Example
///
/// Get the UTC date:
///
/// ```
/// const COMPILE_DATE: time::Date = compile_time::date!();
///
/// let year = COMPILE_DATE.year();
/// let month: u8 = COMPILE_DATE.month().into();
/// let day = COMPILE_DATE.day();
/// let date_string = format!("{year:04}-{month:02}-{day:02}");
///
/// assert_eq!(compile_time::date_str!(), date_string);
/// ```
///
/// Get the date for the local time zone:
///
/// ```
/// const COMPILE_DATE: time::Date = compile_time::date!(local);
///
/// let year = COMPILE_DATE.year();
/// let month: u8 = COMPILE_DATE.month().into();
/// let day = COMPILE_DATE.day();
/// let date_string = format!("{year:04}-{month:02}-{day:02}");
///
/// assert_eq!(compile_time::date_str!(local), date_string);
/// ```
#[cfg(feature = "time")]
#[proc_macro]
pub fn date_str(input: TokenStream) -> TokenStream {
  use syn::parse_macro_input;
  use time::macros::format_description;

  use datetime::TimeInput;

  let input = parse_macro_input!(input as TimeInput);
  let now = match input.now() {
    Ok(now) => now,
    Err(err) => return err.into_compile_error().into(),
  };

  let date = now.date();

  let fmt = format_description!("[year]-[month]-[day]");
  let date_str = date.format(&fmt).unwrap();

  quote! { #date_str }.into()
}

/// Returns the compile time as [`time::Time`].
///
/// By default, the returned time is in UTC, call `time!(local)`
/// to return the local time.
///
/// # Example
///
/// Get the UTC time:
///
/// ```
/// const COMPILE_TIME: time::Time = compile_time::time!();
///
/// let hour = COMPILE_TIME.hour();
/// let minute = COMPILE_TIME.minute();
/// let second = COMPILE_TIME.second();
/// println!("Compiled at {hour:02}:{minute:02}:{second:02}.");
/// ```
///
/// Get the time for the local time zone:
///
/// ```
/// const COMPILE_TIME: time::Time = compile_time::time!(local);
///
/// let hour = COMPILE_TIME.hour();
/// let minute = COMPILE_TIME.minute();
/// let second = COMPILE_TIME.second();
/// println!("Compiled at {hour:02}:{minute:02}:{second:02}.");
/// ```
#[cfg(feature = "time")]
#[proc_macro]
pub fn time(input: TokenStream) -> TokenStream {
  use syn::parse_macro_input;

  use datetime::TimeInput;

  let input = parse_macro_input!(input as TimeInput);
  let now = match input.now() {
    Ok(now) => now,
    Err(err) => return err.into_compile_error().into(),
  };

  let time = now.time();

  let hour = time.hour();
  let minute = time.minute();
  let second = time.second();

  let time_prefix = quote! { ::compile_time::__re_exports::time };
  quote! {
    const {
      match #time_prefix::Time::from_hms(#hour, #minute, #second) {
        Ok(time) => time,
        _ => ::core::unreachable!(),
      }
    }
  }
  .into()
}

/// Returns the compile time as `&'static str` in `hh:mm:ss` format.
///
/// By default, the returned time is in UTC, call `time_str!(local)`
/// to return the local time.
///
/// # Example
///
/// Get the UTC time:
///
/// ```
/// const COMPILE_TIME: time::Time = compile_time::time!();
///
/// let hour = COMPILE_TIME.hour();
/// let minute = COMPILE_TIME.minute();
/// let second = COMPILE_TIME.second();
/// let time_string = format!("{hour:02}:{minute:02}:{second:02}");
///
/// assert_eq!(compile_time::time_str!(), time_string);
/// ```
///
/// Get the time for the local time zone:
///
/// ```
/// const COMPILE_TIME: time::Time = compile_time::time!(local);
///
/// let hour = COMPILE_TIME.hour();
/// let minute = COMPILE_TIME.minute();
/// let second = COMPILE_TIME.second();
/// let time_string = format!("{hour:02}:{minute:02}:{second:02}");
///
/// assert_eq!(compile_time::time_str!(local), time_string);
/// ```
#[cfg(feature = "time")]
#[proc_macro]
pub fn time_str(input: TokenStream) -> TokenStream {
  use syn::parse_macro_input;
  use time::macros::format_description;

  use datetime::TimeInput;

  let input = parse_macro_input!(input as TimeInput);
  let now = match input.now() {
    Ok(now) => now,
    Err(err) => return err.into_compile_error().into(),
  };

  let time = now.time();

  let fmt = format_description!("[hour]:[minute]:[second]");
  let time_str = time.format(&fmt).unwrap();

  quote! { #time_str }.into()
}

/// Returns the compile date and time as [`time::OffsetDateTime`].
///
/// By default, the returned datetime is in UTC, call `datetime!(local)`
/// to return the local date and time.
///
/// # Example
///
/// Get the UTC date and time:
///
/// ```
/// const COMPILE_DATETIME: time::OffsetDateTime = compile_time::datetime!();
///
/// let year = COMPILE_DATETIME.year();
/// let month = COMPILE_DATETIME.month();
/// let day = COMPILE_DATETIME.day();
/// let hour = COMPILE_DATETIME.hour();
/// let minute = COMPILE_DATETIME.minute();
/// let second = COMPILE_DATETIME.second();
/// println!("Compiled at {hour:02}:{minute:02}:{second:02} on {month} {day}, {year}.");
/// #
/// # // Evaluation is only done once.
/// # std::thread::sleep(std::time::Duration::from_secs(1));
/// # assert_eq!(COMPILE_DATETIME, compile_time::datetime!());
/// #
/// # // Additional sanity check.
/// # let now = time::OffsetDateTime::now_utc();
/// # let yesterday = now.saturating_sub(time::Duration::days(1));
/// # assert!(COMPILE_DATETIME > yesterday);
/// # assert!(COMPILE_DATETIME < now);
/// ```
///
/// Get the date and time for the local time zone:
///
/// ```
/// const COMPILE_DATETIME: time::OffsetDateTime = compile_time::datetime!(local);
///
/// let year = COMPILE_DATETIME.year();
/// let month = COMPILE_DATETIME.month();
/// let day = COMPILE_DATETIME.day();
/// let hour = COMPILE_DATETIME.hour();
/// let minute = COMPILE_DATETIME.minute();
/// let second = COMPILE_DATETIME.second();
/// println!("Compiled at {hour:02}:{minute:02}:{second:02} on {month} {day}, {year}.");
/// ```
#[cfg(feature = "time")]
#[proc_macro]
pub fn datetime(input: TokenStream) -> TokenStream {
  use syn::parse_macro_input;

  use datetime::TimeInput;

  let input = parse_macro_input!(input as TimeInput);
  let now = match input.now() {
    Ok(now) => now,
    Err(err) => return err.into_compile_error().into(),
  };

  let datetime = now;

  let year = datetime.year();
  let month = format_ident!("{}", format!("{:?}", datetime.month()));
  let day = datetime.day();

  let hour = datetime.hour();
  let minute = datetime.minute();
  let second = datetime.second();

  let time_prefix = quote! { ::compile_time::__re_exports::time };
  let date = quote! {
    match #time_prefix::Date::from_calendar_date(#year, #time_prefix::Month::#month, #day) {
      Ok(date) => date,
      _ => ::core::unreachable!(),
    }
  };

  let time = quote! {
    match #time_prefix::Time::from_hms(#hour, #minute, #second) {
      Ok(time) => time,
      _ => ::core::unreachable!(),
    }
  };

  quote! {
    const { #time_prefix::PrimitiveDateTime::new(#date, #time).assume_utc() }
  }
  .into()
}

/// Returns the compile date and time as `&'static str` in `yyyy-MM-ddThh:mm:ssZ` format.
///
/// By default, the returned datetime is in UTC, call `datetime_str!(local)`
/// to return the local date and time.
///
/// # Example
///
/// Get the UTC date and time:
///
/// ```
/// const COMPILE_DATE_STRING: &str = compile_time::date_str!();
/// const COMPILE_TIME_STRING: &str = compile_time::time_str!();
///
/// let datetime_string = format!("{COMPILE_DATE_STRING}T{COMPILE_TIME_STRING}Z");
/// assert_eq!(compile_time::datetime_str!(), datetime_string);
/// ```
///
/// Get the date and time for the local time zone:
///
/// ```
/// const COMPILE_DATE_STRING: &str = compile_time::date_str!(local);
/// const COMPILE_TIME_STRING: &str = compile_time::time_str!(local);
///
/// let datetime_string = format!("{COMPILE_DATE_STRING}T{COMPILE_TIME_STRING}Z");
/// assert_eq!(compile_time::datetime_str!(local), datetime_string);
/// ```
#[cfg(feature = "time")]
#[proc_macro]
pub fn datetime_str(input: TokenStream) -> TokenStream {
  use syn::parse_macro_input;
  use time::macros::format_description;

  use datetime::TimeInput;

  let input = parse_macro_input!(input as TimeInput);
  let now = match input.now() {
    Ok(now) => now,
    Err(err) => return err.into_compile_error().into(),
  };

  let datetime = now;

  let fmt = format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]Z");
  let datetime_str = datetime.format(&fmt).unwrap();

  quote! { #datetime_str }.into()
}

/// Returns the compile date and time as UNIX timestamp in seconds.
///
/// # Example
///
/// ```
/// const COMPILE_DATETIME: time::OffsetDateTime = compile_time::datetime!();
///
/// assert_eq!(compile_time::unix!(), COMPILE_DATETIME.unix_timestamp());
/// ```
#[cfg(feature = "time")]
#[proc_macro]
pub fn unix(_input: TokenStream) -> TokenStream {
  let datetime = datetime::utc();

  let unix_timestamp = proc_macro2::Literal::i64_unsuffixed(datetime.unix_timestamp());

  quote! {
    #unix_timestamp
  }
  .into()
}

/// Returns the Rust compiler version as [`semver::Version`].
///
/// # Example
///
/// ```
/// const RUSTC_VERSION: semver::Version = compile_time::rustc_version!();
/// assert_eq!(RUSTC_VERSION, rustc_version::version().unwrap());
/// ```
#[cfg(feature = "version")]
#[proc_macro]
pub fn rustc_version(_item: TokenStream) -> TokenStream {
  match version::rustc() {
    Ok(rustc_version::Version { major, minor, patch, pre, build }) => {
      let semver_prefix = quote! { ::compile_time::__re_exports::semver };
      let pre = if pre.is_empty() {
        quote! { #semver_prefix::Prerelease::EMPTY }
      } else {
        let pre = pre.as_str();
        quote! {
          if let Ok(pre) = #semver_prefix::Prerelease::new(#pre) {
            pre
          } else {
            ::core::unreachable!()
          }
        }
      };

      let build = if build.is_empty() {
        quote! { #semver_prefix::BuildMetadata::EMPTY }
      } else {
        let build = build.as_str();
        quote! {
          if let Ok(build) = #semver_prefix::BuildMetadata::new(#build) {
            build
          } else {
            ::core::unreachable!()
          }
        }
      };

      quote! {
        #semver_prefix::Version {
          major: #major,
          minor: #minor,
          patch: #patch,
          pre: #pre,
          build: #build,
        }
      }
    },
    Err(err) => err.into_compile_error(),
  }
  .into()
}

/// Returns the Rust compiler version as `&'static str`.
///
/// # Example
///
/// ```
/// const RUSTC_VERSION_STRING: &str = compile_time::rustc_version_str!();
/// assert_eq!(RUSTC_VERSION_STRING, compile_time::rustc_version_str!());
/// ```
#[cfg(feature = "version")]
#[proc_macro]
pub fn rustc_version_str(_item: TokenStream) -> TokenStream {
  match version::rustc() {
    Ok(rustc_version) => {
      let rustc_version_string = rustc_version.to_string();
      quote! { #rustc_version_string }
    },
    Err(err) => err.into_compile_error(),
  }
  .into()
}

/// Returns the Rust compiler major version as integer literal.
///
/// # Example
///
/// ```
/// const RUSTC_VERSION: semver::Version = compile_time::rustc_version!();
/// assert_eq!(RUSTC_VERSION.major, compile_time::rustc_version_major!());
/// ```
#[cfg(feature = "version")]
#[proc_macro]
pub fn rustc_version_major(_item: TokenStream) -> TokenStream {
  match version::rustc() {
    Ok(rustc_version) => {
      let major = rustc_version.major;
      proc_macro2::Literal::u64_unsuffixed(major).to_token_stream()
    },
    Err(err) => err.into_compile_error(),
  }
  .into()
}

/// Returns the Rust compiler minor version as integer literal.
///
/// # Example
///
/// ```
/// const RUSTC_VERSION: semver::Version = compile_time::rustc_version!();
/// assert_eq!(RUSTC_VERSION.minor, compile_time::rustc_version_minor!());
/// ```
#[cfg(feature = "version")]
#[proc_macro]
pub fn rustc_version_minor(_item: TokenStream) -> TokenStream {
  match version::rustc() {
    Ok(rustc_version) => {
      let minor = rustc_version.minor;
      proc_macro2::Literal::u64_unsuffixed(minor).to_token_stream()
    },
    Err(err) => err.into_compile_error(),
  }
  .into()
}

/// Returns the Rust compiler patch version as integer literal.
///
/// # Example
///
/// ```
/// const RUSTC_VERSION: semver::Version = compile_time::rustc_version!();
/// assert_eq!(RUSTC_VERSION.minor, compile_time::rustc_version_minor!());
/// ```
#[cfg(feature = "version")]
#[proc_macro]
pub fn rustc_version_patch(_item: TokenStream) -> TokenStream {
  match version::rustc() {
    Ok(rustc_version) => {
      let patch = rustc_version.patch;
      proc_macro2::Literal::u64_unsuffixed(patch).to_token_stream()
    },
    Err(err) => err.into_compile_error(),
  }
  .into()
}

/// Returns the Rust compiler pre version as `&'static str`.
///
/// # Example
///
/// ```
/// const RUSTC_VERSION: semver::Version = compile_time::rustc_version!();
/// assert_eq!(RUSTC_VERSION.pre.as_str(), compile_time::rustc_version_pre!());
/// ```
#[cfg(feature = "version")]
#[proc_macro]
pub fn rustc_version_pre(_item: TokenStream) -> TokenStream {
  match version::rustc() {
    Ok(rustc_version) => {
      let pre = rustc_version.pre.as_str();
      quote! { #pre }
    },
    Err(err) => err.into_compile_error(),
  }
  .into()
}

/// Returns the Rust compiler build version as a `&'static str`.
///
/// # Example
///
/// ```
/// const RUSTC_VERSION: semver::Version = compile_time::rustc_version!();
/// assert_eq!(RUSTC_VERSION.build.as_str(), compile_time::rustc_version_build!());
/// ```
#[cfg(feature = "version")]
#[proc_macro]
pub fn rustc_version_build(_input: TokenStream) -> TokenStream {
  match version::rustc() {
    Ok(rustc_version) => {
      let build = rustc_version.build.as_str();
      quote! { #build }
    },
    Err(err) => err.into_compile_error(),
  }
  .into()
}

/// Runs the given command and returns its standard output as a `&'static [u8]`.
///
/// Produces a compile error if the command fails or of the output is not valid UTF-8.
///
/// # Example
///
/// ```
/// const MAGIC_NUMBER: &[u8] = compile_time::command_bytes!("echo", "42");
///
/// assert_eq!(MAGIC_NUMBER, b"42\n");
/// ```
#[proc_macro]
#[cfg(feature = "command")]
pub fn command_bytes(input: TokenStream) -> TokenStream {
  use proc_macro2::Span;
  use syn::{parse_macro_input, LitByteStr};

  use command::CommandInput;

  let input = parse_macro_input!(input as CommandInput);
  match command::output(input) {
    Ok(output) => {
      let output = LitByteStr::new(&output, Span::call_site());
      quote! { #output }.into()
    },
    Err(e) => e,
  }
}

/// Runs the given command and returns its standard output as a `&'static str`.
///
/// Produces a compile error if the command fails or of the output is not valid UTF-8.
///
/// # Example
///
/// ```
/// const MAGIC_NUMBER: &str = compile_time::command_str!("echo", "42");
///
/// assert_eq!(MAGIC_NUMBER, "42\n");
/// ```
#[proc_macro]
#[cfg(feature = "command")]
pub fn command_str(input: TokenStream) -> TokenStream {
  use proc_macro2::Span;
  use syn::{parse_macro_input, LitStr};

  use command::CommandInput;

  let input = parse_macro_input!(input as CommandInput);
  match command::output(input) {
    Ok(output) => {
      let output_string = match String::from_utf8(output) {
        Ok(string) => string,
        Err(_) => {
          return quote! {
            ::core::compile_error!("Command output is not valid UTF-8.")
          }
          .into()
        },
      };

      let output = LitStr::new(&output_string, Span::call_site());
      quote! { #output }.into()
    },
    Err(e) => e,
  }
}