featurecomb 0.2.0

Define feature groups and enforce relations between Cargo features from your manifest
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
//! featurecomb allows you to define groups of [Cargo
//! features](https://doc.rust-lang.org/cargo/reference/features.html) and define different
//! kinds of relations between features and these feature groups from your [crate's
//! manifest](https://doc.rust-lang.org/cargo/reference/manifest.html), and enforce them at compile
//! time.
//!
//! # Installation
//!
//! Simply add `featurecomb` as a dependency to your crate.
//!
//! # Usage
//!
//! Define feature groups and feature relations in your manifest [`metadata`
//! table](https://doc.rust-lang.org/cargo/reference/manifest.html#the-metadata-table)
//! as explained below, and use the [`#[featurecomb::comb]`](macro@crate::comb) attribute macro in
//! your crate top module to have these checked automatically at compile time.
//!
//! ## How it works
//!
//! featurecomb generates compile-time checks using [`#[cfg]`-gated `compile_error!`
//! statements](https://doc.rust-lang.org/cargo/reference/features.html#mutually-exclusive-features)
//! so that the requirements defined are checked by the compiler.
//!
//! ## Feature groups
//!
//! Feature groups are defined in the `[package.metadata.feature-groups]` table.
//! They do not live in the same namespace as features, i.e., feature groups can be named the same
//! as existing features and will not conflict with them.
//!
//! ### Marking features as mutually exclusive: `$group.xor`
//!
//! Features of a group can be marked as mutually exclusive using the `xor` table:
//!
//! ```
//! # r#"
//! # [package]
//! # name = "example"
//! #
//! [package.metadata.feature-groups]
//! openssl.xor = { features = ["native-openssl", "vendored-openssl"] }
//! # "#;
//! ```
//!
//! Performance note: the number of [generated checks](#how-it-works) increases quadratically with
//! the number of features in the group.
//!
//! ### Requiring exactly one feature: `$group.exactly-one`
//!
//! When features of a group are mutually exclusive but one must always be enabled, the
//! `exactly-one` table is to be used instead:
//!
//! ```
//! # r#"
//! # [package]
//! # name = "example"
//! #
//! [package.metadata.feature-groups]
//! llvm-version.exactly-one = { features = ["llvm-16", "llvm-17", "llvm-18"] }
//! # "#;
//! ```
//!
//! Performance note: the number of [generated checks](#how-it-works) increases quadratically with
//! the number of features in the group.
//!
//! ### Defining a feature group with no relations
//!
//! A feature group can also be defined without enforcing any relations between the features of
//! that group:
//!
//! ```
//! # r#"
//! # [package]
//! # name = "example"
//! #
//! [package.metadata.feature-groups]
//! ip-version = { features = ["ipv4", "ipv6"] }
//! # "#;
//! ```
//!
//! This is useful so that the group can be [*required* by a
//! feature](#requiring-groups-and-features-featurerequires), to express an "at least one"
//! relation.
//!
//! ## Features
//!
//! Feature relations are defined in the `[package.metadata.feature-groups.features]` table.
//! They define relations for features already existing in the standard
//! [`[features]`](https://doc.rust-lang.org/cargo/reference/features.html#the-features-section)
//! table.
//!
//! ### Requiring groups and features: `$feature.requires`
//!
//! The `requires` table on a feature *requires* that the features and features groups listed be
//! enabled when that feature is enabled:
//!
//! ```
//! # r#"
//! # [package]
//! # name = "example"
//! #
//! [package.metadata.feature-groups.features]
//! tls.requires = { groups = ["openssl", "tls-version"] }
//! # "#;
//! ```
//!
//! ```
//! # r#"
//! # [package]
//! # name = "example"
//! #
//! [package.metadata.feature-groups.features]
//! usb-hid.requires = { features = ["usb"] }
//! # "#;
//! ```
//!
//! It is possible to use the `groups` and `features` keys at the same time, in which case all
//! features and feature groups listed are *required*.
//!
//! # Example
//!
//! See the `examples` directory in the repository, which contains a playground to try out the
//! following example:
//!
//! ```
//! # r#"
//! # [package]
//! # name = "example"
//! #
//! [package.metadata.feature-groups]
//! ip-version = { features = ["ipv4", "ipv6"] }
//! llvm-version.exactly-one = { features = ["llvm-16", "llvm-17", "llvm-18"] }
//! openssl.xor = { features = ["native-openssl", "vendored-openssl"] }
//! tls-version = { features = ["tls-12", "tls-13"] }
//!
//! [package.metadata.feature-groups.features]
//! tls.requires = { groups = ["openssl", "tls-version"] }
//! usb-hid.requires = { features = ["usb"] }
//!
//! [features]
//! ipv4 = []
//! ipv6 = []
//!
//! llvm-16 = []
//! llvm-17 = []
//! llvm-18 = []
//!
//! usb = []
//! usb-hid = []
//!
//! tls = []
//! tls-12 = []
//! tls-13 = []
//! native-openssl = []
//! vendored-openssl = []
//! # "#;
//! ```
//!
//! # Compatibility
//!
//! The error messages generated by this crate should not be considered stable.

mod manifest;

use std::{fs, path::Path};

use featurecomb_schema as schema;
use proc_macro::TokenStream;
use quote::quote;

use crate::manifest::Manifest;

const MANIFEST_FILE_NAME: &str = "Cargo.toml";

/// This macro reads the feature groups and the feature relations defined in your crate's manifest,
/// and enforces them at compile time.
///
/// It needs to be applied to a dummy item in your crate's top module.
/// This dummy item will be discarded by this macro.
/// An empty inline module can be used for this purpose, as follows:
///
/// ```
/// #[featurecomb::comb]
/// mod _featurecomb {}
/// ```
///
/// When [issue #54726](https://github.com/rust-lang/rust/issues/54726) is resolved, it should be
/// possible to use this macro as an inner attribute, at crate root.
#[expect(clippy::missing_panics_doc)]
#[proc_macro_attribute]
pub fn comb(_attr: TokenStream, _item: TokenStream) -> TokenStream {
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
    let manifest_path = Path::new(&manifest_dir).join(MANIFEST_FILE_NAME);

    let manifest =
        fs::read_to_string(manifest_path).expect("the crate manifest should not disappear");

    let checks = generate_checks_from_manifest(&manifest);

    TokenStream::from(quote! { #(#checks)* })
}

fn generate_checks_from_manifest(manifest: &str) -> Vec<proc_macro2::TokenStream> {
    let manifest = match Manifest::<schema::Metadata>::from_str(manifest) {
        Ok(manifest) => manifest,
        Err(manifest::Error::Parse(err)) => {
            panic!("the crate manifest `metadata.features-group` subtable should conform to the expected schema\n{err}");
        }
    };

    let feature_groups = get_feature_groups(&manifest);

    let Some(feature_groups) = feature_groups else {
        return Vec::new();
    };

    check_feature_existence(manifest.features.as_ref(), feature_groups);

    let mut checks = Vec::new();

    if let Some(feature_table) = &feature_groups.features {
        for (feature_name, feature_relations) in feature_table.iter() {
            checks.extend(generate_feature_relation_checks(
                feature_groups,
                feature_name,
                feature_relations,
            ));
        }
    }

    for (feature_group_name, feature_group) in &feature_groups.groups {
        checks.extend(generate_group_checks(
            feature_groups,
            feature_group_name,
            feature_group,
        ));
    }

    checks
}

// Implicit features are not supported, as [they are expected to be
// removed](https://github.com/rust-lang/cargo/issues/12826).
fn check_feature_existence(
    feature_set: Option<&manifest::FeatureSet>,
    feature_groups: &schema::FeatureGroups,
) {
    use schema::FeatureRelations;

    let Some(feature_set) = feature_set else {
        return;
    };

    for (feature_group_name, feature_group) in &feature_groups.groups {
        if let Some(features) = feature_group.features() {
            let undefined_feature = features
                .iter()
                .find(|f| !is_feature_defined(feature_set, f));

            if let Some(undefined_feature) = undefined_feature {
                panic!(
                    "feature `{}` referenced in feature group `{}` is not defined",
                    undefined_feature.name(),
                    feature_group_name.name(),
                );
            }
        }
    }

    let Some(feature_table) = &feature_groups.features else {
        return;
    };

    for (feature_name, feature_relations) in feature_table.iter() {
        assert!(
            is_feature_defined(feature_set, feature_name),
            "feature `{}` referenced in `feature-groups.features` is not defined",
            feature_name.name(),
        );

        match feature_relations {
            FeatureRelations::Requires {
                features: Some(features),
                ..
            } => {
                for f in features {
                    assert!(
                        is_feature_defined(feature_set, f),
                        "feature `{}` referenced in `feature-groups.features.{}.requires` is not defined",
                        f.name(),
                        feature_name.name(),
                    );
                }
            }
            FeatureRelations::Requires { features: None, .. } => {}
        }
    }
}

fn is_feature_defined(
    feature_set: &manifest::FeatureSet,
    feature_name: &schema::FeatureName,
) -> bool {
    feature_set.contains_key(feature_name.name())
}

fn generate_feature_relation_checks(
    feature_groups: &schema::FeatureGroups,
    feature_name: &schema::FeatureName,
    feature_relations: &schema::FeatureRelations,
) -> Vec<proc_macro2::TokenStream> {
    use schema::FeatureRelations;

    let mut checks = Vec::new();

    if let FeatureRelations::Requires {
        groups: Some(required_groups),
        ..
    } = feature_relations
    {
        for required_group in required_groups {
            let required_features = feature_groups
                .features_in_group(required_group)
                .collect::<Vec<_>>();

            let required_group = required_group.name();
            let candidates = format_candidate_features(required_features.iter().copied());

            let error_message = format!(
                "feature `{}` requires that some features from feature group `{required_group}` be enabled.
Candidate features: {candidates}",
                feature_name.name(),
            );

            let feature = feature_name.name();
            let required_features = required_features.into_iter().map(schema::FeatureName::name);

            let check = quote! {
                #[cfg(all(feature = #feature, not(any(#(feature = #required_features),*))))]
                compile_error!(#error_message);
            };
            checks.push(check);
        }
    }

    if let FeatureRelations::Requires {
        features: Some(required_features),
        ..
    } = feature_relations
    {
        for required_feature in required_features {
            let error_message = format!(
                "feature `{}` requires that feature `{}` be enabled as well",
                feature_name.name(),
                required_feature.name(),
            );

            let feature = feature_name.name();
            let required_feature = required_feature.name();

            let check = quote! {
                #[cfg(all(feature = #feature, not(feature = #required_feature)))]
                compile_error!(#error_message);
            };
            checks.push(check);
        }
    }

    checks
}

fn format_candidate_features<'a>(
    features: impl Iterator<Item = &'a schema::FeatureName>,
) -> String {
    let candidates = features
        .map(|f| format!("`{}`", f.name()))
        .collect::<Vec<_>>();
    candidates.join(", ")
}

fn generate_group_checks(
    feature_groups: &schema::FeatureGroups,
    feature_group_name: &schema::FeatureGroupName,
    feature_group: &schema::FeatureGroup,
) -> Vec<proc_macro2::TokenStream> {
    use schema::FeatureGroup;

    let features = feature_groups
        .features_in_group(feature_group_name)
        .collect::<Vec<_>>();

    if features.len() <= 1 {
        return Vec::new();
    }

    let mut checks = Vec::new();

    match feature_group {
        FeatureGroup::ExactlyOne { .. } | FeatureGroup::Xor { .. } => {
            let mut i = 0;

            for feature_a in &features {
                for feature_b in features.iter().skip(i) {
                    if feature_a == feature_b {
                        continue;
                    }

                    let feature_a = feature_a.name();
                    let feature_b = feature_b.name();

                    let error_message = format!(
                        "features `{feature_a}` and `{feature_b}` are part of the `{}` feature group and cannot be enabled at the same time",
                        feature_group_name.name(),
                    );
                    let check = quote! {
                        #[cfg(all(feature = #feature_a, feature = #feature_b))]
                        compile_error!(#error_message);
                    };
                    checks.push(check);
                    i += 1;
                }
            }
        }
        FeatureGroup::Or { .. } => {
            // No check to issue
        }
    }

    if matches!(feature_group, FeatureGroup::ExactlyOne { .. }) {
        let candidates = format_candidate_features(features.iter().copied());
        let features = features.into_iter().map(schema::FeatureName::name);
        let error_message = format!(
            "feature group `{}` requires that one of its features be enabled.
Candidates: {candidates}",
            feature_group_name.name(),
        );
        let check = quote! {
            #[cfg(not(any(#(feature = #features),*)))]
            compile_error!(#error_message);
        };
        checks.push(check);
    }

    checks
}

fn get_feature_groups(manifest: &Manifest<schema::Metadata>) -> Option<&schema::FeatureGroups> {
    manifest
        .package
        .as_ref()?
        .metadata
        .as_ref()?
        .feature_groups
        .as_ref()
}

#[cfg(test)]
mod tests {
    use dir_test::{dir_test, Fixture};
    use insta::assert_snapshot;

    use super::*;

    #[dir_test(
        dir: "$CARGO_MANIFEST_DIR/tests/fixtures",
        glob: "**/*.toml",
    )]
    #[expect(clippy::needless_pass_by_value)]
    fn manifest(fixture: Fixture<&str>) {
        let fixture_toml = fixture.content();
        let fixture_name = Path::new(fixture.path())
            .file_name()
            .unwrap()
            .to_string_lossy()
            .to_string();

        let checks = generate_checks_from_manifest(fixture_toml);

        let rust = checks
            .iter()
            .map(|s| prettyplease::unparse(&syn::parse_file(&s.to_string()).unwrap()))
            .collect::<Vec<_>>();
        let rust = rust.join("\n");
        assert_snapshot!(fixture_name, rust);
    }
}