Skip to content

Commit ffe0a1c

Browse files
authored
Rollup merge of #71314 - mibac138:cfg-version, r=petrochenkov
Implement RFC 2523, `#[cfg(version(..))]` Hi! This is my first contribution to rust, I hope I didn't miss anything. I tried to implement this feature so that `#[cfg(version(1.44.0))]` works but the parser was printing an error that I wasn't sure how to fix so I just opted for implementing `#[cfg(version("1.44.0"))]` (note the quotes). Tracking issue: #64796
2 parents 8cb8d9c + 8a77d1c commit ffe0a1c

File tree

12 files changed

+283
-19
lines changed

12 files changed

+283
-19
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -3593,6 +3593,7 @@ dependencies = [
35933593
"rustc_session",
35943594
"rustc_span",
35953595
"serialize",
3596+
"version_check",
35963597
]
35973598

35983599
[[package]]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# `cfg_version`
2+
3+
The tracking issue for this feature is: [#64796]
4+
5+
[#64796]: https://github.com/rust-lang/rust/issues/64796
6+
7+
------------------------
8+
9+
The `cfg_version` feature makes it possible to execute different code
10+
depending on the compiler version.
11+
12+
## Examples
13+
14+
```rust
15+
#![feature(cfg_version)]
16+
17+
#[cfg(version("1.42"))]
18+
fn a() {
19+
// ...
20+
}
21+
22+
#[cfg(not(version("1.42")))]
23+
fn a() {
24+
// ...
25+
}
26+
27+
fn b() {
28+
if cfg!(version("1.42")) {
29+
// ...
30+
} else {
31+
// ...
32+
}
33+
}
34+
```

src/librustc_attr/Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ authors = ["The Rust Project Developers"]
33
name = "rustc_attr"
44
version = "0.0.0"
55
edition = "2018"
6+
build = "build.rs"
67

78
[lib]
89
name = "rustc_attr"
@@ -19,3 +20,4 @@ rustc_feature = { path = "../librustc_feature" }
1920
rustc_macros = { path = "../librustc_macros" }
2021
rustc_session = { path = "../librustc_session" }
2122
rustc_ast = { path = "../librustc_ast" }
23+
version_check = "0.9"

src/librustc_attr/build.rs

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
fn main() {
2+
println!("cargo:rerun-if-changed=build.rs");
3+
println!("cargo:rerun-if-env-changed=CFG_VERSION");
4+
}

src/librustc_attr/builtin.rs

+50-13
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use super::{find_by_name, mark_used};
44

5-
use rustc_ast::ast::{self, Attribute, MetaItem, MetaItemKind, NestedMetaItem};
5+
use rustc_ast::ast::{self, Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem};
66
use rustc_ast_pretty::pprust;
77
use rustc_errors::{struct_span_err, Applicability, Handler};
88
use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
@@ -11,6 +11,7 @@ use rustc_session::parse::{feature_err, ParseSess};
1111
use rustc_span::hygiene::Transparency;
1212
use rustc_span::{symbol::sym, symbol::Symbol, Span};
1313
use std::num::NonZeroU32;
14+
use version_check::Version;
1415

1516
pub fn is_builtin_attr(attr: &Attribute) -> bool {
1617
attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
@@ -568,11 +569,8 @@ pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
568569

569570
/// Tests if a cfg-pattern matches the cfg set
570571
pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
571-
eval_condition(cfg, sess, &mut |cfg| {
572-
let gate = find_gated_cfg(|sym| cfg.check_name(sym));
573-
if let (Some(feats), Some(gated_cfg)) = (features, gate) {
574-
gate_cfg(&gated_cfg, cfg.span, sess, feats);
575-
}
572+
eval_condition(cfg, sess, features, &mut |cfg| {
573+
try_gate_cfg(cfg, sess, features);
576574
let error = |span, msg| {
577575
sess.span_diagnostic.span_err(span, msg);
578576
true
@@ -603,6 +601,13 @@ pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Feat
603601
})
604602
}
605603

604+
fn try_gate_cfg(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) {
605+
let gate = find_gated_cfg(|sym| cfg.check_name(sym));
606+
if let (Some(feats), Some(gated_cfg)) = (features, gate) {
607+
gate_cfg(&gated_cfg, cfg.span, sess, feats);
608+
}
609+
}
610+
606611
fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
607612
let (cfg, feature, has_feature) = gated_cfg;
608613
if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
@@ -616,9 +621,41 @@ fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &F
616621
pub fn eval_condition(
617622
cfg: &ast::MetaItem,
618623
sess: &ParseSess,
624+
features: Option<&Features>,
619625
eval: &mut impl FnMut(&ast::MetaItem) -> bool,
620626
) -> bool {
621627
match cfg.kind {
628+
ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
629+
try_gate_cfg(cfg, sess, features);
630+
let (min_version, span) = match &mis[..] {
631+
[NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
632+
(sym, span)
633+
}
634+
[NestedMetaItem::Literal(Lit { span, .. })
635+
| NestedMetaItem::MetaItem(MetaItem { span, .. })] => {
636+
sess.span_diagnostic
637+
.struct_span_err(*span, &*format!("expected a version literal"))
638+
.emit();
639+
return false;
640+
}
641+
[..] => {
642+
sess.span_diagnostic
643+
.struct_span_err(cfg.span, "expected single version literal")
644+
.emit();
645+
return false;
646+
}
647+
};
648+
let min_version = match Version::parse(&min_version.as_str()) {
649+
Some(ver) => ver,
650+
None => {
651+
sess.span_diagnostic.struct_span_err(*span, "invalid version literal").emit();
652+
return false;
653+
}
654+
};
655+
let version = Version::parse(env!("CFG_VERSION")).unwrap();
656+
657+
version >= min_version
658+
}
622659
ast::MetaItemKind::List(ref mis) => {
623660
for mi in mis.iter() {
624661
if !mi.is_meta_item() {
@@ -634,12 +671,12 @@ pub fn eval_condition(
634671
// The unwraps below may look dangerous, but we've already asserted
635672
// that they won't fail with the loop above.
636673
match cfg.name_or_empty() {
637-
sym::any => {
638-
mis.iter().any(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
639-
}
640-
sym::all => {
641-
mis.iter().all(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval))
642-
}
674+
sym::any => mis
675+
.iter()
676+
.any(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
677+
sym::all => mis
678+
.iter()
679+
.all(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
643680
sym::not => {
644681
if mis.len() != 1 {
645682
struct_span_err!(
@@ -652,7 +689,7 @@ pub fn eval_condition(
652689
return false;
653690
}
654691

655-
!eval_condition(mis[0].meta_item().unwrap(), sess, eval)
692+
!eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
656693
}
657694
_ => {
658695
struct_span_err!(

src/librustc_attr/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
//! The goal is to move the definition of `MetaItem` and things that don't need to be in `syntax`
55
//! to this crate.
66
7+
#![feature(or_patterns)]
8+
79
mod builtin;
810

911
pub use builtin::*;

src/librustc_feature/active.rs

+3
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,9 @@ declare_features! (
562562
/// Allows the use of `#[target_feature]` on safe functions.
563563
(active, target_feature_11, "1.45.0", Some(69098), None),
564564

565+
/// Allow conditional compilation depending on rust version
566+
(active, cfg_version, "1.45.0", Some(64796), None),
567+
565568
// -------------------------------------------------------------------------
566569
// feature-group-end: actual feature gates
567570
// -------------------------------------------------------------------------

src/librustc_feature/builtin_attrs.rs

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ const GATED_CFGS: &[GatedCfg] = &[
2626
(sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
2727
(sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
2828
(sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)),
29+
(sym::version, sym::cfg_version, cfg_fn!(cfg_version)),
2930
];
3031

3132
/// Find a gated cfg determined by the `pred`icate which is given the cfg's name.

src/librustc_span/symbol.rs

+2
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ symbols! {
192192
cfg_target_has_atomic,
193193
cfg_target_thread_local,
194194
cfg_target_vendor,
195+
cfg_version,
195196
char,
196197
clippy,
197198
clone,
@@ -805,6 +806,7 @@ symbols! {
805806
var,
806807
vec,
807808
Vec,
809+
version,
808810
vis,
809811
visible_private_types,
810812
volatile,

src/librustc_trait_selection/traits/on_unimplemented.rs

+11-6
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ impl<'tcx> OnUnimplementedDirective {
8181
None,
8282
)
8383
})?;
84-
attr::eval_condition(cond, &tcx.sess.parse_sess, &mut |_| true);
84+
attr::eval_condition(cond, &tcx.sess.parse_sess, Some(tcx.features()), &mut |_| true);
8585
Some(cond.clone())
8686
};
8787

@@ -208,11 +208,16 @@ impl<'tcx> OnUnimplementedDirective {
208208

209209
for command in self.subcommands.iter().chain(Some(self)).rev() {
210210
if let Some(ref condition) = command.condition {
211-
if !attr::eval_condition(condition, &tcx.sess.parse_sess, &mut |c| {
212-
c.ident().map_or(false, |ident| {
213-
options.contains(&(ident.name, c.value_str().map(|s| s.to_string())))
214-
})
215-
}) {
211+
if !attr::eval_condition(
212+
condition,
213+
&tcx.sess.parse_sess,
214+
Some(tcx.features()),
215+
&mut |c| {
216+
c.ident().map_or(false, |ident| {
217+
options.contains(&(ident.name, c.value_str().map(|s| s.to_string())))
218+
})
219+
},
220+
) {
216221
debug!("evaluate: skipping {:?} due to condition", command);
217222
continue;
218223
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#[cfg(version("1.44"))]
2+
//~^ ERROR `cfg(version)` is experimental and subject to change
3+
fn foo() -> bool { true }
4+
#[cfg(not(version("1.44")))]
5+
//~^ ERROR `cfg(version)` is experimental and subject to change
6+
fn foo() -> bool { false }
7+
8+
#[cfg(version("1.43", "1.44", "1.45"))] //~ ERROR: expected single version literal
9+
//~^ ERROR `cfg(version)` is experimental and subject to change
10+
fn bar() -> bool { false }
11+
#[cfg(version(false))] //~ ERROR: expected a version literal
12+
//~^ ERROR `cfg(version)` is experimental and subject to change
13+
fn bar() -> bool { false }
14+
#[cfg(version("foo"))] //~ ERROR: invalid version literal
15+
//~^ ERROR `cfg(version)` is experimental and subject to change
16+
fn bar() -> bool { false }
17+
#[cfg(version("999"))]
18+
//~^ ERROR `cfg(version)` is experimental and subject to change
19+
fn bar() -> bool { false }
20+
#[cfg(version("-1"))] //~ ERROR: invalid version literal
21+
//~^ ERROR `cfg(version)` is experimental and subject to change
22+
fn bar() -> bool { false }
23+
#[cfg(version("65536"))] //~ ERROR: invalid version literal
24+
//~^ ERROR `cfg(version)` is experimental and subject to change
25+
fn bar() -> bool { false }
26+
#[cfg(version("0"))]
27+
//~^ ERROR `cfg(version)` is experimental and subject to change
28+
fn bar() -> bool { true }
29+
30+
#[cfg(version("1.65536.2"))]
31+
//~^ ERROR `cfg(version)` is experimental and subject to change
32+
fn version_check_bug() {}
33+
34+
fn main() {
35+
// This should fail but due to a bug in version_check `1.65536.2` is interpreted as `1.2`.
36+
// See https://github.com/SergioBenitez/version_check/issues/11
37+
version_check_bug();
38+
assert!(foo());
39+
assert!(bar());
40+
assert!(cfg!(version("1.42"))); //~ ERROR `cfg(version)` is experimental and subject to change
41+
}

0 commit comments

Comments
 (0)