Giter VIP home page Giter VIP logo

cfg-if's Introduction

cfg-if

Documentation

A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted.

[dependencies]
cfg-if = "1.0"

Example

cfg_if::cfg_if! {
    if #[cfg(unix)] {
        fn foo() { /* unix specific functionality */ }
    } else if #[cfg(target_pointer_width = "32")] {
        fn foo() { /* non-unix, 32-bit functionality */ }
    } else {
        fn foo() { /* fallback implementation */ }
    }
}

fn main() {
    foo();
}

The cfg_if! block above is expanded to:

#[cfg(unix)]
fn foo() { /* unix specific functionality */ }
#[cfg(all(target_pointer_width = "32", not(unix)))]
fn foo() { /* non-unix, 32-bit functionality */ }
#[cfg(not(any(unix, target_pointer_width = "32")))]
fn foo() { /* fallback implementation */ }        

License

This project is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in cfg-if by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

cfg-if's People

Contributors

alexcrichton avatar atouchet avatar billyrieger avatar camsteffen avatar clarfonthey avatar dependabot-preview[bot] avatar dependabot[bot] avatar dhylands avatar guillaumegomez avatar johntitor avatar joycebrum avatar lokathor avatar mgeisler avatar msmorgan avatar nasso avatar stoeckmann avatar tgross35 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cfg-if's Issues

Allow in expression position

Summary:

This macro is currently allowed for statements, but is not allowed as an expression. But, I think it could work as an expression.

Repro:

Try this short program:

use cfg_if::cfg_if;

fn main() {
	let value = cfg_if! {
        if #[cfg(feature = "testfeature")] {
            3 // No `debug` library
        } else {
            4
        }
    };
    println!("Value {}", value);
}

It will fail with this long and vaguely alarming set of messages:

error: macro expansion ignores token `$crate` and any following
  --> /Users/mcc/.cargo/registry/src/github.com-1ecc6299db9ec823/cfg-if-1.0.0/src/lib.rs:79:9
   |
79 |           $crate::cfg_if! { @__items ($($not,)* $($m,)*) ; $($rest)* }
   |           ^^^^^^
   | 
  ::: src/main.rs:4:17
   |
4  |       let value = cfg_if! {
   |  _________________-
5  | |         if #[cfg(feature = "testfeature")] {
6  | |             3 // No `debug` library
7  | |         } else {
8  | |             4
9  | |         }
10 | |     };
   | |     -
   | |     |
   | |_____caused by the macro expansion here
   |       help: you might be missing a semicolon here: `;`
   |
   = note: the usage of `cfg_if!` is likely invalid in expression context

error[E0658]: attributes on expressions are experimental
  --> src/main.rs:4:14
   |
4  |       let value = cfg_if! {
   |  _________________^
5  | |         if #[cfg(feature = "testfeature")] {
6  | |             3 // No `debug` library
7  | |         } else {
8  | |             4
9  | |         }
10 | |     };
   | |_____^
   |
   = note: see issue #15701 <https://github.com/rust-lang/rust/issues/15701> for more information
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: removing an expression is not supported in this position
  --> src/main.rs:4:14
   |
4  |       let value = cfg_if! {
   |  _________________^
5  | |         if #[cfg(feature = "testfeature")] {
6  | |             3 // No `debug` library
7  | |         } else {
8  | |             4
9  | |         }
10 | |     };
   | |_____^
   |
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0658`.
error: could not compile `ifcfgtest`

Analysis:

You can actually make this work now by just wrapping an extra {} around the cfg_if expression:

fn main() {
	let value = {cfg_if! {
        if #[cfg(feature = "testfeature")] {
            3 // No `debug` library
        } else {
            4
        }
    }};
    println!("Value {}", value);
}

If you do this, rather than the cfg_if! being an expression, it is a statement inside of a block expression.

Expected behavior:

The cfg_if! macro should just wrap that extra {} around its result itself, thus making it allowed in an expression context.

`%` anywhere in project path causes "error: could not compile `cfg-if`"

I couldn't find this cause for this issue mentioned elsewhere, so I thought I'd post this to at least save some headaches.

Having the %-character anywhere in the project path causes cfg-if to fail compiling. In the example below I have the %-character as the name of the project folder, but the issue persist if there's a %-sign anywhere.

Reproducing

I can reproduce this issue by creating a new project, adding cfg-if as a dependency, and executing cargo run:

  1. Create a new project
> cargo new test-%-cfg-if
  1. Add cfg-if as a dependency
# --snip--
[dependencies]
cfg-if = "1.0.0"
  1. Run with cargo run
> cargo run
  Compiling cfg-if v1.0.0
error: failed to build archive: No such file or directory
error: aborting due to previous error
error: could not compile `cfg-if`

Running with --verbose yields:

Caused by:
  process didn't exit successfully: `rustc --crate-name cfg_if --edition=2018 /Users/havegum/.cargo/registry/src/github.com-1ecc6299db9ec823/cfg-if-1.0.0/src/lib.rs --error-format=json --json=diagnostic-rendered-ansi --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 -C metadata=33d5df19792096bf -C extra-filename=-33d5df19792096bf --out-dir '/Users/havegum/test-%-cfg-if/target/debug/deps' -L 'dependency=/Users/havegum/test-%-cfg-if/target/debug/deps' --cap-lints allow` (exit code: 1)

Expected outcome

The expected outcome – and what happens if you comment out the dependency – is that the project builds and runs as normal:

> cargo run
   Compiling test-cfg-if v0.1.0 (/Users/havegum/test-%-cfg-if)
    Finished dev [unoptimized + debuginfo] target(s) in 0.98s
     Running `target/debug/test-cfg-if`
Hello, world!

Removing % from the path fixes the error

> mv ../test-%-cfg-if ../test-cfg-if
> cd ../test-cfg-if
> cargo run
   Compiling cfg-if v1.0.0
   Compiling test-cfg-if v0.1.0 (/Users/havegum/test-cfg-if)
    Finished dev [unoptimized + debuginfo] target(s) in 0.93s
     Running `target/debug/test-cfg-if`
Hello, world!

System info

> sw_vers
ProductName:	Mac OS X
ProductVersion:	10.14.6
BuildVersion:	18G103
> rustup --version
rustup 1.23.1 (3df2264a9 2020-11-30)
> rustc --version 
rustc 1.50.0 (cb75ad5db 2021-02-10)
> cargo --version
cargo 1.50.0 (f04e7fab7 2021-02-04)

Expected `fn` not `fn blah`

impl Trait for Struct {
	cfg_if! {
		if #[cfg(feature = "blah")] {
			fn blah(&self) {
				unimplemented!();
			}
		} else {
			fn blah(&self) {
				unimplemented!();
			}
		}
	}
}

This generates the error:

expected one of `const`, `crate`, `default`, `extern`, `fn`, `pub`, `type`, or `unsafe`, found `fn blah(?) { unimplemented!(); }`

expected one of 8 possible tokens here

What gives? Putting the attribute myself works but the macro has a weird failure.

Hash pin main.yml dependencies.

Description

I would like to suggest another security practice recommended by the OpenSSF Scorecard which is to hash pin dependencies to prevent dependency-confusion and typosquatting attacks.

The change would only be applied to GitHub workflows, dockerfiles and shell scripts dependencies. The cfg-if case would only need changes on the GitHub workflow main.yml

This means:

  • Hash pinning GitHub Workflow actions.

Together with the issue I'll also suggest the PR with changes since they are quite simple. I'll also suggest adding github-action for dependabot to update since it is able to update both the hash and the comment version related to it.

Any questions or concerns just let me know.
Thanks!

Additional Context

For more informations about dependency confusion / typosquatting attacks:

For more informations about the dependency-update tools:

error: could not compile `cfg-if` (lib) due to 1 previous error for mipsel-unknown-linux-musl

https://github.com/peterwillcn/shadowsocks-rust-mips/actions/runs/10281532851/job/28451288168

Compiling autocfg v1.3.0
Compiling cfg-if v1.0.0
error[E0463]: can't find crate for `core`
 |
 = note: the `mipsel-unknown-linux-musl` target may not be installed
 = help: consider downloading the target with `rustup target add mipsel-unknown-linux-musl`

  Compiling typenum v1.17.0
For more information about this error, try `rustc --explain E0463`.
error: could not compile `libc` (lib) due to 1 previous error
warning: build failed, waiting for other jobs to finish...
error: could not compile `cfg-if` (lib) due to 1 previous error
[cross] warning: rust-std is not available for mipsel-unknown-linux-musl
[cross] note: you may need to build components for the target via `-Z build-std=<components>` or in your cross configuration specify `target.mipsel-unknown-linux-musl.build-std`
             the available components are core, std, alloc, and proc_macro

failed build release aarch64-apple-ios

error[E0463]: can't find crate for core
|
= note: the aarch64-apple-ios target may not be installed

error: aborting due to previous error

For more information about this error, try rustc --explain E0463.
error: could not compile cfg-if

To learn more, run the command again with --verbose.
warning: build failed, waiting for other jobs to finish...
error[E0463]: can't find crate for core
|
= note: the aarch64-apple-ios target may not be installed

error: aborting due to previous error

For more information about this error, try rustc --explain E0463.
error: build failed
[ERROR cargo_lipo] Failed to build "rust_sdk" for "aarch64-apple-ios": Executing "/Users/xxxx/.rustup/toolchains/nightly-x86_64-apple-darwin/bin/cargo" "--color" "auto" "build" "-p" "rust_sdk" "--target" "aarch64-apple-ios" "--release" "--lib" finished with error status: exit code: 101

Merge cfg-if into std?

Seeing as search engines are useless for searching for if this has been answered before I'll ask the question directly here. I apologize if it has been answered elsewhere.

crates.io (total):
image

lib.rs (monthly):
image

This crate is being used by an absurd amount of users and according to lib.rs >68 000 crates. Which states quite clearly that cfg-if is sorely wanted by Rust users. This crate is also very simple only supplying a single macro that is below a hundred lines of code.

There is thus a quite obvious question to ask: Why is this not part of the standard library? Why is it instead maintained as a separate crate by the Rust team?

I'd love to see this as part of the standard library as it'd be one less dependency one has to worry if it is going to be xz'ed in the dependency tree or not.

found crate `cfg_if` compiled by an incompatible version of rustc

I think this is more of a rust issue rather than cfg-if issue so just reporting it here. I was building cfg-if using stable compiler, I might have built it with nightly compiler in the past. Feel free to close this (since I don't think it is actionable), I did send this to rust rust-lang/rust#86551. Note that cargo b works but only cargo c does not work.

> cargo c
error[E0514]: found crate `cfg_if` compiled by an incompatible version of rustc
 --> /home/ivan/.cargo/registry/src/github.com-1ecc6299db9ec823/instant-0.1.10/src/lib.rs:1:1
  |
1 | cfg_if::cfg_if! {
  | ^^^^^^
  |
  = help: please recompile that crate using this compiler (rustc 1.55.0-nightly (32c9b7b09 2021-07-21))
  = note: the following crate versions were found:
          crate `cfg_if` compiled by rustc 1.55.0-nightly (6d820866a 2021-06-29): /home/ivan/src/pickfire/rs/helix/target/debug/deps/libcfg_if-a9897b30e482daf2.rmeta

error: could not compile `which` due to previous error
warning: build failed, waiting for other jobs to finish...
error[E0514]: found crate `cfg_if` compiled by an incompatible version of rustc
   --> /home/ivan/.cargo/registry/src/github.com-1ecc6299db9ec823/log-0.4.14/src/lib.rs:283:1
    |
283 | extern crate cfg_if;
    | ^^^^^^^^^^^^^^^^^^^^
    |
    = help: please recompile that crate using this compiler (rustc 1.55.0-nightly (32c9b7b09 2021-07-21))
    = note: the following crate versions were found:
            crate `cfg_if` compiled by rustc 1.55.0-nightly (6d820866a 2021-06-29): /home/ivan/src/pickfire/rs/helix/target/debug/deps/libcfg_if-a9897b30e482daf2.rmeta

error[E0514]: found crate `cfg_if` compiled by an incompatible version of rustc
  --> /home/ivan/.cargo/registry/src/github.com-1ecc6299db9ec823/crossbeam-utils-0.8.5/src/lib.rs:95:5
   |
95 | use cfg_if::cfg_if;
   |     ^^^^^^
   |
   = help: please recompile that crate using this compiler (rustc 1.55.0-nightly (32c9b7b09 2021-07-21))
   = note: the following crate versions were found:
           crate `cfg_if` compiled by rustc 1.55.0-nightly (6d820866a 2021-06-29): /home/ivan/src/pickfire/rs/helix/target/debug/deps/libcfg_if-a9897b30e482daf2.rmeta

error[E0514]: found crate `tinyvec_macros` compiled by an incompatible version of rustc
 --> /home/ivan/.cargo/registry/src/github.com-1ecc6299db9ec823/tinyvec-1.3.0/src/tinyvec.rs:7:5
  |
7 | use tinyvec_macros::impl_mirrored;
  |     ^^^^^^^^^^^^^^
  |
  = help: please recompile that crate using this compiler (rustc 1.55.0-nightly (32c9b7b09 2021-07-21))
  = note: the following crate versions were found:
          crate `tinyvec_macros` compiled by rustc 1.55.0-nightly (6d820866a 2021-06-29): /home/ivan/src/pickfire/rs/helix/target/debug/deps/libtinyvec_macros-177747a26e6502c4.rmeta

error[E0514]: found crate `cfg_if` compiled by an incompatible version of rustc
   --> /home/ivan/.cargo/registry/src/github.com-1ecc6299db9ec823/encoding_rs-0.8.28/src/lib.rs:689:1
    |
689 | extern crate cfg_if;
    | ^^^^^^^^^^^^^^^^^^^^
    |
    = help: please recompile that crate using this compiler (rustc 1.55.0-nightly (32c9b7b09 2021-07-21))
    = note: the following crate versions were found:
            crate `cfg_if` compiled by rustc 1.55.0-nightly (6d820866a 2021-06-29): /home/ivan/src/pickfire/rs/helix/target/debug/deps/libcfg_if-a9897b30e482daf2.rmeta

error: build failed

What's stopping 1.0?

What problems does the crate have that are blockers for issuing a 1.0.0 version?

Failed to build under win64

cargo build --verbose --release
warning: could not canonicalize path: 'n:\cfg-if'
warning: could not canonicalize path: 'n:\'
    Updating crates.io index
   Compiling cfg-if v1.0.0 (N:\cfg-if)
     Running `rustc --crate-name cfg_if --edition=2018 src\lib.rs --error-format=json --json=diagnostic-rendered-ansi --crate-type lib --emit=dep-info,metadata,link -C opt-level=3 -C embed-bitcode=no -C metadata=0693a248e62814cf -C extra-filename=-0693a248e62814cf --out-dir n:\cfg-if\target\release\deps -L dependency=n:\cfg-if\target\release\deps`
error: failed to build archive: function not supported

error: could not compile `cfg-if` due to previous error

Caused by:
  process didn't exit successfully: `rustc --crate-name cfg_if --edition=2018 src\lib.rs --error-format=json --json=diagnostic-rendered-ansi --crate-type lib --emit=dep-info,metadata,link -C opt-level=3 -C embed-bitcode=no -C metadata=0693a248e62814cf -C extra-filename=-0693a248e62814cf --out-dir n:\cfg-if\target\release\deps -L dependency=n:\cfg-if\target\release\deps` (exit code: 1)

cfg-if is awkward to use with 2018 edition

In order to use cfg-if with Rust 2018 style 'use' for macros, it is necessary to also import __cfg_if_apply, and __cfg_if_items. Perhaps these can be referenced via $crate so that the cfg_if macro will work even as the only macro imported.

New crates.io release

Please publish a new version on crates.io containing the no_std functionality. It would be great if I could depend on this crate without referencing the git repository directly.

Nested if

Allowing nested if-statment can reduce indent level:

cfg_if! {
    if #[cfg(windows)] {
        mod windows_only;

        if #[test] {
            mod test;
        }
    }
}

Is that reasonable?

rustfmt-formattable syntax?

I'm aware how minimal and stable this crate is and has been for a long time, but something that's always put me off from using it (usually in favor of manual #[cfg] attributes) is how its syntax is completely unfamiliar to rustfmt, and therefore any expressions or items inside of a cfg_if! block can't get the advantages that rustfmt brings.

// stays as is when `cargo fmt` is run
cfg_if! {
    if #[cfg(foobar)] {
        fn baz() { qux();   flop()
        }
    }
    else {
        fn bar() {
        }
    }
}

Was there a reason that you didn't choose a more traditional/valid rust syntax for the macro? e.g.

cfg_if!(if cfg!(foobar) {
    fn baz() {
        qux();
        flop()
    }
} else {
    fn bar() {}
});

I'm aware that rustfmt wasn't as popular/well-integrated in 2017, but I feel like a syntax like this would greatly improve the ergonomics of this crate.

(feel free to ignore, I was just surprised that there wasn't an issue about this already)

unexpected behavior inside struct, for feature-gated arguments

Attempting the following:

pub(crate) struct Args {
	cfg_if! {
		if #[cfg(feature = "my_feat")] {
			some_feature_gated_arg: u8,
			some_other_feature_gated_arg: u8,
		} else {}
	}
	// ...
}

causes compile time errors. This would have been helpful to note in the Readme/docs.

Consider expanding through an indirect macro

See rust-lang/rfcs#2523 (comment), where @ogoffart mentions that:

I suppose it would not make sense to relax the parsing rules of items that are disabled by #[cfg]

So one must wrap the item inside a macro such as cfg-if!{...} but which would not expand the items for the disabled configuration. Something like this should work: #[cfg($cfg)] identity!{ $($body)* }.

Currently in libc we can't write:

cfg_if! {
    if #[cfg(foo)] {
        #[repr(align(16))] struct F;
    }
}

because older libsyntax versions chuckle on the align(16) (https://rust.godbolt.org/z/eZYANH). It would be nice if cfg_if! could be improved with such an indirect macro approach to make that work.

Automated releases

Automated releases can help keep your releases consistent, transparent for users and, save maintainance time. It also improves the security of the release by using a "trusted builder". A "trusted builder" provides a higher level of confidence, for example, that cargo command was not modified.

To do that, we could use GitHub workflows. We would need to store the crates.io API token in GitHub secrets, then create a workflow to publish cfg-if to crates.io. Here's a quick draft:

on:
  push:
    tags:
      - '*'
...
  - name: Checkout code
    uses: actions/checkout
  - name: Install rust toolchain
    uses: actions-rs/toolchain
  - name: Publish
    run: cargo publish --token ${CRATES_TOKEN}
Additional context

About me, I'm Gabriela and I work on behalf of Google and the OpenSSF suggesting supply-chain security changes.

no-std controlled by feature?

The reason why having an explicit use-std feature would be useful, is that currently rustc cannot compile '[no_std]' crates dynamically.

Strange compilation error on CI with backtrace-rs crate due to cfg-if

Hi!

We had a strange compilation error in our CI related to cfg-if following last backtrace-rs update. The error was introduced by commit rust-lang/backtrace-rs@7a1d357.

   Compiling backtrace v0.3.42 (https://github.com/Devolutions/backtrace-rs?branch=test#46961d32)
error: target pointer width detected: 64
  --> C:\Users\ContainerAdministrator\.cargo\git\checkouts\backtrace-rs-ac5effeeee72e05a\46961d3\src\backtrace\dbghelp.rs:25:1
   |
25 | compile_error!("target pointer width detected: 64");
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: expected an item keyword
   --> C:\Users\ContainerAdministrator\.cargo\git\checkouts\backtrace-rs-ac5effeeee72e05a\46961d3\src\backtrace\dbghelp.rs:126:13
    |
126 |             let function_table_access = dbghelp.SymFunctionTableAccess64();
    |             ^^^

error: aborting due to 2 previous errors

error: could not compile `backtrace`.

The first error was produced by myself with following code:

#[cfg(target_pointer_width = "64")]
compile_error!("target pointer width detected: 64");

showing target_pointer_width is indeed 64.

The build is performed on a Windows x86_64 build container on Microsoft Azure Pipeline but doesn't arise in our other pipelines with similar setup. We can't reproduce it locally on 32 bits and 64 bits targets either.

We managed to build by removing cfg-if usage and writing what I suppose to be the cfg-if generated code by hand: Devolutions/backtrace-rs@9f2328e

This is very strange because the error occurs in only one pipeline and can be prevented by not using cfg-if. This is really mysterious to us. Do you have any idea?

Thank you!

crates.io version differs from GH version, breaking Miri

Miri is currently broken because it cannot build libstd with xargo, and fixing that does not work because the released version of this crate does not actually have the rustc-dep-of-std feature. In the tarball on crates.io, the Cargo.toml.orig looks like

[package]
name = "cfg-if"
version = "0.1.9"
authors = ["Alex Crichton <[email protected]>"]
license = "MIT/Apache-2.0"
readme = "README.md"
repository = "https://github.com/alexcrichton/cfg-if"
homepage = "https://github.com/alexcrichton/cfg-if"
documentation = "https://docs.rs/cfg-if"
description = """
A macro to ergonomically define an item depending on a large number of #[cfg]
parameters. Structured like an if-else chain, the first matching branch is the
item that gets emitted.
"""

[badges]
travis-ci = { repository = "alexcrichton/cfg-if" }

# [dependencies]
# core = { version = "1.0.0", optional = true, package = 'rustc-std-workspace-core' }
# compiler_builtins = { version = '0.1.2', optional = true }
#
# [features]
# rustc-dep-of-std = ['core', 'compiler_builtins']

variant macro for blocks

I often want to cfg some code, but I want to do it on blocks inside a function instead of at the item level.

Would you be open to adding a second macro such as cfg_if_block (or other name) that does all the same stuff but working on :block instead of :item? I can do the PR if you're interested in the idea.

Document Supported Versions

It would be nice if cfg-if documented the versions of Rustc it currently supports, using a badge similar to:
Rustc Version 1.24+
Rustc Version 1.31+

Version 0.1.10 recently broke compatibility with for versions <= 1.31.0, with the following errors:

  • feature rename-dependency is required
  • Produces the warning: non-ident macro paths are experimental (see issue #35896).

I'm fine with breaking backwards compatibility for deprecated compiler versions (especially ones with vulnerabilities, like <= 1.25.0), but it would be nice to document what Rustc versions are, in-fact, supported. I believe the current supported version is 1.31.0.

cargo build failed permission denied

windows 7 x64, cargo build failed permission denied

active toolchain
nightly-x86_64-pc-windows-msvc (default)
rustc 1.51.0-nightly (04caa632d 2021-01-30)

/e/gitlocal/cfg-if (main)
$ cargo build --verbose
Compiling cfg-if v1.0.0 (E:\gitlocal\cfg-if)
Running rustc --crate-name cfg_if --edition=2018 'src\lib.rs' --error-format=json --json=diagnostic-rendered-ansi --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 -C metadata=c2a97ad137455fb4 -C extra-filename=-c2a97ad137455fb4 --out-dir 'E:\gitlocal\cfg-if\target\debug\deps' -C 'incremental=E:\gitlocal\cfg-if\target\debug\incremental' -L 'dependency=E:\gitlocal\cfg-if\target\debug\deps'
error: failed to build archive: permission denied

error: aborting due to previous error

error: could not compile cfg-if

Caused by:
process didn't exit successfully: rustc --crate-name cfg_if --edition=2018 'src\lib.rs' --error-format=json --json=diagnostic-rendered-ansi --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 -C metadata=c2a97ad137455fb4 -C extra-filename=-c2a97ad137455fb4 --out-dir 'E:\gitlocal\cfg-if\target\debug\deps' -C 'incremental=E:\gitlocal\cfg-if\target\debug\incremental' -L 'dependency=E:\gitlocal\cfg-if\target\debug\deps' (exit code: 1)

Set minimal permissions to github workflow

I would like to suggest setting the permissions to the github workflows (currently the main.yml file) as read only on the top level and any write permission be given at the run level.

This is necessary due to a behavior of github workflow to grant to GITHUB_TOKEN write permissions to all types of permissions, regardless of they being used or not. In case of the workflow getting compromised, an attacker can exploit this permissions.

Thus, it is both a recommendation from OpenSSF Scorecard and the Github to always use credentials that are minimally scoped.

I'll submit a PR with the following changes, so feel free to raise any questions you might have.
Thanks!

Disclosure: I'm from Google, working with the OpenSSF to help many open source projects to increase their supply-chain security.

0.1.6 Doesn't compile on 1.33.0

The only released version (0.1.6) of this crate don't compile on rustc version 1.33.0.

   Compiling cfg-if v0.1.6 (/home/remi/cfg-if-0.1.6)                                                                                                                                                                                                                                                                                                  
error: missing documentation for macro                                                                                                                                                                                                                                                                                                                
  --> src/lib.rs:36:1                                                                                                                                                                                                                                                                                                                                 
   |                                                                                                                                                                                                                                                                                                                                                  
36 | macro_rules! cfg_if {                                                                                                                                                                                                                                                                                                                            
   | ^^^^^^^^^^^^^^^^^^^                                                                                                                                                                                                                                                                                                                              
   |                                                                                                                                                                                                                                                                                                                                                  
note: lint level defined here                                                                                                                                                                                                                                                                                                                         
  --> src/lib.rs:32:9
   |
32 | #![deny(missing_docs)]
   |         ^^^^^^^^^^^^

error: aborting due to previous error

Traceback (most recent call last):
  File "/home/remi/.cargo/bin/rustc", line 10, in <module>
    ['/home/remi/.cargo/bin/hidden/rustc'] + sys.argv[1:]))
  File "/usr/lib/python2.7/subprocess.py", line 190, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/home/remi/.cargo/bin/hidden/rustc', '--crate-name', 'cfg_if', 'src/lib.rs', '--color', 'always', '--crate-type', 'lib', '--emit=dep-info,link', '-C', 'debuginfo=2', '-C', 'metadata=ce0cffa0b54188f9', '-C', 'extra-filename=-ce0cffa0b54188f9', '--out-dir', '/home/remi/cfg-if-0.1.6/target/debug/deps',
'-C', 'incremental=/home/remi/cfg-if-0.1.6/target/debug/incremental', '-L', 'dependency=/home/remi/cfg-if-0.1.6/target/debug/deps']' returned non-zero exit status 1
error: Could not compile `cfg-if`.

To learn more, run the command again with --verbose.

I think this problem is fixed on tip, but I think a new version of this crate needs to be published for others to use it now on 1.33.0?

use of undeclared crate or module `cfg_if` on Appveyor

I want to use cfg_if, v1.0 in my project and while cfg_if works locally on my system (MacOS) as well as on GitHub Actions (MacOS and Ubuntu), it gives an error on Appveyor:

   | cfg_if::cfg_if! {
   | ^^^^^^ use of undeclared crate or module `cfg_if`

My code looks like this:

cfg_if::cfg_if! {
    // 1. The features "jem" and "rp" cannot be activated simultaneously
    // 2. jemalloc cannot be used with MSVC!
    if #[cfg(all(target_env = "msvc", feature = "jem"))] {
        compile_error!("The feature `jemalloc` cannot be activated on MSVC");
    } else if #[cfg(feature = "jem")] {
        use jemallocator::Jemalloc;
        #[global_allocator]
        static JEMALLOC_GLOBAL: Jemalloc = Jemalloc;
    } else if #[cfg(feature = "rp")] {
        #[global_allocator]
        static RPMALLOC_GLOBAL: rpmalloc::RpMalloc = rpmalloc::RpMalloc;
    }
}

Including extern crate cfg_if does not seem to help. At the same time, [all tests] on Ubuntu and MacOS pass on GA.

Crate is not clear enough about cfg-if being limited to items

I was trying to generate a bunch of identical functions with different bodies, so I was writing them similar to this minimal example:

#[macro_use]
extern crate cfg_if;

fn a() {}
            
fn b() {
    cfg_if! {
        if #[cfg(target_os = "linux")] {
            a()
        }
    }
}

fn main() {
    b();
}

but this fails with:

error: expected one of `!` or `::`, found `(`
 --> src/main.rs:9:14
  |
9 |             a()
  |              ^ expected one of `!` or `::` here

error: Could not compile `playground`.

To learn more, run the command again with --verbose.

This was very confusing and I didn't see anything about this in the generated cfg-if docs. I went on the Rust IRC channel and scottmcm was kind enough to point out that in the crate description visible on Crates.io "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted." it talks about items, which are a specific language term.

So now I understand a little bit better the limitations, I think there are two ways to better convey this to users:

  • Use the term item within the generated docs and be sure to link to the relevant section in the reference that I linked to above.
  • Emit better errors for when there isn't a macro match (not certain if this is currently possible).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.