• Stars
    star
    2,433
  • Rank 18,115 (Top 0.4 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created almost 8 years ago
  • Updated 12 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Subcommand to show result of macro expansion

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 -- -Zunpretty=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.toml if there is one (usually ~/.cargo/config.toml).

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"

Enable paging of the output with the pager setting:

[expand]
pager = true

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.

More Repositories

1

cxx

Safe interop between Rust and C++
Rust
5,106
star
2

anyhow

Flexible concrete Error type built on std::error::Error
Rust
4,193
star
3

thiserror

derive(Error) for struct and enum error types
Rust
3,352
star
4

proc-macro-workshop

Learn to write Rust procedural macros  [Rust Latam conference, Montevideo Uruguay, March 2019]
Rust
2,988
star
5

syn

Parser for Rust source code
Rust
2,574
star
6

async-trait

Type erasure for async trait methods
Rust
1,495
star
7

case-studies

Analysis of various tricky Rust code
Rust
1,340
star
8

rust-quiz

Medium to hard Rust questions with explanations
Rust
1,318
star
9

quote

Rust quasi-quoting
Rust
1,173
star
10

watt

Runtime for executing procedural macros as WebAssembly
Rust
1,062
star
11

typetag

Serde serializable and deserializable trait objects
Rust
888
star
12

paste

Macros for all your token pasting needs
Rust
852
star
13

serde-yaml

Strongly typed YAML library for Rust
Rust
804
star
14

no-panic

Attribute macro to require that the compiler prove a function can't ever panic
Rust
758
star
15

inventory

Typed distributed plugin registration
Rust
714
star
16

rust-toolchain

Concise GitHub Action for installing a Rust toolchain
Shell
621
star
17

trybuild

Test harness for ui tests of compiler diagnostics
Rust
615
star
18

miniserde

Data structure serialization library with several opposite design goals from Serde
Rust
612
star
19

reflect

Compile-time reflection API for developing robust procedural macros (proof of concept)
Rust
602
star
20

request-for-implementation

Crates that don't exist, but should
597
star
21

indoc

Indented document literals for Rust
Rust
537
star
22

prettyplease

A minimal `syn` syntax tree pretty-printer
Rust
517
star
23

erased-serde

Type-erased Serialize, Serializer and Deserializer traits
Rust
503
star
24

semver

Parser and evaluator for Cargo's flavor of Semantic Versioning
Rust
500
star
25

dyn-clone

Clone trait that is object-safe
Rust
486
star
26

ryu

Fast floating point to string conversion
Rust
471
star
27

linkme

Safe cross-platform linker shenanigans
Rust
399
star
28

semver-trick

How to avoid complicated coordinated upgrades
Rust
383
star
29

cargo-llvm-lines

Count lines of LLVM IR per generic function
Rust
368
star
30

efg

Conditional compilation using boolean expression syntax, rather than any(), all(), not()
Rust
297
star
31

rust-faq

Frequently Asked Questions Β· The Rust Programming Language
262
star
32

rustversion

Conditional compilation according to rustc compiler version
Rust
256
star
33

itoa

Fast function for printing integer primitives to a decimal string
Rust
248
star
34

path-to-error

Find out path at which a deserialization error occurred
Rust
241
star
35

cargo-tally

Graph the number of crates that depend on your crate over time
Rust
212
star
36

proc-macro-hack

Procedural macros in expression position
Rust
203
star
37

monostate

Type that deserializes only from one specific value
Rust
194
star
38

colorous

Color schemes for charts and maps
Rust
193
star
39

readonly

Struct fields that are made read-only accessible to other modules
Rust
187
star
40

dissimilar

Diff library with semantic cleanup, based on Google's diff-match-patch
Rust
175
star
41

star-history

Graph history of GitHub stars of a user or repo over time
Rust
156
star
42

ref-cast

Safely cast &T to &U where the struct U contains a single field of type T.
Rust
154
star
43

automod

Pull in every source file in a directory as a module
Rust
129
star
44

inherent

Make trait methods callable without the trait in scope
Rust
128
star
45

ghost

Define your own PhantomData
Rust
115
star
46

faketty

Wrapper to exec a command in a pty, even if redirecting the output
Rust
113
star
47

dtoa

Fast functions for printing floating-point primitives to a decimal string
Rust
110
star
48

clang-ast

Rust
108
star
49

seq-macro

Macro to repeat sequentially indexed copies of a fragment of code
Rust
102
star
50

remain

Compile-time checks that an enum or match is written in sorted order
Rust
99
star
51

mashup

Concatenate identifiers in a macro invocation
Rust
96
star
52

noisy-clippy

Rust
84
star
53

tt-call

Token tree calling convention
Rust
77
star
54

basic-toml

Minimal TOML library with few dependencies
Rust
76
star
55

squatternaut

A snapshot of name squatting on crates.io
Rust
73
star
56

serde-ignored

Find out about keys that are ignored when deserializing data
Rust
68
star
57

enumn

Convert number to enum
Rust
66
star
58

bootstrap

Bootstrapping rustc from source
Shell
62
star
59

essay

docs.rs as a publishing platform?
Rust
62
star
60

db-dump

Library for scripting analyses against crates.io's database dumps
Rust
60
star
61

scratch

Compile-time temporary directory shared by multiple crates and erased by `cargo clean`
Rust
59
star
62

gflags

Command line flags library that does not require a central list of all the flags
Rust
55
star
63

install

Fast `cargo install` action using a GitHub-based binary cache
Shell
55
star
64

oqueue

Non-interleaving multithreaded output queue
Rust
53
star
65

serde-starlark

Serde serializer for generating Starlark build targets
Rust
53
star
66

build-alert

Rust
51
star
67

unicode-ident

Determine whether characters have the XID_Start or XID_Continue properties
Rust
51
star
68

lalrproc

Proof of concept of procedural macro input parsed by LALRPOP
Rust
50
star
69

dragonbox

Rust
50
star
70

sha1dir

Checksum of a directory tree
Rust
38
star
71

hackfn

Fake implementation of `std::ops::Fn` for user-defined data types
Rust
38
star
72

reduce

iter.reduce(fn) in Rust
Rust
37
star
73

link-cplusplus

Link libstdc++ or libc++ automatically or manually
Rust
36
star
74

argv

Non-allocating iterator over command line arguments
Rust
33
star
75

get-all-crates

Download .crate files of all versions of all crates from crates.io
Rust
31
star
76

threadbound

Make any value Sync but only available on its original thread
Rust
31
star
77

dircnt

Count directory entriesβ€”`ls | wc -l` but faster
Rust
27
star
78

unsafe-libyaml

libyaml transpiled to rust by c2rust
Rust
27
star
79

serde-stacker

Serializer and Deserializer adapters that avoid stack overflows by dynamically growing the stack
Rust
27
star
80

cargo-unlock

Remove Cargo.lock lockfile
Rust
25
star
81

respan

Macros to erase scope information from tokens
Rust
24
star
82

isatty

libc::isatty that also works on Windows
Rust
21
star
83

iota

Related constants in Rust: 1 << iota
Rust
20
star
84

foreach

18
star
85

bufsize

bytes::BufMut implementation to count buffer size
Rust
18
star
86

hire

How to hire dtolnay
18
star
87

precise

Full precision decimal representation of f64
Rust
17
star
88

dashboard

15
star
89

rustflags

Parser for CARGO_ENCODED_RUSTFLAGS
Rust
13
star
90

libfyaml-rs

Rust binding for libfyaml
Rust
11
star
91

install-buck2

Install precompiled Buck2 build system
6
star
92

mailingset

Set-algebraic operations on mailing lists
Python
5
star
93

.github

5
star
94

jq-gdb

gdb pretty-printer for jv objects
Python
1
star