#inspect #cargo-subcommand #cargo #cli #unpretty

bin+lib cargo-inspect

此插件扩展了 Cargo,允许您对 Rust 代码进行反解糖,并查看幕后发生了什么

12 个版本 (重大变更)

0.10.3 2020 年 6 月 5 日
0.10.0 2019 年 2 月 22 日
0.5.0 2018 年 12 月 16 日
0.4.0 2018 年 11 月 30 日

#248 in Cargo 插件

Apache-2.0/MITLGPL-3.0-or-later

200KB
457

cargo-inspect

Logo

docs Build Status

Rust 在幕后做了什么?

生活只有两种方式。
一种是将一切视为理所当然,另一种是将一切视为奇迹。 —— 阿尔伯特·爱因斯坦

安装

您需要 Rust 夜间版本和 rustfmt 以开始。
您可以通过 rustup 安装这些。

rustup install nightly
rustup component add rustfmt

一切准备就绪?让我们开始吧!

cargo install cargo-inspect

使用方法

在任何 Rust 文件上调用它

cargo inspect main.rs

如果您没有指定文件,将分析当前包。

cargo inspect

根据包的大小,这可能需要一段时间。
请耐心等待。

它还可以比较两个文件输出!试试这个

cargo inspect --diff examples/range.rs,examples/range_inclusive.rs --plain

配置

USAGE:
    cargo inspect [FLAGS] [OPTIONS] [INPUT_FILE]

FLAGS:
    -h, --help
            Prints help information

        --list-themes
            Should we list all pretty printer themes?

        --plain
            Don't highlight output

    -V, --version
            Prints version information

    -v, --verbose
            Print the original code as a comment above the desugared code


OPTIONS:
        --theme <THEME>
            Specify a theme override for the pretty printer

        --diff <files>
            Diff input files

        --format <format>
            Override for the format that gets outputted when the `unpretty` mode is set to `flowgraph` [default: svg]

        --unpretty <unpretty>
            rustc "unpretty" parameters

            *Note*: For `--unpretty=flowgraph=[symbol]` you need to have `dot` on your PATH. [default: hir]

ARGS:
    <INPUT_FILE>
            Input file

背景

Rust 允许使用许多语法糖,这使其编写起来很愉快。然而,有时很难揭开幕布,看看编译器对我们代码做了什么。

引用 @tshepang 的话,“了解这些便利之处是好事,以避免对幕后发生的事情感到困惑……我们对世界的神秘思考越少,就越好。”

  • 生命周期省略
  • 类型推断
  • 语法糖
  • 隐式解引用
  • 类型转换
  • 隐藏代码(例如,预定义)

我总是对编程语言在幕后如何工作很感兴趣,我的代码是如何展开的,以便编译器后端更容易维护。

目标是使编译器更容易为普通人所接近。
神秘!探索!发现!

我的博客 上了解更多关于 cargo-inspect 的背景信息。

代码示例

If-let 被反解糖为 match

考虑以下代码片段

fn main() {
    if let Some(x) = Some(1) {
        // Do something with x
    }
}

编译时,Rust 首先会对其进行解糖。要查看这一步骤后的代码,请运行

cargo inspect examples/if_let.rs

这会产生以下输出

Please run the command to reproduce the desugared output

您可以看到 if let 被解糖为一个 match 语句。

要更改颜色方案,请尝试 cargo-inspect --list-themes,例如。

cargo inspect examples/if_let.rs --theme GitHub

Please run the command to reproduce the desugared output

哦,如果您已安装 graphviz,您还可以从代码中打印出漂亮的流程图

cargo inspect --unpretty=flowgraph=main examples/if_let.rs

Please run the command to reproduce the desugared output

更多示例

请参阅 examples 文件夹中的更多示例。您也可以贡献更多。

魔法调料

世界上最好的事物都是由简单的构建块组装而成的。这个工具站在巨人的肩膀上。为了施展魔法,它会运行以下命令

  1. rustc -Zinspect=hir,用于检索 HIR。
  2. rustfmt,用于格式化输出。
  3. prettyprint,用于语法高亮,这是一个围绕出色的 syntectbat 集成的包装。

贡献

这是一个年轻的项目,既有优点也有缺点。

  • 一切都在变化中,事物可能随时会出错。😫
  • 有许多机会塑造和塑造这个项目。😊

因此,今天就开始贡献吧!

已知问题

到目前为止,这是一个非常脆弱的工具。如果它失败,它可能会产生可怕的输出。已被警告。但当然,它不会吃掉您的代码。😊

许可

根据您的要求,许可为以下之一

任选其一。

致谢

放大镜由 Rawpixel.com 设计

依赖关系

~19–31MB
~433K SLoC