Skip to content

Commit b685ada

Browse files
authored
Merge pull request #19243 from Veykril/push-qrrqsywkwyzp
Allow unsetting default cfgs
2 parents 8ff0b67 + 5e18ad0 commit b685ada

File tree

10 files changed

+96
-64
lines changed

10 files changed

+96
-64
lines changed

crates/cfg/src/cfg_expr.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,25 @@ pub enum CfgAtom {
1818
KeyValue { key: Symbol, value: Symbol },
1919
}
2020

21+
impl PartialOrd for CfgAtom {
22+
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
23+
Some(self.cmp(other))
24+
}
25+
}
26+
27+
impl Ord for CfgAtom {
28+
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
29+
match (self, other) {
30+
(CfgAtom::Flag(a), CfgAtom::Flag(b)) => a.as_str().cmp(b.as_str()),
31+
(CfgAtom::Flag(_), CfgAtom::KeyValue { .. }) => std::cmp::Ordering::Less,
32+
(CfgAtom::KeyValue { .. }, CfgAtom::Flag(_)) => std::cmp::Ordering::Greater,
33+
(CfgAtom::KeyValue { key, value }, CfgAtom::KeyValue { key: key2, value: value2 }) => {
34+
key.as_str().cmp(key2.as_str()).then(value.as_str().cmp(value2.as_str()))
35+
}
36+
}
37+
}
38+
}
39+
2140
impl fmt::Display for CfgAtom {
2241
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2342
match self {

crates/cfg/src/dnf.rs

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,9 @@ impl DnfExpr {
6666
}
6767
}
6868

69-
res.enabled.sort_unstable_by(compare);
69+
res.enabled.sort_unstable();
7070
res.enabled.dedup();
71-
res.disabled.sort_unstable_by(compare);
71+
res.disabled.sort_unstable();
7272
res.disabled.dedup();
7373
Some(res)
7474
}
@@ -114,25 +114,14 @@ impl DnfExpr {
114114
};
115115

116116
// Undo the FxHashMap randomization for consistent output.
117-
diff.enable.sort_unstable_by(compare);
118-
diff.disable.sort_unstable_by(compare);
117+
diff.enable.sort_unstable();
118+
diff.disable.sort_unstable();
119119

120120
Some(diff)
121121
})
122122
}
123123
}
124124

125-
fn compare(a: &CfgAtom, b: &CfgAtom) -> std::cmp::Ordering {
126-
match (a, b) {
127-
(CfgAtom::Flag(a), CfgAtom::Flag(b)) => a.as_str().cmp(b.as_str()),
128-
(CfgAtom::Flag(_), CfgAtom::KeyValue { .. }) => std::cmp::Ordering::Less,
129-
(CfgAtom::KeyValue { .. }, CfgAtom::Flag(_)) => std::cmp::Ordering::Greater,
130-
(CfgAtom::KeyValue { key, value }, CfgAtom::KeyValue { key: key2, value: value2 }) => {
131-
key.as_str().cmp(key2.as_str()).then(value.as_str().cmp(value2.as_str()))
132-
}
133-
}
134-
}
135-
136125
impl fmt::Display for DnfExpr {
137126
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138127
if self.conjunctions.len() != 1 {

crates/cfg/src/lib.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -148,16 +148,20 @@ pub struct CfgDiff {
148148
}
149149

150150
impl CfgDiff {
151-
/// Create a new CfgDiff. Will return None if the same item appears more than once in the set
152-
/// of both.
153-
pub fn new(enable: Vec<CfgAtom>, disable: Vec<CfgAtom>) -> Option<CfgDiff> {
154-
let mut occupied = FxHashSet::default();
155-
if enable.iter().chain(disable.iter()).any(|item| !occupied.insert(item)) {
156-
// was present
157-
return None;
151+
/// Create a new CfgDiff.
152+
pub fn new(mut enable: Vec<CfgAtom>, mut disable: Vec<CfgAtom>) -> CfgDiff {
153+
enable.sort();
154+
enable.dedup();
155+
disable.sort();
156+
disable.dedup();
157+
for i in (0..enable.len()).rev() {
158+
if let Some(j) = disable.iter().position(|atom| *atom == enable[i]) {
159+
enable.remove(i);
160+
disable.remove(j);
161+
}
158162
}
159163

160-
Some(CfgDiff { enable, disable })
164+
CfgDiff { enable, disable }
161165
}
162166

163167
/// Returns the total number of atoms changed by this diff.

crates/project-model/src/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ fn check_crate_graph(crate_graph: CrateGraph, expect: ExpectFile) {
166166
#[test]
167167
fn cargo_hello_world_project_model_with_wildcard_overrides() {
168168
let cfg_overrides = CfgOverrides {
169-
global: CfgDiff::new(Vec::new(), vec![CfgAtom::Flag(sym::test.clone())]).unwrap(),
169+
global: CfgDiff::new(Vec::new(), vec![CfgAtom::Flag(sym::test.clone())]),
170170
selective: Default::default(),
171171
};
172172
let (crate_graph, _proc_macros) =
@@ -185,7 +185,7 @@ fn cargo_hello_world_project_model_with_selective_overrides() {
185185
global: Default::default(),
186186
selective: std::iter::once((
187187
"libc".to_owned(),
188-
CfgDiff::new(Vec::new(), vec![CfgAtom::Flag(sym::test.clone())]).unwrap(),
188+
CfgDiff::new(Vec::new(), vec![CfgAtom::Flag(sym::test.clone())]),
189189
))
190190
.collect(),
191191
};

crates/project-model/src/workspace.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,7 +1521,7 @@ fn extend_crate_graph_with_sysroot(
15211521
) -> (SysrootPublicDeps, Option<CrateId>) {
15221522
let mut pub_deps = vec![];
15231523
let mut libproc_macro = None;
1524-
let diff = CfgDiff::new(vec![], vec![CfgAtom::Flag(sym::test.clone())]).unwrap();
1524+
let diff = CfgDiff::new(vec![], vec![CfgAtom::Flag(sym::test.clone())]);
15251525
for (cid, c) in sysroot_crate_graph.iter_mut() {
15261526
// uninject `test` flag so `core` keeps working.
15271527
Arc::make_mut(&mut c.cfg_options).apply_diff(diff.clone());
@@ -1599,8 +1599,7 @@ fn sysroot_to_crate_graph(
15991599
CfgAtom::Flag(sym::miri.clone()),
16001600
],
16011601
vec![],
1602-
)
1603-
.unwrap(),
1602+
),
16041603
..Default::default()
16051604
},
16061605
&WorkspaceBuildScripts::default(),
@@ -1623,8 +1622,7 @@ fn sysroot_to_crate_graph(
16231622
CfgAtom::Flag(sym::miri.clone()),
16241623
],
16251624
vec![],
1626-
)
1627-
.unwrap(),
1625+
),
16281626
..Default::default()
16291627
},
16301628
false,

crates/rust-analyzer/src/cli/analysis_stats.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ impl flags::AnalysisStats {
6969
all_targets: true,
7070
set_test: !self.no_test,
7171
cfg_overrides: CfgOverrides {
72-
global: CfgDiff::new(vec![CfgAtom::Flag(hir::sym::miri.clone())], vec![]).unwrap(),
72+
global: CfgDiff::new(vec![CfgAtom::Flag(hir::sym::miri.clone())], vec![]),
7373
selective: Default::default(),
7474
},
7575
..Default::default()

crates/rust-analyzer/src/config.rs

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use ide_db::{
1818
imports::insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
1919
SnippetCap,
2020
};
21-
use itertools::Itertools;
21+
use itertools::{Either, Itertools};
2222
use paths::{Utf8Path, Utf8PathBuf};
2323
use project_model::{
2424
CargoConfig, CargoFeatures, ProjectJson, ProjectJsonData, ProjectJsonFromCommand,
@@ -589,6 +589,10 @@ config_data! {
589589
/// avoid checking unnecessary things.
590590
cargo_buildScripts_useRustcWrapper: bool = true,
591591
/// List of cfg options to enable with the given values.
592+
///
593+
/// To enable a name without a value, use `"key"`.
594+
/// To enable a name with a value, use `"key=value"`.
595+
/// To disable, prefix the entry with a `!`.
592596
cargo_cfgs: Vec<String> = {
593597
vec!["debug_assertions".into(), "miri".into()]
594598
},
@@ -1980,27 +1984,35 @@ impl Config {
19801984
rustc_source,
19811985
extra_includes,
19821986
cfg_overrides: project_model::CfgOverrides {
1983-
global: CfgDiff::new(
1984-
self.cargo_cfgs(source_root)
1985-
.iter()
1986-
// parse any cfg setting formatted as key=value or just key (without value)
1987-
.filter_map(|s| {
1988-
let mut sp = s.splitn(2, "=");
1989-
let key = sp.next();
1990-
let val = sp.next();
1991-
key.map(|key| (key, val))
1992-
})
1993-
.map(|(key, val)| match val {
1994-
Some(val) => CfgAtom::KeyValue {
1995-
key: Symbol::intern(key),
1996-
value: Symbol::intern(val),
1997-
},
1998-
None => CfgAtom::Flag(Symbol::intern(key)),
1999-
})
2000-
.collect(),
2001-
vec![],
2002-
)
2003-
.unwrap(),
1987+
global: {
1988+
let (enabled, disabled): (Vec<_>, Vec<_>) =
1989+
self.cargo_cfgs(source_root).iter().partition_map(|s| {
1990+
s.strip_prefix("!").map_or(Either::Left(s), Either::Right)
1991+
});
1992+
CfgDiff::new(
1993+
enabled
1994+
.into_iter()
1995+
// parse any cfg setting formatted as key=value or just key (without value)
1996+
.map(|s| match s.split_once("=") {
1997+
Some((key, val)) => CfgAtom::KeyValue {
1998+
key: Symbol::intern(key),
1999+
value: Symbol::intern(val),
2000+
},
2001+
None => CfgAtom::Flag(Symbol::intern(s)),
2002+
})
2003+
.collect(),
2004+
disabled
2005+
.into_iter()
2006+
.map(|s| match s.split_once("=") {
2007+
Some((key, val)) => CfgAtom::KeyValue {
2008+
key: Symbol::intern(key),
2009+
value: Symbol::intern(val),
2010+
},
2011+
None => CfgAtom::Flag(Symbol::intern(s)),
2012+
})
2013+
.collect(),
2014+
)
2015+
},
20042016
selective: Default::default(),
20052017
},
20062018
wrap_rustc_in_build_scripts: *self.cargo_buildScripts_useRustcWrapper(source_root),

crates/rust-analyzer/src/flycheck.rs

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,14 @@ struct FlycheckActor {
244244
/// The receiver side of the channel mentioned above.
245245
command_receiver: Option<Receiver<CargoCheckMessage>>,
246246
diagnostics_cleared_for: FxHashSet<Arc<PackageId>>,
247-
diagnostics_cleared_for_all: bool,
248-
diagnostics_received: bool,
247+
diagnostics_received: DiagnosticsReceived,
248+
}
249+
250+
#[derive(PartialEq)]
251+
enum DiagnosticsReceived {
252+
Yes,
253+
No,
254+
YesAndClearedForAll,
249255
}
250256

251257
#[allow(clippy::large_enum_variant)]
@@ -276,8 +282,7 @@ impl FlycheckActor {
276282
command_handle: None,
277283
command_receiver: None,
278284
diagnostics_cleared_for: Default::default(),
279-
diagnostics_cleared_for_all: false,
280-
diagnostics_received: false,
285+
diagnostics_received: DiagnosticsReceived::No,
281286
}
282287
}
283288

@@ -354,7 +359,7 @@ impl FlycheckActor {
354359
error
355360
);
356361
}
357-
if !self.diagnostics_received {
362+
if self.diagnostics_received == DiagnosticsReceived::No {
358363
tracing::trace!(flycheck_id = self.id, "clearing diagnostics");
359364
// We finished without receiving any diagnostics.
360365
// Clear everything for good measure
@@ -396,7 +401,7 @@ impl FlycheckActor {
396401
package_id = package_id.as_ref().map(|it| &it.repr),
397402
"diagnostic received"
398403
);
399-
self.diagnostics_received = true;
404+
self.diagnostics_received = DiagnosticsReceived::Yes;
400405
if let Some(package_id) = &package_id {
401406
if self.diagnostics_cleared_for.insert(package_id.clone()) {
402407
tracing::trace!(
@@ -409,8 +414,10 @@ impl FlycheckActor {
409414
package_id: Some(package_id.clone()),
410415
});
411416
}
412-
} else if !self.diagnostics_cleared_for_all {
413-
self.diagnostics_cleared_for_all = true;
417+
} else if self.diagnostics_received
418+
!= DiagnosticsReceived::YesAndClearedForAll
419+
{
420+
self.diagnostics_received = DiagnosticsReceived::YesAndClearedForAll;
414421
self.send(FlycheckMessage::ClearDiagnostics {
415422
id: self.id,
416423
package_id: None,
@@ -445,8 +452,7 @@ impl FlycheckActor {
445452

446453
fn clear_diagnostics_state(&mut self) {
447454
self.diagnostics_cleared_for.clear();
448-
self.diagnostics_cleared_for_all = false;
449-
self.diagnostics_received = false;
455+
self.diagnostics_received = DiagnosticsReceived::No;
450456
}
451457

452458
/// Construct a `Command` object for checking the user's code. If the user

docs/book/src/configuration_generated.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,10 @@ Default:
102102

103103
List of cfg options to enable with the given values.
104104

105+
To enable a name without a value, use `"key"`.
106+
To enable a name with a value, use `"key=value"`.
107+
To disable, prefix the entry with a `!`.
108+
105109

106110
**rust-analyzer.cargo.extraArgs** (default: [])
107111

editors/code/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -825,7 +825,7 @@
825825
"title": "cargo",
826826
"properties": {
827827
"rust-analyzer.cargo.cfgs": {
828-
"markdownDescription": "List of cfg options to enable with the given values.",
828+
"markdownDescription": "List of cfg options to enable with the given values.\n\nTo enable a name without a value, use `\"key\"`.\nTo enable a name with a value, use `\"key=value\"`.\nTo disable, prefix the entry with a `!`.",
829829
"default": [
830830
"debug_assertions",
831831
"miri"

0 commit comments

Comments
 (0)