Full Code of oli-obk/priroda for AI

main 0cc9d44c3726 cached
21 files
129.3 KB
34.4k tokens
120 symbols
1 requests
Download .txt
Repository: oli-obk/priroda
Branch: main
Commit: 0cc9d44c3726
Files: 21
Total size: 129.3 KB

Directory structure:
gitextract_34yhs5wo/

├── .github/
│   └── workflows/
│       └── build.yml
├── .gitignore
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── Rocket.toml
├── example.rs
├── resources/
│   ├── positioning.css
│   ├── style-default.css
│   ├── svg-pan-zoom.js
│   └── zoom_mir.js
├── rust-toolchain
└── src/
    ├── main.rs
    ├── render/
    │   ├── graphviz.rs
    │   ├── locals.rs
    │   ├── mod.rs
    │   └── source.rs
    ├── step.rs
    └── watch/
        ├── mod.rs
        └── stack_trace.rs

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/build.yml
================================================
name: Continuous Integration

on: [push, pull_request]

jobs:
  check:
    name: Check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      # Toolchain installation should appear as a seperate step for timing purposes
      - run: rustup show
      - name: Setup Graphviz
        uses: ts-graphviz/setup-graphviz@v1
      - uses: actions-rs/cargo@v1
        with:
          command: check
  fmt:
    name: Rustfmt
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: rustup component add rustfmt
      - uses: actions-rs/cargo@v1
        with:
          command: fmt
          args: --all -- --check


================================================
FILE: .gitignore
================================================
/target
flame_graph*
config.json


================================================
FILE: Cargo.toml
================================================
[package]
authors = ["Oliver Schneider <priroda-tsm-i-77ksi-11f77i@oli-obk.de>"]
description = "A graphical debugger for Rust MIR."
license = "MIT/Apache-2.0"
name = "priroda"
repository = "https://github.com/oli-obk/priroda"
version = "0.1.0"
edition = "2018"


[dependencies]
regex = "1.3"
lazy_static = "1.4.0"
rocket = "0.4.7"
# This needs to be the version of miri for the nightly in the `rust-toolchain` file
miri = { git = "https://github.com/rust-lang/miri.git", rev = "ae964207bb17911cf96d9744d9469fa2734093a8" }

log = "0.4"
env_logger = "0.7"

serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

open = "1.4.0"
syntect = "4.2"
horrorshow = "0.8"
cgraph = { git = "https://github.com/oli-obk/cgraph.git", rev = "5e6a6d4527522609772a9a9a1565b74c9bfe1560" }

# Uncomment to use local checkout of miri
# [patch."https://github.com/rust-lang/miri.git"]
# miri = { path = "../miri" }

[features]
static_resources = []

[package.metadata.rust-analyzer]
rustc_private = true

[profile.dev]
debug = 1


================================================
FILE: LICENSE-APACHE
================================================
                              Apache License
                        Version 2.0, January 2004
                     http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

   "License" shall mean the terms and conditions for use, reproduction,
   and distribution as defined by Sections 1 through 9 of this document.

   "Licensor" shall mean the copyright owner or entity authorized by
   the copyright owner that is granting the License.

   "Legal Entity" shall mean the union of the acting entity and all
   other entities that control, are controlled by, or are under common
   control with that entity. For the purposes of this definition,
   "control" means (i) the power, direct or indirect, to cause the
   direction or management of such entity, whether by contract or
   otherwise, or (ii) ownership of fifty percent (50%) or more of the
   outstanding shares, or (iii) beneficial ownership of such entity.

   "You" (or "Your") shall mean an individual or Legal Entity
   exercising permissions granted by this License.

   "Source" form shall mean the preferred form for making modifications,
   including but not limited to software source code, documentation
   source, and configuration files.

   "Object" form shall mean any form resulting from mechanical
   transformation or translation of a Source form, including but
   not limited to compiled object code, generated documentation,
   and conversions to other media types.

   "Work" shall mean the work of authorship, whether in Source or
   Object form, made available under the License, as indicated by a
   copyright notice that is included in or attached to the work
   (an example is provided in the Appendix below).

   "Derivative Works" shall mean any work, whether in Source or Object
   form, that is based on (or derived from) the Work and for which the
   editorial revisions, annotations, elaborations, or other modifications
   represent, as a whole, an original work of authorship. For the purposes
   of this License, Derivative Works shall not include works that remain
   separable from, or merely link (or bind by name) to the interfaces of,
   the Work and Derivative Works thereof.

   "Contribution" shall mean any work of authorship, including
   the original version of the Work and any modifications or additions
   to that Work or Derivative Works thereof, that is intentionally
   submitted to Licensor for inclusion in the Work by the copyright owner
   or by an individual or Legal Entity authorized to submit on behalf of
   the copyright owner. For the purposes of this definition, "submitted"
   means any form of electronic, verbal, or written communication sent
   to the Licensor or its representatives, including but not limited to
   communication on electronic mailing lists, source code control systems,
   and issue tracking systems that are managed by, or on behalf of, the
   Licensor for the purpose of discussing and improving the Work, but
   excluding communication that is conspicuously marked or otherwise
   designated in writing by the copyright owner as "Not a Contribution."

   "Contributor" shall mean Licensor and any individual or Legal Entity
   on behalf of whom a Contribution has been received by Licensor and
   subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   copyright license to reproduce, prepare Derivative Works of,
   publicly display, publicly perform, sublicense, and distribute the
   Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   (except as stated in this section) patent license to make, have made,
   use, offer to sell, sell, import, and otherwise transfer the Work,
   where such license applies only to those patent claims licensable
   by such Contributor that are necessarily infringed by their
   Contribution(s) alone or by combination of their Contribution(s)
   with the Work to which such Contribution(s) was submitted. If You
   institute patent litigation against any entity (including a
   cross-claim or counterclaim in a lawsuit) alleging that the Work
   or a Contribution incorporated within the Work constitutes direct
   or contributory patent infringement, then any patent licenses
   granted to You under this License for that Work shall terminate
   as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
   Work or Derivative Works thereof in any medium, with or without
   modifications, and in Source or Object form, provided that You
   meet the following conditions:

   (a) You must give any other recipients of the Work or
       Derivative Works a copy of this License; and

   (b) You must cause any modified files to carry prominent notices
       stating that You changed the files; and

   (c) You must retain, in the Source form of any Derivative Works
       that You distribute, all copyright, patent, trademark, and
       attribution notices from the Source form of the Work,
       excluding those notices that do not pertain to any part of
       the Derivative Works; and

   (d) If the Work includes a "NOTICE" text file as part of its
       distribution, then any Derivative Works that You distribute must
       include a readable copy of the attribution notices contained
       within such NOTICE file, excluding those notices that do not
       pertain to any part of the Derivative Works, in at least one
       of the following places: within a NOTICE text file distributed
       as part of the Derivative Works; within the Source form or
       documentation, if provided along with the Derivative Works; or,
       within a display generated by the Derivative Works, if and
       wherever such third-party notices normally appear. The contents
       of the NOTICE file are for informational purposes only and
       do not modify the License. You may add Your own attribution
       notices within Derivative Works that You distribute, alongside
       or as an addendum to the NOTICE text from the Work, provided
       that such additional attribution notices cannot be construed
       as modifying the License.

   You may add Your own copyright statement to Your modifications and
   may provide additional or different license terms and conditions
   for use, reproduction, or distribution of Your modifications, or
   for any such Derivative Works as a whole, provided Your use,
   reproduction, and distribution of the Work otherwise complies with
   the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
   any Contribution intentionally submitted for inclusion in the Work
   by You to the Licensor shall be under the terms and conditions of
   this License, without any additional terms or conditions.
   Notwithstanding the above, nothing herein shall supersede or modify
   the terms of any separate license agreement you may have executed
   with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
   names, trademarks, service marks, or product names of the Licensor,
   except as required for reasonable and customary use in describing the
   origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
   agreed to in writing, Licensor provides the Work (and each
   Contributor provides its Contributions) on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   implied, including, without limitation, any warranties or conditions
   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
   PARTICULAR PURPOSE. You are solely responsible for determining the
   appropriateness of using or redistributing the Work and assume any
   risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
   whether in tort (including negligence), contract, or otherwise,
   unless required by applicable law (such as deliberate and grossly
   negligent acts) or agreed to in writing, shall any Contributor be
   liable to You for damages, including any direct, indirect, special,
   incidental, or consequential damages of any character arising as a
   result of this License or out of the use or inability to use the
   Work (including but not limited to damages for loss of goodwill,
   work stoppage, computer failure or malfunction, or any and all
   other commercial damages or losses), even if such Contributor
   has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
   the Work or Derivative Works thereof, You may choose to offer,
   and charge a fee for, acceptance of support, warranty, indemnity,
   or other liability obligations and/or rights consistent with this
   License. However, in accepting such obligations, You may act only
   on Your own behalf and on Your sole responsibility, not on behalf
   of any other Contributor, and only if You agree to indemnify,
   defend, and hold each Contributor harmless for any liability
   incurred by, or claims asserted against, such Contributor by reason
   of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

   To apply the Apache License to your work, attach the following
   boilerplate notice, with the fields enclosed by brackets "[]"
   replaced with your own identifying information. (Don't include
   the brackets!)  The text should be enclosed in the appropriate
   comment syntax for the file format. We also recommend that a
   file or class name and description of purpose be included on the
   same "printed page" as the copyright notice for easier
   identification within third-party archives.

Copyright 2016 The Miri Developers

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


================================================
FILE: LICENSE-MIT
================================================
Copyright (c) 2016 The Miri Developers

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.


================================================
FILE: README.md
================================================
# Priroda

Priroda is a graphical (UI in browser) debugger for Rust programs

## Setup

You need a few things before you can get started. At the very minimum you need to have
the graphviz libraries present.

* debian/ubuntu: `apt install libgraphviz-dev`

Next, you're going to want a libstd with full MIR. The easiest way to obtain this is via
`cargo miri`:

```bash
# Install cargo miri:
rustup component add miri
# Compile libstd:
cargo miri setup
# Set the MIRI_SYSROOT environment variable to the path printed by the setup command:
export MIRI_SYSROOT=...
```

## Features

* Supports commands known from gdb
  * next, step, continue
* Inspect memory of all stack frames visually
* Follow pointers by clicking hyperlinks
* Track your progress through a function in a graph of the MIR
* Style your debugging experience with CSS

## Usage

`cargo run some_rust_file.rs` will automatically start a http server and open a
browser. UI is changing rapidly right now, so you need to figure out how to use
it by yourself (or by asking on irc) for now.

## Contributing and getting help

Check out the issues on this GitHub repository for some ideas. There's lots that
needs to be done that I haven't documented in the issues yet, however. For more
ideas or help with running or hacking on Priroda, you can ask at [`#miri`] on the
rust-lang zulip.

[`#miri`]: https://rust-lang.zulipchat.com/#narrow/stream/269128-miri

### Miri

This project depends entirely on [Miri](https://github.com/rust-lang/miri).
So if you want to improve something that we fail to interpret, add a unit test
to Miri and fix it there.

## License

Licensed under either of

* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))
* MIT license ([LICENSE-MIT](LICENSE-MIT))

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you shall be dual licensed as above, without any
additional terms or conditions.


================================================
FILE: Rocket.toml
================================================
[development]
address = "localhost"
port = 54321
#spawn_browser = true

[production]
address = "0.0.0.0"
port = 8080
spawn_browser = false

================================================
FILE: example.rs
================================================
#![allow(dead_code)]

fn some_fn() {
    let mut val = 2;
    let mut my_wrapper = MyWrapper(&mut val);
    let wrapper_ref = &mut my_wrapper;
    for i in 0..16 {
        *wrapper_ref.0 = i;
    }
}

struct MyWrapper<'a>(&'a mut u8);

struct SomeRandomStruct<'a, A> {
    ernrer: u8,
    feijoc: i64,
    ioieoe: bool,
    fewije: char,
    chr_ref: &'a char,
    efoiri: A,
    irrfio: SomeOtherStruct,
}

struct SomeOtherStruct {
    efufrr: u8,
    frireg: u16,
}

union SomeUnion {
    a: bool,
    b: u64,
}

fn main() {
    let chr = '4';
    let _rer = SomeRandomStruct {
        ernrer: 24,
        feijoc: -34438,
        ioieoe: true,
        fewije: '@',
        chr_ref: &chr,
        efoiri: Some(2u16),
        irrfio: SomeOtherStruct {
            efufrr: 34,
            frireg: 45804,
        },
    };
    let u = SomeUnion { a: true };
    let abc = Box::new(42);
    some_fn();
    let f = 1.4f64;
    let _sum = 1f64
    +
    f;
    let _s = "ieeoe";
    let _bcd: Box<[u8]> = Box::new([0, 1]);
    let _d = true;
    format!("ewioio: {}", abc);
}


================================================
FILE: resources/positioning.css
================================================
* {
  box-sizing: border-box;
}

body {
  margin: 0px;
  height: 100vh;
  overflow-y: hidden;
}

#left, #right {
  display: inline-block;
  width: calc(50vw - 4px);
  height: 100vh;
  margin: 2px;
  vertical-align: top;
  overflow: auto;
}

#mir {
  width: 100%;
  height: calc(100% - 150px);
}

#mir > svg {
  display: block;
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

#mir > svg:first-child {
  width: 100%;
  height: 100%;
}

#stack, #locals {
  overflow: auto;
}

.vertical {
  writing-mode: tb-rl;
}

@media only screen and (max-width: 600px) {
  body {
    height: unset;
    overflow-y: scroll;
  }
  #left, #right {
    display: block;
    width: 100vw;
    height: unset;
    margin: 2px 0;
    padding: 0 5px;
  }
  #mir {
    width: calc(100vw - 100px) !important;
    height: unset;
  }
  #mir:first-child {
    height: 50vh !important;
  }
}


================================================
FILE: resources/style-default.css
================================================
#mir {
  border: 2px grey solid;
}

#stack {
  border: grey 2px solid;
  margin: 2px 0;
  padding: 2px;
}

#stack table tr td:nth-child(1) {
  color: red;
}

#locals {
  border: grey 2px solid;
  margin: 2px 0;
}

#locals table {
  border-collapse:collapse;
  border: none;
  font-family: monospace;
}

/* left top corner */
#locals table tbody :first-child td {
  border: none;
}

#locals table tr th {
  background-color: lightgrey;
}

#locals table tr th {
  min-width: 14px;
  font-size: 12px
}

#return_ptr {
  display: inline-block;
  border: 1px solid black;
}

#commands {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  padding: 2px;
}

#commands > a {
  text-decoration: none;
  padding-right: 2px;
  margin: 3px;
}

#commands > a > div {
  padding: 5px 7px;
  background: #4479BA;
  color: #FFF;
  border-radius: 4px;
  border: solid 1px #20538D;
  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
  transition-duration: 0.2s;
  user-select:none;
}

#commands > a > div:hover {
  background: #356094;
  border: solid 1px #2A4E77;
  text-decoration: none;
}

#commands > a > div:active {
  box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);
  background: #2E5481;
  border: solid 1px #203E5F;
}

#stack table {
  border: none;
  border-collapse: collapse;
}

#stack table tr :first-child {
  border: none;
}

td {
  padding: 0px;
}


================================================
FILE: resources/svg-pan-zoom.js
================================================
// svg-pan-zoom v3.5.2
// https://github.com/ariutta/svg-pan-zoom
!function t(e,o,n){function i(r,a){if(!o[r]){if(!e[r]){var l="function"==typeof require&&require;if(!a&&l)return l(r,!0);if(s)return s(r,!0);var u=new Error("Cannot find module '"+r+"'");throw u.code="MODULE_NOT_FOUND",u}var h=o[r]={exports:{}};e[r][0].call(h.exports,function(t){var o=e[r][1][t];return i(o?o:t)},h,h.exports,t,e,o,n)}return o[r].exports}for(var s="function"==typeof require&&require,r=0;r<n.length;r++)i(n[r]);return i}({1:[function(t,e,o){var n=t("./svg-pan-zoom.js");!function(t,o){"function"==typeof define&&define.amd?define("svg-pan-zoom",function(){return n}):"undefined"!=typeof e&&e.exports&&(e.exports=n,t.svgPanZoom=n)}(window,document)},{"./svg-pan-zoom.js":4}],2:[function(t,e,o){var n=t("./svg-utilities");e.exports={enable:function(t){var e=t.svg.querySelector("defs");e||(e=document.createElementNS(n.svgNS,"defs"),t.svg.appendChild(e));var o=e.querySelector("style#svg-pan-zoom-controls-styles");if(!o){var i=document.createElementNS(n.svgNS,"style");i.setAttribute("id","svg-pan-zoom-controls-styles"),i.setAttribute("type","text/css"),i.textContent=".svg-pan-zoom-control { cursor: pointer; fill: black; fill-opacity: 0.333; } .svg-pan-zoom-control:hover { fill-opacity: 0.8; } .svg-pan-zoom-control-background { fill: white; fill-opacity: 0.5; } .svg-pan-zoom-control-background { fill-opacity: 0.8; }",e.appendChild(i)}var s=document.createElementNS(n.svgNS,"g");s.setAttribute("id","svg-pan-zoom-controls"),s.setAttribute("transform","translate("+(t.width-70)+" "+(t.height-76)+") scale(0.75)"),s.setAttribute("class","svg-pan-zoom-control"),s.appendChild(this._createZoomIn(t)),s.appendChild(this._createZoomReset(t)),s.appendChild(this._createZoomOut(t)),t.svg.appendChild(s),t.controlIcons=s},_createZoomIn:function(t){var e=document.createElementNS(n.svgNS,"g");e.setAttribute("id","svg-pan-zoom-zoom-in"),e.setAttribute("transform","translate(30.5 5) scale(0.015)"),e.setAttribute("class","svg-pan-zoom-control"),e.addEventListener("click",function(){t.getPublicInstance().zoomIn()},!1),e.addEventListener("touchstart",function(){t.getPublicInstance().zoomIn()},!1);var o=document.createElementNS(n.svgNS,"rect");o.setAttribute("x","0"),o.setAttribute("y","0"),o.setAttribute("width","1500"),o.setAttribute("height","1400"),o.setAttribute("class","svg-pan-zoom-control-background"),e.appendChild(o);var i=document.createElementNS(n.svgNS,"path");return i.setAttribute("d","M1280 576v128q0 26 -19 45t-45 19h-320v320q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-320h-320q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h320v-320q0 -26 19 -45t45 -19h128q26 0 45 19t19 45v320h320q26 0 45 19t19 45zM1536 1120v-960 q0 -119 -84.5 -203.5t-203.5 -84.5h-960q-119 0 -203.5 84.5t-84.5 203.5v960q0 119 84.5 203.5t203.5 84.5h960q119 0 203.5 -84.5t84.5 -203.5z"),i.setAttribute("class","svg-pan-zoom-control-element"),e.appendChild(i),e},_createZoomReset:function(t){var e=document.createElementNS(n.svgNS,"g");e.setAttribute("id","svg-pan-zoom-reset-pan-zoom"),e.setAttribute("transform","translate(5 35) scale(0.4)"),e.setAttribute("class","svg-pan-zoom-control"),e.addEventListener("click",function(){t.getPublicInstance().reset()},!1),e.addEventListener("touchstart",function(){t.getPublicInstance().reset()},!1);var o=document.createElementNS(n.svgNS,"rect");o.setAttribute("x","2"),o.setAttribute("y","2"),o.setAttribute("width","182"),o.setAttribute("height","58"),o.setAttribute("class","svg-pan-zoom-control-background"),e.appendChild(o);var i=document.createElementNS(n.svgNS,"path");i.setAttribute("d","M33.051,20.632c-0.742-0.406-1.854-0.609-3.338-0.609h-7.969v9.281h7.769c1.543,0,2.701-0.188,3.473-0.562c1.365-0.656,2.048-1.953,2.048-3.891C35.032,22.757,34.372,21.351,33.051,20.632z"),i.setAttribute("class","svg-pan-zoom-control-element"),e.appendChild(i);var s=document.createElementNS(n.svgNS,"path");return s.setAttribute("d","M170.231,0.5H15.847C7.102,0.5,0.5,5.708,0.5,11.84v38.861C0.5,56.833,7.102,61.5,15.847,61.5h154.384c8.745,0,15.269-4.667,15.269-10.798V11.84C185.5,5.708,178.976,0.5,170.231,0.5z M42.837,48.569h-7.969c-0.219-0.766-0.375-1.383-0.469-1.852c-0.188-0.969-0.289-1.961-0.305-2.977l-0.047-3.211c-0.03-2.203-0.41-3.672-1.142-4.406c-0.732-0.734-2.103-1.102-4.113-1.102h-7.05v13.547h-7.055V14.022h16.524c2.361,0.047,4.178,0.344,5.45,0.891c1.272,0.547,2.351,1.352,3.234,2.414c0.731,0.875,1.31,1.844,1.737,2.906s0.64,2.273,0.64,3.633c0,1.641-0.414,3.254-1.242,4.84s-2.195,2.707-4.102,3.363c1.594,0.641,2.723,1.551,3.387,2.73s0.996,2.98,0.996,5.402v2.32c0,1.578,0.063,2.648,0.19,3.211c0.19,0.891,0.635,1.547,1.333,1.969V48.569z M75.579,48.569h-26.18V14.022h25.336v6.117H56.454v7.336h16.781v6H56.454v8.883h19.125V48.569z M104.497,46.331c-2.44,2.086-5.887,3.129-10.34,3.129c-4.548,0-8.125-1.027-10.731-3.082s-3.909-4.879-3.909-8.473h6.891c0.224,1.578,0.662,2.758,1.316,3.539c1.196,1.422,3.246,2.133,6.15,2.133c1.739,0,3.151-0.188,4.236-0.562c2.058-0.719,3.087-2.055,3.087-4.008c0-1.141-0.504-2.023-1.512-2.648c-1.008-0.609-2.607-1.148-4.796-1.617l-3.74-0.82c-3.676-0.812-6.201-1.695-7.576-2.648c-2.328-1.594-3.492-4.086-3.492-7.477c0-3.094,1.139-5.664,3.417-7.711s5.623-3.07,10.036-3.07c3.685,0,6.829,0.965,9.431,2.895c2.602,1.93,3.966,4.73,4.093,8.402h-6.938c-0.128-2.078-1.057-3.555-2.787-4.43c-1.154-0.578-2.587-0.867-4.301-0.867c-1.907,0-3.428,0.375-4.565,1.125c-1.138,0.75-1.706,1.797-1.706,3.141c0,1.234,0.561,2.156,1.682,2.766c0.721,0.406,2.25,0.883,4.589,1.43l6.063,1.43c2.657,0.625,4.648,1.461,5.975,2.508c2.059,1.625,3.089,3.977,3.089,7.055C108.157,41.624,106.937,44.245,104.497,46.331z M139.61,48.569h-26.18V14.022h25.336v6.117h-18.281v7.336h16.781v6h-16.781v8.883h19.125V48.569z M170.337,20.14h-10.336v28.43h-7.266V20.14h-10.383v-6.117h27.984V20.14z"),s.setAttribute("class","svg-pan-zoom-control-element"),e.appendChild(s),e},_createZoomOut:function(t){var e=document.createElementNS(n.svgNS,"g");e.setAttribute("id","svg-pan-zoom-zoom-out"),e.setAttribute("transform","translate(30.5 70) scale(0.015)"),e.setAttribute("class","svg-pan-zoom-control"),e.addEventListener("click",function(){t.getPublicInstance().zoomOut()},!1),e.addEventListener("touchstart",function(){t.getPublicInstance().zoomOut()},!1);var o=document.createElementNS(n.svgNS,"rect");o.setAttribute("x","0"),o.setAttribute("y","0"),o.setAttribute("width","1500"),o.setAttribute("height","1400"),o.setAttribute("class","svg-pan-zoom-control-background"),e.appendChild(o);var i=document.createElementNS(n.svgNS,"path");return i.setAttribute("d","M1280 576v128q0 26 -19 45t-45 19h-896q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h896q26 0 45 19t19 45zM1536 1120v-960q0 -119 -84.5 -203.5t-203.5 -84.5h-960q-119 0 -203.5 84.5t-84.5 203.5v960q0 119 84.5 203.5t203.5 84.5h960q119 0 203.5 -84.5 t84.5 -203.5z"),i.setAttribute("class","svg-pan-zoom-control-element"),e.appendChild(i),e},disable:function(t){t.controlIcons&&(t.controlIcons.parentNode.removeChild(t.controlIcons),t.controlIcons=null)}}},{"./svg-utilities":5}],3:[function(t,e,o){var n=t("./svg-utilities"),i=t("./utilities"),s=function(t,e){this.init(t,e)};s.prototype.init=function(t,e){this.viewport=t,this.options=e,this.originalState={zoom:1,x:0,y:0},this.activeState={zoom:1,x:0,y:0},this.updateCTMCached=i.proxy(this.updateCTM,this),this.requestAnimationFrame=i.createRequestAnimationFrame(this.options.refreshRate),this.viewBox={x:0,y:0,width:0,height:0},this.cacheViewBox();var o=this.processCTM();this.setCTM(o),this.updateCTM()},s.prototype.cacheViewBox=function(){var t=this.options.svg.getAttribute("viewBox");if(t){var e=t.split(/[\s\,]/).filter(function(t){return t}).map(parseFloat);this.viewBox.x=e[0],this.viewBox.y=e[1],this.viewBox.width=e[2],this.viewBox.height=e[3];var o=Math.min(this.options.width/this.viewBox.width,this.options.height/this.viewBox.height);this.activeState.zoom=o,this.activeState.x=(this.options.width-this.viewBox.width*o)/2,this.activeState.y=(this.options.height-this.viewBox.height*o)/2,this.updateCTMOnNextFrame(),this.options.svg.removeAttribute("viewBox")}else this.simpleViewBoxCache()},s.prototype.simpleViewBoxCache=function(){var t=this.viewport.getBBox();this.viewBox.x=t.x,this.viewBox.y=t.y,this.viewBox.width=t.width,this.viewBox.height=t.height},s.prototype.getViewBox=function(){return i.extend({},this.viewBox)},s.prototype.processCTM=function(){var t=this.getCTM();if(this.options.fit||this.options.contain){var e;e=this.options.fit?Math.min(this.options.width/this.viewBox.width,this.options.height/this.viewBox.height):Math.max(this.options.width/this.viewBox.width,this.options.height/this.viewBox.height),t.a=e,t.d=e,t.e=-this.viewBox.x*e,t.f=-this.viewBox.y*e}if(this.options.center){var o=.5*(this.options.width-(this.viewBox.width+2*this.viewBox.x)*t.a),n=.5*(this.options.height-(this.viewBox.height+2*this.viewBox.y)*t.a);t.e=o,t.f=n}return this.originalState.zoom=t.a,this.originalState.x=t.e,this.originalState.y=t.f,t},s.prototype.getOriginalState=function(){return i.extend({},this.originalState)},s.prototype.getState=function(){return i.extend({},this.activeState)},s.prototype.getZoom=function(){return this.activeState.zoom},s.prototype.getRelativeZoom=function(){return this.activeState.zoom/this.originalState.zoom},s.prototype.computeRelativeZoom=function(t){return t/this.originalState.zoom},s.prototype.getPan=function(){return{x:this.activeState.x,y:this.activeState.y}},s.prototype.getCTM=function(){var t=this.options.svg.createSVGMatrix();return t.a=this.activeState.zoom,t.b=0,t.c=0,t.d=this.activeState.zoom,t.e=this.activeState.x,t.f=this.activeState.y,t},s.prototype.setCTM=function(t){var e=this.isZoomDifferent(t),o=this.isPanDifferent(t);if(e||o){if(e&&(this.options.beforeZoom(this.getRelativeZoom(),this.computeRelativeZoom(t.a))===!1?(t.a=t.d=this.activeState.zoom,e=!1):(this.updateCache(t),this.options.onZoom(this.getRelativeZoom()))),o){var n=this.options.beforePan(this.getPan(),{x:t.e,y:t.f}),s=!1,r=!1;n===!1?(t.e=this.getPan().x,t.f=this.getPan().y,s=r=!0):i.isObject(n)&&(n.x===!1?(t.e=this.getPan().x,s=!0):i.isNumber(n.x)&&(t.e=n.x),n.y===!1?(t.f=this.getPan().y,r=!0):i.isNumber(n.y)&&(t.f=n.y)),s&&r||!this.isPanDifferent(t)?o=!1:(this.updateCache(t),this.options.onPan(this.getPan()))}(e||o)&&this.updateCTMOnNextFrame()}},s.prototype.isZoomDifferent=function(t){return this.activeState.zoom!==t.a},s.prototype.isPanDifferent=function(t){return this.activeState.x!==t.e||this.activeState.y!==t.f},s.prototype.updateCache=function(t){this.activeState.zoom=t.a,this.activeState.x=t.e,this.activeState.y=t.f},s.prototype.pendingUpdate=!1,s.prototype.updateCTMOnNextFrame=function(){this.pendingUpdate||(this.pendingUpdate=!0,this.requestAnimationFrame.call(window,this.updateCTMCached))},s.prototype.updateCTM=function(){var t=this.getCTM();n.setCTM(this.viewport,t,this.defs),this.pendingUpdate=!1,this.options.onUpdatedCTM&&this.options.onUpdatedCTM(t)},e.exports=function(t,e){return new s(t,e)}},{"./svg-utilities":5,"./utilities":7}],4:[function(t,e,o){var n=t("./uniwheel"),i=t("./control-icons"),s=t("./utilities"),r=t("./svg-utilities"),a=t("./shadow-viewport"),l=function(t,e){this.init(t,e)},u={viewportSelector:".svg-pan-zoom_viewport",panEnabled:!0,controlIconsEnabled:!1,zoomEnabled:!0,dblClickZoomEnabled:!0,mouseWheelZoomEnabled:!0,preventMouseEventsDefault:!0,zoomScaleSensitivity:.1,minZoom:.5,maxZoom:10,fit:!0,contain:!1,center:!0,refreshRate:"auto",beforeZoom:null,onZoom:null,beforePan:null,onPan:null,customEventsHandler:null,eventsListenerElement:null,onUpdatedCTM:null};l.prototype.init=function(t,e){var o=this;this.svg=t,this.defs=t.querySelector("defs"),r.setupSvgAttributes(this.svg),this.options=s.extend(s.extend({},u),e),this.state="none";var n=r.getBoundingClientRectNormalized(t);this.width=n.width,this.height=n.height,this.viewport=a(r.getOrCreateViewport(this.svg,this.options.viewportSelector),{svg:this.svg,width:this.width,height:this.height,fit:this.options.fit,contain:this.options.contain,center:this.options.center,refreshRate:this.options.refreshRate,beforeZoom:function(t,e){if(o.viewport&&o.options.beforeZoom)return o.options.beforeZoom(t,e)},onZoom:function(t){if(o.viewport&&o.options.onZoom)return o.options.onZoom(t)},beforePan:function(t,e){if(o.viewport&&o.options.beforePan)return o.options.beforePan(t,e)},onPan:function(t){if(o.viewport&&o.options.onPan)return o.options.onPan(t)},onUpdatedCTM:function(t){if(o.viewport&&o.options.onUpdatedCTM)return o.options.onUpdatedCTM(t)}});var l=this.getPublicInstance();l.setBeforeZoom(this.options.beforeZoom),l.setOnZoom(this.options.onZoom),l.setBeforePan(this.options.beforePan),l.setOnPan(this.options.onPan),l.setOnUpdatedCTM(this.options.onUpdatedCTM),this.options.controlIconsEnabled&&i.enable(this),this.lastMouseWheelEventTime=Date.now(),this.setupHandlers()},l.prototype.setupHandlers=function(){var t=this,e=null;if(this.eventListeners={mousedown:function(o){var n=t.handleMouseDown(o,e);return e=o,n},touchstart:function(o){var n=t.handleMouseDown(o,e);return e=o,n},mouseup:function(e){return t.handleMouseUp(e)},touchend:function(e){return t.handleMouseUp(e)},mousemove:function(e){return t.handleMouseMove(e)},touchmove:function(e){return t.handleMouseMove(e)},mouseleave:function(e){return t.handleMouseUp(e)},touchleave:function(e){return t.handleMouseUp(e)},touchcancel:function(e){return t.handleMouseUp(e)}},null!=this.options.customEventsHandler){this.options.customEventsHandler.init({svgElement:this.svg,eventsListenerElement:this.options.eventsListenerElement,instance:this.getPublicInstance()});var o=this.options.customEventsHandler.haltEventListeners;if(o&&o.length)for(var n=o.length-1;n>=0;n--)this.eventListeners.hasOwnProperty(o[n])&&delete this.eventListeners[o[n]]}for(var i in this.eventListeners)(this.options.eventsListenerElement||this.svg).addEventListener(i,this.eventListeners[i],!1);this.options.mouseWheelZoomEnabled&&(this.options.mouseWheelZoomEnabled=!1,this.enableMouseWheelZoom())},l.prototype.enableMouseWheelZoom=function(){if(!this.options.mouseWheelZoomEnabled){var t=this;this.wheelListener=function(e){return t.handleMouseWheel(e)},n.on(this.options.eventsListenerElement||this.svg,this.wheelListener,!1),this.options.mouseWheelZoomEnabled=!0}},l.prototype.disableMouseWheelZoom=function(){this.options.mouseWheelZoomEnabled&&(n.off(this.options.eventsListenerElement||this.svg,this.wheelListener,!1),this.options.mouseWheelZoomEnabled=!1)},l.prototype.handleMouseWheel=function(t){if(this.options.zoomEnabled&&"none"===this.state){this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1);var e=t.deltaY||1,o=Date.now()-this.lastMouseWheelEventTime,n=3+Math.max(0,30-o);this.lastMouseWheelEventTime=Date.now(),"deltaMode"in t&&0===t.deltaMode&&t.wheelDelta&&(e=0===t.deltaY?0:Math.abs(t.wheelDelta)/t.deltaY),e=-.3<e&&e<.3?e:(e>0?1:-1)*Math.log(Math.abs(e)+10)/n;var i=this.svg.getScreenCTM().inverse(),s=r.getEventPoint(t,this.svg).matrixTransform(i),a=Math.pow(1+this.options.zoomScaleSensitivity,-1*e);this.zoomAtPoint(a,s)}},l.prototype.zoomAtPoint=function(t,e,o){var n=this.viewport.getOriginalState();o?(t=Math.max(this.options.minZoom*n.zoom,Math.min(this.options.maxZoom*n.zoom,t)),t/=this.getZoom()):this.getZoom()*t<this.options.minZoom*n.zoom?t=this.options.minZoom*n.zoom/this.getZoom():this.getZoom()*t>this.options.maxZoom*n.zoom&&(t=this.options.maxZoom*n.zoom/this.getZoom());var i=this.viewport.getCTM(),s=e.matrixTransform(i.inverse()),r=this.svg.createSVGMatrix().translate(s.x,s.y).scale(t).translate(-s.x,-s.y),a=i.multiply(r);a.a!==i.a&&this.viewport.setCTM(a)},l.prototype.zoom=function(t,e){this.zoomAtPoint(t,r.getSvgCenterPoint(this.svg,this.width,this.height),e)},l.prototype.publicZoom=function(t,e){e&&(t=this.computeFromRelativeZoom(t)),this.zoom(t,e)},l.prototype.publicZoomAtPoint=function(t,e,o){if(o&&(t=this.computeFromRelativeZoom(t)),"SVGPoint"!==s.getType(e)){if(!("x"in e&&"y"in e))throw new Error("Given point is invalid");e=r.createSVGPoint(this.svg,e.x,e.y)}this.zoomAtPoint(t,e,o)},l.prototype.getZoom=function(){return this.viewport.getZoom()},l.prototype.getRelativeZoom=function(){return this.viewport.getRelativeZoom()},l.prototype.computeFromRelativeZoom=function(t){return t*this.viewport.getOriginalState().zoom},l.prototype.resetZoom=function(){var t=this.viewport.getOriginalState();this.zoom(t.zoom,!0)},l.prototype.resetPan=function(){this.pan(this.viewport.getOriginalState())},l.prototype.reset=function(){this.resetZoom(),this.resetPan()},l.prototype.handleDblClick=function(t){if(this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1),this.options.controlIconsEnabled){var e=t.target.getAttribute("class")||"";if(e.indexOf("svg-pan-zoom-control")>-1)return!1}var o;o=t.shiftKey?1/(2*(1+this.options.zoomScaleSensitivity)):2*(1+this.options.zoomScaleSensitivity);var n=r.getEventPoint(t,this.svg).matrixTransform(this.svg.getScreenCTM().inverse());this.zoomAtPoint(o,n)},l.prototype.handleMouseDown=function(t,e){this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1),s.mouseAndTouchNormalize(t,this.svg),this.options.dblClickZoomEnabled&&s.isDblClick(t,e)?this.handleDblClick(t):(this.state="pan",this.firstEventCTM=this.viewport.getCTM(),this.stateOrigin=r.getEventPoint(t,this.svg).matrixTransform(this.firstEventCTM.inverse()))},l.prototype.handleMouseMove=function(t){if(this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1),"pan"===this.state&&this.options.panEnabled){var e=r.getEventPoint(t,this.svg).matrixTransform(this.firstEventCTM.inverse()),o=this.firstEventCTM.translate(e.x-this.stateOrigin.x,e.y-this.stateOrigin.y);this.viewport.setCTM(o)}},l.prototype.handleMouseUp=function(t){this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1),"pan"===this.state&&(this.state="none")},l.prototype.fit=function(){var t=this.viewport.getViewBox(),e=Math.min(this.width/t.width,this.height/t.height);this.zoom(e,!0)},l.prototype.contain=function(){var t=this.viewport.getViewBox(),e=Math.max(this.width/t.width,this.height/t.height);this.zoom(e,!0)},l.prototype.center=function(){var t=this.viewport.getViewBox(),e=.5*(this.width-(t.width+2*t.x)*this.getZoom()),o=.5*(this.height-(t.height+2*t.y)*this.getZoom());this.getPublicInstance().pan({x:e,y:o})},l.prototype.updateBBox=function(){this.viewport.simpleViewBoxCache()},l.prototype.pan=function(t){var e=this.viewport.getCTM();e.e=t.x,e.f=t.y,this.viewport.setCTM(e)},l.prototype.panBy=function(t){var e=this.viewport.getCTM();e.e+=t.x,e.f+=t.y,this.viewport.setCTM(e)},l.prototype.getPan=function(){var t=this.viewport.getState();return{x:t.x,y:t.y}},l.prototype.resize=function(){var t=r.getBoundingClientRectNormalized(this.svg);this.width=t.width,this.height=t.height;var e=this.viewport;e.options.width=this.width,e.options.height=this.height,e.processCTM(),this.options.controlIconsEnabled&&(this.getPublicInstance().disableControlIcons(),this.getPublicInstance().enableControlIcons())},l.prototype.destroy=function(){var t=this;this.beforeZoom=null,this.onZoom=null,this.beforePan=null,this.onPan=null,this.onUpdatedCTM=null,null!=this.options.customEventsHandler&&this.options.customEventsHandler.destroy({svgElement:this.svg,eventsListenerElement:this.options.eventsListenerElement,instance:this.getPublicInstance()});for(var e in this.eventListeners)(this.options.eventsListenerElement||this.svg).removeEventListener(e,this.eventListeners[e],!1);this.disableMouseWheelZoom(),this.getPublicInstance().disableControlIcons(),this.reset(),h=h.filter(function(e){return e.svg!==t.svg}),delete this.options,delete this.viewport,delete this.publicInstance,delete this.pi,this.getPublicInstance=function(){return null}},l.prototype.getPublicInstance=function(){var t=this;return this.publicInstance||(this.publicInstance=this.pi={enablePan:function(){return t.options.panEnabled=!0,t.pi},disablePan:function(){return t.options.panEnabled=!1,t.pi},isPanEnabled:function(){return!!t.options.panEnabled},pan:function(e){return t.pan(e),t.pi},panBy:function(e){return t.panBy(e),t.pi},getPan:function(){return t.getPan()},setBeforePan:function(e){return t.options.beforePan=null===e?null:s.proxy(e,t.publicInstance),t.pi},setOnPan:function(e){return t.options.onPan=null===e?null:s.proxy(e,t.publicInstance),t.pi},enableZoom:function(){return t.options.zoomEnabled=!0,t.pi},disableZoom:function(){return t.options.zoomEnabled=!1,t.pi},isZoomEnabled:function(){return!!t.options.zoomEnabled},enableControlIcons:function(){return t.options.controlIconsEnabled||(t.options.controlIconsEnabled=!0,i.enable(t)),t.pi},disableControlIcons:function(){return t.options.controlIconsEnabled&&(t.options.controlIconsEnabled=!1,i.disable(t)),t.pi},isControlIconsEnabled:function(){return!!t.options.controlIconsEnabled},enableDblClickZoom:function(){return t.options.dblClickZoomEnabled=!0,t.pi},disableDblClickZoom:function(){return t.options.dblClickZoomEnabled=!1,t.pi},isDblClickZoomEnabled:function(){return!!t.options.dblClickZoomEnabled},enableMouseWheelZoom:function(){return t.enableMouseWheelZoom(),t.pi},disableMouseWheelZoom:function(){return t.disableMouseWheelZoom(),t.pi},isMouseWheelZoomEnabled:function(){return!!t.options.mouseWheelZoomEnabled},setZoomScaleSensitivity:function(e){return t.options.zoomScaleSensitivity=e,t.pi},setMinZoom:function(e){return t.options.minZoom=e,t.pi},setMaxZoom:function(e){return t.options.maxZoom=e,t.pi},setBeforeZoom:function(e){return t.options.beforeZoom=null===e?null:s.proxy(e,t.publicInstance),t.pi},setOnZoom:function(e){return t.options.onZoom=null===e?null:s.proxy(e,t.publicInstance),t.pi},zoom:function(e){return t.publicZoom(e,!0),t.pi},zoomBy:function(e){return t.publicZoom(e,!1),t.pi},zoomAtPoint:function(e,o){return t.publicZoomAtPoint(e,o,!0),t.pi},zoomAtPointBy:function(e,o){return t.publicZoomAtPoint(e,o,!1),t.pi},zoomIn:function(){return this.zoomBy(1+t.options.zoomScaleSensitivity),t.pi},zoomOut:function(){return this.zoomBy(1/(1+t.options.zoomScaleSensitivity)),t.pi},getZoom:function(){return t.getRelativeZoom()},setOnUpdatedCTM:function(e){return t.options.onUpdatedCTM=null===e?null:s.proxy(e,t.publicInstance),t.pi},resetZoom:function(){return t.resetZoom(),t.pi},resetPan:function(){return t.resetPan(),t.pi},reset:function(){return t.reset(),t.pi},fit:function(){return t.fit(),t.pi},contain:function(){return t.contain(),t.pi},center:function(){return t.center(),t.pi},updateBBox:function(){return t.updateBBox(),t.pi},resize:function(){return t.resize(),t.pi},getSizes:function(){return{width:t.width,height:t.height,realZoom:t.getZoom(),viewBox:t.viewport.getViewBox()}},destroy:function(){return t.destroy(),t.pi}}),this.publicInstance};var h=[],c=function(t,e){var o=s.getSvg(t);if(null===o)return null;for(var n=h.length-1;n>=0;n--)if(h[n].svg===o)return h[n].instance.getPublicInstance();return h.push({svg:o,instance:new l(o,e)}),h[h.length-1].instance.getPublicInstance()};e.exports=c},{"./control-icons":2,"./shadow-viewport":3,"./svg-utilities":5,"./uniwheel":6,"./utilities":7}],5:[function(t,e,o){var n=t("./utilities"),i="unknown";document.documentMode&&(i="ie"),e.exports={svgNS:"http://www.w3.org/2000/svg",xmlNS:"http://www.w3.org/XML/1998/namespace",xmlnsNS:"http://www.w3.org/2000/xmlns/",xlinkNS:"http://www.w3.org/1999/xlink",evNS:"http://www.w3.org/2001/xml-events",getBoundingClientRectNormalized:function(t){if(t.clientWidth&&t.clientHeight)return{width:t.clientWidth,height:t.clientHeight};if(t.getBoundingClientRect())return t.getBoundingClientRect();throw new Error("Cannot get BoundingClientRect for SVG.")},getOrCreateViewport:function(t,e){var o=null;if(o=n.isElement(e)?e:t.querySelector(e),!o){var i=Array.prototype.slice.call(t.childNodes||t.children).filter(function(t){return"defs"!==t.nodeName&&"#text"!==t.nodeName});1===i.length&&"g"===i[0].nodeName&&null===i[0].getAttribute("transform")&&(o=i[0])}if(!o){var s="viewport-"+(new Date).toISOString().replace(/\D/g,"");o=document.createElementNS(this.svgNS,"g"),o.setAttribute("id",s);var r=t.childNodes||t.children;if(r&&r.length>0)for(var a=r.length;a>0;a--)"defs"!==r[r.length-a].nodeName&&o.appendChild(r[r.length-a]);t.appendChild(o)}var l=[];return o.getAttribute("class")&&(l=o.getAttribute("class").split(" ")),~l.indexOf("svg-pan-zoom_viewport")||(l.push("svg-pan-zoom_viewport"),o.setAttribute("class",l.join(" "))),o},setupSvgAttributes:function(t){if(t.setAttribute("xmlns",this.svgNS),t.setAttributeNS(this.xmlnsNS,"xmlns:xlink",this.xlinkNS),t.setAttributeNS(this.xmlnsNS,"xmlns:ev",this.evNS),null!==t.parentNode){var e=t.getAttribute("style")||"";e.toLowerCase().indexOf("overflow")===-1&&t.setAttribute("style","overflow: hidden; "+e)}},internetExplorerRedisplayInterval:300,refreshDefsGlobal:n.throttle(function(){for(var t=document.querySelectorAll("defs"),e=t.length,o=0;o<e;o++){var n=t[o];n.parentNode.insertBefore(n,n)}},this.internetExplorerRedisplayInterval),setCTM:function(t,e,o){var n=this,s="matrix("+e.a+","+e.b+","+e.c+","+e.d+","+e.e+","+e.f+")";t.setAttributeNS(null,"transform",s),"transform"in t.style?t.style.transform=s:"-ms-transform"in t.style?t.style["-ms-transform"]=s:"-webkit-transform"in t.style&&(t.style["-webkit-transform"]=s),"ie"===i&&o&&(o.parentNode.insertBefore(o,o),window.setTimeout(function(){n.refreshDefsGlobal()},n.internetExplorerRedisplayInterval))},getEventPoint:function(t,e){var o=e.createSVGPoint();return n.mouseAndTouchNormalize(t,e),o.x=t.clientX,o.y=t.clientY,o},getSvgCenterPoint:function(t,e,o){return this.createSVGPoint(t,e/2,o/2)},createSVGPoint:function(t,e,o){var n=t.createSVGPoint();return n.x=e,n.y=o,n}}},{"./utilities":7}],6:[function(t,e,o){e.exports=function(){function t(t,e,o){var n=function(t){!t&&(t=window.event);var o={originalEvent:t,target:t.target||t.srcElement,type:"wheel",deltaMode:"MozMousePixelScroll"==t.type?0:1,deltaX:0,delatZ:0,preventDefault:function(){t.preventDefault?t.preventDefault():t.returnValue=!1}};return"mousewheel"==u?(o.deltaY=-.025*t.wheelDelta,t.wheelDeltaX&&(o.deltaX=-.025*t.wheelDeltaX)):o.deltaY=t.detail,e(o)};return c.push({element:t,fn:n,capture:o}),n}function e(t,e){for(var o=0;o<c.length;o++)if(c[o].element===t&&c[o].capture===e)return c[o].fn;return function(){}}function o(t,e){for(var o=0;o<c.length;o++)if(c[o].element===t&&c[o].capture===e)return c.splice(o,1)}function n(e,o,n,i){var s;s="wheel"===u?n:t(e,n,i),e[a](h+o,s,i||!1)}function i(t,n,i,s){var r;r="wheel"===u?i:e(t,s),t[l](h+n,r,s||!1),o(t,s)}function s(t,e,o){n(t,u,e,o),"DOMMouseScroll"==u&&n(t,"MozMousePixelScroll",e,o)}function r(t,e,o){i(t,u,e,o),"DOMMouseScroll"==u&&i(t,"MozMousePixelScroll",e,o)}var a,l,u,h="",c=[];return window.addEventListener?(a="addEventListener",l="removeEventListener"):(a="attachEvent",l="detachEvent",h="on"),u="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll",{on:s,off:r}}()},{}],7:[function(t,e,o){function n(t){return function(e){window.setTimeout(e,t)}}e.exports={extend:function(t,e){t=t||{};for(var o in e)this.isObject(e[o])?t[o]=this.extend(t[o],e[o]):t[o]=e[o];return t},isElement:function(t){return t instanceof HTMLElement||t instanceof SVGElement||t instanceof SVGSVGElement||t&&"object"==typeof t&&null!==t&&1===t.nodeType&&"string"==typeof t.nodeName},isObject:function(t){return"[object Object]"===Object.prototype.toString.call(t)},isNumber:function(t){return!isNaN(parseFloat(t))&&isFinite(t)},getSvg:function(t){var e,o;if(this.isElement(t))e=t;else{if(!("string"==typeof t||t instanceof String))throw new Error("Provided selector is not an HTML object nor String");if(e=document.querySelector(t),!e)throw new Error("Provided selector did not find any elements. Selector: "+t)}if("svg"===e.tagName.toLowerCase())o=e;else if("object"===e.tagName.toLowerCase())o=e.contentDocument.documentElement;else{if("embed"!==e.tagName.toLowerCase())throw"img"===e.tagName.toLowerCase()?new Error('Cannot script an SVG in an "img" element. Please use an "object" element or an in-line SVG.'):new Error("Cannot get SVG.");o=e.getSVGDocument().documentElement}return o},proxy:function(t,e){return function(){return t.apply(e,arguments)}},getType:function(t){return Object.prototype.toString.apply(t).replace(/^\[object\s/,"").replace(/\]$/,"")},mouseAndTouchNormalize:function(t,e){if(void 0===t.clientX||null===t.clientX)if(t.clientX=0,t.clientY=0,void 0!==t.touches&&t.touches.length){if(void 0!==t.touches[0].clientX)t.clientX=t.touches[0].clientX,t.clientY=t.touches[0].clientY;else if(void 0!==t.touches[0].pageX){var o=e.getBoundingClientRect();t.clientX=t.touches[0].pageX-o.left,t.clientY=t.touches[0].pageY-o.top}}else void 0!==t.originalEvent&&void 0!==t.originalEvent.clientX&&(t.clientX=t.originalEvent.clientX,t.clientY=t.originalEvent.clientY)},isDblClick:function(t,e){if(2===t.detail)return!0;if(void 0!==e&&null!==e){var o=t.timeStamp-e.timeStamp,n=Math.sqrt(Math.pow(t.clientX-e.clientX,2)+Math.pow(t.clientY-e.clientY,2));return o<250&&n<10}return!1},now:Date.now||function(){return(new Date).getTime()},throttle:function(t,e,o){var n,i,s,r=this,a=null,l=0;o||(o={});var u=function(){l=o.leading===!1?0:r.now(),a=null,s=t.apply(n,i),a||(n=i=null)};return function(){var h=r.now();l||o.leading!==!1||(l=h);var c=e-(h-l);return n=this,i=arguments,c<=0||c>e?(clearTimeout(a),a=null,l=h,s=t.apply(n,i),a||(n=i=null)):a||o.trailing===!1||(a=setTimeout(u,c)),s}},createRequestAnimationFrame:function(t){var e=null;return"auto"!==t&&t<60&&t>1&&(e=Math.floor(1e3/t)),null===e?window.requestAnimationFrame||n(33):n(e)}}},{}]},{},[1]);

================================================
FILE: resources/zoom_mir.js
================================================
function enable_mir_mousewheel() {
  var svg = svgPanZoom("#mir > svg", {
    controlIconsEnabled: true,
    zoomScaleSensitivity: 0.5,
    maxZoom: 50.0,
    minZoom: 1.0,
    fit: true,
  });
}


================================================
FILE: rust-toolchain
================================================
[toolchain]
channel = "nightly-2021-03-13"
components = ["miri", "rustc-dev", "llvm-tools-preview"]


================================================
FILE: src/main.rs
================================================
#![feature(rustc_private, decl_macro, plugin, try_blocks, proc_macro_hygiene)]
#![feature(never_type)]
#![allow(unused_attributes)]
#![recursion_limit = "5000"]
#![warn(rust_2018_idioms)]

extern crate rustc_driver;
extern crate rustc_hir;
extern crate rustc_index;
extern crate rustc_interface;
extern crate rustc_middle;
extern crate rustc_mir;
extern crate rustc_span;
extern crate rustc_target;
extern crate rustc_type_ir;

#[macro_use]
extern crate rocket;

mod render;
mod step;
mod watch;

use std::ops::FnOnce;
use std::path::PathBuf;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};

use miri::Evaluator;
use rustc_driver::Compilation;
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_interface::interface;
use rustc_middle::mir;
use rustc_middle::ty::TyCtxt;

use rocket::response::content::*;
use rocket::response::status::BadRequest;
use rocket::response::NamedFile;
use rocket::State;

use serde::Deserialize;
use step::{step, ShouldContinue};

use crate::step::BreakpointTree;

fn should_hide_stmt(stmt: &mir::Statement<'_>) -> bool {
    use rustc_middle::mir::StatementKind::*;
    match stmt.kind {
        StorageLive(_) | StorageDead(_) | Nop => true,
        _ => false,
    }
}

type InterpCx<'tcx> = rustc_mir::interpret::InterpCx<'tcx, 'tcx, Evaluator<'tcx, 'tcx>>;

pub struct PrirodaContext<'a, 'tcx: 'a> {
    ecx: InterpCx<'tcx>,
    step_count: &'a mut u128,
    traces: watch::Traces<'tcx>,
    config: &'a mut Config,
    skip_to_main: bool,
}

impl<'a, 'tcx: 'a> PrirodaContext<'a, 'tcx> {
    fn restart(&mut self) {
        self.ecx = create_ecx(self.ecx.tcx.tcx);
        *self.step_count = 0;
        self.traces.clear(); // Cleanup all traces
        self.to_main();
    }

    // Step to main
    fn to_main(&mut self) {
        if self.skip_to_main {
            let main_id = self
                .ecx
                .tcx
                .tcx
                .entry_fn(LOCAL_CRATE)
                .expect("no main or start function found")
                .0
                .to_def_id();

            let _ = step(self, |ecx| {
                let frame = ecx.frame();
                if main_id == frame.instance.def_id() {
                    ShouldContinue::Stop
                } else {
                    ShouldContinue::Continue
                }
            });
        }
    }
}

#[derive(Deserialize)]
pub struct Config {
    #[serde(default = "true_bool")]
    auto_refresh: bool,
    #[serde(default = "default_theme")]
    theme: String,
    #[serde(default)]
    bptree: BreakpointTree,
}

fn true_bool() -> bool {
    true
}
fn default_theme() -> String {
    "default".to_string()
}

impl Default for Config {
    fn default() -> Self {
        ::std::fs::File::open("config.json")
            .map(|f| serde_json::from_reader(f).unwrap())
            .unwrap_or(Config {
                auto_refresh: true,
                theme: "default".to_string(),
                bptree: step::BreakpointTree::default(),
            })
    }
}

type RResult<T> = Result<T, Html<String>>;

fn create_ecx<'mir, 'tcx>(tcx: TyCtxt<'tcx>) -> InterpCx<'tcx> {
    let (main_id, _) = tcx
        .entry_fn(LOCAL_CRATE)
        .expect("no main or start function found");

    miri::create_ecx(
        tcx,
        main_id.to_def_id(),
        miri::MiriConfig {
            args: vec![],
            communicate: true,
            excluded_env_vars: vec![],
            ignore_leaks: true,
            seed: None,
            tracked_pointer_tag: None,
            tracked_alloc_id: None,
            tracked_call_id: None,
            validate: true,
            stacked_borrows: false,
            check_alignment: miri::AlignmentCheck::None,
            track_raw: false,
            data_race_detector: false,
            cmpxchg_weak_failure_rate: 0.8,
        },
    )
    .unwrap()
    .0
}

pub struct PrirodaSender(
    Mutex<::std::sync::mpsc::Sender<Box<dyn FnOnce(&mut PrirodaContext<'_, '_>) + Send>>>,
);

impl PrirodaSender {
    fn do_work<'r, T, F>(&self, f: F) -> Result<T, Html<String>>
    where
        T: rocket::response::Responder<'r> + Send + 'static,
        F: FnOnce(&mut PrirodaContext<'_, '_>) -> T + Send + 'static,
    {
        let (tx, rx) = mpsc::sync_channel(0);
        let sender = self.0.lock().unwrap_or_else(|err| err.into_inner());
        match sender.send(Box::new(move |pcx: &mut PrirodaContext<'_, '_>| {
            tx.send(f(pcx)).unwrap();
        })) {
            Ok(()) => match rx.recv() {
                Ok(val) => Ok(val),
                Err(mpsc::RecvError) => Err(Html(
                    "<center><h1>Miri crashed please go to <a href='/'>index</a></h1></center>"
                        .to_string(),
                )),
            },
            Err(_) => Err(Html(
                "<center><h1>Miri crashed too often. Please restart priroda.</h1></center>"
                    .to_string(),
            )),
        }
    }
}

#[get("/please_panic")]
fn please_panic(sender: State<'_, PrirodaSender>) -> RResult<()> {
    sender.do_work(|_pcx| panic!("You requested a panic"))
}

#[cfg(not(feature = "static_resources"))]
#[get("/resources/<path..>")]
fn resources(path: PathBuf) -> Result<NamedFile, std::io::Error> {
    let mut res_path = PathBuf::from("./resources/");
    res_path.push(path);
    NamedFile::open(res_path)
}

#[cfg(feature = "static_resources")]
#[get("/resources/<path..>")]
fn resources(path: PathBuf) -> Result<Content<&'static str>, std::io::Error> {
    use rocket::http::ContentType;
    use std::io::{Error, ErrorKind};
    match path.as_os_str().to_str() {
        Some("svg-pan-zoom.js") => Ok(Content(
            ContentType::JavaScript,
            include_str!("../resources/svg-pan-zoom.js"),
        )),
        Some("zoom_mir.js") => Ok(Content(
            ContentType::JavaScript,
            include_str!("../resources/zoom_mir.js"),
        )),
        Some("style-default.css") => Ok(Content(
            ContentType::CSS,
            include_str!("../resources/style-default.css"),
        )),
        Some("positioning.css") => Ok(Content(
            ContentType::CSS,
            include_str!("../resources/positioning.css"),
        )),
        _ => Err(Error::new(ErrorKind::InvalidInput, "Unknown resource")),
    }
}

#[get("/step_count")]
fn step_count(sender: State<'_, PrirodaSender>) -> RResult<String> {
    sender.do_work(|pcx| format!("{}", pcx.step_count))
}

fn server(sender: PrirodaSender) {
    use rocket::config::Value;
    rocket::ignite()
        .manage(sender)
        .mount("/", routes![please_panic, resources, step_count])
        .mount("/", render::routes::routes())
        .mount("/breakpoints", step::bp_routes::routes())
        .mount("/step", step::step_routes::routes())
        .mount("/watch", watch::routes())
        .attach(rocket::fairing::AdHoc::on_launch(
            "Priroda, because code has no privacy rights",
            |rocket| {
                let config = rocket.config();
                if config.extras.get("spawn_browser") == Some(&Value::Boolean(true)) {
                    let addr = format!("http://{}:{}", config.address, config.port);
                    if open::that(&addr).is_err() {
                        println!("open {} in your browser", addr);
                    }
                }
            },
        ))
        .launch();
}

// Copied from miri/bin/miri.rs
fn find_sysroot() -> String {
    if let Ok(sysroot) = std::env::var("MIRI_SYSROOT") {
        return sysroot;
    }

    // Taken from https://github.com/rust-lang/rust-clippy/pull/911
    let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
    let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
    match (home, toolchain) {
        (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
        _ => option_env!("RUST_SYSROOT")
            .expect("need to specify RUST_SYSROOT env var or use rustup or multirust")
            .to_owned(),
    }
}

struct PrirodaCompilerCalls {
    step_count: Arc<Mutex<u128>>,
    config: Arc<Mutex<Config>>,
    receiver: Arc<Mutex<mpsc::Receiver<Box<dyn FnOnce(&mut PrirodaContext<'_, '_>) + Send>>>>,
    skip_to_main: bool,
}

impl rustc_driver::Callbacks for PrirodaCompilerCalls {
    fn after_analysis<'tcx>(
        &mut self,
        compiler: &interface::Compiler,
        queries: &'tcx rustc_interface::Queries<'tcx>,
    ) -> Compilation {
        compiler.session().abort_if_errors();

        queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {
            let mut step_count = self
                .step_count
                .lock()
                .unwrap_or_else(|err| err.into_inner());
            let mut config = self.config.lock().unwrap_or_else(|err| err.into_inner());

            let mut pcx = PrirodaContext {
                ecx: create_ecx(tcx),
                step_count: &mut *step_count,
                traces: watch::Traces::new(),
                config: &mut *config,
                skip_to_main: self.skip_to_main,
            };
            // Whether we reset to the same place where miri crashed
            let mut reset = false;
            // Step to the position where miri crashed if it crashed
            for _ in 0..*pcx.step_count {
                reset = true;
                match pcx.ecx.step() {
                    Ok(true) => {}
                    res => panic!("Miri is not deterministic causing error {:?}", res),
                }
            }

            // Just ignore poisoning by panicking
            let receiver = self.receiver.lock().unwrap_or_else(|err| err.into_inner());

            // At the very beginning, go to the start of main unless we have already crashed and are trying to reset
            if !reset {
                pcx.to_main();
            }
            // process commands
            for command in receiver.iter() {
                command(&mut pcx);
            }
        });

        compiler.session().abort_if_errors();

        Compilation::Stop
    }
}

fn main() {
    rustc_driver::init_rustc_env_logger();
    let mut args: Vec<String> = std::env::args().collect();

    // TODO: Move to a 'proper' argument parser
    // Maybe use xflags?

    let sysroot_flag = String::from("--sysroot");
    if !args.contains(&sysroot_flag) {
        args.push(sysroot_flag);
        args.push(find_sysroot());
    }

    // Use the --no-main flag to stop
    let stops_at_start = args
        .iter()
        .enumerate()
        .find(|(_, v)| v.as_str() == "--no-main")
        .map(|(i, _)| i);

    if let Some(index) = stops_at_start {
        // We pass these arguments to miri.
        // This is the lowest-effort way to not pass our custom argument to miri
        args.remove(index);
    }
    // Eagerly initialise syntect static
    // Makes highlighting performance profiles clearer
    render::initialise_statics();

    // setup http server and similar
    let (sender, receiver) = mpsc::channel();
    let sender = PrirodaSender(Mutex::new(sender));
    let step_count = Arc::new(Mutex::new(0));
    let config = Arc::new(Mutex::new(Config::default()));

    let handle = std::thread::spawn(move || {
        let args = Arc::new(args);
        let receiver = Arc::new(Mutex::new(receiver));
        for i in 0..5 {
            if i != 0 {
                println!(
                    "\n============== Miri crashed - restart try {} ==============\n",
                    i
                );
            }
            let step_count = step_count.clone();
            let config = config.clone();
            let receiver = receiver.clone();
            let args = args.clone();
            // Ignore result to restart in case of a crash
            let _ = std::thread::spawn(move || {
                let _ = rustc_driver::catch_fatal_errors(move || {
                    rustc_driver::RunCompiler::new(
                        &*args,
                        &mut PrirodaCompilerCalls {
                            step_count,
                            config,
                            receiver,
                            skip_to_main: stops_at_start.is_none(),
                        },
                    )
                    .run()
                });
            })
            .join();
            std::thread::sleep(std::time::Duration::from_millis(200));
        }
        println!("\n============== Miri crashed too often. Aborting ==============\n");
    });
    server(sender);
    handle.join().unwrap();
}


================================================
FILE: src/render/graphviz.rs
================================================
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::step::LocalBreakpoints;
use miri::{FrameData, Tag};
use rustc_middle::mir::*;
use rustc_mir::interpret::Frame;
use std::fmt::{self, Debug, Write};

pub fn render_html<'tcx>(
    frame: &Frame<'_, '_, Tag, FrameData<'_>>,
    breakpoints: LocalBreakpoints<'_>,
) -> String {
    let mut rendered = String::new();

    render_mir_svg(&frame.body, breakpoints, &mut rendered, None).unwrap();

    let (block, statement_index) = if let Some(location) = frame.current_loc().ok() {
        (location.block, location.statement_index)
    } else {
        rendered.push_str("<div style='color: red;'>Unwinding</div>");
        return rendered;
    };

    let (bb, stmt) = {
        let blck = &frame.body.basic_blocks()[block];
        (
            block.index() + 1,
            if statement_index == blck.statements.len() {
                if blck.statements.is_empty() {
                    6
                } else {
                    blck.statements.len() + 7
                }
            } else {
                assert!(statement_index < blck.statements.len());
                statement_index + 6
            },
        )
    };
    let edge_colors = {
        let blck = &frame.body.basic_blocks()[block];
        let (targets, unwind) = if statement_index == blck.statements.len() {
            use rustc_middle::mir::TerminatorKind::*;
            match blck.terminator().kind {
                Goto { target } => (vec![target], None),
                SwitchInt { ref targets, .. } => (targets.all_targets().to_owned(), None),
                Drop { target, unwind, .. } | DropAndReplace { target, unwind, .. } => {
                    (vec![target], unwind)
                }
                Call {
                    ref destination,
                    cleanup,
                    ..
                } => {
                    if let Some((_, target)) = *destination {
                        (vec![target], cleanup)
                    } else {
                        (vec![], cleanup)
                    }
                }
                _ => (vec![], None),
            }
        } else {
            (vec![], None)
        };
        format!(
            "let edge_colors = {{{}}};",
            targets
                .into_iter()
                .map(|target| (block, target, "green"))
                .chain(unwind.into_iter().map(|target| (block, target, "red")))
                .map(|(from, to, color)| format!(
                    "'bb{}->bb{}':'{}'",
                    from.index(),
                    to.index(),
                    color
                ))
                .collect::<Vec<_>>()
                .join(",")
        )
    };
    rendered
        .write_fmt(format_args!(
            r##"<style>
        #node{} > text:nth-child({}) {{
            fill: red;
        }}
        .edge-green > path, .edge-green > polygon, .edge-green > text {{
            fill: green;
            stroke: green;
        }}
        .edge-red > path, .edge-red > polygon, .edge-red > text {{
            fill: red;
            stroke: red;
        }}
        .edge > path {{
            fill: none;
        }}
        </style>
        <script>
        {edge_colors}
        for(let el of document.querySelectorAll("#mir > svg #graph0 .edge")) {{
            let title = el.querySelector("title").textContent;
            if(title in edge_colors) {{
                el.classList.add("edge-" + edge_colors[title]);
            }}
        }}
        </script>"##,
            bb,
            stmt,
            edge_colors = edge_colors
        ))
        .unwrap();
    rendered
}

/// Write a graphviz DOT graph of a list of MIRs.
pub fn render_mir_svg<W: Write>(
    mir: &Body<'_>,
    breakpoints: LocalBreakpoints<'_>,
    w: &mut W,
    promoted: Option<usize>,
) -> fmt::Result {
    let mut dot = String::new();
    if let Some(promoted) = promoted {
        writeln!(dot, "digraph promoted{} {{", promoted)?;
    } else {
        writeln!(dot, "digraph Body {{")?;
    }

    // Global graph properties
    writeln!(dot, r#"    graph [fontname="monospace"];"#)?;
    writeln!(dot, r#"    node [fontname="monospace"];"#)?;
    writeln!(dot, r#"    edge [fontname="monospace"];"#)?;

    // Nodes
    for (block, _) in mir.basic_blocks().iter_enumerated() {
        write_node(block, mir, breakpoints, promoted, &mut dot)?;
    }

    // Edges
    for (source, _) in mir.basic_blocks().iter_enumerated() {
        write_edges(source, mir, &mut dot)?;
    }
    writeln!(dot, "}}")?;
    w.write_str(
        ::std::str::from_utf8(&::cgraph::Graph::parse(dot).unwrap().render_dot().unwrap()).unwrap(),
    )
}

/// Write a graphviz HTML-styled label for the given basic block, with
/// all necessary escaping already performed. (This is suitable for
/// emitting directly, as is done in this module, or for use with the
/// `LabelText::HtmlStr` from libgraphviz.)
fn write_node_label<W: Write>(
    block: BasicBlock,
    mir: &Body<'_>,
    breakpoints: LocalBreakpoints<'_>,
    promoted: Option<usize>,
    w: &mut W,
) -> fmt::Result {
    let data = &mir[block];

    write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#)?;

    // Basic block number at the top.
    write!(
        w,
        r#"<tr><td bgcolor="gray" align="center">{blk}</td></tr>"#,
        blk = node(promoted, block)
    )?;

    // List of statements in the middle.
    if !data.statements.is_empty() {
        write!(w, r#"<tr><td align="left" balign="left">"#)?;
        for (statement_index, statement) in data.statements.iter().enumerate() {
            if breakpoints.breakpoint_exists(Some(Location {
                block,
                statement_index,
            })) {
                write!(w, "+ ")?;
            } else {
                write!(w, "&nbsp; ")?;
            }
            if crate::should_hide_stmt(statement) {
                write!(w, "&lt;+&gt;<br/>")?;
            } else {
                write!(w, "{}<br/>", escape(statement))?;
            }
        }
        write!(w, "</td></tr>")?;
    }

    // Terminator head at the bottom, not including the list of successor blocks. Those will be
    // displayed as labels on the edges between blocks.
    let mut terminator_head = String::new();
    data.terminator()
        .kind
        .fmt_head(&mut terminator_head)
        .unwrap();
    write!(
        w,
        r#"<tr><td align="left">{}</td></tr>"#,
        escape_html(&terminator_head)
    )?;

    // Close the table
    writeln!(w, "</table>")
}

/// Write a graphviz DOT node for the given basic block.
fn write_node<W: Write>(
    block: BasicBlock,
    mir: &Body<'_>,
    breakpoints: LocalBreakpoints<'_>,
    promoted: Option<usize>,
    w: &mut W,
) -> fmt::Result {
    // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
    write!(
        w,
        r#"    "{}" [shape="none", label=<"#,
        node(promoted, block)
    )?;
    write_node_label(block, mir, breakpoints, promoted, w)?;
    // Close the node label and the node itself.
    writeln!(w, ">];")
}

/// Write graphviz DOT edges with labels between the given basic block and all of its successors.
fn write_edges<W: Write>(source: BasicBlock, mir: &Body<'_>, w: &mut W) -> fmt::Result {
    let terminator = mir[source].terminator();
    let labels = terminator.kind.fmt_successor_labels();

    for (&target, label) in terminator.successors().zip(labels) {
        writeln!(
            w,
            r#"    {} -> {} [label="{}"];"#,
            node(None, source),
            node(None, target),
            label
        )?;
    }

    Ok(())
}

fn node(promoted: Option<usize>, block: BasicBlock) -> String {
    if let Some(promoted) = promoted {
        format!("promoted{}.{}", promoted, block.index())
    } else {
        format!("bb{}", block.index())
    }
}

fn escape<T: Debug>(t: &T) -> String {
    escape_html(&format!("{:?}", t)).into_owned()
}

fn escape_html(s: &str) -> ::std::borrow::Cow<'_, str> {
    ::rocket::http::RawStr::from_str(s).html_escape()
}


================================================
FILE: src/render/locals.rs
================================================
use rustc_middle::mir::{
    self,
    interpret::{InterpError, UndefinedBehaviorInfo},
};
use rustc_middle::ty::{subst::Subst, ParamEnv, TyKind, TypeAndMut};
use rustc_mir::interpret::{
    Allocation, Frame, Immediate, InterpResult, MemPlaceMeta, OpTy, Operand, Pointer, Scalar,
    ScalarMaybeUninit,
};
use rustc_target::abi::{Abi, Size};

use miri::{AllocExtra, Tag};

use horrorshow::prelude::*;
use horrorshow::Template;

use crate::InterpCx;

pub fn render_locals<'tcx>(
    ecx: &InterpCx<'tcx>,
    frame: &Frame<'tcx, 'tcx, Tag, miri::FrameData<'tcx>>,
) -> String {
    let &Frame {
        ref body,
        ref return_place,
        ref instance,
        ..
    } = frame;

    //               name    ty      alloc        val     style
    let locals: Vec<(String, String, Option<u64>, String, &str)> = body
        .local_decls
        .iter_enumerated()
        .map(|(id, local_decl)| {
            let name = body
                .var_debug_info
                .iter()
                .find(|var_debug_info| match var_debug_info.value {
                    mir::VarDebugInfoContents::Place(place) => {
                        place.projection.is_empty() && place.local == id
                    }
                    _ => false,
                })
                .map(|var_debug_info| var_debug_info.name.as_str().to_string())
                .unwrap_or_else(String::new);

            // FIXME Don't panic when trying to read from uninit variable.
            // Panic message:
            // > error: internal compiler error: src/librustc_mir/interpret/eval_context.rs:142:
            // > The type checker should prevent reading from a never-written local
            let op_ty = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                if id == mir::RETURN_PLACE {
                    return_place
                        .map(|p| ecx.place_to_op(&p).unwrap())
                        .ok_or(false)
                } else {
                    ecx.access_local(frame, id, None).map_err(|_| false)
                }
            })) {
                Ok(op_ty) => op_ty,
                Err(_) => Err(true),
            };

            let (alloc, val, style) = match op_ty {
                Err(false) => (None, "&lt;dead&gt;".to_owned(), "font-size: 0;"),
                Err(true) => (None, "&lt;uninit&gt;".to_owned(), "color: darkmagenta;"),
                Ok(op_ty) => match print_operand(ecx, op_ty) {
                    Ok((alloc, text)) => (alloc, text, ""),
                    Err(()) => (None, "&lt;error&gt;".to_owned(), "color: red;"),
                },
            };
            let ty = ecx.tcx.normalize_erasing_regions(
                ParamEnv::reveal_all(),
                local_decl.ty.subst(ecx.tcx.tcx, instance.substs),
            );
            (name, ty.to_string(), alloc, val, style)
        })
        .collect();

    let (arg_count, var_count, tmp_count) = (
        body.args_iter().count(),
        body.vars_iter().count(),
        body.temps_iter().count(),
    );

    (horrorshow::html! {
        table(border="1") {
            tr {
                td(width="20px");
                th { : "id" }
                th { : "name" }
                th { : "alloc" }
                th { : "memory" }
                th { : "type" }
            }
            @ for (i, &(ref name, ref ty, alloc, ref text, ref style)) in locals.iter().enumerate() {
                tr(style=style) {
                    @if i == 0 {
                        th(rowspan=1) { span(class="vertical") { : "Return" } }
                    } else if i == 1 && arg_count != 0 {
                        th(rowspan=arg_count) { span(class="vertical") { : "Arguments" } }
                    } else if i == arg_count + 1 && var_count != 0 {
                        th(rowspan=var_count) { span(class="vertical") { : "Variables" } }
                    } else if i == var_count + arg_count + 1 && tmp_count != 0 {
                        th(rowspan=tmp_count) { span(class="vertical") { : "Temporaries" } }
                    }
                    td { : format!("_{}", i) }
                    td { : name }
                    @if let Some(alloc) = alloc {
                        td { : alloc.to_string() }
                    } else {
                        td;
                    }
                    td { : Raw(text) }
                    td { : ty }
                }
            }
        }
    }).into_string()
        .unwrap()
}

fn print_scalar_maybe_undef(val: ScalarMaybeUninit<miri::Tag>) -> String {
    match val {
        ScalarMaybeUninit::Uninit => "&lt;undef &gt;".to_string(),
        ScalarMaybeUninit::Scalar(val) => print_scalar(val),
    }
}

fn print_scalar(val: Scalar<miri::Tag>) -> String {
    match val {
        Scalar::Ptr(ptr) => format!(
            "<a href=\"/ptr/{alloc}/{offset}\">Pointer({alloc})[{offset}]</a>",
            alloc = ptr.alloc_id.0,
            offset = ptr.offset.bytes()
        ),
        Scalar::Int(int) => {
            if int.size().bytes() == 0 {
                // Can't use `Debug` impl directly because it would be unescaped
                "&lt;zst&gt;".to_string()
            } else {
                format!("0x{:X}", int)
            }
        }
    }
}

fn pp_operand<'tcx>(
    ecx: &InterpCx<'tcx>,
    op_ty: OpTy<'tcx, miri::Tag>,
) -> InterpResult<'tcx, String> {
    let err = || InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(String::new()));
    match op_ty.layout.ty.kind() {
        TyKind::RawPtr(TypeAndMut { ty, .. }) | TyKind::Ref(_, ty, _)
            if matches!(ty.kind(), TyKind::Str) =>
        {
            if let Operand::Immediate(val) = *op_ty {
                if let Immediate::ScalarPair(
                    ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)),
                    ScalarMaybeUninit::Scalar(Scalar::Int(int)),
                ) = val
                {
                    if let Ok(allocation) = ecx.memory.get_raw(ptr.alloc_id) {
                        let offset = ptr.offset.bytes();
                        if (offset as u128) < allocation.len() as u128 {
                            let start = offset as usize;
                            let len = int.assert_bits(int.size());
                            let end = start.checked_add(len as usize).ok_or(err())?;
                            let alloc_bytes = &allocation
                                .inspect_with_uninit_and_ptr_outside_interpreter(start..end);
                            let s = String::from_utf8_lossy(alloc_bytes);
                            return Ok(format!("\"{}\"", s));
                        }
                    }
                }
            }
        }
        TyKind::Adt(adt_def, _substs) => {
            if let Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Uninit)) = *op_ty {
                Err(err())?;
            }

            let variant = ecx.read_discriminant(&op_ty)?.1;
            let adt_fields = &adt_def.variants[variant].fields;

            let should_collapse = adt_fields.len() > 1;

            //println!("{:?} {:?} {:?}", val, ty, adt_def.variants);
            let mut pretty = ecx
                .tcx
                .def_path_str(adt_def.did)
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .to_string();

            if adt_def.is_enum() {
                pretty.push_str("::");
                pretty.push_str(&*adt_def.variants[variant].ident.as_str());
            }
            pretty.push_str(" { ");

            if should_collapse {
                pretty.push_str("<details>");
            }

            for (i, adt_field) in adt_fields.iter().enumerate() {
                let field_pretty: InterpResult<'_, String> = try {
                    let field_op_ty = ecx.operand_field(&op_ty, i as usize)?;
                    pp_operand(ecx, field_op_ty)?
                };

                pretty.push_str(&format!(
                    "{}: {}, ",
                    adt_field.ident.as_str(),
                    match field_pretty {
                        Ok(field_pretty) => field_pretty,
                        Err(_err) => "<span style='color: red;'>&lt;err&gt;</span>".to_string(),
                    }
                ));
                if should_collapse {
                    pretty.push_str("<br>");
                }
            }

            if should_collapse {
                pretty.push_str("</details>");
            }

            pretty.push_str("}");
            println!("pretty adt: {}", pretty);
            return Ok(pretty);
        }
        _ => {}
    }

    if op_ty.layout.size.bytes() == 0 {
        Err(err())?;
    }
    if let Abi::Scalar(_) = op_ty.layout.abi {
    } else {
        Err(err())?;
    }
    let scalar = ecx.read_scalar(&op_ty)?;
    if let ScalarMaybeUninit::Scalar(Scalar::Ptr(_)) = &scalar {
        return Ok(print_scalar_maybe_undef(scalar)); // If the value is a ptr, print it
    }
    match op_ty.layout.ty.kind() {
        TyKind::Bool => {
            if scalar.to_bool()? {
                Ok("true".to_string())
            } else {
                Ok("false".to_string())
            }
        }
        TyKind::Char => {
            let chr = scalar.to_char()?;
            if chr.is_ascii() {
                Ok(format!("'{}'", chr))
            } else {
                Err(err().into())
            }
        }
        TyKind::Uint(_) => Ok(format!("{0}", scalar.to_u64()?)),
        TyKind::Int(_) => Ok(format!("{0}", scalar.to_i64()?)),
        TyKind::Float(float_ty) => match float_ty {
            rustc_type_ir::FloatTy::F32 => Ok(format!("{}", scalar.to_f32()?)),
            rustc_type_ir::FloatTy::F64 => Ok(format!("{}", scalar.to_f64()?)),
        },
        _ => Err(err().into()),
    }
}

pub fn print_operand<'a, 'tcx: 'a>(
    ecx: &InterpCx<'tcx>,
    op_ty: OpTy<'tcx, miri::Tag>,
) -> Result<(Option<u64>, String), ()> {
    let pretty = pp_operand(ecx, op_ty);

    let (alloc, txt) = match *op_ty {
        Operand::Indirect(place) => {
            let size: u64 = op_ty.layout.size.bytes();
            if place.meta == MemPlaceMeta::None {
                let ptr = place.to_ref().to_scalar().unwrap();
                if ptr.is_ptr() {
                    let (alloc, txt, _len) = print_ptr(ecx, ptr.assert_ptr(), Some(size))?;
                    (alloc, txt)
                } else {
                    (None, format!("{:?}", ptr))
                }
            } else {
                (None, format!("{:?}", place)) // FIXME better printing for unsized locals
            }
        }
        Operand::Immediate(Immediate::Scalar(scalar)) => (None, print_scalar_maybe_undef(scalar)),
        Operand::Immediate(Immediate::ScalarPair(val, extra)) => (
            None,
            format!(
                "{}, {}",
                print_scalar_maybe_undef(val),
                print_scalar_maybe_undef(extra)
            ),
        ),
    };
    let txt = if let Ok(pretty) = pretty {
        format!("{} ({})", pretty, txt)
    } else {
        txt
    };
    Ok((alloc, txt))
}

pub fn print_ptr(
    ecx: &InterpCx<'_>,
    ptr: Pointer<Tag>,
    size: Option<u64>,
) -> Result<(Option<u64>, String, u64), ()> {
    if let Ok(alloc) = ecx.memory.get_raw(ptr.alloc_id) {
        let s = print_alloc(ecx.tcx.data_layout.pointer_size.bytes(), ptr, alloc, size);
        debug_assert!(ecx.memory.get_fn(ptr.into()).is_err());
        Ok((Some(ptr.alloc_id.0), s, alloc.len() as u64))
    } else if let Ok(_) = ecx.memory.get_fn(ptr.into()) {
        // FIXME: print function name
        Ok((None, "function pointer".to_string(), 16))
    } else {
        Err(())
    }
}

pub fn print_alloc(
    ptr_size: u64,
    ptr: Pointer<Tag>,
    alloc: &Allocation<Tag, AllocExtra>,
    size: Option<u64>,
) -> String {
    use std::fmt::Write;
    let end = size
        .map(|s| s + ptr.offset.bytes())
        .unwrap_or(alloc.len() as u64);
    let mut s = String::new();
    let mut i = ptr.offset.bytes();
    while i < end {
        if let Some((_tag, reloc)) = alloc.relocations().get(&Size::from_bytes(i)) {
            i += ptr_size;
            write!(&mut s,
                "<a style=\"text-decoration: none\" href=\"/ptr/{alloc}/{offset}\">┠{nil:─<wdt$}┨</a>",
                alloc = reloc,
                offset = ptr.offset.bytes(),
                nil = "",
                wdt = (ptr_size * 2 - 2) as usize,
            ).unwrap();
        } else {
            if alloc
                .init_mask()
                .is_range_initialized(Size::from_bytes(i), Size::from_bytes(i + 1))
                .is_ok()
            {
                let byte = alloc
                    .inspect_with_uninit_and_ptr_outside_interpreter(i as usize..i as usize + 1)[0];
                write!(&mut s, "{:02x}", byte).unwrap();
            } else {
                let ub_chars = [
                    '∅', '∆', '∇', '∓', '∞', '⊙', '⊠', '⊘', '⊗', '⊛', '⊝', '⊡', '⊠',
                ];
                let c1 = (ptr.alloc_id.0 * 769 + i as u64 * 5689) as usize % ub_chars.len();
                let c2 = (ptr.alloc_id.0 * 997 + i as u64 * 7193) as usize % ub_chars.len();
                write!(&mut s, "<mark>{}{}</mark>", ub_chars[c1], ub_chars[c2]).unwrap();
            }
            i += 1;
        }
    }
    s
}


================================================
FILE: src/render/mod.rs
================================================
mod graphviz;
pub mod locals;
mod source;

pub use source::initialise_statics;

use rustc_hir::definitions::DefPathData;
use rustc_mir::interpret::{AllocId, Machine, Pointer};
use rustc_target::abi::Size;

use horrorshow::{Raw, Template};
use rocket::response::content::Html;

use crate::step::Breakpoint;
use crate::PrirodaContext;

pub fn template(pcx: &PrirodaContext<'_, '_>, title: String, t: impl Template) -> Html<String> {
    let mut buf = String::new();
    (horrorshow::html! {
        html {
            head {
                title { : title }
                meta(charset = "UTF-8") {}
                script(src="/resources/svg-pan-zoom.js") {}
                script(src="/resources/zoom_mir.js") {}
                : Raw(refresh_script(pcx))
            }
            body(onload="enable_mir_mousewheel()") {
                link(rel="stylesheet", href="/resources/positioning.css");
                link(rel="stylesheet", href=format!("/resources/style-{}.css", pcx.config.theme));
                : t
            }
        }
    })
    .write_to_string(&mut buf)
    .unwrap();
    Html(buf)
}

pub fn refresh_script(pcx: &PrirodaContext<'_, '_>) -> String {
    if pcx.config.auto_refresh {
        r#"<script>
            setInterval(() => {
                fetch("/step_count").then((res) => {
                    if(res.status == 200) {
                        return res.text();
                    } else {
                        throw "";
                    }
                }).then((res) => {
                    if(res != #step_count#) {
                        window.location.reload();
                    }
                }).catch(()=>{});
            }, 1000);
        </script>"#
            .replace("#step_count#", &format!("{}", pcx.step_count))
    } else {
        String::new()
    }
}

pub fn render_main_window(
    pcx: &PrirodaContext<'_, '_>,
    display_frame: Option<usize>,
    message: String,
) -> Html<String> {
    let is_active_stack_frame = match display_frame {
        Some(n) => n == Machine::stack(&pcx.ecx).len() - 1,
        None => true,
    };
    let frame = display_frame
        .and_then(|frame| Machine::stack(&pcx.ecx).get(frame))
        .or_else(|| Machine::stack(&pcx.ecx).last());
    let stack: Vec<(String, String, String)> = Machine::stack(&pcx.ecx)
        .iter()
        .map(|frame| {
            let instance = &frame.instance;
            let span = frame.current_source_info().unwrap().span;
            let name = if pcx
                .ecx
                .tcx
                .def_key(instance.def_id())
                .disambiguated_data
                .data
                == DefPathData::ClosureExpr
            {
                "inside call to closure".to_string()
            } else {
                instance.to_string()
            };
            let span = self::source::pretty_src_path(span);
            (name, span, format!("{:?}", instance.def_id()))
        })
        .collect();
    let rendered_breakpoints: Vec<String> = pcx
        .config
        .bptree
        .iter()
        .map(|&Breakpoint(def_id, bb, stmt)| format!("{:?}@{}:{}", def_id, bb.index(), stmt))
        .collect();
    let rendered_locals = frame
        .map(|frame| locals::render_locals(&pcx.ecx, frame))
        .unwrap_or_else(String::new);

    let rendered_source = source::render_source(pcx.ecx.tcx.tcx, frame);

    let mir_graph = frame.map(|frame| {
        graphviz::render_html(frame, pcx.config.bptree.for_def_id(frame.instance.def_id()))
    });

    let filename = pcx
        .ecx
        .tcx
        .sess
        .local_crate_source_file
        .as_ref()
        .map(|f| f.display().to_string())
        .unwrap_or_else(|| "no file name".to_string());
    template(
        pcx,
        filename,
        horrorshow::html! {
            div(id="left") {
                div(id="commands") {
                    @ if is_active_stack_frame {
                        a(href="/step/single") { div(title="Execute next MIR statement/terminator") { : "Step" } }
                        a(href="/step/next") { div(title="Run until after the next MIR statement/terminator") { : "Next" } }
                        a(href="/step/return") { div(title="Run until the function returns") { : "Return" } }
                        a(href="/step/single_back") { div(title="Execute previous MIR statement/terminator (restarts and steps till one stmt before the current stmt)") { : "Step back (slow)" } }
                        a(href="/step/continue") { div(title="Run until termination or breakpoint") { : "Continue" } }
                        a(href="/step/restart") { div(title="Abort execution and restart") { : "Restart" } }
                        a(href="/breakpoints/add_here") { div(title="Add breakpoint at current location") { : "Add breakpoint here"} }
                        a(href="/breakpoints/remove_all") { div(title="Remove all breakpoints") { : "Remove all breakpoints"} }
                    } else {
                        a(href="/") { div(title="Go to active stack frame") { : "Go back to active stack frame" } }
                    }
                }
                div(id="messages") {
                    p { : message }
                }
                div(id="mir") {
                    : Raw(mir_graph.unwrap_or_else(|| "no current function".to_string()))
                }
            }
            div(id="right") {
                div {
                    : format!("Step count: {}", pcx.step_count);
                }
                div(id="stack") {
                    table(border="1") {
                        @ for (i, &(ref s, ref span, ref def_id)) in stack.iter().enumerate().rev() {
                            tr {
                                @ if i == display_frame.unwrap_or(stack.len() - 1) { td { : Raw("&#8594;") } } else { td; }
                                td { : s }
                                td { : span }
                                td { : def_id }
                                @ if i == display_frame.unwrap_or(stack.len() - 1) { td; } else { td { a(href=format!("/frame/{}", i)) { : "View" } } }
                            }
                        }
                    }
                }
                div(id="breakpoints") {
                    : "Breakpoints: "; br;
                    table(border="1") {
                        @ for bp in rendered_breakpoints {
                            tr {
                                td { : &bp }
                                td { a(href=format!("/breakpoints/remove/{}", bp)) { : "remove" } }
                            }
                        }
                    }
                }
                div(id="locals") {
                    : Raw(rendered_locals)
                }
                div(id="source") {
                    : rendered_source
                }
            }
        },
    )
}

pub fn render_reverse_ptr(pcx: &PrirodaContext<'_, '_>, alloc_id: u64) -> Html<String> {
    let allocs: Vec<_> = pcx.ecx.memory.alloc_map().iter(|values| {
        values
            .filter_map(|(&id, (_kind, alloc))| {
                alloc
                    .relocations()
                    .values()
                    .find(|&&(_tag, reloc)| reloc == id)
                    .map(|_| id)
            })
            .collect()
    });
    template(
        pcx,
        format!("Allocations with pointers to Allocation {}", alloc_id),
        horrorshow::html! {
            @for id in allocs {
                a(href=format!("/ptr/{}", id)) { : format!("Allocation {}", id) }
                br;
            }
        },
    )
}

pub fn render_ptr_memory(
    pcx: &PrirodaContext<'_, '_>,
    alloc_id: AllocId,
    offset: u64,
) -> Html<String> {
    let (mem, offset, rest) = if let Ok((_, mem, bytes)) = locals::print_ptr(
        &pcx.ecx,
        Pointer::new(alloc_id, Size::from_bytes(offset))
            .with_tag(miri::Tag::Untagged)
            .into(),
        None,
    ) {
        if bytes * 2 > offset {
            (mem, offset, (bytes * 2 - offset - 1) as usize)
        } else if bytes * 2 == 0 && offset == 0 {
            (mem, 0, 0)
        } else {
            ("out of bounds offset".to_string(), 0, 0)
        }
    } else {
        ("unknown memory".to_string(), 0, 0)
    };
    template(
        pcx,
        format!("Allocation {}", alloc_id),
        horrorshow::html! {
            span(style="font-family: monospace") {
                : format!("{nil:.<offset$}┌{nil:─<rest$}", nil = "", offset = offset as usize, rest = rest)
            }
            br;
            span(style="font-family: monospace") { : Raw(mem) }
            br;
            a(href=format!("/reverse_ptr/{}", alloc_id)) { : "List allocations with pointers into this allocation" }
        },
    )
}

pub struct FlashString(String);

impl<'a, 'r> ::rocket::request::FromRequest<'a, 'r> for FlashString {
    type Error = !;
    fn from_request(request: &'a rocket::Request<'r>) -> rocket::request::Outcome<Self, !> {
        rocket::Outcome::Success(FlashString(
            Option::<rocket::request::FlashMessage<'_, '_>>::from_request(request)?
                .map(|flash| flash.msg().to_string())
                .unwrap_or_else(String::new),
        ))
    }
}

pub mod routes {
    use super::*;
    use crate::*;

    pub fn routes() -> Vec<::rocket::Route> {
        routes![index, frame, frame_invalid, ptr, reverse_ptr]
    }

    #[get("/")]
    pub fn index(
        sender: rocket::State<'_, crate::PrirodaSender>,
        flash: FlashString,
    ) -> crate::RResult<Html<String>> {
        sender.do_work(move |pcx| render::render_main_window(pcx, None, flash.0))
    }

    #[get("/frame/<frame>")]
    pub fn frame(
        sender: rocket::State<'_, crate::PrirodaSender>,
        flash: FlashString,
        frame: usize,
    ) -> crate::RResult<Html<String>> {
        sender.do_work(move |pcx| render::render_main_window(pcx, Some(frame), flash.0))
    }

    #[get("/frame/<frame>", rank = 42)] // Error handler
    fn frame_invalid(frame: String) -> BadRequest<String> {
        BadRequest(Some(format!(
            "not a number: {:?}",
            frame.parse::<usize>().unwrap_err()
        )))
    }
    #[get("/ptr/<alloc_id>/<offset>")]
    pub fn ptr(
        sender: rocket::State<'_, crate::PrirodaSender>,
        alloc_id: u64,
        offset: u64,
    ) -> crate::RResult<Html<String>> {
        sender.do_work(move |pcx| render::render_ptr_memory(pcx, AllocId(alloc_id), offset))
    }

    #[get("/reverse_ptr/<ptr>")]
    fn reverse_ptr(
        sender: rocket::State<'_, crate::PrirodaSender>,
        ptr: u64,
    ) -> crate::RResult<Html<String>> {
        sender.do_work(move |pcx| render::render_reverse_ptr(pcx, ptr))
    }
}


================================================
FILE: src/render/source.rs
================================================
use std::collections::HashMap;
use std::{cell::RefCell, ops::Range};

use miri::{FrameData, Tag};
use rustc_middle::ty::TyCtxt;
use rustc_mir::interpret::Frame;
use rustc_span::Span;

use horrorshow::prelude::*;
use syntect::easy::HighlightLines;
use syntect::highlighting::{Style, ThemeSet};
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::SyntaxSet;
use syntect::util::{split_at, LinesWithEndings};

lazy_static::lazy_static! {
    static ref SYNTAX_SET: SyntaxSet = SyntaxSet::load_defaults_nonewlines();
    static ref THEME_SET: ThemeSet = ThemeSet::load_defaults();

    static ref RUST_SOURCE: regex::Regex = regex::Regex::new("/rustc/\\w+/").unwrap();
    static ref STD_SRC: Option<String> = {
        if let Ok(output) = std::process::Command::new("rustc").arg("--print").arg("sysroot").output() {
            if let Ok(sysroot) = String::from_utf8(output.stdout) {
                Some(sysroot.trim().to_string() + "/lib/rustlib/src/rust/")
            } else {
                None
            }
        } else {
            None
        }
    };
}

pub fn initialise_statics() {
    let _ = (&*SYNTAX_SET, &*THEME_SET);
}

pub fn pretty_src_path(span: Span) -> String {
    let span = format!("{:?}", span);
    let span = RUST_SOURCE.replace(span.as_ref(), "<rust>/").to_string();
    if let Some(std_src) = &*STD_SRC {
        span.replace(std_src, "<rust>/")
    } else {
        span
    }
}

thread_local! {
    // This is a thread local, because a `Span` is only valid within one thread
    static CACHED_HIGHLIGHTED_FILES: RefCell<HashMap<u64, HighlightCacheEntry>> = {
        RefCell::new(HashMap::new())
    };
}

pub struct HighlightCacheEntry {
    pub string: String,
    pub highlighted: Vec<(Style, Range<usize>)>,
}

pub fn render_source(
    tcx: TyCtxt<'_>,
    frame: Option<&Frame<'_, '_, Tag, FrameData<'_>>>,
) -> Box<dyn RenderBox + Send> {
    let before_time = ::std::time::Instant::now();

    if frame.is_none() {
        return Box::new(FnRenderer::new(|_| {}));
    }
    let frame = frame.unwrap();
    let mut instr_spans = if let Some(location) = frame.current_loc().ok() {
        let stmt = location.statement_index;
        let block = location.block;
        if stmt == frame.body[block].statements.len() {
            vec![frame.body[block].terminator().source_info.span]
        } else {
            vec![frame.body[block].statements[stmt].source_info.span]
        }
    } else {
        vec![frame.body.span]
    };
    // Get the original macro caller
    while let Some(span) = instr_spans
        .last()
        .unwrap()
        .macro_backtrace()
        .next()
        .map(|b| b.call_site)
    {
        instr_spans.push(span);
    }

    let highlighted_sources = instr_spans
        .into_iter()
        .rev()
        .map(|sp| {
            let (src, lo, hi) = match get_file_source_for_span(tcx, sp) {
                Ok(res) => res,
                Err(err) => return (format!("{:?}", sp), err),
            };

            CACHED_HIGHLIGHTED_FILES.with(|highlight_cache| {
                use std::collections::hash_map::DefaultHasher;
                use std::hash::{Hash, Hasher};

                let mut hasher = DefaultHasher::new();
                src.hash(&mut hasher);
                let hash = hasher.finish();

                let mut cache = highlight_cache.borrow_mut();
                let entry = cache.entry(hash).or_insert_with(|| {
                    let before_time = ::std::time::Instant::now();
                    let highlighted = syntax_highlight(&src);
                    let after_time = ::std::time::Instant::now();
                    println!("h: {:?}", after_time - before_time);
                    HighlightCacheEntry {
                        string: src,
                        highlighted,
                    }
                });
                (
                    pretty_src_path(sp),
                    mark_span(&entry.string, &entry.highlighted, lo, hi),
                )
            })
        })
        .collect::<Vec<_>>();

    let after_time = ::std::time::Instant::now();
    println!("s: {:?}", after_time - before_time);

    let style = if let Some(bg_color) = THEME_SET.themes["Solarized (dark)"].settings.background {
        format!(
            "background-color: #{:02x}{:02x}{:02x}; display: block;",
            bg_color.r, bg_color.g, bg_color.b
        )
    } else {
        String::new()
    };

    horrorshow::box_html! {
        pre {
            code(id="the_code", style=style) {
                @ for (sp, source) in highlighted_sources {
                    span(style = "color: aqua;") {
                        :sp; br;
                    }
                    : Raw(source);
                    br; br;
                }
            }
        }
    }
}

fn get_file_source_for_span(tcx: TyCtxt<'_>, sp: Span) -> Result<(String, usize, usize), String> {
    let source_map = tcx.sess.source_map();
    let _ = source_map.span_to_snippet(sp); // Ensure file src is loaded

    let src = if let Ok(file_lines) = source_map.span_to_lines(sp) {
        if let Some(ref src) = file_lines.file.src {
            src.to_string()
        } else if let Some(src) = file_lines.file.external_src.borrow().get_source() {
            src.to_string()
        } else {
            return Err("<no source info for span>".to_string());
        }
    } else {
        return Err("<couldnt get lines for span>".to_string());
    };
    let lo = source_map.bytepos_to_file_charpos(sp.lo()).0;
    let hi = source_map.bytepos_to_file_charpos(sp.hi()).0;
    Ok((src, lo, hi))
}

fn syntax_highlight<'a, 's>(src: &'s str) -> Vec<(Style, Range<usize>)> {
    let theme = &THEME_SET.themes["Solarized (dark)"];
    let mut h = HighlightLines::new(
        &SYNTAX_SET
            .find_syntax_by_extension("rs")
            .unwrap()
            .to_owned(),
        theme,
    );
    let mut index = 0;
    let mut highlighted = Vec::new();
    for line in LinesWithEndings::from(src) {
        highlighted.extend(
            h.highlight(line, &SYNTAX_SET)
                .into_iter()
                .map(|(style, str)| {
                    let idx = index;
                    index += str.len();
                    (style, idx..index)
                }),
        );
    }
    highlighted
}

fn mark_span(file_contents: &str, src: &[(Style, Range<usize>)], lo: usize, hi: usize) -> String {
    let src = src
        .iter()
        .map(|(style, range)| (*style, &file_contents[range.clone()]))
        .collect::<Vec<_>>();
    let (before, with) = split_at(&src, lo);
    let (it, after) = split_at(&with, hi - lo);

    let before = styled_line_to_highlighted_html(&before, IncludeBackground::No);
    let it = styled_line_to_highlighted_html(&it, IncludeBackground::No);
    let after = styled_line_to_highlighted_html(&after, IncludeBackground::No);

    if lo == hi {
        assert_eq!(it.len(), 0);
        format!("{}<span style='background-color: lightcoral; border-radius: 5px; padding: 1px;'>←</span>{}", before, after)
    } else {
        assert_ne!(it.len(), 0);
        format!("{}<span style='background-color: lightcoral; border-radius: 5px; padding: 1px;'>{}</span>{}", before, it, after)
    }
}


================================================
FILE: src/step.rs
================================================
use rustc_hir::def_id::{CrateNum, DefId, DefIndex};
use rustc_index::vec::Idx;
use rustc_middle::mir;
use rustc_mir::interpret::Machine;
use std::collections::{HashMap, HashSet};
use std::iter::Iterator;

use miri::*;
use serde::de::{Deserialize, Deserializer, Error as SerdeError};

use crate::{InterpCx, PrirodaContext};

pub enum ShouldContinue {
    Continue,
    Stop,
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Breakpoint(pub DefId, pub mir::BasicBlock, pub usize);

#[derive(Default)]
pub struct BreakpointTree(HashMap<DefId, HashSet<Breakpoint>>);

impl<'de> Deserialize<'de> for BreakpointTree {
    fn deserialize<D: Deserializer<'de>>(deser: D) -> Result<Self, D::Error> {
        let mut map = HashMap::new();
        for (k, v) in HashMap::<String, HashSet<(usize, usize)>>::deserialize(deser)? {
            let def_id = parse_def_id(&k).map_err(SerdeError::custom)?;
            map.insert(
                def_id,
                v.into_iter()
                    .map(|(bb, instr)| Breakpoint(def_id, mir::BasicBlock::new(bb), instr))
                    .collect::<HashSet<Breakpoint>>(),
            );
        }
        Ok(BreakpointTree(map))
    }
}

impl BreakpointTree {
    pub fn add_breakpoint(&mut self, bp: Breakpoint) {
        self.0.entry(bp.0).or_insert_with(HashSet::new).insert(bp);
    }

    pub fn remove_breakpoint(&mut self, bp: Breakpoint) -> bool {
        self.0
            .get_mut(&bp.0)
            .map(|local| local.remove(&bp))
            .unwrap_or(false)
    }

    pub fn remove_all(&mut self) {
        self.0.clear();
    }

    pub fn for_def_id(&self, def_id: DefId) -> LocalBreakpoints<'_> {
        if let Some(bps) = self.0.get(&def_id) {
            LocalBreakpoints::SomeBps(bps)
        } else {
            LocalBreakpoints::NoBp
        }
    }

    pub fn is_at_breakpoint(&self, ecx: &InterpCx<'_>) -> bool {
        let frame = ecx.frame();
        self.for_def_id(frame.instance.def_id())
            .breakpoint_exists(frame.current_loc().ok())
    }

    pub fn iter(&self) -> impl Iterator<Item = &Breakpoint> {
        self.0.values().flat_map(|local| local.iter())
    }
}

#[derive(Copy, Clone)]
pub enum LocalBreakpoints<'a> {
    NoBp,
    SomeBps(&'a HashSet<Breakpoint>),
}

impl<'a> LocalBreakpoints<'a> {
    pub fn breakpoint_exists(self, location: Option<mir::Location>) -> bool {
        if let Some(location) = location {
            match self {
                LocalBreakpoints::NoBp => false,
                LocalBreakpoints::SomeBps(bps) => bps
                    .iter()
                    .any(|bp| bp.1 == location.block && bp.2 == location.statement_index),
            }
        } else {
            // Unwinding, but no cleanup for this frame
            // FIXME make this configurable
            false
        }
    }
}

pub fn step<F>(pcx: &mut PrirodaContext<'_, '_>, continue_while: F) -> String
where
    F: Fn(&InterpCx<'_>) -> ShouldContinue,
{
    let mut message = None;
    let ret: InterpResult<'_, _> = try {
        loop {
            let is_main_thread_active = pcx.ecx.get_active_thread() == 0.into();
            if is_main_thread_active && Machine::stack(&pcx.ecx).len() <= 1 && is_ret(&pcx.ecx) {
                // When the main thread exists, the program terminates. However,
                // we want to prevent stepping out of the program.
                break;
            }
            match pcx.ecx.schedule()? {
                SchedulingAction::ExecuteStep => {}
                SchedulingAction::ExecuteTimeoutCallback => {
                    pcx.ecx.run_timeout_callback()?;
                    continue;
                }
                SchedulingAction::ExecuteDtors => {
                    // This will either enable the thread again (so we go back
                    // to `ExecuteStep`), or determine that this thread is done
                    // for good.
                    pcx.ecx.schedule_next_tls_dtor_for_active_thread()?;
                    continue;
                }
                SchedulingAction::Stop => {
                    message = Some("interpretation finished".to_string());
                    break;
                }
            }
            let info = pcx.ecx.preprocess_diagnostics();
            if !pcx.ecx.step()? {
                message = Some("a terminated thread was scheduled for execution".to_string());
                break;
            }
            pcx.ecx.process_diagnostics(info);

            *pcx.step_count += 1;
            crate::watch::step_callback(pcx);

            if let Some(frame) = Machine::stack(&pcx.ecx).last() {
                if let Some(location) = frame.current_loc().ok() {
                    let blck = &frame.body.basic_blocks()[location.block];
                    if location.statement_index != blck.statements.len()
                        && crate::should_hide_stmt(&blck.statements[location.statement_index])
                        && !pcx.config.bptree.is_at_breakpoint(&pcx.ecx)
                    {
                        continue;
                    }
                } else {
                    // Unwinding, but no cleanup for this frame
                    // FIXME make step behaviour configurable
                }
            }
            if let ShouldContinue::Stop = continue_while(&pcx.ecx) {
                break;
            }
            if pcx.config.bptree.is_at_breakpoint(&pcx.ecx) {
                break;
            }
        }
    };
    match ret {
        Err(e) => {
            message = Some(format!("{:?}", e));
        }
        Ok(_) => {}
    }
    message.unwrap_or_else(String::new)
}

pub fn is_ret(ecx: &InterpCx<'_>) -> bool {
    if let Some(frame) = Machine::stack(&ecx).last() {
        if let Some(location) = frame.current_loc().ok() {
            let basic_block = &frame.body.basic_blocks()[location.block];

            match basic_block.terminator().kind {
                rustc_middle::mir::TerminatorKind::Return
                | rustc_middle::mir::TerminatorKind::Resume => {
                    location.statement_index >= basic_block.statements.len()
                }
                _ => false,
            }
        } else {
            true // Unwinding, but no cleanup necessary for current frame
        }
    } else {
        true
    }
}

fn parse_breakpoint_from_url(s: &str) -> Result<Breakpoint, String> {
    let regex = ::regex::Regex::new(r#"([^@]+)@(\d+):(\d+)"#).unwrap();
    // DefId(1:14824 ~ mycrate::main)@1:3
    //       ^ ^                      ^ ^
    //       | |                      | statement
    //       | |                      BasicBlock
    //       | DefIndex::as_array_index()
    //       CrateNum

    let s = s.replace("%20", " ");
    let caps = regex
        .captures(&s)
        .ok_or_else(|| format!("Invalid breakpoint {}", s))?;

    // Parse DefId
    let def_id = parse_def_id(caps.get(1).unwrap().as_str())?;

    // Parse block and stmt
    let bb = mir::BasicBlock::new(
        caps.get(2)
            .unwrap()
            .as_str()
            .parse::<usize>()
            .map_err(|_| "block id is not a positive integer")?,
    );
    let stmt = caps
        .get(3)
        .unwrap()
        .as_str()
        .parse::<usize>()
        .map_err(|_| "stmt id is not a positive integer")?;

    Ok(Breakpoint(def_id, bb, stmt))
}

fn parse_def_id(s: &str) -> Result<DefId, String> {
    let regex = ::regex::Regex::new(r#"DefId\((\d+):(\d+) ~ [^\)]+\)"#).unwrap();
    let caps = regex
        .captures(&s)
        .ok_or_else(|| format!("Invalid def_id {}", s))?;

    let crate_num = CrateNum::new(caps.get(1).unwrap().as_str().parse::<usize>().unwrap());
    let index = caps
        .get(2)
        .unwrap()
        .as_str()
        .parse::<usize>()
        .map_err(|_| "index is not a positive integer".to_string())?;
    let def_index = DefIndex::from_usize(index);
    Ok(DefId {
        krate: crate_num,
        index: def_index,
    })
}

pub mod step_routes {
    use rocket::response;

    use super::*;

    pub fn routes() -> Vec<::rocket::Route> {
        routes![restart, single, single_back, next, return_, continue_]
    }

    #[get("/restart")]
    fn restart(
        sender: rocket::State<'_, crate::PrirodaSender>,
    ) -> crate::RResult<response::Flash<response::Redirect>> {
        sender.do_work(move |pcx| {
            pcx.restart();
            response::Flash::success(response::Redirect::to("/"), "restarted")
        })
    }

    #[get("/single")]
    fn single(
        sender: rocket::State<'_, crate::PrirodaSender>,
    ) -> crate::RResult<response::Flash<response::Redirect>> {
        sender.do_work(move |pcx| {
            response::Flash::success(
                response::Redirect::to("/"),
                step(pcx, |_ecx| ShouldContinue::Stop),
            )
        })
    }

    #[get("/single_back")]
    fn single_back(
        sender: rocket::State<'_, crate::PrirodaSender>,
    ) -> crate::RResult<response::Flash<response::Redirect>> {
        sender.do_work(move |pcx| {
            let orig_step_count = *pcx.step_count;
            pcx.restart();
            *pcx.step_count = orig_step_count;
            let msg = if *pcx.step_count > 0 {
                *pcx.step_count -= 1;
                for _ in 0..*pcx.step_count {
                    match pcx.ecx.step() {
                        Ok(true) => crate::watch::step_callback(pcx), // Rebuild traces till the current instruction
                        res => {
                            return response::Flash::warning(
                                response::Redirect::to("/"),
                                format!("Miri is not deterministic causing error {:?}", res),
                            )
                        }
                    }
                }
                "stepped back".to_string()
            } else {
                "already at the start".to_string()
            };

            response::Flash::success(response::Redirect::to("/"), msg)
        })
    }

    #[get("/next")]
    fn next(
        sender: rocket::State<'_, crate::PrirodaSender>,
    ) -> crate::RResult<response::Flash<response::Redirect>> {
        sender.do_work(move |pcx| {
            let frame = Machine::stack(&pcx.ecx).len();
            let (block, stmt): (Option<mir::BasicBlock>, _) =
                if let Some(location) = pcx.ecx.frame().current_loc().ok() {
                    (Some(location.block), Some(location.statement_index))
                } else {
                    (None, None)
                };
            let msg = step(pcx, move |ecx| {
                let (curr_block, curr_stmt) = if let Some(location) = ecx.frame().current_loc().ok()
                {
                    (Some(location.block), Some(location.statement_index))
                } else {
                    (None, None)
                };
                if Machine::stack(&ecx).len() <= frame && (block < curr_block || stmt < curr_stmt) {
                    ShouldContinue::Stop
                } else {
                    ShouldContinue::Continue
                }
            });
            response::Flash::success(response::Redirect::to("/"), msg)
        })
    }

    #[get("/return")]
    fn return_(
        sender: rocket::State<'_, crate::PrirodaSender>,
    ) -> crate::RResult<response::Flash<response::Redirect>> {
        sender.do_work(move |pcx| {
            let frame = Machine::stack(&pcx.ecx).len();
            let msg = step(pcx, |ecx| {
                if Machine::stack(&ecx).len() <= frame && is_ret(&ecx) {
                    ShouldContinue::Stop
                } else {
                    ShouldContinue::Continue
                }
            });
            response::Flash::success(response::Redirect::to("/"), msg)
        })
    }

    #[get("/continue")]
    fn continue_(
        sender: rocket::State<'_, crate::PrirodaSender>,
    ) -> crate::RResult<response::Flash<response::Redirect>> {
        sender.do_work(move |pcx| {
            response::Flash::success(
                response::Redirect::to("/"),
                step(pcx, |_ecx| ShouldContinue::Continue),
            )
        })
    }
}

pub mod bp_routes {
    use super::*;
    use std::path::PathBuf;

    pub fn routes() -> Vec<::rocket::Route> {
        routes![add_here, add, remove, remove_all]
    }

    #[get("/add_here")]
    pub fn add_here(
        sender: rocket::State<'_, crate::PrirodaSender>,
    ) -> crate::RResult<rocket::response::Flash<rocket::response::Redirect>> {
        sender.do_work(move |pcx| {
            let frame = pcx.ecx.frame();
            let msg = if let Some(location) = frame.current_loc().ok() {
                pcx.config.bptree.add_breakpoint(Breakpoint(
                    frame.instance.def_id(),
                    location.block,
                    location.statement_index,
                ));
                format!(
                    "Breakpoint added for {:?}@{}:{}",
                    frame.instance.def_id(),
                    location.block.index(),
                    location.statement_index
                )
            } else {
                format!("Can't set breakpoint for unwinding without cleanup yet")
            };
            rocket::response::Flash::success(rocket::response::Redirect::to("/"), msg)
        })
    }

    #[get("/add/<path..>")]
    pub fn add(
        sender: rocket::State<'_, crate::PrirodaSender>,
        path: PathBuf,
    ) -> crate::RResult<rocket::response::Flash<rocket::response::Redirect>> {
        sender.do_work(move |pcx| {
            let path = path.to_string_lossy();
            let res = parse_breakpoint_from_url(&path);
            let msg = match res {
                Ok(breakpoint) => {
                    pcx.config.bptree.add_breakpoint(breakpoint);
                    format!(
                        "Breakpoint added for {:?}@{}:{}",
                        breakpoint.0,
                        breakpoint.1.index(),
                        breakpoint.2
                    )
                }
                Err(e) => e,
            };
            rocket::response::Flash::success(rocket::response::Redirect::to("/"), msg)
        })
    }

    #[get("/remove/<path..>")]
    pub fn remove(
        sender: rocket::State<'_, crate::PrirodaSender>,
        path: PathBuf,
    ) -> crate::RResult<rocket::response::Flash<rocket::response::Redirect>> {
        sender.do_work(move |pcx| {
            let path = path.to_string_lossy();
            let res = parse_breakpoint_from_url(&path);
            let msg = match res {
                Ok(breakpoint) => {
                    if pcx.config.bptree.remove_breakpoint(breakpoint) {
                        format!(
                            "Breakpoint removed for {:?}@{}:{}",
                            breakpoint.0,
                            breakpoint.1.index(),
                            breakpoint.2
                        )
                    } else {
                        format!(
                            "No breakpoint for for {:?}@{}:{}",
                            breakpoint.0,
                            breakpoint.1.index(),
                            breakpoint.2
                        )
                    }
                }
                Err(e) => e,
            };
            rocket::response::Flash::success(rocket::response::Redirect::to("/"), msg)
        })
    }

    #[get("/remove_all")]
    pub fn remove_all(
        sender: rocket::State<'_, crate::PrirodaSender>,
    ) -> crate::RResult<rocket::response::Flash<rocket::response::Redirect>> {
        sender.do_work(move |pcx| {
            pcx.config.bptree.remove_all();
            rocket::response::Flash::success(
                rocket::response::Redirect::to("/"),
                "All breakpoints removed",
            )
        })
    }
}


================================================
FILE: src/watch/mod.rs
================================================
use std::collections::HashMap;
use std::fmt::Write;

use rustc_middle::mir::interpret::{Allocation, Pointer, PointerArithmetic};
use rustc_middle::ty::Instance;
use rustc_mir::interpret::AllocId;
use rustc_target::abi::Size;

use crate::*;

mod stack_trace;

#[derive(Debug)]
pub struct Traces<'tcx> {
    alloc_traces: HashMap<AllocId, AllocTrace>,
    stack_traces_cpu: Vec<(Vec<(Instance<'tcx>,)>, u128)>,
    stack_traces_mem: Vec<(Vec<(Instance<'tcx>,)>, u128)>,
}

impl<'tcx> Traces<'tcx> {
    pub fn new() -> Self {
        let alloc_traces = HashMap::new();
        //for i in 0..700 {
        //    alloc_traces.insert(AllocId(i), AllocTrace::new());
        //}
        Traces {
            alloc_traces,
            stack_traces_cpu: Vec::new(),
            stack_traces_mem: Vec::new(),
        }
    }

    /// Clear the traces. This should be called before restarting the evaluation.
    pub fn clear(&mut self) {
        // We have to replace all values of alloc_traces by empty AllocTraces,
        // because stepping back will change the alloc id's
        self.alloc_traces.clear();

        // We can just empty the stack traces, because they will be rebuild during stepping
        self.stack_traces_cpu.clear();
        self.stack_traces_mem.clear();
    }
}

#[derive(Debug)]
struct AllocTrace {
    trace_points: Vec<(u128, AllocTracePoint)>,
}

impl AllocTrace {
    fn new() -> Self {
        AllocTrace {
            trace_points: Vec::new(),
        }
    }
}

#[derive(Debug)]
enum AllocTracePoint {
    Changed(Allocation<miri::Tag, miri::AllocExtra>),
    Deallocated,
}

fn eq_alloc(
    a: &Allocation<miri::Tag, miri::AllocExtra>,
    b: &Allocation<miri::Tag, miri::AllocExtra>,
) -> bool {
    let Allocation {
        align: a_align,
        mutability: a_mut,
        extra: _,
        size: a_size,
        ..
    } = a;
    let Allocation {
        align: b_align,
        mutability: b_mut,
        extra: _,
        size: b_size,
        ..
    } = b;
    a_align == b_align
        && a_mut == b_mut
        && a_size == b_size
        && a.inspect_with_uninit_and_ptr_outside_interpreter(0..a.len())
            == b.inspect_with_uninit_and_ptr_outside_interpreter(0..b.len())
        && a.relocations() == b.relocations()
        && a.init_mask() == b.init_mask()
}

pub fn step_callback(pcx: &mut PrirodaContext<'_, '_>) {
    {
        let ecx = &pcx.ecx;
        let traces = &mut pcx.traces;

        // Collect alloc traces
        for (alloc_id, alloc_trace) in &mut traces.alloc_traces {
            if let Ok(alloc) = ecx.memory.get_raw(*alloc_id) {
                if let Some(&(prev_step_count, AllocTracePoint::Changed(ref prev_alloc))) =
                    alloc_trace.trace_points.last()
                {
                    if eq_alloc(alloc, prev_alloc) || *pcx.step_count == prev_step_count {
                        continue;
                    }
                }

                alloc_trace
                    .trace_points
                    .push((*pcx.step_count, AllocTracePoint::Changed(alloc.clone())));
            } else if !matches!(
                alloc_trace.trace_points.last(),
                Some(&(_, AllocTracePoint::Deallocated))
            ) && !alloc_trace.trace_points.is_empty()
            {
                alloc_trace
                    .trace_points
                    .push((*pcx.step_count, AllocTracePoint::Deallocated));
            }
        }
    }

    stack_trace::step_callback(pcx);
}

pub fn routes() -> Vec<::rocket::Route> {
    routes![watch::show, watch::continue_and_show, watch::add]
}

#[get("/show")]
fn show(sender: rocket::State<'_, crate::PrirodaSender>) -> crate::RResult<Html<String>> {
    sender.do_work(|pcx| {
        let mut buf = String::new();

        stack_trace::show(pcx, &mut buf).unwrap();

        let mut alloc_traces = pcx.traces.alloc_traces.iter().collect::<Vec<_>>();
        alloc_traces.sort_by_key(|(id, _)| id.0);
        for (alloc_id, alloc_trace) in alloc_traces {
            if alloc_trace.trace_points.is_empty() {
                writeln!(buf, "<h2>Alloc {} has never existed</h2>", alloc_id.0).unwrap();
                continue;
            }

            writeln!(buf, "<h2>Alloc {}</h2>\n<table border='1'>", alloc_id.0).unwrap();
            for (step_count, trace_point) in &alloc_trace.trace_points {
                let content = match trace_point {
                    AllocTracePoint::Changed(alloc) => crate::render::locals::print_alloc(
                        pcx.ecx.memory.pointer_size().bytes(),
                        Pointer::new(*alloc_id, Size::from_bytes(0)).with_tag(miri::Tag::Untagged),
                        alloc,
                        None,
                    ),
                    AllocTracePoint::Deallocated => "Dealloc".to_string(),
                };
                writeln!(
                    buf,
                    "<tr>\n<td>{}</td>\n<td>{}</td>\n</tr>",
                    step_count, content
                )
                .unwrap();
            }
            writeln!(buf, "</table>\n").unwrap();
        }

        Html(buf)
    })
}

#[get("/continue_and_show")]
pub fn continue_and_show(sender: State<'_, PrirodaSender>) -> RResult<Html<String>> {
    sender.do_work(move |pcx| {
        crate::step::step(pcx, |_ecx| crate::step::ShouldContinue::Continue);
    })?;
    show(sender)
}

#[get("/add/<id>")]
pub fn add(
    sender: rocket::State<'_, crate::PrirodaSender>,
    id: u64,
) -> crate::RResult<rocket::response::Redirect> {
    sender.do_work(move |pcx| {
        pcx.traces
            .alloc_traces
            .insert(AllocId(id), AllocTrace::new());
        step_callback(pcx);
        rocket::response::Redirect::to("/")
    })
}


================================================
FILE: src/watch/stack_trace.rs
================================================
use std::fmt::Write;
use std::io::{self, Write as IoWrite};
use std::process::{Command, Stdio};

use rustc_middle::ty::{self, Instance, InstanceDef, ParamEnv};
use rustc_mir::interpret::Machine;

use crate::*;

pub(super) fn step_callback(pcx: &mut PrirodaContext<'_, '_>) {
    let ecx = &pcx.ecx;
    let traces = &mut pcx.traces;

    let stack_trace = Machine::stack(ecx)
        .iter()
        .map(|frame| (frame.instance,))
        .collect::<Vec<_>>();
    insert_stack_trace(&mut traces.stack_traces_cpu, stack_trace.clone(), 1);

    let location = if let Some(location) = ecx.frame().current_loc().ok() {
        location
    } else {
        return; // Unwinding, but no cleanup for current frame needed
    };
    let mir::Location {
        block,
        statement_index: stmt,
    } = location;
    let blck = &ecx.frame().body.basic_blocks()[block];

    if stmt == blck.statements.len() {
        use rustc_middle::mir::TerminatorKind::*;
        match &blck.terminator().kind {
            Call { func, args, .. } => {
                if let Some(instance) = instance_for_call_operand(ecx, &func) {
                    insert_stack_traces_for_instance(pcx, stack_trace, instance, Some(&args));
                }
            }
            Drop { place, .. } => {
                let location_ty = place.ty(ecx.frame().body, ecx.tcx.tcx).ty;
                let location_ty = ecx.tcx.subst_and_normalize_erasing_regions(
                    ecx.frame().instance.substs,
                    ParamEnv::reveal_all(),
                    location_ty,
                );
                let instance = Instance::resolve_drop_in_place(ecx.tcx.tcx, location_ty);
                insert_stack_traces_for_instance(pcx, stack_trace, instance, None);
            }
            _ => {}
        }
    }
}

fn instance_for_call_operand<'a, 'tcx: 'a>(
    ecx: &InterpCx<'tcx>,
    func: &'tcx rustc_middle::mir::Operand<'_>,
) -> Option<Instance<'tcx>> {
    let res: ::miri::InterpResult<'_, Instance<'_>> = try {
        let func = ecx.eval_operand(func, None)?;

        match func.layout.ty.kind() {
            ty::FnPtr(_) => {
                let fn_ptr = ecx.read_scalar(&func)?.check_init()?;
                if let Ok(instance) = ecx.memory.get_fn(fn_ptr)?.as_instance() {
                    instance
                } else {
                    return None;
                }
            }
            ty::FnDef(def_id, substs) => {
                let substs = ecx.tcx.subst_and_normalize_erasing_regions(
                    ecx.frame().instance.substs,
                    ParamEnv::reveal_all(),
                    *substs,
                );
                ty::Instance::resolve(*ecx.tcx, ParamEnv::reveal_all(), *def_id, substs)
                    .unwrap()
                    .unwrap()
            }
            _ => {
                panic!("can't handle callee of type {:?}", func.layout.ty);
            }
        }
    };
    Some(res.unwrap())
}

fn insert_stack_traces_for_instance<'a, 'tcx: 'a>(
    pcx: &mut PrirodaContext<'a, 'tcx>,
    mut stack_trace: Vec<(Instance<'tcx>,)>,
    instance: Instance<'tcx>,
    args: Option<&[mir::Operand<'tcx>]>,
) {
    let ecx = &pcx.ecx;
    let traces = &mut pcx.traces;

    let item_path = ecx.tcx.def_path_str(instance.def_id());

    stack_trace.push((instance,));
    insert_stack_trace(&mut traces.stack_traces_cpu, stack_trace.clone(), 1);

    let _: ::miri::InterpResult<'_> = try {
        let args = if let Some(args) = args {
            args.into_iter()
                .map(|op| ecx.eval_operand(op, None))
                .collect::<Result<Vec<_>, _>>()?
        } else {
            return;
        };

        match &item_path[..] {
            "alloc::alloc::::__rust_alloc" | "alloc::alloc::::__rust_alloc_zeroed" => {
                let size = ecx.read_scalar(&args[0])?.to_machine_usize(&ecx.tcx.tcx)?;
                insert_stack_trace(&mut traces.stack_traces_mem, stack_trace, size as u128);
            }
            "alloc::alloc::::__rust_realloc" => {
                let old_size = ecx.read_scalar(&args[1])?.to_machine_usize(&ecx.tcx.tcx)?;
                let new_size = ecx.read_scalar(&args[3])?.to_machine_usize(&ecx.tcx.tcx)?;
                if new_size > old_size {
                    insert_stack_trace(
                        &mut traces.stack_traces_mem,
                        stack_trace,
                        (new_size - old_size) as u128,
                    );
                }
            }
            _ => {}
        }
    };
}

fn insert_stack_trace<T: Eq>(traces: &mut Vec<(T, u128)>, trace: T, count: u128) {
    if let Some(t) = traces.last_mut() {
        if t.0 == trace {
            t.1 += count;
            return;
        }
    }
    traces.push((trace, count));
}

pub(super) fn show(pcx: &PrirodaContext<'_, '_>, buf: &mut impl Write) -> io::Result<()> {
    writeln!(buf, "{}\n", crate::render::refresh_script(pcx)).unwrap();
    create_flame_graph(
        &pcx.ecx,
        &mut *buf,
        &pcx.traces.stack_traces_cpu,
        "Cpu usage",
        "instructions",
        "java",
        "flame_graph_cpu",
    )?;
    create_flame_graph(
        &pcx.ecx,
        &mut *buf,
        &pcx.traces.stack_traces_mem,
        "Memory usage",
        "bytes",
        "mem",
        "flame_graph_mem",
    )?;
    print_stack_traces(&pcx.ecx, &mut *buf, &pcx.traces.stack_traces_cpu).unwrap();
    Ok(())
}

fn create_flame_graph<'a, 'tcx: 'a>(
    ecx: &InterpCx<'tcx>,
    mut buf: impl Write,
    traces: &[(Vec<(Instance<'tcx>,)>, u128)],
    name: &str,
    count_name: &str,
    color_scheme: &str,
    _file_name: &str,
) -> io::Result<()> {
    let mut flame_data = String::new();
    for (stack_trace, count) in traces {
        let mut last_crate = rustc_hir::def_id::LOCAL_CRATE;
        writeln!(
            flame_data,
            "{} {}",
            stack_trace
                .iter()
                .map(|(instance,)| {
                    let mut name = ecx.tcx.def_path_str(instance.def_id());
                    match instance.def {
                        InstanceDef::Intrinsic(..) => name.push_str("_[k]"),
                        InstanceDef::DropGlue(..) => name.push_str("_[k]"),
                        _ => {
                            if instance.def_id().is_local() {
                                name.push_str("_[j]");
                            }
                        }
                    }
                    if last_crate != instance.def_id().krate {
                        name = "-;".to_string() + &name;
                        last_crate = instance.def_id().krate;
                    }
                    name
                })
                .collect::<Vec<_>>()
                .join(";"),
            count
        )
        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
    }

    //::std::fs::write(format!("./resources/{}.txt", _file_name), flame_data.as_bytes())?;

    let child = Command::new("../FlameGraph/flamegraph.pl")
        .arg("-")
        .arg("--title")
        .arg(name)
        .arg("--countname")
        .arg(count_name)
        .arg("--colors")
        .arg(color_scheme)
        .arg("--minwidth")
        .arg("0.01")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn();
    match child {
        Ok(mut child) => {
            child
                .stdin
                .as_mut()
                .unwrap()
                .write_all(flame_data.as_bytes())?;
            match child.wait_with_output() {
                Ok(output) => {
                    let flame_graph = String::from_utf8(output.stdout).unwrap();
                    //::std::fs::write(format!("./resources/{}.svg", _file_name), flame_graph.as_bytes())?;
                    writeln!(buf, "{}", flame_graph).unwrap()
                }
                Err(err) => writeln!(buf, "<h1><pre>Wait error: {:?}</pre></h1>", err).unwrap(),
            }
        }
        Err(err) => writeln!(buf, "<h1><pre>Spawn error: {:?}</pre></h1>", err).unwrap(),
    }

    Ok(())
}

fn print_stack_traces<'a, 'tcx: 'a>(
    ecx: &InterpCx<'tcx>,
    mut buf: impl Write,
    traces: &[(Vec<(Instance<'tcx>,)>, u128)],
) -> ::std::fmt::Result {
    let name_for_instance = |i: Instance<'_>| {
        ecx.tcx
            .def_path_str(i.def_id())
            .replace("<", "&lt;")
            .replace(">", "&gt;")
    };
    writeln!(buf, "<h1>Stack trace</h1>\n<ul>\n")?;
    for (stack_trace, count) in traces {
        writeln!(
            buf,
            "<li>{2}{0} ({1})</li>\n",
            name_for_instance(stack_trace.last().unwrap().0),
            count,
            format!(
                "{nil: <indent$}",
                nil = "",
                indent = 4 * (stack_trace.len() - 1)
            )
            .replace(" ", "&nbsp;")
        )?;
    }
    writeln!(buf, "</ul>")?;
    Ok(())
}
Download .txt
gitextract_34yhs5wo/

├── .github/
│   └── workflows/
│       └── build.yml
├── .gitignore
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── Rocket.toml
├── example.rs
├── resources/
│   ├── positioning.css
│   ├── style-default.css
│   ├── svg-pan-zoom.js
│   └── zoom_mir.js
├── rust-toolchain
└── src/
    ├── main.rs
    ├── render/
    │   ├── graphviz.rs
    │   ├── locals.rs
    │   ├── mod.rs
    │   └── source.rs
    ├── step.rs
    └── watch/
        ├── mod.rs
        └── stack_trace.rs
Download .txt
SYMBOL INDEX (120 symbols across 11 files)

FILE: example.rs
  function some_fn (line 3) | fn some_fn() {
  type MyWrapper (line 12) | struct MyWrapper<'a>(&'a mut u8);
  type SomeRandomStruct (line 14) | struct SomeRandomStruct<'a, A> {
  type SomeOtherStruct (line 24) | struct SomeOtherStruct {
  function main (line 34) | fn main() {

FILE: resources/svg-pan-zoom.js
  function i (line 3) | function i(r,a){if(!o[r]){if(!e[r]){var l="function"==typeof require&&re...
  function t (line 3) | function t(t,e,o){var n=function(t){!t&&(t=window.event);var o={original...
  function e (line 3) | function e(t,e){for(var o=0;o<c.length;o++)if(c[o].element===t&&c[o].cap...
  function o (line 3) | function o(t,e){for(var o=0;o<c.length;o++)if(c[o].element===t&&c[o].cap...
  function n (line 3) | function n(e,o,n,i){var s;s="wheel"===u?n:t(e,n,i),e[a](h+o,s,i||!1)}
  function i (line 3) | function i(t,n,i,s){var r;r="wheel"===u?i:e(t,s),t[l](h+n,r,s||!1),o(t,s)}
  function s (line 3) | function s(t,e,o){n(t,u,e,o),"DOMMouseScroll"==u&&n(t,"MozMousePixelScro...
  function r (line 3) | function r(t,e,o){i(t,u,e,o),"DOMMouseScroll"==u&&i(t,"MozMousePixelScro...
  function n (line 3) | function n(t){return function(e){window.setTimeout(e,t)}}

FILE: resources/zoom_mir.js
  function enable_mir_mousewheel (line 1) | function enable_mir_mousewheel() {

FILE: src/main.rs
  function should_hide_stmt (line 46) | fn should_hide_stmt(stmt: &mir::Statement<'_>) -> bool {
  type InterpCx (line 54) | type InterpCx<'tcx> = rustc_mir::interpret::InterpCx<'tcx, 'tcx, Evaluat...
  type PrirodaContext (line 56) | pub struct PrirodaContext<'a, 'tcx: 'a> {
  function restart (line 65) | fn restart(&mut self) {
  function to_main (line 73) | fn to_main(&mut self) {
  type Config (line 97) | pub struct Config {
  function true_bool (line 106) | fn true_bool() -> bool {
  function default_theme (line 109) | fn default_theme() -> String {
  method default (line 114) | fn default() -> Self {
  type RResult (line 125) | type RResult<T> = Result<T, Html<String>>;
  function create_ecx (line 127) | fn create_ecx<'mir, 'tcx>(tcx: TyCtxt<'tcx>) -> InterpCx<'tcx> {
  type PrirodaSender (line 156) | pub struct PrirodaSender(
    method do_work (line 161) | fn do_work<'r, T, F>(&self, f: F) -> Result<T, Html<String>>
  function please_panic (line 187) | fn please_panic(sender: State<'_, PrirodaSender>) -> RResult<()> {
  function resources (line 193) | fn resources(path: PathBuf) -> Result<NamedFile, std::io::Error> {
  function resources (line 201) | fn resources(path: PathBuf) -> Result<Content<&'static str>, std::io::Er...
  function step_count (line 226) | fn step_count(sender: State<'_, PrirodaSender>) -> RResult<String> {
  function server (line 230) | fn server(sender: PrirodaSender) {
  function find_sysroot (line 255) | fn find_sysroot() -> String {
  type PrirodaCompilerCalls (line 271) | struct PrirodaCompilerCalls {
    method after_analysis (line 279) | fn after_analysis<'tcx>(
  function main (line 330) | fn main() {

FILE: src/render/graphviz.rs
  function render_html (line 17) | pub fn render_html<'tcx>(
  function render_mir_svg (line 126) | pub fn render_mir_svg<W: Write>(
  function write_node_label (line 163) | fn write_node_label<W: Write>(
  function write_node (line 220) | fn write_node<W: Write>(
  function write_edges (line 239) | fn write_edges<W: Write>(source: BasicBlock, mir: &Body<'_>, w: &mut W) ...
  function node (line 256) | fn node(promoted: Option<usize>, block: BasicBlock) -> String {
  function escape (line 264) | fn escape<T: Debug>(t: &T) -> String {
  function escape_html (line 268) | fn escape_html(s: &str) -> ::std::borrow::Cow<'_, str> {

FILE: src/render/locals.rs
  function render_locals (line 19) | pub fn render_locals<'tcx>(
  function print_scalar_maybe_undef (line 123) | fn print_scalar_maybe_undef(val: ScalarMaybeUninit<miri::Tag>) -> String {
  function print_scalar (line 130) | fn print_scalar(val: Scalar<miri::Tag>) -> String {
  function pp_operand (line 148) | fn pp_operand<'tcx>(
  function print_operand (line 273) | pub fn print_operand<'a, 'tcx: 'a>(
  function print_ptr (line 312) | pub fn print_ptr(
  function print_alloc (line 329) | pub fn print_alloc(

FILE: src/render/mod.rs
  function template (line 17) | pub fn template(pcx: &PrirodaContext<'_, '_>, title: String, t: impl Tem...
  function refresh_script (line 40) | pub fn refresh_script(pcx: &PrirodaContext<'_, '_>) -> String {
  function render_main_window (line 63) | pub fn render_main_window(
  function render_reverse_ptr (line 185) | pub fn render_reverse_ptr(pcx: &PrirodaContext<'_, '_>, alloc_id: u64) -...
  function render_ptr_memory (line 209) | pub fn render_ptr_memory(
  type FlashString (line 246) | pub struct FlashString(String);
    type Error (line 249) | type Error = !;
    method from_request (line 250) | fn from_request(request: &'a rocket::Request<'r>) -> rocket::request::...
  function routes (line 263) | pub fn routes() -> Vec<::rocket::Route> {
  function index (line 268) | pub fn index(
  function frame (line 276) | pub fn frame(
  function frame_invalid (line 285) | fn frame_invalid(frame: String) -> BadRequest<String> {
  function ptr (line 292) | pub fn ptr(
  function reverse_ptr (line 301) | fn reverse_ptr(

FILE: src/render/source.rs
  function initialise_statics (line 34) | pub fn initialise_statics() {
  function pretty_src_path (line 38) | pub fn pretty_src_path(span: Span) -> String {
  type HighlightCacheEntry (line 55) | pub struct HighlightCacheEntry {
  function render_source (line 60) | pub fn render_source(
  function get_file_source_for_span (line 155) | fn get_file_source_for_span(tcx: TyCtxt<'_>, sp: Span) -> Result<(String...
  function syntax_highlight (line 175) | fn syntax_highlight<'a, 's>(src: &'s str) -> Vec<(Style, Range<usize>)> {
  function mark_span (line 200) | fn mark_span(file_contents: &str, src: &[(Style, Range<usize>)], lo: usi...

FILE: src/step.rs
  type ShouldContinue (line 13) | pub enum ShouldContinue {
  type Breakpoint (line 19) | pub struct Breakpoint(pub DefId, pub mir::BasicBlock, pub usize);
  type BreakpointTree (line 22) | pub struct BreakpointTree(HashMap<DefId, HashSet<Breakpoint>>);
    method deserialize (line 25) | fn deserialize<D: Deserializer<'de>>(deser: D) -> Result<Self, D::Erro...
    method add_breakpoint (line 41) | pub fn add_breakpoint(&mut self, bp: Breakpoint) {
    method remove_breakpoint (line 45) | pub fn remove_breakpoint(&mut self, bp: Breakpoint) -> bool {
    method remove_all (line 52) | pub fn remove_all(&mut self) {
    method for_def_id (line 56) | pub fn for_def_id(&self, def_id: DefId) -> LocalBreakpoints<'_> {
    method is_at_breakpoint (line 64) | pub fn is_at_breakpoint(&self, ecx: &InterpCx<'_>) -> bool {
    method iter (line 70) | pub fn iter(&self) -> impl Iterator<Item = &Breakpoint> {
  type LocalBreakpoints (line 76) | pub enum LocalBreakpoints<'a> {
  function breakpoint_exists (line 82) | pub fn breakpoint_exists(self, location: Option<mir::Location>) -> bool {
  function step (line 98) | pub fn step<F>(pcx: &mut PrirodaContext<'_, '_>, continue_while: F) -> S...
  function is_ret (line 170) | pub fn is_ret(ecx: &InterpCx<'_>) -> bool {
  function parse_breakpoint_from_url (line 190) | fn parse_breakpoint_from_url(s: &str) -> Result<Breakpoint, String> {
  function parse_def_id (line 225) | fn parse_def_id(s: &str) -> Result<DefId, String> {
  function routes (line 250) | pub fn routes() -> Vec<::rocket::Route> {
  function restart (line 255) | fn restart(
  function single (line 265) | fn single(
  function single_back (line 277) | fn single_back(
  function next (line 307) | fn next(
  function return_ (line 336) | fn return_(
  function continue_ (line 353) | fn continue_(
  function routes (line 369) | pub fn routes() -> Vec<::rocket::Route> {
  function add_here (line 374) | pub fn add_here(
  function add (line 399) | pub fn add(
  function remove (line 423) | pub fn remove(
  function remove_all (line 455) | pub fn remove_all(

FILE: src/watch/mod.rs
  type Traces (line 14) | pub struct Traces<'tcx> {
  function new (line 21) | pub fn new() -> Self {
  function clear (line 34) | pub fn clear(&mut self) {
  type AllocTrace (line 46) | struct AllocTrace {
    method new (line 51) | fn new() -> Self {
  type AllocTracePoint (line 59) | enum AllocTracePoint {
  function eq_alloc (line 64) | fn eq_alloc(
  function step_callback (line 91) | pub fn step_callback(pcx: &mut PrirodaContext<'_, '_>) {
  function routes (line 125) | pub fn routes() -> Vec<::rocket::Route> {
  function show (line 130) | fn show(sender: rocket::State<'_, crate::PrirodaSender>) -> crate::RResu...
  function continue_and_show (line 170) | pub fn continue_and_show(sender: State<'_, PrirodaSender>) -> RResult<Ht...
  function add (line 178) | pub fn add(

FILE: src/watch/stack_trace.rs
  function step_callback (line 10) | pub(super) fn step_callback(pcx: &mut PrirodaContext<'_, '_>) {
  function instance_for_call_operand (line 54) | fn instance_for_call_operand<'a, 'tcx: 'a>(
  function insert_stack_traces_for_instance (line 88) | fn insert_stack_traces_for_instance<'a, 'tcx: 'a>(
  function insert_stack_trace (line 132) | fn insert_stack_trace<T: Eq>(traces: &mut Vec<(T, u128)>, trace: T, coun...
  function show (line 142) | pub(super) fn show(pcx: &PrirodaContext<'_, '_>, buf: &mut impl Write) -...
  function create_flame_graph (line 166) | fn create_flame_graph<'a, 'tcx: 'a>(
  function print_stack_traces (line 244) | fn print_stack_traces<'a, 'tcx: 'a>(
Condensed preview — 21 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (138K chars).
[
  {
    "path": ".github/workflows/build.yml",
    "chars": 657,
    "preview": "name: Continuous Integration\n\non: [push, pull_request]\n\njobs:\n  check:\n    name: Check\n    runs-on: ubuntu-latest\n    st"
  },
  {
    "path": ".gitignore",
    "chars": 33,
    "preview": "/target\nflame_graph*\nconfig.json\n"
  },
  {
    "path": "Cargo.toml",
    "chars": 1022,
    "preview": "[package]\nauthors = [\"Oliver Schneider <priroda-tsm-i-77ksi-11f77i@oli-obk.de>\"]\ndescription = \"A graphical debugger for"
  },
  {
    "path": "LICENSE-APACHE",
    "chars": 10842,
    "preview": "                              Apache License\n                        Version 2.0, January 2004\n                     http"
  },
  {
    "path": "LICENSE-MIT",
    "chars": 1063,
    "preview": "Copyright (c) 2016 The Miri Developers\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of "
  },
  {
    "path": "README.md",
    "chars": 1963,
    "preview": "# Priroda\n\nPriroda is a graphical (UI in browser) debugger for Rust programs\n\n## Setup\n\nYou need a few things before you"
  },
  {
    "path": "Rocket.toml",
    "chars": 138,
    "preview": "[development]\naddress = \"localhost\"\nport = 54321\n#spawn_browser = true\n\n[production]\naddress = \"0.0.0.0\"\nport = 8080\nspa"
  },
  {
    "path": "example.rs",
    "chars": 1071,
    "preview": "#![allow(dead_code)]\n\nfn some_fn() {\n    let mut val = 2;\n    let mut my_wrapper = MyWrapper(&mut val);\n    let wrapper_"
  },
  {
    "path": "resources/positioning.css",
    "chars": 885,
    "preview": "* {\n  box-sizing: border-box;\n}\n\nbody {\n  margin: 0px;\n  height: 100vh;\n  overflow-y: hidden;\n}\n\n#left, #right {\n  displ"
  },
  {
    "path": "resources/style-default.css",
    "chars": 1421,
    "preview": "#mir {\n  border: 2px grey solid;\n}\n\n#stack {\n  border: grey 2px solid;\n  margin: 2px 0;\n  padding: 2px;\n}\n\n#stack table "
  },
  {
    "path": "resources/svg-pan-zoom.js",
    "chars": 29732,
    "preview": "// svg-pan-zoom v3.5.2\n// https://github.com/ariutta/svg-pan-zoom\n!function t(e,o,n){function i(r,a){if(!o[r]){if(!e[r])"
  },
  {
    "path": "resources/zoom_mir.js",
    "chars": 196,
    "preview": "function enable_mir_mousewheel() {\n  var svg = svgPanZoom(\"#mir > svg\", {\n    controlIconsEnabled: true,\n    zoomScaleSe"
  },
  {
    "path": "rust-toolchain",
    "chars": 100,
    "preview": "[toolchain]\nchannel = \"nightly-2021-03-13\"\ncomponents = [\"miri\", \"rustc-dev\", \"llvm-tools-preview\"]\n"
  },
  {
    "path": "src/main.rs",
    "chars": 12555,
    "preview": "#![feature(rustc_private, decl_macro, plugin, try_blocks, proc_macro_hygiene)]\n#![feature(never_type)]\n#![allow(unused_a"
  },
  {
    "path": "src/render/graphviz.rs",
    "chars": 8529,
    "preview": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution"
  },
  {
    "path": "src/render/locals.rs",
    "chars": 13390,
    "preview": "use rustc_middle::mir::{\n    self,\n    interpret::{InterpError, UndefinedBehaviorInfo},\n};\nuse rustc_middle::ty::{subst:"
  },
  {
    "path": "src/render/mod.rs",
    "chars": 10827,
    "preview": "mod graphviz;\npub mod locals;\nmod source;\n\npub use source::initialise_statics;\n\nuse rustc_hir::definitions::DefPathData;"
  },
  {
    "path": "src/render/source.rs",
    "chars": 7297,
    "preview": "use std::collections::HashMap;\nuse std::{cell::RefCell, ops::Range};\n\nuse miri::{FrameData, Tag};\nuse rustc_middle::ty::"
  },
  {
    "path": "src/step.rs",
    "chars": 15935,
    "preview": "use rustc_hir::def_id::{CrateNum, DefId, DefIndex};\nuse rustc_index::vec::Idx;\nuse rustc_middle::mir;\nuse rustc_mir::int"
  },
  {
    "path": "src/watch/mod.rs",
    "chars": 5758,
    "preview": "use std::collections::HashMap;\nuse std::fmt::Write;\n\nuse rustc_middle::mir::interpret::{Allocation, Pointer, PointerArit"
  },
  {
    "path": "src/watch/stack_trace.rs",
    "chars": 8942,
    "preview": "use std::fmt::Write;\nuse std::io::{self, Write as IoWrite};\nuse std::process::{Command, Stdio};\n\nuse rustc_middle::ty::{"
  }
]

About this extraction

This page contains the full source code of the oli-obk/priroda GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 21 files (129.3 KB), approximately 34.4k tokens, and a symbol index with 120 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!