Subcommand to show result of macro expansion

Last update: May 18, 2022

cargo-expand

github crates.io build status

Once installed, the following command prints out the result of macro expansion and #[derive] expansion applied to the current crate.

$ cargo expand

This is a wrapper around the more verbose compiler command:

$ cargo rustc --profile=check -- -Zunstable-options --pretty=expanded

Installation

Install with cargo install cargo-expand.

This command optionally uses rustfmt to format the expanded output. The resulting code is typically much more readable than what you get from the compiler. If rustfmt is not available, the expanded code is not formatted. Install rustfmt with rustup component add rustfmt.

Cargo expand relies on unstable compiler flags so it requires a nightly toolchain to be installed, though does not require nightly to be the default toolchain or the one with which cargo expand itself is executed. If the default toolchain is one other than nightly, running cargo expand will find and use nightly anyway.

Example

$ cat src/main.rs

#[derive(Debug)]
struct S;

fn main() {
    println!("{:?}", S);
}

$ cargo expand

#![feature(prelude_import)]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std;
struct S;
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::core::fmt::Debug for S {
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match *self {
            S => {
                let mut debug_trait_builder = f.debug_tuple("S");
                debug_trait_builder.finish()
            }
        }
    }
}
fn main() {
    {
        ::std::io::_print(::core::fmt::Arguments::new_v1(
            &["", "\n"],
            &match (&S,) {
                (arg0,) => [::core::fmt::ArgumentV1::new(arg0, ::core::fmt::Debug::fmt)],
            },
        ));
    };
}

Options

See cargo expand --help for a complete list of options, most of which are consistent with other Cargo subcommands. Here are a few that are common in the context of cargo expand.

To expand a particular test target:

$ cargo expand --test test_something

To expand without rustfmt:

$ cargo expand --ugly

To expand a specific module or type or function only:

$ cargo expand path::to::module

cargo expand punctuated::printing cargo expand token::FatArrow

Configuration

The cargo expand command reads the [expand] section of $CARGO_HOME/config if there is one (usually ~/.cargo/config).

Set the default syntax highlighting theme with the theme setting:

[expand]
theme = "TwoDark"

Run cargo expand --themes to print a list of available themes. Use theme = "none" to disable coloring.

Change the default coloring disposition (normally auto) with the color setting:

[expand]
color = "always"

Disclaimer

Be aware that macro expansion to text is a lossy process. This is a debugging aid only. There should be no expectation that the expanded code can be compiled successfully, nor that if it compiles then it behaves the same as the original code.

For instance the following function returns 3 when compiled ordinarily by Rust but the expanded code compiles and returns 4.

fn f() -> i32 {
    let x = 1;

    macro_rules! first_x {
        () => { x }
    }

    let x = 2;

    x + first_x!()
}

Refer to The Book for more on the considerations around macro hygiene.


License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

GitHub

https://github.com/dtolnay/cargo-expand
Comments
  • 1. cannot expand single item

    I have an issue expanding a single item. I get the error "cannot expand single item (single::item) without rustfmt" it does give the hint to install rustfmt using "rustup component add rustfmt --toolchain nightly"

    however when i run that it says rustfmt is up to date. Even installing to stable is up to date. to the best I can tell rustfmt is installed fine for all toolchains.

    not sure if there is a bug or I am simply doing something wrong.

    Reviewed by jeffwllms at 2019-03-10 18:32
  • 2. Expanding tests

    Related to #20, but I can't seem to use the solution given there:

    $ cargo expand -- --test
    error: Invalid value for '<ITEM>': `--test` is not an identifier
    $ cargo expand --version
    cargo-expand 0.4.4
    

    How should I pass arguments to rustc with the addition of the cargo-expand arguments to expand specific items?

    Reviewed by dbeckwith at 2019-01-21 21:58
  • 3. `cargo expand` fails with memory allocation errors on Ubuntu 18.04

    I cannot get cargo expand to work at all on Ubuntu 18.04. I have replicated this issue in a VM running Ubuntu 18.04 as well. I am using the default example code

    #[derive(Debug)]
    struct S;
    
    fn main() {
        println!("{:?}", S);
    }
    

    but I have also tried with other code and get the same following result when I run cargo expand:

    [email protected]:~/prj/src$ cargo expand
        Checking prj v0.1.0 (/home/vagrant/prj)
        Finished check [unoptimized + debuginfo] target(s) in 0.07s
    
    memory allocation of 8391155392347897856 bytes failedAborted (core dumped)
    

    The number of bytes doesn't change between computers or between different code.

    I don't necessarily need $ cargo expand as $ cargo rustc --profile=check -- -Zunstable-options --pretty=expanded works perfectly but figured this was worth investigating.

    Reviewed by tanyav2 at 2020-06-24 00:05
  • 4. Is it possible to use a pure rust lib rather than onig?

    Is it possible to use a pure rust lib rather than onig? I'm mostly asking this question so that the answer is documented. When it's not pure rust people can have trouble compiling with gcc on windows on gnu toolchain - it requires more setup and configuration of a windows machine than just installing rustup.

    As I said I'm sure there's some good reasons behind using onig versus depending on some parts of ripgrep, just would be nice to know so that I can stop wondering.... :-)

    Reviewed by gilescope at 2020-03-02 14:07
  • 5. UnicodeDecodeError

    cmd: cargo expand --color never version: v0.3.10

    Error:

    ** Error while highlighting:
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1832403: ordinal not in range(128)
       (file "/usr/local/lib/python2.7/site-packages/Pygments-1.6-py2.7.egg/pygments/lexer.py", line 168, in get_tokens)
    

    I don't understand why pygments is invoked at all when using --color never. I can also reproduce without the option.

    Reviewed by gnzlbg at 2017-11-07 15:12
  • 6. Installing with cargo install fails due to semver breakage in onig_sys

    Problem

    When using cargo install cargo-expand the compilation fails due to a semver-breaking release of onig_sys. This does not happen when building the repo using cargo build. This is due to Cargo.lock being pinned to a non-breaking version of onig_sys. cargo install doesn't seem to take the lock-file into account when installing it directly from crates.io.

    Error message on compilation

    $ cargo install cargo-expand
        Updating crates.io index
      Installing cargo-expand v0.4.12
       Compiling proc-macro2 v0.4.30
       Compiling unicode-xid v0.1.0
       Compiling libc v0.2.60
       Compiling syn v0.15.43
       Compiling cc v1.0.38
       Compiling memchr v2.2.1
       Compiling version_check v0.1.5
       Compiling failure_derive v0.1.5
       Compiling log v0.4.8
       Compiling rustc-demangle v0.1.15
       Compiling lazy_static v1.3.0
       Compiling byteorder v1.3.2
       Compiling cfg-if v0.1.9
       Compiling bitflags v1.1.0
       Compiling glob v0.3.0
       Compiling regex-syntax v0.6.11
       Compiling quick-error v1.2.2
       Compiling unicode-width v0.1.5
       Compiling strsim v0.8.0
       Compiling bindgen v0.50.0
       Compiling ansi_term v0.11.0
       Compiling vec_map v0.8.1
       Compiling termcolor v1.0.5
       Compiling semver-parser v0.7.0
       Compiling shlex v0.1.1
       Compiling peeking_take_while v0.1.2
       Compiling strsim v0.7.0
       Compiling pkg-config v0.3.15
       Compiling fnv v1.0.6
       Compiling ident_case v1.0.1
       Compiling autocfg v0.1.5
       Compiling crc32fast v1.2.0
       Compiling ryu v1.0.0
       Compiling serde v1.0.98
       Compiling safemem v0.3.1
       Compiling ppv-lite86 v0.2.5
       Compiling scopeguard v1.0.0
       Compiling smallvec v0.6.10
       Compiling encoding_index_tests v0.1.4
       Compiling itoa v0.4.4
       Compiling linked-hash-map v0.5.2
       Compiling unicode-segmentation v1.3.0
       Compiling derive_builder v0.7.2
       Compiling xml-rs v0.8.0
       Compiling same-file v1.0.5
       Compiling lazycell v1.2.1
       Compiling shell-words v0.1.0
       Compiling remove_dir_all v0.5.2
       Compiling thread_local v0.3.6
       Compiling nom v4.2.3
       Compiling error-chain v0.12.1
       Compiling humantime v1.2.0
       Compiling textwrap v0.11.0
       Compiling clang-sys v0.28.1
       Compiling backtrace-sys v0.1.31
       Compiling libloading v0.5.2
       Compiling miniz-sys v0.1.12
       Compiling ansi_colours v1.0.1
       Compiling semver v0.9.0
       Compiling bincode v1.1.4
       Compiling line-wrap v0.1.1
       Compiling lock_api v0.3.1
       Compiling encoding-index-singlebyte v1.20141219.5
       Compiling encoding-index-tradchinese v1.20141219.5
       Compiling encoding-index-japanese v1.20141219.5
       Compiling encoding-index-korean v1.20141219.5
       Compiling encoding-index-simpchinese v1.20141219.5
       Compiling c2-chacha v0.2.2
       Compiling yaml-rust v0.4.3
       Compiling walkdir v2.2.9
       Compiling heck v0.3.1
       Compiling rustc_version v0.2.3
       Compiling encoding v0.2.33
       Compiling atty v0.2.13
       Compiling getrandom v0.1.8
       Compiling termios v0.3.1
       Compiling clicolors-control v1.0.0
       Compiling dirs v1.0.5
       Compiling directories v1.0.2
       Compiling aho-corasick v0.7.6
       Compiling content_inspector v0.2.4
       Compiling fxhash v0.2.1
       Compiling base64 v0.10.1
       Compiling quote v0.6.13
       Compiling clap v2.33.0
       Compiling parking_lot_core v0.6.2
       Compiling parking_lot v0.9.0
       Compiling rand_core v0.5.0
       Compiling backtrace v0.3.34
       Compiling flate2 v1.0.9
       Compiling cexpr v0.3.5
       Compiling rand_chacha v0.2.1
       Compiling regex v1.2.1
       Compiling rand v0.7.0
       Compiling tempfile v3.1.0
       Compiling env_logger v0.6.2
       Compiling console v0.7.7
       Compiling toolchain_find v0.1.4
       Compiling synstructure v0.10.2
       Compiling darling_core v0.9.0
       Compiling serde_derive v1.0.98
       Compiling structopt-derive v0.2.18
       Compiling syn-select v0.1.4
       Compiling structopt v0.2.18
       Compiling failure v0.1.5
       Compiling which v2.0.1
       Compiling darling_macro v0.9.0
       Compiling plist v0.4.2
       Compiling serde_json v1.0.40
       Compiling toml v0.5.1
       Compiling darling v0.9.0
       Compiling derive_builder_core v0.5.0
       Compiling onig_sys v69.2.0
       Compiling onig v4.3.2
    error[E0412]: cannot find type `OnigRegexMut` in module `onig_sys`
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:142:20
        |
    142 |     raw: onig_sys::OnigRegexMut,
        |                    ^^^^^^^^^^^^ help: a type alias with a similar name exists: `OnigRegex`
    
    error[E0412]: cannot find type `OnigRegexMut` in module `onig_sys`
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:320:32
        |
    320 |         let mut reg: onig_sys::OnigRegexMut = null_mut();
        |                                ^^^^^^^^^^^^ help: a type alias with a similar name exists: `OnigRegex`
    
    error[E0412]: cannot find type `OnigRegexMut` in module `onig_sys`
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:321:50
        |
    321 |         let reg_ptr = &mut reg as *mut onig_sys::OnigRegexMut;
        |                                                  ^^^^^^^^^^^^ help: a type alias with a similar name exists: `OnigRegex`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:326:18
        |
    326 |             enc: null(),
        |                  ^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::OnigEncodingTypeST`
                   found type `*const _`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:327:18
        |
    327 |             par: null(),
        |                  ^^^^^^ types differ in mutability
        |
        = note: expected type `*mut u8`
                   found type `*const _`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:328:22
        |
    328 |             par_end: null(),
        |                      ^^^^^^ types differ in mutability
        |
        = note: expected type `*mut u8`
                   found type `*const _`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:341:17
        |
    341 |                 syntax as *const Syntax as *const onig_sys::OnigSyntaxType,
        |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::OnigSyntaxType`
                   found type `*const onig_sys::OnigSyntaxType`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:346:19
        |
    346 |         if err == onig_sys::ONIG_NORMAL {
        |                   ^^^^^^^^^^^^^^^^^^^^^ expected i32, found u32
    help: you can convert an `u32` to `i32` and panic if the converted value wouldn't fit
        |
    346 |         if err == onig_sys::ONIG_NORMAL.try_into().unwrap() {
        |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:515:17
        |
    515 |                 match_param.as_raw()
        |                 ^^^^^^^^^^^^^^^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::OnigMatchParamStruct`
                   found type `*const onig_sys::OnigMatchParamStruct`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/lib.rs:704:17
        |
    704 |                 match_param.as_raw()
        |                 ^^^^^^^^^^^^^^^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::OnigMatchParamStruct`
                   found type `*const onig_sys::OnigMatchParamStruct`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/find.rs:182:17
        |
    182 |                 scan_cb::<F>,
        |                 ^^^^^^^^^^^^ expected enum `std::option::Option`, found fn item
        |
        = note: expected type `std::option::Option<unsafe extern "C" fn(i32, i32, *mut onig_sys::re_registers, *mut std::ffi::c_void) -> i32>`
                   found type `extern "C" fn(i32, i32, *const onig_sys::re_registers, *mut std::ffi::c_void) -> i32 {find::<impl Regex>::scan_with_region::scan_cb::<F>}`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/region.rs:24:22
       |
    24 |                 beg: null(),
       |                      ^^^^^^ types differ in mutability
       |
       = note: expected type `*mut i32`
                  found type `*const _`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/region.rs:25:22
       |
    25 |                 end: null(),
       |                      ^^^^^^ types differ in mutability
       |
       = note: expected type `*mut i32`
                  found type `*const _`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/region.rs:26:31
       |
    26 |                 history_root: null(),
       |                               ^^^^^^ types differ in mutability
       |
       = note: expected type `*mut onig_sys::OnigCaptureTreeNodeStruct`
                  found type `*const _`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/region.rs:53:57
       |
    53 |             onig_sys::onig_region_copy(&mut region.raw, ptr);
       |                                                         ^^^ types differ in mutability
       |
       = note: expected type `*mut onig_sys::re_registers`
                  found type `*const onig_sys::re_registers`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/region.rs:84:17
       |
    84 |         if r != onig_sys::ONIG_NORMAL {
       |                 ^^^^^^^^^^^^^^^^^^^^^ expected i32, found u32
    help: you can convert an `u32` to `i32` and panic if the converted value wouldn't fit
       |
    84 |         if r != onig_sys::ONIG_NORMAL.try_into().unwrap() {
       |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/region.rs:131:61
        |
    131 |         let tree = unsafe { onig_sys::onig_get_capture_tree(&self.raw) };
        |                                                             ^^^^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::re_registers`
                   found type `&onig_sys::re_registers`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/region.rs:191:17
        |
    191 |                 &self.raw,
        |                 ^^^^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::re_registers`
                   found type `&onig_sys::re_registers`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/region.rs:193:17
        |
    193 |                 traverse_cb::<F>,
        |                 ^^^^^^^^^^^^^^^^
        |                 |
        |                 expected enum `std::option::Option`, found fn item
        |                 help: try using a variant of the expected type: `Some(traverse_cb::<F>)`
        |
        = note: expected type `std::option::Option<unsafe extern "C" fn(i32, i32, i32, i32, i32, *mut std::ffi::c_void) -> i32>`
                   found type `extern "C" fn(i32, i32, i32, i32, i32, *mut std::ffi::c_void) -> i32 {region::Region::tree_traverse_at::traverse_cb::<F>}`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/match_param.rs:30:17
       |
    30 |                 limit as c_uint
       |                 ^^^^^^^^^^^^^^^
       |                 |
       |                 expected u64, found u32
       |                 help: you can convert an `u32` to `u64`: `(limit as c_uint).into()`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/names.rs:64:17
       |
    64 |                 foreach_cb::<F>,
       |                 ^^^^^^^^^^^^^^^ expected enum `std::option::Option`, found fn item
       |
       = note: expected type `std::option::Option<unsafe extern "C" fn(*const u8, *const u8, i32, *mut i32, *mut onig_sys::re_pattern_buffer, *mut std::ffi::c_void) -> i32>`
                  found type `extern "C" fn(*const u8, *const u8, i32, *const i32, *mut onig_sys::re_pattern_buffer, *mut std::ffi::c_void) -> i32 {names::<impl Regex>::foreach_name::foreach_cb::<F>}`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/syntax.rs:99:51
       |
    99 |             let op = onig_sys::onig_get_syntax_op(&self.raw);
       |                                                   ^^^^^^^^^ types differ in mutability
       |
       = note: expected type `*mut onig_sys::OnigSyntaxType`
                  found type `&onig_sys::OnigSyntaxType`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/syntax.rs:100:53
        |
    100 |             let op2 = onig_sys::onig_get_syntax_op2(&self.raw);
        |                                                     ^^^^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::OnigSyntaxType`
                   found type `&onig_sys::OnigSyntaxType`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/syntax.rs:135:88
        |
    135 |         SyntaxBehavior::from_bits_truncate(unsafe { onig_sys::onig_get_syntax_behavior(&self.raw) })
        |                                                                                        ^^^^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::OnigSyntaxType`
                   found type `&onig_sys::OnigSyntaxType`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/syntax.rs:160:85
        |
    160 |         RegexOptions::from_bits_truncate(unsafe { onig_sys::onig_get_syntax_options(&self.raw) })
        |                                                                                     ^^^^^^^^^ types differ in mutability
        |
        = note: expected type `*mut onig_sys::OnigSyntaxType`
                   found type `&onig_sys::OnigSyntaxType`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/utils.rs:37:77
       |
    37 |         unsafe { onig_sys::onig_unicode_define_user_property(name.as_ptr(), raw_ranges.as_ptr()) };
       |                                                                             ^^^^^^^^^^^^^^^^^^^ types differ in mutability
       |
       = note: expected type `*mut u32`
                  found type `*const u32`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/buffers.rs:28:18
       |
    27 |     fn encoding(&self) -> onig_sys::OnigEncoding {
       |                           ---------------------- expected `*mut onig_sys::OnigEncodingTypeST` because of return type
    28 |         unsafe { &onig_sys::OnigEncodingUTF8 }
       |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ in mutability
       |
       = note: expected type `*mut onig_sys::OnigEncodingTypeST`
                  found type `&onig_sys::OnigEncodingTypeST`
    
    error[E0308]: mismatched types
      --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/buffers.rs:97:27
       |
    97 |             enc: unsafe { &onig_sys::OnigEncodingASCII },
       |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ in mutability
       |
       = note: expected type `*mut onig_sys::OnigEncodingTypeST`
                  found type `&onig_sys::OnigEncodingTypeST`
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/flags.rs:263:13
        |
    263 |             onig_sys::ONIG_TRAVERSE_CALLBACK_AT_FIRST;
        |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected i32, found u32
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/flags.rs:266:13
        |
    266 |             onig_sys::ONIG_TRAVERSE_CALLBACK_AT_LAST;
        |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected i32, found u32
    
    error[E0308]: mismatched types
       --> /home/oruud/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/onig-4.3.2/src/flags.rs:269:13
        |
    269 |             onig_sys::ONIG_TRAVERSE_CALLBACK_AT_BOTH;
        |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected i32, found u32
    
    error: aborting due to 31 previous errors
    
    Some errors have detailed explanations: E0308, E0412.
    For more information about an error, try `rustc --explain E0308`.
    error: failed to compile `cargo-expand v0.4.12`, intermediate artifacts can be found at `/tmp/cargo-installgfq3Mf`
    
    Caused by:
      Could not compile `onig`.
    
    To learn more, run the command again with --verbose.
    

    Solution

    • syntec (the dependency which depends on onig) needs to:
    • prettyprint needs to:
      • [ ] depend on the new version of syntect
      • [ ] release a new version
    • cargo-expand needs to:
      • [ ] depend on new version of prettyprint
      • [ ] release a new version

    Workaround

    As mentionned in the introduction, one can still install this directly from the repo because then the Cargo.lock file is honored. However one has to use cargo build --release and then copy the resulting binary into a folder in the $PATH.

    Reviewed by barskern at 2019-08-09 23:37
  • 7. Expanding integration tests

    When running cargo expand --lib --tests integration tests (located in the tests folder) are not epanded. I have confirmed the the same tests as unit tests (located in src/lib.rs) are expanded properly.

    Is there a way to include the integration tests in the expansion?

    Reviewed by bicarlsen at 2022-05-04 20:30
  • 8. Switch to using syn-select

    dtolnay/request-for-implementation#1 asked for a crate to handle syntactic filtering by path in a single file. syn-select is now available, matching the test cases specified in the original ticket.

    Reviewed by TedDriggs at 2019-01-29 17:26
  • 9. Specifying specific functions from an impl

    Surrectly it seems to only support modules and top-level things.

    Maybe it should also support expanding only specific impl or specific function inside impl?

    Reviewed by vi at 2019-01-15 23:35
  • 10. the option `Z` is only accepted on the nightly compiler

    PS D:\RustProject\msg_chain> cargo expand
        Checking msg_chain v0.1.0 (D:\RustProject\msg_chain)
    error: the option `Z` is only accepted on the nightly compiler
    error: could not compile `msg_chain`
    To learn more, run the command again with --verbose.
    

    I am using stable tool chain

    installed toolchains
    --------------------
    
    stable-x86_64-pc-windows-msvc (default)
    nightly-x86_64-pc-windows-msvc
    
    active toolchain
    ----------------
    
    stable-x86_64-pc-windows-msvc (default)
    rustc 1.53.0 (53cb7b09b 2021-06-17)
    

    I think maybe cargo expand failure becuse my crate contain custom derive macro. And I create a crate named ctest with default code src/main.rs

    fn main() {
        println!("Hello, world!");
    }
    

    but cargo expand report the same error

    PS D:\RustProject\ctest> cargo expand
        Checking ctest v0.1.0 (D:\RustProject\ctest)
    error: the option `Z` is only accepted on the nightly compiler
    error: could not compile `ctest`
    To learn more, run the command again with --verbose.
    
    Reviewed by Goodjooy at 2021-07-19 08:32
  • 11. Issue when expanding then testing

    Hello,

    I'm trying to debug a proc_macro and I'm using the expand -> tests methods to debug the generated code.

    I came across an issue here it is:

    I've a simple tests file:

    #[test]
    fn add_one() {
    	assert!(true);
    }
    

    which generate an expand of:

    #![feature(prelude_import)]
    #![no_std]
    #[prelude_import]
    use ::std::prelude::v1::*;
    #[macro_use]
    extern crate std as std;
    extern crate test as test;
    #[cfg(test)]
    #[rustc_test_marker]
    pub const add_one: test::TestDescAndFn = test::TestDescAndFn {
        desc: test::TestDesc {
            name: test::StaticTestName("add_one"),
            ignore: false,
            allow_fail: false,
            should_panic: test::ShouldPanic::No,
        },
        testfn: test::StaticTestFn(|| test::assert_test_result(add_one())),
    };
    fn add_one() {
        if !true {
            {
                ::std::rt::begin_panic("assertion failed: true", &("tests/simple.rs", 3u32, 5u32))
            }
        };
    }
    pub mod __test_reexports {
        pub use super::add_one;
    }
    #[main]
    pub fn main() -> () {
        extern crate test;
        test::test_main_static(&[&__test_reexports::add_one])
    }
    
    

    After adding some missing #[features(test, libstd_sys_internals, rustc_attrs)]

    I try to run tests and get this error:

    error[E0618]: expected function, found `test::TestDescAndFn`
      --> tests/simple-expand.rs:18:60
       |
    11 | / pub const add_one: test::TestDescAndFn = test::TestDescAndFn {
    12 | |     desc: test::TestDesc {
    13 | |         name: test::StaticTestName("add_one"),
    14 | |         ignore: false,
    ...  |
    18 | |     testfn: test::StaticTestFn(|| test::assert_test_result(add_one())),
       | |                                                            ^^^^^^^--
       | |                                                            |
       | |                                                            call expression requires function
    19 | | };
       | |__- `test::TestDescAndFn` defined here
    

    Both the const and the function have the same name and it seems to be a conflict. By renaming the function everything work as expected.

    Am I doing something wrong or is it a limitation of how I tests ? :x

    Reviewed by Freyskeyd at 2019-08-16 14:40
  • 12. Cargo-expand tries to use beta toolchain of cargo

    I'm noticing that in some cases, cargo expand is executing the following command: (as seen using Process Hacker 2)

    "\\?\C:\Users\Stephen\.rustup\toolchains\beta-x86_64-pc-windows-msvc\bin\cargo.exe" rustc --profile=check --color never -- -o C:\Users\Stephen\AppData\Local\Temp\cargo-expandUUE54z\expanded -Zunpretty=expanded
    

    This command then fails with the error:

    error: the option `Z` is only accepted on the nightly compiler
    error: could not compile `app-server-rs`
    

    The issue would seem to be that cargo expand is using the beta-toolchain of cargo, rather than the nightly version that I have installed here: C:\Users\Stephen\.rustup\toolchains\nightly-2021-01-24-x86_64-pc-windows-msvc

    Interestingly, I had cargo expand working fine earlier today, so I must have done something to confuse it. Creating this issue so others hitting the same issue can find the solution. (once I find it myself, haha)

    Reviewed by Venryx at 2022-03-13 06:13
  • 13. Can not expand in test cfg

    Using the example code of lazy_static: https://crates.io/crates/lazy_static and enabled test cfg, the expanding failed.

    #[macro_use]
    extern crate lazy_static;
    
    use std::collections::HashMap;
    
    lazy_static! {
        static ref HASHMAP: HashMap<u32, &'static str> = {
            let mut m = HashMap::new();
            ...
            m
        };
    }
    
    fn main() {
        ...
    }
    
    E:\Test\Rust\test\expand_fail>set RUSTFLAGS=--cfg test
    
    E:\Test\Rust\test\expand_fail>cargo expand main > a.rs
        Checking lazy_static v1.4.0
    error[E0463]: can't find crate for `doc_comment`
       --> d:\Users\jinqing01\.cargo\registry\src\github.com-1ecc6299db9ec823\lazy_static-1.4.0\src\lib.rs:109:1
        |
    109 | extern crate doc_comment;
        | ^^^^^^^^^^^^^^^^^^^^^^^^^ can't find crate
    error: cannot find macro `doctest` in this scope
       --> d:\Users\jinqing01\.cargo\registry\src\github.com-1ecc6299db9ec823\lazy_static-1.4.0\src\lib.rs:112:1
        |
    112 | doctest!("../README.md");
        | ^^^^^^^
    For more information about this error, try `rustc --explain E0463`.
    error: could not compile `lazy_static` due to 2 previous errors
    
    
    Reviewed by jinq0123 at 2022-02-24 03:15
  • 14. Ignoring path to argument

    I find that cargo expand is ignoring the cargo expand path::to::module syntax.

    I suspect this is related to #31 and probably because I am using a multi binary crate --- specifically https://github.com/phillord/horned-owl.

    For example:

    cargo expand
    error: extra arguments to `rustc` can only be passed to one target, consider filtering
    the package by passing, e.g., `--lib` or `--bin NAME` to specify a single target
    

    Likewise, attempting to limit to one lib

    cargo expand io::xml::writer
    error: extra arguments to `rustc` can only be passed to one target, consider filtering
    the package by passing, e.g., `--lib` or `--bin NAME` to specify a single target
    

    Using --lib expands everything.

    cargo expand --lib io::writer::xml
    #[prelude_import]
    use std::prelude::rust_2018::*;
    #[macro_use]
    extern crate std;
    //extern crate curie;
    //extern crate enum_meta;
    #[macro_use]
    extern crate failure;
    //#[macro_use]
    extern crate indexmap;
    extern crate log;
    extern crate quick_xml;
    ..........
    

    --bin works however

    cargo expand --bin horned-triples
    cargo expand --bin horned-triples | more
        Checking horned-owl v0.9.0 (/tmp/horned-owl)
        Finished check [unoptimized + debuginfo] target(s) in 3.49s
    
    #![feature(prelude_import)]
    #[prelude_import]
    use std::prelude::rust_2018::*;
    #[macro_use]
    extern crate std;
    extern crate clap;
    extern crate failure;
    extern crate horned_owl;
    use clap::App;
    use clap::Arg;
    use clap::ArgMatches;
    use failure::Error;
    use horned_owl::error::CommandError;
    use std::fs::File;
    ...........
    
    Reviewed by phillord at 2021-03-19 15:17
  • 15. Expand trybuild-like for tests missing in cargo metadata

    Original idea: https://github.com/dtolnay/trybuild/issues/35 Suggested approach: https://github.com/dtolnay/trybuild/issues/35#issuecomment-539253118

    Solution Summary

    cargo expand should be able to expand the code of a test file somename.rs in the tests directory of a given crate via --test somename even though somename.rs exists but "somename" is not part of the test targets listed for the given crate by cargo-metadata.

    Technical Details

    The expansion should be done in a similar way as the trybuild crate handles building and testing of its tests:

    • pull out the code under test (e.g. our somename.rs) into a temp. directory
    • run rustc against that
      • just like trybuild would
      • using --pretty=expanded instead of building or testing anything
    Reviewed by Robbepop at 2019-10-08 12:42
  • 16. feature: expand only macros that come from a specific crate

    Would be good to be able to only expand specific macros and leave other source as is.

    i.e.: cargo expand --crate="my-crate-derive"

    or cargo expand --derive=MyTraitA,MyTraitB

    at the very least would be good to not expand macros that come from std.

    Reviewed by dr-bonez at 2019-09-06 22:09
Related tags
Provide expansion of proc-macros, in a way that rustc directs you directly to the issues at hand

expander Expands a proc-macro into a file, and uses a include! directive in place. Advantages Only expands a particular proc-macro, not all of them. I

Mar 10, 2022
The [cain!] macro is a macro that rewrites sequential Rust branch statements into nested branches

Note! This crate is experimental and under development. It may include bugs that alter the behavior of your code in unexpected ways. You should review

Jan 19, 2022
The cumulative sibling of `Result` and `Either`.

validated The cumulative sibling of Result and Either. The Validated type has special FromIterator instances that enable all errors in a sequence to b

May 16, 2022
A CLI command to parse kustomize build result and notify it to GitLab

ksnotify A CLI command to parse kustomize build result and notify it to GitLab Caution This repository is under development status. What ksnotify does

Nov 16, 2021
Automatically check for SPF misconfigurations that could result in email spoofing

SPFJack Email spoofing is dead, but misconfiguration never dies. Purpose This project is designed to take in domain names and review their SPF records

Mar 27, 2022
Allows processing of iterators of Result types

try-continue try-continue provides one method, try_continue, which allows you to work with iterators of type Result<T, _>, as if they were simply iter

Dec 26, 2021
wrap errors with automatic backtrace capture and print-on-result-unwrap

backtrace-error This is a tiny crate that provides a tiny error-wrapper struct BacktraceError with only two features: Captures a backtrace on From-con

Jan 11, 2022
CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a "plotable" format.

Lighthouse Groupie CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a "plotable" form

Jan 12, 2022
CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a plotable format.

Lighthouse Aggregator CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a "plotable" f

Jan 12, 2022
A (mostly) drop-in replacement for Rust's Result that provides backtrace support

Errant A (mostly) drop-in replacement for Rust's Result that provides backtrace support. Please note that Errant is still very early in development an

May 16, 2022
Slideo: This tool uses OpenCV to automatically synchronize slides with videos that show these slides.
 Slideo: This tool uses OpenCV to automatically synchronize slides with videos that show these slides.

This tool matches video frames against PDF pages by using computer vision. It also ships a web app in which you can click on a PDF page to play the video from the first frame showing the page. Its primary use-case is to quickly play a recorded lecture from a given slide.

Apr 28, 2022
Show puffin profiler flamegraph in-game using egui

Show puffin profiler flamegraph in-game using egui puffin is an instrumentation profiler where you opt-in to profile parts of your code: fn my_functio

Apr 18, 2022
belt is a command line app that can show your time from a list of selected time zones

A CLI app to show your time from a list of selected time zones, and a rust lib to parse dates in string formats that are commonly used.

May 22, 2022
A simple program to show a histogram on the terminal.

A simple program to show a histogram on the terminal.

Aug 10, 2021
A third-party iTunes addon to show the lyrics on the desktop.
A third-party iTunes addon to show the lyrics on the desktop.

iTunes Desktop Lyrics for Windows A third-party iTunes addon to show the lyrics on the desktop. Preview Prerequisites iTunes Usage Download the binary

May 3, 2022
A third-party iTunes addon to show the lyrics on the desktop.
A third-party iTunes addon to show the lyrics on the desktop.

iLyrics A third-party iTunes addon to show the lyrics on the desktop. Preview Prerequisites iTunes Usage Download the binary or build from source. Run

May 3, 2022
GitHub CLI extension to show & rename the default branch.

gh-default-branch GitHub CLI extension to show & rename the default branch. rename subcommand was inspired by this gist. ⚠️ Caution The rename subcomm

May 12, 2022
Show unused code from multi-crate Rust projects

Warnalyzer Remove unused code from multi-crate Rust projects. The dead_code lint family of rustc is limited to one crate only and thus can't tell whet

May 13, 2022
A library of to show data (in browser, evcxr_jupyter) as table, chart...

showata A library of to show data (in browser, evcxr_jupyter) as table, chart.... The crate provides display for: image vector and slice (as table) nd

May 1, 2022
Show active TCP connections on a TUI world map.
Show active TCP connections on a TUI world map.

Maperick Show active TCP connections on a TUI world map. Still WIP, but it's gonna be good. Setup git clone [email protected]:schlunsen/maperick.git cd m

Apr 30, 2022