[
  {
    "path": ".github/workflows/build.yml",
    "content": "name: Continuous Integration\n\non: [push, pull_request]\n\njobs:\n  check:\n    name: Check\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      # Toolchain installation should appear as a seperate step for timing purposes\n      - run: rustup show\n      - name: Setup Graphviz\n        uses: ts-graphviz/setup-graphviz@v1\n      - uses: actions-rs/cargo@v1\n        with:\n          command: check\n  fmt:\n    name: Rustfmt\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - run: rustup component add rustfmt\n      - uses: actions-rs/cargo@v1\n        with:\n          command: fmt\n          args: --all -- --check\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\nflame_graph*\nconfig.json\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nauthors = [\"Oliver Schneider <priroda-tsm-i-77ksi-11f77i@oli-obk.de>\"]\ndescription = \"A graphical debugger for Rust MIR.\"\nlicense = \"MIT/Apache-2.0\"\nname = \"priroda\"\nrepository = \"https://github.com/oli-obk/priroda\"\nversion = \"0.1.0\"\nedition = \"2018\"\n\n\n[dependencies]\nregex = \"1.3\"\nlazy_static = \"1.4.0\"\nrocket = \"0.4.7\"\n# This needs to be the version of miri for the nightly in the `rust-toolchain` file\nmiri = { git = \"https://github.com/rust-lang/miri.git\", rev = \"ae964207bb17911cf96d9744d9469fa2734093a8\" }\n\nlog = \"0.4\"\nenv_logger = \"0.7\"\n\nserde = { version = \"1.0\", features = [\"derive\"] }\nserde_json = \"1.0\"\n\nopen = \"1.4.0\"\nsyntect = \"4.2\"\nhorrorshow = \"0.8\"\ncgraph = { git = \"https://github.com/oli-obk/cgraph.git\", rev = \"5e6a6d4527522609772a9a9a1565b74c9bfe1560\" }\n\n# Uncomment to use local checkout of miri\n# [patch.\"https://github.com/rust-lang/miri.git\"]\n# miri = { path = \"../miri\" }\n\n[features]\nstatic_resources = []\n\n[package.metadata.rust-analyzer]\nrustc_private = true\n\n[profile.dev]\ndebug = 1\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                              Apache License\n                        Version 2.0, January 2004\n                     http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n   \"License\" shall mean the terms and conditions for use, reproduction,\n   and distribution as defined by Sections 1 through 9 of this document.\n\n   \"Licensor\" shall mean the copyright owner or entity authorized by\n   the copyright owner that is granting the License.\n\n   \"Legal Entity\" shall mean the union of the acting entity and all\n   other entities that control, are controlled by, or are under common\n   control with that entity. For the purposes of this definition,\n   \"control\" means (i) the power, direct or indirect, to cause the\n   direction or management of such entity, whether by contract or\n   otherwise, or (ii) ownership of fifty percent (50%) or more of the\n   outstanding shares, or (iii) beneficial ownership of such entity.\n\n   \"You\" (or \"Your\") shall mean an individual or Legal Entity\n   exercising permissions granted by this License.\n\n   \"Source\" form shall mean the preferred form for making modifications,\n   including but not limited to software source code, documentation\n   source, and configuration files.\n\n   \"Object\" form shall mean any form resulting from mechanical\n   transformation or translation of a Source form, including but\n   not limited to compiled object code, generated documentation,\n   and conversions to other media types.\n\n   \"Work\" shall mean the work of authorship, whether in Source or\n   Object form, made available under the License, as indicated by a\n   copyright notice that is included in or attached to the work\n   (an example is provided in the Appendix below).\n\n   \"Derivative Works\" shall mean any work, whether in Source or Object\n   form, that is based on (or derived from) the Work and for which the\n   editorial revisions, annotations, elaborations, or other modifications\n   represent, as a whole, an original work of authorship. For the purposes\n   of this License, Derivative Works shall not include works that remain\n   separable from, or merely link (or bind by name) to the interfaces of,\n   the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including\n   the original version of the Work and any modifications or additions\n   to that Work or Derivative Works thereof, that is intentionally\n   submitted to Licensor for inclusion in the Work by the copyright owner\n   or by an individual or Legal Entity authorized to submit on behalf of\n   the copyright owner. For the purposes of this definition, \"submitted\"\n   means any form of electronic, verbal, or written communication sent\n   to the Licensor or its representatives, including but not limited to\n   communication on electronic mailing lists, source code control systems,\n   and issue tracking systems that are managed by, or on behalf of, the\n   Licensor for the purpose of discussing and improving the Work, but\n   excluding communication that is conspicuously marked or otherwise\n   designated in writing by the copyright owner as \"Not a Contribution.\"\n\n   \"Contributor\" shall mean Licensor and any individual or Legal Entity\n   on behalf of whom a Contribution has been received by Licensor and\n   subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   copyright license to reproduce, prepare Derivative Works of,\n   publicly display, publicly perform, sublicense, and distribute the\n   Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   (except as stated in this section) patent license to make, have made,\n   use, offer to sell, sell, import, and otherwise transfer the Work,\n   where such license applies only to those patent claims licensable\n   by such Contributor that are necessarily infringed by their\n   Contribution(s) alone or by combination of their Contribution(s)\n   with the Work to which such Contribution(s) was submitted. If You\n   institute patent litigation against any entity (including a\n   cross-claim or counterclaim in a lawsuit) alleging that the Work\n   or a Contribution incorporated within the Work constitutes direct\n   or contributory patent infringement, then any patent licenses\n   granted to You under this License for that Work shall terminate\n   as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n   Work or Derivative Works thereof in any medium, with or without\n   modifications, and in Source or Object form, provided that You\n   meet the following conditions:\n\n   (a) You must give any other recipients of the Work or\n       Derivative Works a copy of this License; and\n\n   (b) You must cause any modified files to carry prominent notices\n       stating that You changed the files; and\n\n   (c) You must retain, in the Source form of any Derivative Works\n       that You distribute, all copyright, patent, trademark, and\n       attribution notices from the Source form of the Work,\n       excluding those notices that do not pertain to any part of\n       the Derivative Works; and\n\n   (d) If the Work includes a \"NOTICE\" text file as part of its\n       distribution, then any Derivative Works that You distribute must\n       include a readable copy of the attribution notices contained\n       within such NOTICE file, excluding those notices that do not\n       pertain to any part of the Derivative Works, in at least one\n       of the following places: within a NOTICE text file distributed\n       as part of the Derivative Works; within the Source form or\n       documentation, if provided along with the Derivative Works; or,\n       within a display generated by the Derivative Works, if and\n       wherever such third-party notices normally appear. The contents\n       of the NOTICE file are for informational purposes only and\n       do not modify the License. You may add Your own attribution\n       notices within Derivative Works that You distribute, alongside\n       or as an addendum to the NOTICE text from the Work, provided\n       that such additional attribution notices cannot be construed\n       as modifying the License.\n\n   You may add Your own copyright statement to Your modifications and\n   may provide additional or different license terms and conditions\n   for use, reproduction, or distribution of Your modifications, or\n   for any such Derivative Works as a whole, provided Your use,\n   reproduction, and distribution of the Work otherwise complies with\n   the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n   any Contribution intentionally submitted for inclusion in the Work\n   by You to the Licensor shall be under the terms and conditions of\n   this License, without any additional terms or conditions.\n   Notwithstanding the above, nothing herein shall supersede or modify\n   the terms of any separate license agreement you may have executed\n   with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n   agreed to in writing, Licensor provides the Work (and each\n   Contributor provides its Contributions) on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n   implied, including, without limitation, any warranties or conditions\n   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n   PARTICULAR PURPOSE. You are solely responsible for determining the\n   appropriateness of using or redistributing the Work and assume any\n   risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n   whether in tort (including negligence), contract, or otherwise,\n   unless required by applicable law (such as deliberate and grossly\n   negligent acts) or agreed to in writing, shall any Contributor be\n   liable to You for damages, including any direct, indirect, special,\n   incidental, or consequential damages of any character arising as a\n   result of this License or out of the use or inability to use the\n   Work (including but not limited to damages for loss of goodwill,\n   work stoppage, computer failure or malfunction, or any and all\n   other commercial damages or losses), even if such Contributor\n   has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n   the Work or Derivative Works thereof, You may choose to offer,\n   and charge a fee for, acceptance of support, warranty, indemnity,\n   or other liability obligations and/or rights consistent with this\n   License. However, in accepting such obligations, You may act only\n   on Your own behalf and on Your sole responsibility, not on behalf\n   of any other Contributor, and only if You agree to indemnify,\n   defend, and hold each Contributor harmless for any liability\n   incurred by, or claims asserted against, such Contributor by reason\n   of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n   To apply the Apache License to your work, attach the following\n   boilerplate notice, with the fields enclosed by brackets \"[]\"\n   replaced with your own identifying information. (Don't include\n   the brackets!)  The text should be enclosed in the appropriate\n   comment syntax for the file format. We also recommend that a\n   file or class name and description of purpose be included on the\n   same \"printed page\" as the copyright notice for easier\n   identification within third-party archives.\n\nCopyright 2016 The Miri Developers\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "Copyright (c) 2016 The Miri Developers\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Priroda\n\nPriroda is a graphical (UI in browser) debugger for Rust programs\n\n## Setup\n\nYou need a few things before you can get started. At the very minimum you need to have\nthe graphviz libraries present.\n\n* debian/ubuntu: `apt install libgraphviz-dev`\n\nNext, you're going to want a libstd with full MIR. The easiest way to obtain this is via\n`cargo miri`:\n\n```bash\n# Install cargo miri:\nrustup component add miri\n# Compile libstd:\ncargo miri setup\n# Set the MIRI_SYSROOT environment variable to the path printed by the setup command:\nexport MIRI_SYSROOT=...\n```\n\n## Features\n\n* Supports commands known from gdb\n  * next, step, continue\n* Inspect memory of all stack frames visually\n* Follow pointers by clicking hyperlinks\n* Track your progress through a function in a graph of the MIR\n* Style your debugging experience with CSS\n\n## Usage\n\n`cargo run some_rust_file.rs` will automatically start a http server and open a\nbrowser. UI is changing rapidly right now, so you need to figure out how to use\nit by yourself (or by asking on irc) for now.\n\n## Contributing and getting help\n\nCheck out the issues on this GitHub repository for some ideas. There's lots that\nneeds to be done that I haven't documented in the issues yet, however. For more\nideas or help with running or hacking on Priroda, you can ask at [`#miri`] on the\nrust-lang zulip.\n\n[`#miri`]: https://rust-lang.zulipchat.com/#narrow/stream/269128-miri\n\n### Miri\n\nThis project depends entirely on [Miri](https://github.com/rust-lang/miri).\nSo if you want to improve something that we fail to interpret, add a unit test\nto Miri and fix it there.\n\n## License\n\nLicensed under either of\n\n* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))\n* MIT license ([LICENSE-MIT](LICENSE-MIT))\n\n### Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in the work by you shall be dual licensed as above, without any\nadditional terms or conditions.\n"
  },
  {
    "path": "Rocket.toml",
    "content": "[development]\naddress = \"localhost\"\nport = 54321\n#spawn_browser = true\n\n[production]\naddress = \"0.0.0.0\"\nport = 8080\nspawn_browser = false"
  },
  {
    "path": "example.rs",
    "content": "#![allow(dead_code)]\n\nfn some_fn() {\n    let mut val = 2;\n    let mut my_wrapper = MyWrapper(&mut val);\n    let wrapper_ref = &mut my_wrapper;\n    for i in 0..16 {\n        *wrapper_ref.0 = i;\n    }\n}\n\nstruct MyWrapper<'a>(&'a mut u8);\n\nstruct SomeRandomStruct<'a, A> {\n    ernrer: u8,\n    feijoc: i64,\n    ioieoe: bool,\n    fewije: char,\n    chr_ref: &'a char,\n    efoiri: A,\n    irrfio: SomeOtherStruct,\n}\n\nstruct SomeOtherStruct {\n    efufrr: u8,\n    frireg: u16,\n}\n\nunion SomeUnion {\n    a: bool,\n    b: u64,\n}\n\nfn main() {\n    let chr = '4';\n    let _rer = SomeRandomStruct {\n        ernrer: 24,\n        feijoc: -34438,\n        ioieoe: true,\n        fewije: '@',\n        chr_ref: &chr,\n        efoiri: Some(2u16),\n        irrfio: SomeOtherStruct {\n            efufrr: 34,\n            frireg: 45804,\n        },\n    };\n    let u = SomeUnion { a: true };\n    let abc = Box::new(42);\n    some_fn();\n    let f = 1.4f64;\n    let _sum = 1f64\n    +\n    f;\n    let _s = \"ieeoe\";\n    let _bcd: Box<[u8]> = Box::new([0, 1]);\n    let _d = true;\n    format!(\"ewioio: {}\", abc);\n}\n"
  },
  {
    "path": "resources/positioning.css",
    "content": "* {\n  box-sizing: border-box;\n}\n\nbody {\n  margin: 0px;\n  height: 100vh;\n  overflow-y: hidden;\n}\n\n#left, #right {\n  display: inline-block;\n  width: calc(50vw - 4px);\n  height: 100vh;\n  margin: 2px;\n  vertical-align: top;\n  overflow: auto;\n}\n\n#mir {\n  width: 100%;\n  height: calc(100% - 150px);\n}\n\n#mir > svg {\n  display: block;\n  max-width: 100%;\n  max-height: 100%;\n  width: auto;\n  height: auto;\n}\n\n#mir > svg:first-child {\n  width: 100%;\n  height: 100%;\n}\n\n#stack, #locals {\n  overflow: auto;\n}\n\n.vertical {\n  writing-mode: tb-rl;\n}\n\n@media only screen and (max-width: 600px) {\n  body {\n    height: unset;\n    overflow-y: scroll;\n  }\n  #left, #right {\n    display: block;\n    width: 100vw;\n    height: unset;\n    margin: 2px 0;\n    padding: 0 5px;\n  }\n  #mir {\n    width: calc(100vw - 100px) !important;\n    height: unset;\n  }\n  #mir:first-child {\n    height: 50vh !important;\n  }\n}\n"
  },
  {
    "path": "resources/style-default.css",
    "content": "#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 tr td:nth-child(1) {\n  color: red;\n}\n\n#locals {\n  border: grey 2px solid;\n  margin: 2px 0;\n}\n\n#locals table {\n  border-collapse:collapse;\n  border: none;\n  font-family: monospace;\n}\n\n/* left top corner */\n#locals table tbody :first-child td {\n  border: none;\n}\n\n#locals table tr th {\n  background-color: lightgrey;\n}\n\n#locals table tr th {\n  min-width: 14px;\n  font-size: 12px\n}\n\n#return_ptr {\n  display: inline-block;\n  border: 1px solid black;\n}\n\n#commands {\n  display: flex;\n  width: 100%;\n  flex-wrap: wrap;\n  padding: 2px;\n}\n\n#commands > a {\n  text-decoration: none;\n  padding-right: 2px;\n  margin: 3px;\n}\n\n#commands > a > div {\n  padding: 5px 7px;\n  background: #4479BA;\n  color: #FFF;\n  border-radius: 4px;\n  border: solid 1px #20538D;\n  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);\n  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);\n  transition-duration: 0.2s;\n  user-select:none;\n}\n\n#commands > a > div:hover {\n  background: #356094;\n  border: solid 1px #2A4E77;\n  text-decoration: none;\n}\n\n#commands > a > div:active {\n  box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);\n  background: #2E5481;\n  border: solid 1px #203E5F;\n}\n\n#stack table {\n  border: none;\n  border-collapse: collapse;\n}\n\n#stack table tr :first-child {\n  border: none;\n}\n\ntd {\n  padding: 0px;\n}\n"
  },
  {
    "path": "resources/svg-pan-zoom.js",
    "content": "// 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]){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]);"
  },
  {
    "path": "resources/zoom_mir.js",
    "content": "function enable_mir_mousewheel() {\n  var svg = svgPanZoom(\"#mir > svg\", {\n    controlIconsEnabled: true,\n    zoomScaleSensitivity: 0.5,\n    maxZoom: 50.0,\n    minZoom: 1.0,\n    fit: true,\n  });\n}\n"
  },
  {
    "path": "rust-toolchain",
    "content": "[toolchain]\nchannel = \"nightly-2021-03-13\"\ncomponents = [\"miri\", \"rustc-dev\", \"llvm-tools-preview\"]\n"
  },
  {
    "path": "src/main.rs",
    "content": "#![feature(rustc_private, decl_macro, plugin, try_blocks, proc_macro_hygiene)]\n#![feature(never_type)]\n#![allow(unused_attributes)]\n#![recursion_limit = \"5000\"]\n#![warn(rust_2018_idioms)]\n\nextern crate rustc_driver;\nextern crate rustc_hir;\nextern crate rustc_index;\nextern crate rustc_interface;\nextern crate rustc_middle;\nextern crate rustc_mir;\nextern crate rustc_span;\nextern crate rustc_target;\nextern crate rustc_type_ir;\n\n#[macro_use]\nextern crate rocket;\n\nmod render;\nmod step;\nmod watch;\n\nuse std::ops::FnOnce;\nuse std::path::PathBuf;\nuse std::sync::mpsc;\nuse std::sync::{Arc, Mutex};\n\nuse miri::Evaluator;\nuse rustc_driver::Compilation;\nuse rustc_hir::def_id::LOCAL_CRATE;\nuse rustc_interface::interface;\nuse rustc_middle::mir;\nuse rustc_middle::ty::TyCtxt;\n\nuse rocket::response::content::*;\nuse rocket::response::status::BadRequest;\nuse rocket::response::NamedFile;\nuse rocket::State;\n\nuse serde::Deserialize;\nuse step::{step, ShouldContinue};\n\nuse crate::step::BreakpointTree;\n\nfn should_hide_stmt(stmt: &mir::Statement<'_>) -> bool {\n    use rustc_middle::mir::StatementKind::*;\n    match stmt.kind {\n        StorageLive(_) | StorageDead(_) | Nop => true,\n        _ => false,\n    }\n}\n\ntype InterpCx<'tcx> = rustc_mir::interpret::InterpCx<'tcx, 'tcx, Evaluator<'tcx, 'tcx>>;\n\npub struct PrirodaContext<'a, 'tcx: 'a> {\n    ecx: InterpCx<'tcx>,\n    step_count: &'a mut u128,\n    traces: watch::Traces<'tcx>,\n    config: &'a mut Config,\n    skip_to_main: bool,\n}\n\nimpl<'a, 'tcx: 'a> PrirodaContext<'a, 'tcx> {\n    fn restart(&mut self) {\n        self.ecx = create_ecx(self.ecx.tcx.tcx);\n        *self.step_count = 0;\n        self.traces.clear(); // Cleanup all traces\n        self.to_main();\n    }\n\n    // Step to main\n    fn to_main(&mut self) {\n        if self.skip_to_main {\n            let main_id = self\n                .ecx\n                .tcx\n                .tcx\n                .entry_fn(LOCAL_CRATE)\n                .expect(\"no main or start function found\")\n                .0\n                .to_def_id();\n\n            let _ = step(self, |ecx| {\n                let frame = ecx.frame();\n                if main_id == frame.instance.def_id() {\n                    ShouldContinue::Stop\n                } else {\n                    ShouldContinue::Continue\n                }\n            });\n        }\n    }\n}\n\n#[derive(Deserialize)]\npub struct Config {\n    #[serde(default = \"true_bool\")]\n    auto_refresh: bool,\n    #[serde(default = \"default_theme\")]\n    theme: String,\n    #[serde(default)]\n    bptree: BreakpointTree,\n}\n\nfn true_bool() -> bool {\n    true\n}\nfn default_theme() -> String {\n    \"default\".to_string()\n}\n\nimpl Default for Config {\n    fn default() -> Self {\n        ::std::fs::File::open(\"config.json\")\n            .map(|f| serde_json::from_reader(f).unwrap())\n            .unwrap_or(Config {\n                auto_refresh: true,\n                theme: \"default\".to_string(),\n                bptree: step::BreakpointTree::default(),\n            })\n    }\n}\n\ntype RResult<T> = Result<T, Html<String>>;\n\nfn create_ecx<'mir, 'tcx>(tcx: TyCtxt<'tcx>) -> InterpCx<'tcx> {\n    let (main_id, _) = tcx\n        .entry_fn(LOCAL_CRATE)\n        .expect(\"no main or start function found\");\n\n    miri::create_ecx(\n        tcx,\n        main_id.to_def_id(),\n        miri::MiriConfig {\n            args: vec![],\n            communicate: true,\n            excluded_env_vars: vec![],\n            ignore_leaks: true,\n            seed: None,\n            tracked_pointer_tag: None,\n            tracked_alloc_id: None,\n            tracked_call_id: None,\n            validate: true,\n            stacked_borrows: false,\n            check_alignment: miri::AlignmentCheck::None,\n            track_raw: false,\n            data_race_detector: false,\n            cmpxchg_weak_failure_rate: 0.8,\n        },\n    )\n    .unwrap()\n    .0\n}\n\npub struct PrirodaSender(\n    Mutex<::std::sync::mpsc::Sender<Box<dyn FnOnce(&mut PrirodaContext<'_, '_>) + Send>>>,\n);\n\nimpl PrirodaSender {\n    fn do_work<'r, T, F>(&self, f: F) -> Result<T, Html<String>>\n    where\n        T: rocket::response::Responder<'r> + Send + 'static,\n        F: FnOnce(&mut PrirodaContext<'_, '_>) -> T + Send + 'static,\n    {\n        let (tx, rx) = mpsc::sync_channel(0);\n        let sender = self.0.lock().unwrap_or_else(|err| err.into_inner());\n        match sender.send(Box::new(move |pcx: &mut PrirodaContext<'_, '_>| {\n            tx.send(f(pcx)).unwrap();\n        })) {\n            Ok(()) => match rx.recv() {\n                Ok(val) => Ok(val),\n                Err(mpsc::RecvError) => Err(Html(\n                    \"<center><h1>Miri crashed please go to <a href='/'>index</a></h1></center>\"\n                        .to_string(),\n                )),\n            },\n            Err(_) => Err(Html(\n                \"<center><h1>Miri crashed too often. Please restart priroda.</h1></center>\"\n                    .to_string(),\n            )),\n        }\n    }\n}\n\n#[get(\"/please_panic\")]\nfn please_panic(sender: State<'_, PrirodaSender>) -> RResult<()> {\n    sender.do_work(|_pcx| panic!(\"You requested a panic\"))\n}\n\n#[cfg(not(feature = \"static_resources\"))]\n#[get(\"/resources/<path..>\")]\nfn resources(path: PathBuf) -> Result<NamedFile, std::io::Error> {\n    let mut res_path = PathBuf::from(\"./resources/\");\n    res_path.push(path);\n    NamedFile::open(res_path)\n}\n\n#[cfg(feature = \"static_resources\")]\n#[get(\"/resources/<path..>\")]\nfn resources(path: PathBuf) -> Result<Content<&'static str>, std::io::Error> {\n    use rocket::http::ContentType;\n    use std::io::{Error, ErrorKind};\n    match path.as_os_str().to_str() {\n        Some(\"svg-pan-zoom.js\") => Ok(Content(\n            ContentType::JavaScript,\n            include_str!(\"../resources/svg-pan-zoom.js\"),\n        )),\n        Some(\"zoom_mir.js\") => Ok(Content(\n            ContentType::JavaScript,\n            include_str!(\"../resources/zoom_mir.js\"),\n        )),\n        Some(\"style-default.css\") => Ok(Content(\n            ContentType::CSS,\n            include_str!(\"../resources/style-default.css\"),\n        )),\n        Some(\"positioning.css\") => Ok(Content(\n            ContentType::CSS,\n            include_str!(\"../resources/positioning.css\"),\n        )),\n        _ => Err(Error::new(ErrorKind::InvalidInput, \"Unknown resource\")),\n    }\n}\n\n#[get(\"/step_count\")]\nfn step_count(sender: State<'_, PrirodaSender>) -> RResult<String> {\n    sender.do_work(|pcx| format!(\"{}\", pcx.step_count))\n}\n\nfn server(sender: PrirodaSender) {\n    use rocket::config::Value;\n    rocket::ignite()\n        .manage(sender)\n        .mount(\"/\", routes![please_panic, resources, step_count])\n        .mount(\"/\", render::routes::routes())\n        .mount(\"/breakpoints\", step::bp_routes::routes())\n        .mount(\"/step\", step::step_routes::routes())\n        .mount(\"/watch\", watch::routes())\n        .attach(rocket::fairing::AdHoc::on_launch(\n            \"Priroda, because code has no privacy rights\",\n            |rocket| {\n                let config = rocket.config();\n                if config.extras.get(\"spawn_browser\") == Some(&Value::Boolean(true)) {\n                    let addr = format!(\"http://{}:{}\", config.address, config.port);\n                    if open::that(&addr).is_err() {\n                        println!(\"open {} in your browser\", addr);\n                    }\n                }\n            },\n        ))\n        .launch();\n}\n\n// Copied from miri/bin/miri.rs\nfn find_sysroot() -> String {\n    if let Ok(sysroot) = std::env::var(\"MIRI_SYSROOT\") {\n        return sysroot;\n    }\n\n    // Taken from https://github.com/rust-lang/rust-clippy/pull/911\n    let home = option_env!(\"RUSTUP_HOME\").or(option_env!(\"MULTIRUST_HOME\"));\n    let toolchain = option_env!(\"RUSTUP_TOOLCHAIN\").or(option_env!(\"MULTIRUST_TOOLCHAIN\"));\n    match (home, toolchain) {\n        (Some(home), Some(toolchain)) => format!(\"{}/toolchains/{}\", home, toolchain),\n        _ => option_env!(\"RUST_SYSROOT\")\n            .expect(\"need to specify RUST_SYSROOT env var or use rustup or multirust\")\n            .to_owned(),\n    }\n}\n\nstruct PrirodaCompilerCalls {\n    step_count: Arc<Mutex<u128>>,\n    config: Arc<Mutex<Config>>,\n    receiver: Arc<Mutex<mpsc::Receiver<Box<dyn FnOnce(&mut PrirodaContext<'_, '_>) + Send>>>>,\n    skip_to_main: bool,\n}\n\nimpl rustc_driver::Callbacks for PrirodaCompilerCalls {\n    fn after_analysis<'tcx>(\n        &mut self,\n        compiler: &interface::Compiler,\n        queries: &'tcx rustc_interface::Queries<'tcx>,\n    ) -> Compilation {\n        compiler.session().abort_if_errors();\n\n        queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {\n            let mut step_count = self\n                .step_count\n                .lock()\n                .unwrap_or_else(|err| err.into_inner());\n            let mut config = self.config.lock().unwrap_or_else(|err| err.into_inner());\n\n            let mut pcx = PrirodaContext {\n                ecx: create_ecx(tcx),\n                step_count: &mut *step_count,\n                traces: watch::Traces::new(),\n                config: &mut *config,\n                skip_to_main: self.skip_to_main,\n            };\n            // Whether we reset to the same place where miri crashed\n            let mut reset = false;\n            // Step to the position where miri crashed if it crashed\n            for _ in 0..*pcx.step_count {\n                reset = true;\n                match pcx.ecx.step() {\n                    Ok(true) => {}\n                    res => panic!(\"Miri is not deterministic causing error {:?}\", res),\n                }\n            }\n\n            // Just ignore poisoning by panicking\n            let receiver = self.receiver.lock().unwrap_or_else(|err| err.into_inner());\n\n            // At the very beginning, go to the start of main unless we have already crashed and are trying to reset\n            if !reset {\n                pcx.to_main();\n            }\n            // process commands\n            for command in receiver.iter() {\n                command(&mut pcx);\n            }\n        });\n\n        compiler.session().abort_if_errors();\n\n        Compilation::Stop\n    }\n}\n\nfn main() {\n    rustc_driver::init_rustc_env_logger();\n    let mut args: Vec<String> = std::env::args().collect();\n\n    // TODO: Move to a 'proper' argument parser\n    // Maybe use xflags?\n\n    let sysroot_flag = String::from(\"--sysroot\");\n    if !args.contains(&sysroot_flag) {\n        args.push(sysroot_flag);\n        args.push(find_sysroot());\n    }\n\n    // Use the --no-main flag to stop\n    let stops_at_start = args\n        .iter()\n        .enumerate()\n        .find(|(_, v)| v.as_str() == \"--no-main\")\n        .map(|(i, _)| i);\n\n    if let Some(index) = stops_at_start {\n        // We pass these arguments to miri.\n        // This is the lowest-effort way to not pass our custom argument to miri\n        args.remove(index);\n    }\n    // Eagerly initialise syntect static\n    // Makes highlighting performance profiles clearer\n    render::initialise_statics();\n\n    // setup http server and similar\n    let (sender, receiver) = mpsc::channel();\n    let sender = PrirodaSender(Mutex::new(sender));\n    let step_count = Arc::new(Mutex::new(0));\n    let config = Arc::new(Mutex::new(Config::default()));\n\n    let handle = std::thread::spawn(move || {\n        let args = Arc::new(args);\n        let receiver = Arc::new(Mutex::new(receiver));\n        for i in 0..5 {\n            if i != 0 {\n                println!(\n                    \"\\n============== Miri crashed - restart try {} ==============\\n\",\n                    i\n                );\n            }\n            let step_count = step_count.clone();\n            let config = config.clone();\n            let receiver = receiver.clone();\n            let args = args.clone();\n            // Ignore result to restart in case of a crash\n            let _ = std::thread::spawn(move || {\n                let _ = rustc_driver::catch_fatal_errors(move || {\n                    rustc_driver::RunCompiler::new(\n                        &*args,\n                        &mut PrirodaCompilerCalls {\n                            step_count,\n                            config,\n                            receiver,\n                            skip_to_main: stops_at_start.is_none(),\n                        },\n                    )\n                    .run()\n                });\n            })\n            .join();\n            std::thread::sleep(std::time::Duration::from_millis(200));\n        }\n        println!(\"\\n============== Miri crashed too often. Aborting ==============\\n\");\n    });\n    server(sender);\n    handle.join().unwrap();\n}\n"
  },
  {
    "path": "src/render/graphviz.rs",
    "content": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse crate::step::LocalBreakpoints;\nuse miri::{FrameData, Tag};\nuse rustc_middle::mir::*;\nuse rustc_mir::interpret::Frame;\nuse std::fmt::{self, Debug, Write};\n\npub fn render_html<'tcx>(\n    frame: &Frame<'_, '_, Tag, FrameData<'_>>,\n    breakpoints: LocalBreakpoints<'_>,\n) -> String {\n    let mut rendered = String::new();\n\n    render_mir_svg(&frame.body, breakpoints, &mut rendered, None).unwrap();\n\n    let (block, statement_index) = if let Some(location) = frame.current_loc().ok() {\n        (location.block, location.statement_index)\n    } else {\n        rendered.push_str(\"<div style='color: red;'>Unwinding</div>\");\n        return rendered;\n    };\n\n    let (bb, stmt) = {\n        let blck = &frame.body.basic_blocks()[block];\n        (\n            block.index() + 1,\n            if statement_index == blck.statements.len() {\n                if blck.statements.is_empty() {\n                    6\n                } else {\n                    blck.statements.len() + 7\n                }\n            } else {\n                assert!(statement_index < blck.statements.len());\n                statement_index + 6\n            },\n        )\n    };\n    let edge_colors = {\n        let blck = &frame.body.basic_blocks()[block];\n        let (targets, unwind) = if statement_index == blck.statements.len() {\n            use rustc_middle::mir::TerminatorKind::*;\n            match blck.terminator().kind {\n                Goto { target } => (vec![target], None),\n                SwitchInt { ref targets, .. } => (targets.all_targets().to_owned(), None),\n                Drop { target, unwind, .. } | DropAndReplace { target, unwind, .. } => {\n                    (vec![target], unwind)\n                }\n                Call {\n                    ref destination,\n                    cleanup,\n                    ..\n                } => {\n                    if let Some((_, target)) = *destination {\n                        (vec![target], cleanup)\n                    } else {\n                        (vec![], cleanup)\n                    }\n                }\n                _ => (vec![], None),\n            }\n        } else {\n            (vec![], None)\n        };\n        format!(\n            \"let edge_colors = {{{}}};\",\n            targets\n                .into_iter()\n                .map(|target| (block, target, \"green\"))\n                .chain(unwind.into_iter().map(|target| (block, target, \"red\")))\n                .map(|(from, to, color)| format!(\n                    \"'bb{}->bb{}':'{}'\",\n                    from.index(),\n                    to.index(),\n                    color\n                ))\n                .collect::<Vec<_>>()\n                .join(\",\")\n        )\n    };\n    rendered\n        .write_fmt(format_args!(\n            r##\"<style>\n        #node{} > text:nth-child({}) {{\n            fill: red;\n        }}\n        .edge-green > path, .edge-green > polygon, .edge-green > text {{\n            fill: green;\n            stroke: green;\n        }}\n        .edge-red > path, .edge-red > polygon, .edge-red > text {{\n            fill: red;\n            stroke: red;\n        }}\n        .edge > path {{\n            fill: none;\n        }}\n        </style>\n        <script>\n        {edge_colors}\n        for(let el of document.querySelectorAll(\"#mir > svg #graph0 .edge\")) {{\n            let title = el.querySelector(\"title\").textContent;\n            if(title in edge_colors) {{\n                el.classList.add(\"edge-\" + edge_colors[title]);\n            }}\n        }}\n        </script>\"##,\n            bb,\n            stmt,\n            edge_colors = edge_colors\n        ))\n        .unwrap();\n    rendered\n}\n\n/// Write a graphviz DOT graph of a list of MIRs.\npub fn render_mir_svg<W: Write>(\n    mir: &Body<'_>,\n    breakpoints: LocalBreakpoints<'_>,\n    w: &mut W,\n    promoted: Option<usize>,\n) -> fmt::Result {\n    let mut dot = String::new();\n    if let Some(promoted) = promoted {\n        writeln!(dot, \"digraph promoted{} {{\", promoted)?;\n    } else {\n        writeln!(dot, \"digraph Body {{\")?;\n    }\n\n    // Global graph properties\n    writeln!(dot, r#\"    graph [fontname=\"monospace\"];\"#)?;\n    writeln!(dot, r#\"    node [fontname=\"monospace\"];\"#)?;\n    writeln!(dot, r#\"    edge [fontname=\"monospace\"];\"#)?;\n\n    // Nodes\n    for (block, _) in mir.basic_blocks().iter_enumerated() {\n        write_node(block, mir, breakpoints, promoted, &mut dot)?;\n    }\n\n    // Edges\n    for (source, _) in mir.basic_blocks().iter_enumerated() {\n        write_edges(source, mir, &mut dot)?;\n    }\n    writeln!(dot, \"}}\")?;\n    w.write_str(\n        ::std::str::from_utf8(&::cgraph::Graph::parse(dot).unwrap().render_dot().unwrap()).unwrap(),\n    )\n}\n\n/// Write a graphviz HTML-styled label for the given basic block, with\n/// all necessary escaping already performed. (This is suitable for\n/// emitting directly, as is done in this module, or for use with the\n/// `LabelText::HtmlStr` from libgraphviz.)\nfn write_node_label<W: Write>(\n    block: BasicBlock,\n    mir: &Body<'_>,\n    breakpoints: LocalBreakpoints<'_>,\n    promoted: Option<usize>,\n    w: &mut W,\n) -> fmt::Result {\n    let data = &mir[block];\n\n    write!(w, r#\"<table border=\"0\" cellborder=\"1\" cellspacing=\"0\">\"#)?;\n\n    // Basic block number at the top.\n    write!(\n        w,\n        r#\"<tr><td bgcolor=\"gray\" align=\"center\">{blk}</td></tr>\"#,\n        blk = node(promoted, block)\n    )?;\n\n    // List of statements in the middle.\n    if !data.statements.is_empty() {\n        write!(w, r#\"<tr><td align=\"left\" balign=\"left\">\"#)?;\n        for (statement_index, statement) in data.statements.iter().enumerate() {\n            if breakpoints.breakpoint_exists(Some(Location {\n                block,\n                statement_index,\n            })) {\n                write!(w, \"+ \")?;\n            } else {\n                write!(w, \"&nbsp; \")?;\n            }\n            if crate::should_hide_stmt(statement) {\n                write!(w, \"&lt;+&gt;<br/>\")?;\n            } else {\n                write!(w, \"{}<br/>\", escape(statement))?;\n            }\n        }\n        write!(w, \"</td></tr>\")?;\n    }\n\n    // Terminator head at the bottom, not including the list of successor blocks. Those will be\n    // displayed as labels on the edges between blocks.\n    let mut terminator_head = String::new();\n    data.terminator()\n        .kind\n        .fmt_head(&mut terminator_head)\n        .unwrap();\n    write!(\n        w,\n        r#\"<tr><td align=\"left\">{}</td></tr>\"#,\n        escape_html(&terminator_head)\n    )?;\n\n    // Close the table\n    writeln!(w, \"</table>\")\n}\n\n/// Write a graphviz DOT node for the given basic block.\nfn write_node<W: Write>(\n    block: BasicBlock,\n    mir: &Body<'_>,\n    breakpoints: LocalBreakpoints<'_>,\n    promoted: Option<usize>,\n    w: &mut W,\n) -> fmt::Result {\n    // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.\n    write!(\n        w,\n        r#\"    \"{}\" [shape=\"none\", label=<\"#,\n        node(promoted, block)\n    )?;\n    write_node_label(block, mir, breakpoints, promoted, w)?;\n    // Close the node label and the node itself.\n    writeln!(w, \">];\")\n}\n\n/// Write graphviz DOT edges with labels between the given basic block and all of its successors.\nfn write_edges<W: Write>(source: BasicBlock, mir: &Body<'_>, w: &mut W) -> fmt::Result {\n    let terminator = mir[source].terminator();\n    let labels = terminator.kind.fmt_successor_labels();\n\n    for (&target, label) in terminator.successors().zip(labels) {\n        writeln!(\n            w,\n            r#\"    {} -> {} [label=\"{}\"];\"#,\n            node(None, source),\n            node(None, target),\n            label\n        )?;\n    }\n\n    Ok(())\n}\n\nfn node(promoted: Option<usize>, block: BasicBlock) -> String {\n    if let Some(promoted) = promoted {\n        format!(\"promoted{}.{}\", promoted, block.index())\n    } else {\n        format!(\"bb{}\", block.index())\n    }\n}\n\nfn escape<T: Debug>(t: &T) -> String {\n    escape_html(&format!(\"{:?}\", t)).into_owned()\n}\n\nfn escape_html(s: &str) -> ::std::borrow::Cow<'_, str> {\n    ::rocket::http::RawStr::from_str(s).html_escape()\n}\n"
  },
  {
    "path": "src/render/locals.rs",
    "content": "use rustc_middle::mir::{\n    self,\n    interpret::{InterpError, UndefinedBehaviorInfo},\n};\nuse rustc_middle::ty::{subst::Subst, ParamEnv, TyKind, TypeAndMut};\nuse rustc_mir::interpret::{\n    Allocation, Frame, Immediate, InterpResult, MemPlaceMeta, OpTy, Operand, Pointer, Scalar,\n    ScalarMaybeUninit,\n};\nuse rustc_target::abi::{Abi, Size};\n\nuse miri::{AllocExtra, Tag};\n\nuse horrorshow::prelude::*;\nuse horrorshow::Template;\n\nuse crate::InterpCx;\n\npub fn render_locals<'tcx>(\n    ecx: &InterpCx<'tcx>,\n    frame: &Frame<'tcx, 'tcx, Tag, miri::FrameData<'tcx>>,\n) -> String {\n    let &Frame {\n        ref body,\n        ref return_place,\n        ref instance,\n        ..\n    } = frame;\n\n    //               name    ty      alloc        val     style\n    let locals: Vec<(String, String, Option<u64>, String, &str)> = body\n        .local_decls\n        .iter_enumerated()\n        .map(|(id, local_decl)| {\n            let name = body\n                .var_debug_info\n                .iter()\n                .find(|var_debug_info| match var_debug_info.value {\n                    mir::VarDebugInfoContents::Place(place) => {\n                        place.projection.is_empty() && place.local == id\n                    }\n                    _ => false,\n                })\n                .map(|var_debug_info| var_debug_info.name.as_str().to_string())\n                .unwrap_or_else(String::new);\n\n            // FIXME Don't panic when trying to read from uninit variable.\n            // Panic message:\n            // > error: internal compiler error: src/librustc_mir/interpret/eval_context.rs:142:\n            // > The type checker should prevent reading from a never-written local\n            let op_ty = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {\n                if id == mir::RETURN_PLACE {\n                    return_place\n                        .map(|p| ecx.place_to_op(&p).unwrap())\n                        .ok_or(false)\n                } else {\n                    ecx.access_local(frame, id, None).map_err(|_| false)\n                }\n            })) {\n                Ok(op_ty) => op_ty,\n                Err(_) => Err(true),\n            };\n\n            let (alloc, val, style) = match op_ty {\n                Err(false) => (None, \"&lt;dead&gt;\".to_owned(), \"font-size: 0;\"),\n                Err(true) => (None, \"&lt;uninit&gt;\".to_owned(), \"color: darkmagenta;\"),\n                Ok(op_ty) => match print_operand(ecx, op_ty) {\n                    Ok((alloc, text)) => (alloc, text, \"\"),\n                    Err(()) => (None, \"&lt;error&gt;\".to_owned(), \"color: red;\"),\n                },\n            };\n            let ty = ecx.tcx.normalize_erasing_regions(\n                ParamEnv::reveal_all(),\n                local_decl.ty.subst(ecx.tcx.tcx, instance.substs),\n            );\n            (name, ty.to_string(), alloc, val, style)\n        })\n        .collect();\n\n    let (arg_count, var_count, tmp_count) = (\n        body.args_iter().count(),\n        body.vars_iter().count(),\n        body.temps_iter().count(),\n    );\n\n    (horrorshow::html! {\n        table(border=\"1\") {\n            tr {\n                td(width=\"20px\");\n                th { : \"id\" }\n                th { : \"name\" }\n                th { : \"alloc\" }\n                th { : \"memory\" }\n                th { : \"type\" }\n            }\n            @ for (i, &(ref name, ref ty, alloc, ref text, ref style)) in locals.iter().enumerate() {\n                tr(style=style) {\n                    @if i == 0 {\n                        th(rowspan=1) { span(class=\"vertical\") { : \"Return\" } }\n                    } else if i == 1 && arg_count != 0 {\n                        th(rowspan=arg_count) { span(class=\"vertical\") { : \"Arguments\" } }\n                    } else if i == arg_count + 1 && var_count != 0 {\n                        th(rowspan=var_count) { span(class=\"vertical\") { : \"Variables\" } }\n                    } else if i == var_count + arg_count + 1 && tmp_count != 0 {\n                        th(rowspan=tmp_count) { span(class=\"vertical\") { : \"Temporaries\" } }\n                    }\n                    td { : format!(\"_{}\", i) }\n                    td { : name }\n                    @if let Some(alloc) = alloc {\n                        td { : alloc.to_string() }\n                    } else {\n                        td;\n                    }\n                    td { : Raw(text) }\n                    td { : ty }\n                }\n            }\n        }\n    }).into_string()\n        .unwrap()\n}\n\nfn print_scalar_maybe_undef(val: ScalarMaybeUninit<miri::Tag>) -> String {\n    match val {\n        ScalarMaybeUninit::Uninit => \"&lt;undef &gt;\".to_string(),\n        ScalarMaybeUninit::Scalar(val) => print_scalar(val),\n    }\n}\n\nfn print_scalar(val: Scalar<miri::Tag>) -> String {\n    match val {\n        Scalar::Ptr(ptr) => format!(\n            \"<a href=\\\"/ptr/{alloc}/{offset}\\\">Pointer({alloc})[{offset}]</a>\",\n            alloc = ptr.alloc_id.0,\n            offset = ptr.offset.bytes()\n        ),\n        Scalar::Int(int) => {\n            if int.size().bytes() == 0 {\n                // Can't use `Debug` impl directly because it would be unescaped\n                \"&lt;zst&gt;\".to_string()\n            } else {\n                format!(\"0x{:X}\", int)\n            }\n        }\n    }\n}\n\nfn pp_operand<'tcx>(\n    ecx: &InterpCx<'tcx>,\n    op_ty: OpTy<'tcx, miri::Tag>,\n) -> InterpResult<'tcx, String> {\n    let err = || InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(String::new()));\n    match op_ty.layout.ty.kind() {\n        TyKind::RawPtr(TypeAndMut { ty, .. }) | TyKind::Ref(_, ty, _)\n            if matches!(ty.kind(), TyKind::Str) =>\n        {\n            if let Operand::Immediate(val) = *op_ty {\n                if let Immediate::ScalarPair(\n                    ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)),\n                    ScalarMaybeUninit::Scalar(Scalar::Int(int)),\n                ) = val\n                {\n                    if let Ok(allocation) = ecx.memory.get_raw(ptr.alloc_id) {\n                        let offset = ptr.offset.bytes();\n                        if (offset as u128) < allocation.len() as u128 {\n                            let start = offset as usize;\n                            let len = int.assert_bits(int.size());\n                            let end = start.checked_add(len as usize).ok_or(err())?;\n                            let alloc_bytes = &allocation\n                                .inspect_with_uninit_and_ptr_outside_interpreter(start..end);\n                            let s = String::from_utf8_lossy(alloc_bytes);\n                            return Ok(format!(\"\\\"{}\\\"\", s));\n                        }\n                    }\n                }\n            }\n        }\n        TyKind::Adt(adt_def, _substs) => {\n            if let Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Uninit)) = *op_ty {\n                Err(err())?;\n            }\n\n            let variant = ecx.read_discriminant(&op_ty)?.1;\n            let adt_fields = &adt_def.variants[variant].fields;\n\n            let should_collapse = adt_fields.len() > 1;\n\n            //println!(\"{:?} {:?} {:?}\", val, ty, adt_def.variants);\n            let mut pretty = ecx\n                .tcx\n                .def_path_str(adt_def.did)\n                .replace(\"<\", \"&lt;\")\n                .replace(\">\", \"&gt;\")\n                .to_string();\n\n            if adt_def.is_enum() {\n                pretty.push_str(\"::\");\n                pretty.push_str(&*adt_def.variants[variant].ident.as_str());\n            }\n            pretty.push_str(\" { \");\n\n            if should_collapse {\n                pretty.push_str(\"<details>\");\n            }\n\n            for (i, adt_field) in adt_fields.iter().enumerate() {\n                let field_pretty: InterpResult<'_, String> = try {\n                    let field_op_ty = ecx.operand_field(&op_ty, i as usize)?;\n                    pp_operand(ecx, field_op_ty)?\n                };\n\n                pretty.push_str(&format!(\n                    \"{}: {}, \",\n                    adt_field.ident.as_str(),\n                    match field_pretty {\n                        Ok(field_pretty) => field_pretty,\n                        Err(_err) => \"<span style='color: red;'>&lt;err&gt;</span>\".to_string(),\n                    }\n                ));\n                if should_collapse {\n                    pretty.push_str(\"<br>\");\n                }\n            }\n\n            if should_collapse {\n                pretty.push_str(\"</details>\");\n            }\n\n            pretty.push_str(\"}\");\n            println!(\"pretty adt: {}\", pretty);\n            return Ok(pretty);\n        }\n        _ => {}\n    }\n\n    if op_ty.layout.size.bytes() == 0 {\n        Err(err())?;\n    }\n    if let Abi::Scalar(_) = op_ty.layout.abi {\n    } else {\n        Err(err())?;\n    }\n    let scalar = ecx.read_scalar(&op_ty)?;\n    if let ScalarMaybeUninit::Scalar(Scalar::Ptr(_)) = &scalar {\n        return Ok(print_scalar_maybe_undef(scalar)); // If the value is a ptr, print it\n    }\n    match op_ty.layout.ty.kind() {\n        TyKind::Bool => {\n            if scalar.to_bool()? {\n                Ok(\"true\".to_string())\n            } else {\n                Ok(\"false\".to_string())\n            }\n        }\n        TyKind::Char => {\n            let chr = scalar.to_char()?;\n            if chr.is_ascii() {\n                Ok(format!(\"'{}'\", chr))\n            } else {\n                Err(err().into())\n            }\n        }\n        TyKind::Uint(_) => Ok(format!(\"{0}\", scalar.to_u64()?)),\n        TyKind::Int(_) => Ok(format!(\"{0}\", scalar.to_i64()?)),\n        TyKind::Float(float_ty) => match float_ty {\n            rustc_type_ir::FloatTy::F32 => Ok(format!(\"{}\", scalar.to_f32()?)),\n            rustc_type_ir::FloatTy::F64 => Ok(format!(\"{}\", scalar.to_f64()?)),\n        },\n        _ => Err(err().into()),\n    }\n}\n\npub fn print_operand<'a, 'tcx: 'a>(\n    ecx: &InterpCx<'tcx>,\n    op_ty: OpTy<'tcx, miri::Tag>,\n) -> Result<(Option<u64>, String), ()> {\n    let pretty = pp_operand(ecx, op_ty);\n\n    let (alloc, txt) = match *op_ty {\n        Operand::Indirect(place) => {\n            let size: u64 = op_ty.layout.size.bytes();\n            if place.meta == MemPlaceMeta::None {\n                let ptr = place.to_ref().to_scalar().unwrap();\n                if ptr.is_ptr() {\n                    let (alloc, txt, _len) = print_ptr(ecx, ptr.assert_ptr(), Some(size))?;\n                    (alloc, txt)\n                } else {\n                    (None, format!(\"{:?}\", ptr))\n                }\n            } else {\n                (None, format!(\"{:?}\", place)) // FIXME better printing for unsized locals\n            }\n        }\n        Operand::Immediate(Immediate::Scalar(scalar)) => (None, print_scalar_maybe_undef(scalar)),\n        Operand::Immediate(Immediate::ScalarPair(val, extra)) => (\n            None,\n            format!(\n                \"{}, {}\",\n                print_scalar_maybe_undef(val),\n                print_scalar_maybe_undef(extra)\n            ),\n        ),\n    };\n    let txt = if let Ok(pretty) = pretty {\n        format!(\"{} ({})\", pretty, txt)\n    } else {\n        txt\n    };\n    Ok((alloc, txt))\n}\n\npub fn print_ptr(\n    ecx: &InterpCx<'_>,\n    ptr: Pointer<Tag>,\n    size: Option<u64>,\n) -> Result<(Option<u64>, String, u64), ()> {\n    if let Ok(alloc) = ecx.memory.get_raw(ptr.alloc_id) {\n        let s = print_alloc(ecx.tcx.data_layout.pointer_size.bytes(), ptr, alloc, size);\n        debug_assert!(ecx.memory.get_fn(ptr.into()).is_err());\n        Ok((Some(ptr.alloc_id.0), s, alloc.len() as u64))\n    } else if let Ok(_) = ecx.memory.get_fn(ptr.into()) {\n        // FIXME: print function name\n        Ok((None, \"function pointer\".to_string(), 16))\n    } else {\n        Err(())\n    }\n}\n\npub fn print_alloc(\n    ptr_size: u64,\n    ptr: Pointer<Tag>,\n    alloc: &Allocation<Tag, AllocExtra>,\n    size: Option<u64>,\n) -> String {\n    use std::fmt::Write;\n    let end = size\n        .map(|s| s + ptr.offset.bytes())\n        .unwrap_or(alloc.len() as u64);\n    let mut s = String::new();\n    let mut i = ptr.offset.bytes();\n    while i < end {\n        if let Some((_tag, reloc)) = alloc.relocations().get(&Size::from_bytes(i)) {\n            i += ptr_size;\n            write!(&mut s,\n                \"<a style=\\\"text-decoration: none\\\" href=\\\"/ptr/{alloc}/{offset}\\\">┠{nil:─<wdt$}┨</a>\",\n                alloc = reloc,\n                offset = ptr.offset.bytes(),\n                nil = \"\",\n                wdt = (ptr_size * 2 - 2) as usize,\n            ).unwrap();\n        } else {\n            if alloc\n                .init_mask()\n                .is_range_initialized(Size::from_bytes(i), Size::from_bytes(i + 1))\n                .is_ok()\n            {\n                let byte = alloc\n                    .inspect_with_uninit_and_ptr_outside_interpreter(i as usize..i as usize + 1)[0];\n                write!(&mut s, \"{:02x}\", byte).unwrap();\n            } else {\n                let ub_chars = [\n                    '∅', '∆', '∇', '∓', '∞', '⊙', '⊠', '⊘', '⊗', '⊛', '⊝', '⊡', '⊠',\n                ];\n                let c1 = (ptr.alloc_id.0 * 769 + i as u64 * 5689) as usize % ub_chars.len();\n                let c2 = (ptr.alloc_id.0 * 997 + i as u64 * 7193) as usize % ub_chars.len();\n                write!(&mut s, \"<mark>{}{}</mark>\", ub_chars[c1], ub_chars[c2]).unwrap();\n            }\n            i += 1;\n        }\n    }\n    s\n}\n"
  },
  {
    "path": "src/render/mod.rs",
    "content": "mod graphviz;\npub mod locals;\nmod source;\n\npub use source::initialise_statics;\n\nuse rustc_hir::definitions::DefPathData;\nuse rustc_mir::interpret::{AllocId, Machine, Pointer};\nuse rustc_target::abi::Size;\n\nuse horrorshow::{Raw, Template};\nuse rocket::response::content::Html;\n\nuse crate::step::Breakpoint;\nuse crate::PrirodaContext;\n\npub fn template(pcx: &PrirodaContext<'_, '_>, title: String, t: impl Template) -> Html<String> {\n    let mut buf = String::new();\n    (horrorshow::html! {\n        html {\n            head {\n                title { : title }\n                meta(charset = \"UTF-8\") {}\n                script(src=\"/resources/svg-pan-zoom.js\") {}\n                script(src=\"/resources/zoom_mir.js\") {}\n                : Raw(refresh_script(pcx))\n            }\n            body(onload=\"enable_mir_mousewheel()\") {\n                link(rel=\"stylesheet\", href=\"/resources/positioning.css\");\n                link(rel=\"stylesheet\", href=format!(\"/resources/style-{}.css\", pcx.config.theme));\n                : t\n            }\n        }\n    })\n    .write_to_string(&mut buf)\n    .unwrap();\n    Html(buf)\n}\n\npub fn refresh_script(pcx: &PrirodaContext<'_, '_>) -> String {\n    if pcx.config.auto_refresh {\n        r#\"<script>\n            setInterval(() => {\n                fetch(\"/step_count\").then((res) => {\n                    if(res.status == 200) {\n                        return res.text();\n                    } else {\n                        throw \"\";\n                    }\n                }).then((res) => {\n                    if(res != #step_count#) {\n                        window.location.reload();\n                    }\n                }).catch(()=>{});\n            }, 1000);\n        </script>\"#\n            .replace(\"#step_count#\", &format!(\"{}\", pcx.step_count))\n    } else {\n        String::new()\n    }\n}\n\npub fn render_main_window(\n    pcx: &PrirodaContext<'_, '_>,\n    display_frame: Option<usize>,\n    message: String,\n) -> Html<String> {\n    let is_active_stack_frame = match display_frame {\n        Some(n) => n == Machine::stack(&pcx.ecx).len() - 1,\n        None => true,\n    };\n    let frame = display_frame\n        .and_then(|frame| Machine::stack(&pcx.ecx).get(frame))\n        .or_else(|| Machine::stack(&pcx.ecx).last());\n    let stack: Vec<(String, String, String)> = Machine::stack(&pcx.ecx)\n        .iter()\n        .map(|frame| {\n            let instance = &frame.instance;\n            let span = frame.current_source_info().unwrap().span;\n            let name = if pcx\n                .ecx\n                .tcx\n                .def_key(instance.def_id())\n                .disambiguated_data\n                .data\n                == DefPathData::ClosureExpr\n            {\n                \"inside call to closure\".to_string()\n            } else {\n                instance.to_string()\n            };\n            let span = self::source::pretty_src_path(span);\n            (name, span, format!(\"{:?}\", instance.def_id()))\n        })\n        .collect();\n    let rendered_breakpoints: Vec<String> = pcx\n        .config\n        .bptree\n        .iter()\n        .map(|&Breakpoint(def_id, bb, stmt)| format!(\"{:?}@{}:{}\", def_id, bb.index(), stmt))\n        .collect();\n    let rendered_locals = frame\n        .map(|frame| locals::render_locals(&pcx.ecx, frame))\n        .unwrap_or_else(String::new);\n\n    let rendered_source = source::render_source(pcx.ecx.tcx.tcx, frame);\n\n    let mir_graph = frame.map(|frame| {\n        graphviz::render_html(frame, pcx.config.bptree.for_def_id(frame.instance.def_id()))\n    });\n\n    let filename = pcx\n        .ecx\n        .tcx\n        .sess\n        .local_crate_source_file\n        .as_ref()\n        .map(|f| f.display().to_string())\n        .unwrap_or_else(|| \"no file name\".to_string());\n    template(\n        pcx,\n        filename,\n        horrorshow::html! {\n            div(id=\"left\") {\n                div(id=\"commands\") {\n                    @ if is_active_stack_frame {\n                        a(href=\"/step/single\") { div(title=\"Execute next MIR statement/terminator\") { : \"Step\" } }\n                        a(href=\"/step/next\") { div(title=\"Run until after the next MIR statement/terminator\") { : \"Next\" } }\n                        a(href=\"/step/return\") { div(title=\"Run until the function returns\") { : \"Return\" } }\n                        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)\" } }\n                        a(href=\"/step/continue\") { div(title=\"Run until termination or breakpoint\") { : \"Continue\" } }\n                        a(href=\"/step/restart\") { div(title=\"Abort execution and restart\") { : \"Restart\" } }\n                        a(href=\"/breakpoints/add_here\") { div(title=\"Add breakpoint at current location\") { : \"Add breakpoint here\"} }\n                        a(href=\"/breakpoints/remove_all\") { div(title=\"Remove all breakpoints\") { : \"Remove all breakpoints\"} }\n                    } else {\n                        a(href=\"/\") { div(title=\"Go to active stack frame\") { : \"Go back to active stack frame\" } }\n                    }\n                }\n                div(id=\"messages\") {\n                    p { : message }\n                }\n                div(id=\"mir\") {\n                    : Raw(mir_graph.unwrap_or_else(|| \"no current function\".to_string()))\n                }\n            }\n            div(id=\"right\") {\n                div {\n                    : format!(\"Step count: {}\", pcx.step_count);\n                }\n                div(id=\"stack\") {\n                    table(border=\"1\") {\n                        @ for (i, &(ref s, ref span, ref def_id)) in stack.iter().enumerate().rev() {\n                            tr {\n                                @ if i == display_frame.unwrap_or(stack.len() - 1) { td { : Raw(\"&#8594;\") } } else { td; }\n                                td { : s }\n                                td { : span }\n                                td { : def_id }\n                                @ if i == display_frame.unwrap_or(stack.len() - 1) { td; } else { td { a(href=format!(\"/frame/{}\", i)) { : \"View\" } } }\n                            }\n                        }\n                    }\n                }\n                div(id=\"breakpoints\") {\n                    : \"Breakpoints: \"; br;\n                    table(border=\"1\") {\n                        @ for bp in rendered_breakpoints {\n                            tr {\n                                td { : &bp }\n                                td { a(href=format!(\"/breakpoints/remove/{}\", bp)) { : \"remove\" } }\n                            }\n                        }\n                    }\n                }\n                div(id=\"locals\") {\n                    : Raw(rendered_locals)\n                }\n                div(id=\"source\") {\n                    : rendered_source\n                }\n            }\n        },\n    )\n}\n\npub fn render_reverse_ptr(pcx: &PrirodaContext<'_, '_>, alloc_id: u64) -> Html<String> {\n    let allocs: Vec<_> = pcx.ecx.memory.alloc_map().iter(|values| {\n        values\n            .filter_map(|(&id, (_kind, alloc))| {\n                alloc\n                    .relocations()\n                    .values()\n                    .find(|&&(_tag, reloc)| reloc == id)\n                    .map(|_| id)\n            })\n            .collect()\n    });\n    template(\n        pcx,\n        format!(\"Allocations with pointers to Allocation {}\", alloc_id),\n        horrorshow::html! {\n            @for id in allocs {\n                a(href=format!(\"/ptr/{}\", id)) { : format!(\"Allocation {}\", id) }\n                br;\n            }\n        },\n    )\n}\n\npub fn render_ptr_memory(\n    pcx: &PrirodaContext<'_, '_>,\n    alloc_id: AllocId,\n    offset: u64,\n) -> Html<String> {\n    let (mem, offset, rest) = if let Ok((_, mem, bytes)) = locals::print_ptr(\n        &pcx.ecx,\n        Pointer::new(alloc_id, Size::from_bytes(offset))\n            .with_tag(miri::Tag::Untagged)\n            .into(),\n        None,\n    ) {\n        if bytes * 2 > offset {\n            (mem, offset, (bytes * 2 - offset - 1) as usize)\n        } else if bytes * 2 == 0 && offset == 0 {\n            (mem, 0, 0)\n        } else {\n            (\"out of bounds offset\".to_string(), 0, 0)\n        }\n    } else {\n        (\"unknown memory\".to_string(), 0, 0)\n    };\n    template(\n        pcx,\n        format!(\"Allocation {}\", alloc_id),\n        horrorshow::html! {\n            span(style=\"font-family: monospace\") {\n                : format!(\"{nil:.<offset$}┌{nil:─<rest$}\", nil = \"\", offset = offset as usize, rest = rest)\n            }\n            br;\n            span(style=\"font-family: monospace\") { : Raw(mem) }\n            br;\n            a(href=format!(\"/reverse_ptr/{}\", alloc_id)) { : \"List allocations with pointers into this allocation\" }\n        },\n    )\n}\n\npub struct FlashString(String);\n\nimpl<'a, 'r> ::rocket::request::FromRequest<'a, 'r> for FlashString {\n    type Error = !;\n    fn from_request(request: &'a rocket::Request<'r>) -> rocket::request::Outcome<Self, !> {\n        rocket::Outcome::Success(FlashString(\n            Option::<rocket::request::FlashMessage<'_, '_>>::from_request(request)?\n                .map(|flash| flash.msg().to_string())\n                .unwrap_or_else(String::new),\n        ))\n    }\n}\n\npub mod routes {\n    use super::*;\n    use crate::*;\n\n    pub fn routes() -> Vec<::rocket::Route> {\n        routes![index, frame, frame_invalid, ptr, reverse_ptr]\n    }\n\n    #[get(\"/\")]\n    pub fn index(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n        flash: FlashString,\n    ) -> crate::RResult<Html<String>> {\n        sender.do_work(move |pcx| render::render_main_window(pcx, None, flash.0))\n    }\n\n    #[get(\"/frame/<frame>\")]\n    pub fn frame(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n        flash: FlashString,\n        frame: usize,\n    ) -> crate::RResult<Html<String>> {\n        sender.do_work(move |pcx| render::render_main_window(pcx, Some(frame), flash.0))\n    }\n\n    #[get(\"/frame/<frame>\", rank = 42)] // Error handler\n    fn frame_invalid(frame: String) -> BadRequest<String> {\n        BadRequest(Some(format!(\n            \"not a number: {:?}\",\n            frame.parse::<usize>().unwrap_err()\n        )))\n    }\n    #[get(\"/ptr/<alloc_id>/<offset>\")]\n    pub fn ptr(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n        alloc_id: u64,\n        offset: u64,\n    ) -> crate::RResult<Html<String>> {\n        sender.do_work(move |pcx| render::render_ptr_memory(pcx, AllocId(alloc_id), offset))\n    }\n\n    #[get(\"/reverse_ptr/<ptr>\")]\n    fn reverse_ptr(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n        ptr: u64,\n    ) -> crate::RResult<Html<String>> {\n        sender.do_work(move |pcx| render::render_reverse_ptr(pcx, ptr))\n    }\n}\n"
  },
  {
    "path": "src/render/source.rs",
    "content": "use std::collections::HashMap;\nuse std::{cell::RefCell, ops::Range};\n\nuse miri::{FrameData, Tag};\nuse rustc_middle::ty::TyCtxt;\nuse rustc_mir::interpret::Frame;\nuse rustc_span::Span;\n\nuse horrorshow::prelude::*;\nuse syntect::easy::HighlightLines;\nuse syntect::highlighting::{Style, ThemeSet};\nuse syntect::html::{styled_line_to_highlighted_html, IncludeBackground};\nuse syntect::parsing::SyntaxSet;\nuse syntect::util::{split_at, LinesWithEndings};\n\nlazy_static::lazy_static! {\n    static ref SYNTAX_SET: SyntaxSet = SyntaxSet::load_defaults_nonewlines();\n    static ref THEME_SET: ThemeSet = ThemeSet::load_defaults();\n\n    static ref RUST_SOURCE: regex::Regex = regex::Regex::new(\"/rustc/\\\\w+/\").unwrap();\n    static ref STD_SRC: Option<String> = {\n        if let Ok(output) = std::process::Command::new(\"rustc\").arg(\"--print\").arg(\"sysroot\").output() {\n            if let Ok(sysroot) = String::from_utf8(output.stdout) {\n                Some(sysroot.trim().to_string() + \"/lib/rustlib/src/rust/\")\n            } else {\n                None\n            }\n        } else {\n            None\n        }\n    };\n}\n\npub fn initialise_statics() {\n    let _ = (&*SYNTAX_SET, &*THEME_SET);\n}\n\npub fn pretty_src_path(span: Span) -> String {\n    let span = format!(\"{:?}\", span);\n    let span = RUST_SOURCE.replace(span.as_ref(), \"<rust>/\").to_string();\n    if let Some(std_src) = &*STD_SRC {\n        span.replace(std_src, \"<rust>/\")\n    } else {\n        span\n    }\n}\n\nthread_local! {\n    // This is a thread local, because a `Span` is only valid within one thread\n    static CACHED_HIGHLIGHTED_FILES: RefCell<HashMap<u64, HighlightCacheEntry>> = {\n        RefCell::new(HashMap::new())\n    };\n}\n\npub struct HighlightCacheEntry {\n    pub string: String,\n    pub highlighted: Vec<(Style, Range<usize>)>,\n}\n\npub fn render_source(\n    tcx: TyCtxt<'_>,\n    frame: Option<&Frame<'_, '_, Tag, FrameData<'_>>>,\n) -> Box<dyn RenderBox + Send> {\n    let before_time = ::std::time::Instant::now();\n\n    if frame.is_none() {\n        return Box::new(FnRenderer::new(|_| {}));\n    }\n    let frame = frame.unwrap();\n    let mut instr_spans = if let Some(location) = frame.current_loc().ok() {\n        let stmt = location.statement_index;\n        let block = location.block;\n        if stmt == frame.body[block].statements.len() {\n            vec![frame.body[block].terminator().source_info.span]\n        } else {\n            vec![frame.body[block].statements[stmt].source_info.span]\n        }\n    } else {\n        vec![frame.body.span]\n    };\n    // Get the original macro caller\n    while let Some(span) = instr_spans\n        .last()\n        .unwrap()\n        .macro_backtrace()\n        .next()\n        .map(|b| b.call_site)\n    {\n        instr_spans.push(span);\n    }\n\n    let highlighted_sources = instr_spans\n        .into_iter()\n        .rev()\n        .map(|sp| {\n            let (src, lo, hi) = match get_file_source_for_span(tcx, sp) {\n                Ok(res) => res,\n                Err(err) => return (format!(\"{:?}\", sp), err),\n            };\n\n            CACHED_HIGHLIGHTED_FILES.with(|highlight_cache| {\n                use std::collections::hash_map::DefaultHasher;\n                use std::hash::{Hash, Hasher};\n\n                let mut hasher = DefaultHasher::new();\n                src.hash(&mut hasher);\n                let hash = hasher.finish();\n\n                let mut cache = highlight_cache.borrow_mut();\n                let entry = cache.entry(hash).or_insert_with(|| {\n                    let before_time = ::std::time::Instant::now();\n                    let highlighted = syntax_highlight(&src);\n                    let after_time = ::std::time::Instant::now();\n                    println!(\"h: {:?}\", after_time - before_time);\n                    HighlightCacheEntry {\n                        string: src,\n                        highlighted,\n                    }\n                });\n                (\n                    pretty_src_path(sp),\n                    mark_span(&entry.string, &entry.highlighted, lo, hi),\n                )\n            })\n        })\n        .collect::<Vec<_>>();\n\n    let after_time = ::std::time::Instant::now();\n    println!(\"s: {:?}\", after_time - before_time);\n\n    let style = if let Some(bg_color) = THEME_SET.themes[\"Solarized (dark)\"].settings.background {\n        format!(\n            \"background-color: #{:02x}{:02x}{:02x}; display: block;\",\n            bg_color.r, bg_color.g, bg_color.b\n        )\n    } else {\n        String::new()\n    };\n\n    horrorshow::box_html! {\n        pre {\n            code(id=\"the_code\", style=style) {\n                @ for (sp, source) in highlighted_sources {\n                    span(style = \"color: aqua;\") {\n                        :sp; br;\n                    }\n                    : Raw(source);\n                    br; br;\n                }\n            }\n        }\n    }\n}\n\nfn get_file_source_for_span(tcx: TyCtxt<'_>, sp: Span) -> Result<(String, usize, usize), String> {\n    let source_map = tcx.sess.source_map();\n    let _ = source_map.span_to_snippet(sp); // Ensure file src is loaded\n\n    let src = if let Ok(file_lines) = source_map.span_to_lines(sp) {\n        if let Some(ref src) = file_lines.file.src {\n            src.to_string()\n        } else if let Some(src) = file_lines.file.external_src.borrow().get_source() {\n            src.to_string()\n        } else {\n            return Err(\"<no source info for span>\".to_string());\n        }\n    } else {\n        return Err(\"<couldnt get lines for span>\".to_string());\n    };\n    let lo = source_map.bytepos_to_file_charpos(sp.lo()).0;\n    let hi = source_map.bytepos_to_file_charpos(sp.hi()).0;\n    Ok((src, lo, hi))\n}\n\nfn syntax_highlight<'a, 's>(src: &'s str) -> Vec<(Style, Range<usize>)> {\n    let theme = &THEME_SET.themes[\"Solarized (dark)\"];\n    let mut h = HighlightLines::new(\n        &SYNTAX_SET\n            .find_syntax_by_extension(\"rs\")\n            .unwrap()\n            .to_owned(),\n        theme,\n    );\n    let mut index = 0;\n    let mut highlighted = Vec::new();\n    for line in LinesWithEndings::from(src) {\n        highlighted.extend(\n            h.highlight(line, &SYNTAX_SET)\n                .into_iter()\n                .map(|(style, str)| {\n                    let idx = index;\n                    index += str.len();\n                    (style, idx..index)\n                }),\n        );\n    }\n    highlighted\n}\n\nfn mark_span(file_contents: &str, src: &[(Style, Range<usize>)], lo: usize, hi: usize) -> String {\n    let src = src\n        .iter()\n        .map(|(style, range)| (*style, &file_contents[range.clone()]))\n        .collect::<Vec<_>>();\n    let (before, with) = split_at(&src, lo);\n    let (it, after) = split_at(&with, hi - lo);\n\n    let before = styled_line_to_highlighted_html(&before, IncludeBackground::No);\n    let it = styled_line_to_highlighted_html(&it, IncludeBackground::No);\n    let after = styled_line_to_highlighted_html(&after, IncludeBackground::No);\n\n    if lo == hi {\n        assert_eq!(it.len(), 0);\n        format!(\"{}<span style='background-color: lightcoral; border-radius: 5px; padding: 1px;'>←</span>{}\", before, after)\n    } else {\n        assert_ne!(it.len(), 0);\n        format!(\"{}<span style='background-color: lightcoral; border-radius: 5px; padding: 1px;'>{}</span>{}\", before, it, after)\n    }\n}\n"
  },
  {
    "path": "src/step.rs",
    "content": "use rustc_hir::def_id::{CrateNum, DefId, DefIndex};\nuse rustc_index::vec::Idx;\nuse rustc_middle::mir;\nuse rustc_mir::interpret::Machine;\nuse std::collections::{HashMap, HashSet};\nuse std::iter::Iterator;\n\nuse miri::*;\nuse serde::de::{Deserialize, Deserializer, Error as SerdeError};\n\nuse crate::{InterpCx, PrirodaContext};\n\npub enum ShouldContinue {\n    Continue,\n    Stop,\n}\n\n#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]\npub struct Breakpoint(pub DefId, pub mir::BasicBlock, pub usize);\n\n#[derive(Default)]\npub struct BreakpointTree(HashMap<DefId, HashSet<Breakpoint>>);\n\nimpl<'de> Deserialize<'de> for BreakpointTree {\n    fn deserialize<D: Deserializer<'de>>(deser: D) -> Result<Self, D::Error> {\n        let mut map = HashMap::new();\n        for (k, v) in HashMap::<String, HashSet<(usize, usize)>>::deserialize(deser)? {\n            let def_id = parse_def_id(&k).map_err(SerdeError::custom)?;\n            map.insert(\n                def_id,\n                v.into_iter()\n                    .map(|(bb, instr)| Breakpoint(def_id, mir::BasicBlock::new(bb), instr))\n                    .collect::<HashSet<Breakpoint>>(),\n            );\n        }\n        Ok(BreakpointTree(map))\n    }\n}\n\nimpl BreakpointTree {\n    pub fn add_breakpoint(&mut self, bp: Breakpoint) {\n        self.0.entry(bp.0).or_insert_with(HashSet::new).insert(bp);\n    }\n\n    pub fn remove_breakpoint(&mut self, bp: Breakpoint) -> bool {\n        self.0\n            .get_mut(&bp.0)\n            .map(|local| local.remove(&bp))\n            .unwrap_or(false)\n    }\n\n    pub fn remove_all(&mut self) {\n        self.0.clear();\n    }\n\n    pub fn for_def_id(&self, def_id: DefId) -> LocalBreakpoints<'_> {\n        if let Some(bps) = self.0.get(&def_id) {\n            LocalBreakpoints::SomeBps(bps)\n        } else {\n            LocalBreakpoints::NoBp\n        }\n    }\n\n    pub fn is_at_breakpoint(&self, ecx: &InterpCx<'_>) -> bool {\n        let frame = ecx.frame();\n        self.for_def_id(frame.instance.def_id())\n            .breakpoint_exists(frame.current_loc().ok())\n    }\n\n    pub fn iter(&self) -> impl Iterator<Item = &Breakpoint> {\n        self.0.values().flat_map(|local| local.iter())\n    }\n}\n\n#[derive(Copy, Clone)]\npub enum LocalBreakpoints<'a> {\n    NoBp,\n    SomeBps(&'a HashSet<Breakpoint>),\n}\n\nimpl<'a> LocalBreakpoints<'a> {\n    pub fn breakpoint_exists(self, location: Option<mir::Location>) -> bool {\n        if let Some(location) = location {\n            match self {\n                LocalBreakpoints::NoBp => false,\n                LocalBreakpoints::SomeBps(bps) => bps\n                    .iter()\n                    .any(|bp| bp.1 == location.block && bp.2 == location.statement_index),\n            }\n        } else {\n            // Unwinding, but no cleanup for this frame\n            // FIXME make this configurable\n            false\n        }\n    }\n}\n\npub fn step<F>(pcx: &mut PrirodaContext<'_, '_>, continue_while: F) -> String\nwhere\n    F: Fn(&InterpCx<'_>) -> ShouldContinue,\n{\n    let mut message = None;\n    let ret: InterpResult<'_, _> = try {\n        loop {\n            let is_main_thread_active = pcx.ecx.get_active_thread() == 0.into();\n            if is_main_thread_active && Machine::stack(&pcx.ecx).len() <= 1 && is_ret(&pcx.ecx) {\n                // When the main thread exists, the program terminates. However,\n                // we want to prevent stepping out of the program.\n                break;\n            }\n            match pcx.ecx.schedule()? {\n                SchedulingAction::ExecuteStep => {}\n                SchedulingAction::ExecuteTimeoutCallback => {\n                    pcx.ecx.run_timeout_callback()?;\n                    continue;\n                }\n                SchedulingAction::ExecuteDtors => {\n                    // This will either enable the thread again (so we go back\n                    // to `ExecuteStep`), or determine that this thread is done\n                    // for good.\n                    pcx.ecx.schedule_next_tls_dtor_for_active_thread()?;\n                    continue;\n                }\n                SchedulingAction::Stop => {\n                    message = Some(\"interpretation finished\".to_string());\n                    break;\n                }\n            }\n            let info = pcx.ecx.preprocess_diagnostics();\n            if !pcx.ecx.step()? {\n                message = Some(\"a terminated thread was scheduled for execution\".to_string());\n                break;\n            }\n            pcx.ecx.process_diagnostics(info);\n\n            *pcx.step_count += 1;\n            crate::watch::step_callback(pcx);\n\n            if let Some(frame) = Machine::stack(&pcx.ecx).last() {\n                if let Some(location) = frame.current_loc().ok() {\n                    let blck = &frame.body.basic_blocks()[location.block];\n                    if location.statement_index != blck.statements.len()\n                        && crate::should_hide_stmt(&blck.statements[location.statement_index])\n                        && !pcx.config.bptree.is_at_breakpoint(&pcx.ecx)\n                    {\n                        continue;\n                    }\n                } else {\n                    // Unwinding, but no cleanup for this frame\n                    // FIXME make step behaviour configurable\n                }\n            }\n            if let ShouldContinue::Stop = continue_while(&pcx.ecx) {\n                break;\n            }\n            if pcx.config.bptree.is_at_breakpoint(&pcx.ecx) {\n                break;\n            }\n        }\n    };\n    match ret {\n        Err(e) => {\n            message = Some(format!(\"{:?}\", e));\n        }\n        Ok(_) => {}\n    }\n    message.unwrap_or_else(String::new)\n}\n\npub fn is_ret(ecx: &InterpCx<'_>) -> bool {\n    if let Some(frame) = Machine::stack(&ecx).last() {\n        if let Some(location) = frame.current_loc().ok() {\n            let basic_block = &frame.body.basic_blocks()[location.block];\n\n            match basic_block.terminator().kind {\n                rustc_middle::mir::TerminatorKind::Return\n                | rustc_middle::mir::TerminatorKind::Resume => {\n                    location.statement_index >= basic_block.statements.len()\n                }\n                _ => false,\n            }\n        } else {\n            true // Unwinding, but no cleanup necessary for current frame\n        }\n    } else {\n        true\n    }\n}\n\nfn parse_breakpoint_from_url(s: &str) -> Result<Breakpoint, String> {\n    let regex = ::regex::Regex::new(r#\"([^@]+)@(\\d+):(\\d+)\"#).unwrap();\n    // DefId(1:14824 ~ mycrate::main)@1:3\n    //       ^ ^                      ^ ^\n    //       | |                      | statement\n    //       | |                      BasicBlock\n    //       | DefIndex::as_array_index()\n    //       CrateNum\n\n    let s = s.replace(\"%20\", \" \");\n    let caps = regex\n        .captures(&s)\n        .ok_or_else(|| format!(\"Invalid breakpoint {}\", s))?;\n\n    // Parse DefId\n    let def_id = parse_def_id(caps.get(1).unwrap().as_str())?;\n\n    // Parse block and stmt\n    let bb = mir::BasicBlock::new(\n        caps.get(2)\n            .unwrap()\n            .as_str()\n            .parse::<usize>()\n            .map_err(|_| \"block id is not a positive integer\")?,\n    );\n    let stmt = caps\n        .get(3)\n        .unwrap()\n        .as_str()\n        .parse::<usize>()\n        .map_err(|_| \"stmt id is not a positive integer\")?;\n\n    Ok(Breakpoint(def_id, bb, stmt))\n}\n\nfn parse_def_id(s: &str) -> Result<DefId, String> {\n    let regex = ::regex::Regex::new(r#\"DefId\\((\\d+):(\\d+) ~ [^\\)]+\\)\"#).unwrap();\n    let caps = regex\n        .captures(&s)\n        .ok_or_else(|| format!(\"Invalid def_id {}\", s))?;\n\n    let crate_num = CrateNum::new(caps.get(1).unwrap().as_str().parse::<usize>().unwrap());\n    let index = caps\n        .get(2)\n        .unwrap()\n        .as_str()\n        .parse::<usize>()\n        .map_err(|_| \"index is not a positive integer\".to_string())?;\n    let def_index = DefIndex::from_usize(index);\n    Ok(DefId {\n        krate: crate_num,\n        index: def_index,\n    })\n}\n\npub mod step_routes {\n    use rocket::response;\n\n    use super::*;\n\n    pub fn routes() -> Vec<::rocket::Route> {\n        routes![restart, single, single_back, next, return_, continue_]\n    }\n\n    #[get(\"/restart\")]\n    fn restart(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n    ) -> crate::RResult<response::Flash<response::Redirect>> {\n        sender.do_work(move |pcx| {\n            pcx.restart();\n            response::Flash::success(response::Redirect::to(\"/\"), \"restarted\")\n        })\n    }\n\n    #[get(\"/single\")]\n    fn single(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n    ) -> crate::RResult<response::Flash<response::Redirect>> {\n        sender.do_work(move |pcx| {\n            response::Flash::success(\n                response::Redirect::to(\"/\"),\n                step(pcx, |_ecx| ShouldContinue::Stop),\n            )\n        })\n    }\n\n    #[get(\"/single_back\")]\n    fn single_back(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n    ) -> crate::RResult<response::Flash<response::Redirect>> {\n        sender.do_work(move |pcx| {\n            let orig_step_count = *pcx.step_count;\n            pcx.restart();\n            *pcx.step_count = orig_step_count;\n            let msg = if *pcx.step_count > 0 {\n                *pcx.step_count -= 1;\n                for _ in 0..*pcx.step_count {\n                    match pcx.ecx.step() {\n                        Ok(true) => crate::watch::step_callback(pcx), // Rebuild traces till the current instruction\n                        res => {\n                            return response::Flash::warning(\n                                response::Redirect::to(\"/\"),\n                                format!(\"Miri is not deterministic causing error {:?}\", res),\n                            )\n                        }\n                    }\n                }\n                \"stepped back\".to_string()\n            } else {\n                \"already at the start\".to_string()\n            };\n\n            response::Flash::success(response::Redirect::to(\"/\"), msg)\n        })\n    }\n\n    #[get(\"/next\")]\n    fn next(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n    ) -> crate::RResult<response::Flash<response::Redirect>> {\n        sender.do_work(move |pcx| {\n            let frame = Machine::stack(&pcx.ecx).len();\n            let (block, stmt): (Option<mir::BasicBlock>, _) =\n                if let Some(location) = pcx.ecx.frame().current_loc().ok() {\n                    (Some(location.block), Some(location.statement_index))\n                } else {\n                    (None, None)\n                };\n            let msg = step(pcx, move |ecx| {\n                let (curr_block, curr_stmt) = if let Some(location) = ecx.frame().current_loc().ok()\n                {\n                    (Some(location.block), Some(location.statement_index))\n                } else {\n                    (None, None)\n                };\n                if Machine::stack(&ecx).len() <= frame && (block < curr_block || stmt < curr_stmt) {\n                    ShouldContinue::Stop\n                } else {\n                    ShouldContinue::Continue\n                }\n            });\n            response::Flash::success(response::Redirect::to(\"/\"), msg)\n        })\n    }\n\n    #[get(\"/return\")]\n    fn return_(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n    ) -> crate::RResult<response::Flash<response::Redirect>> {\n        sender.do_work(move |pcx| {\n            let frame = Machine::stack(&pcx.ecx).len();\n            let msg = step(pcx, |ecx| {\n                if Machine::stack(&ecx).len() <= frame && is_ret(&ecx) {\n                    ShouldContinue::Stop\n                } else {\n                    ShouldContinue::Continue\n                }\n            });\n            response::Flash::success(response::Redirect::to(\"/\"), msg)\n        })\n    }\n\n    #[get(\"/continue\")]\n    fn continue_(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n    ) -> crate::RResult<response::Flash<response::Redirect>> {\n        sender.do_work(move |pcx| {\n            response::Flash::success(\n                response::Redirect::to(\"/\"),\n                step(pcx, |_ecx| ShouldContinue::Continue),\n            )\n        })\n    }\n}\n\npub mod bp_routes {\n    use super::*;\n    use std::path::PathBuf;\n\n    pub fn routes() -> Vec<::rocket::Route> {\n        routes![add_here, add, remove, remove_all]\n    }\n\n    #[get(\"/add_here\")]\n    pub fn add_here(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n    ) -> crate::RResult<rocket::response::Flash<rocket::response::Redirect>> {\n        sender.do_work(move |pcx| {\n            let frame = pcx.ecx.frame();\n            let msg = if let Some(location) = frame.current_loc().ok() {\n                pcx.config.bptree.add_breakpoint(Breakpoint(\n                    frame.instance.def_id(),\n                    location.block,\n                    location.statement_index,\n                ));\n                format!(\n                    \"Breakpoint added for {:?}@{}:{}\",\n                    frame.instance.def_id(),\n                    location.block.index(),\n                    location.statement_index\n                )\n            } else {\n                format!(\"Can't set breakpoint for unwinding without cleanup yet\")\n            };\n            rocket::response::Flash::success(rocket::response::Redirect::to(\"/\"), msg)\n        })\n    }\n\n    #[get(\"/add/<path..>\")]\n    pub fn add(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n        path: PathBuf,\n    ) -> crate::RResult<rocket::response::Flash<rocket::response::Redirect>> {\n        sender.do_work(move |pcx| {\n            let path = path.to_string_lossy();\n            let res = parse_breakpoint_from_url(&path);\n            let msg = match res {\n                Ok(breakpoint) => {\n                    pcx.config.bptree.add_breakpoint(breakpoint);\n                    format!(\n                        \"Breakpoint added for {:?}@{}:{}\",\n                        breakpoint.0,\n                        breakpoint.1.index(),\n                        breakpoint.2\n                    )\n                }\n                Err(e) => e,\n            };\n            rocket::response::Flash::success(rocket::response::Redirect::to(\"/\"), msg)\n        })\n    }\n\n    #[get(\"/remove/<path..>\")]\n    pub fn remove(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n        path: PathBuf,\n    ) -> crate::RResult<rocket::response::Flash<rocket::response::Redirect>> {\n        sender.do_work(move |pcx| {\n            let path = path.to_string_lossy();\n            let res = parse_breakpoint_from_url(&path);\n            let msg = match res {\n                Ok(breakpoint) => {\n                    if pcx.config.bptree.remove_breakpoint(breakpoint) {\n                        format!(\n                            \"Breakpoint removed for {:?}@{}:{}\",\n                            breakpoint.0,\n                            breakpoint.1.index(),\n                            breakpoint.2\n                        )\n                    } else {\n                        format!(\n                            \"No breakpoint for for {:?}@{}:{}\",\n                            breakpoint.0,\n                            breakpoint.1.index(),\n                            breakpoint.2\n                        )\n                    }\n                }\n                Err(e) => e,\n            };\n            rocket::response::Flash::success(rocket::response::Redirect::to(\"/\"), msg)\n        })\n    }\n\n    #[get(\"/remove_all\")]\n    pub fn remove_all(\n        sender: rocket::State<'_, crate::PrirodaSender>,\n    ) -> crate::RResult<rocket::response::Flash<rocket::response::Redirect>> {\n        sender.do_work(move |pcx| {\n            pcx.config.bptree.remove_all();\n            rocket::response::Flash::success(\n                rocket::response::Redirect::to(\"/\"),\n                \"All breakpoints removed\",\n            )\n        })\n    }\n}\n"
  },
  {
    "path": "src/watch/mod.rs",
    "content": "use std::collections::HashMap;\nuse std::fmt::Write;\n\nuse rustc_middle::mir::interpret::{Allocation, Pointer, PointerArithmetic};\nuse rustc_middle::ty::Instance;\nuse rustc_mir::interpret::AllocId;\nuse rustc_target::abi::Size;\n\nuse crate::*;\n\nmod stack_trace;\n\n#[derive(Debug)]\npub struct Traces<'tcx> {\n    alloc_traces: HashMap<AllocId, AllocTrace>,\n    stack_traces_cpu: Vec<(Vec<(Instance<'tcx>,)>, u128)>,\n    stack_traces_mem: Vec<(Vec<(Instance<'tcx>,)>, u128)>,\n}\n\nimpl<'tcx> Traces<'tcx> {\n    pub fn new() -> Self {\n        let alloc_traces = HashMap::new();\n        //for i in 0..700 {\n        //    alloc_traces.insert(AllocId(i), AllocTrace::new());\n        //}\n        Traces {\n            alloc_traces,\n            stack_traces_cpu: Vec::new(),\n            stack_traces_mem: Vec::new(),\n        }\n    }\n\n    /// Clear the traces. This should be called before restarting the evaluation.\n    pub fn clear(&mut self) {\n        // We have to replace all values of alloc_traces by empty AllocTraces,\n        // because stepping back will change the alloc id's\n        self.alloc_traces.clear();\n\n        // We can just empty the stack traces, because they will be rebuild during stepping\n        self.stack_traces_cpu.clear();\n        self.stack_traces_mem.clear();\n    }\n}\n\n#[derive(Debug)]\nstruct AllocTrace {\n    trace_points: Vec<(u128, AllocTracePoint)>,\n}\n\nimpl AllocTrace {\n    fn new() -> Self {\n        AllocTrace {\n            trace_points: Vec::new(),\n        }\n    }\n}\n\n#[derive(Debug)]\nenum AllocTracePoint {\n    Changed(Allocation<miri::Tag, miri::AllocExtra>),\n    Deallocated,\n}\n\nfn eq_alloc(\n    a: &Allocation<miri::Tag, miri::AllocExtra>,\n    b: &Allocation<miri::Tag, miri::AllocExtra>,\n) -> bool {\n    let Allocation {\n        align: a_align,\n        mutability: a_mut,\n        extra: _,\n        size: a_size,\n        ..\n    } = a;\n    let Allocation {\n        align: b_align,\n        mutability: b_mut,\n        extra: _,\n        size: b_size,\n        ..\n    } = b;\n    a_align == b_align\n        && a_mut == b_mut\n        && a_size == b_size\n        && a.inspect_with_uninit_and_ptr_outside_interpreter(0..a.len())\n            == b.inspect_with_uninit_and_ptr_outside_interpreter(0..b.len())\n        && a.relocations() == b.relocations()\n        && a.init_mask() == b.init_mask()\n}\n\npub fn step_callback(pcx: &mut PrirodaContext<'_, '_>) {\n    {\n        let ecx = &pcx.ecx;\n        let traces = &mut pcx.traces;\n\n        // Collect alloc traces\n        for (alloc_id, alloc_trace) in &mut traces.alloc_traces {\n            if let Ok(alloc) = ecx.memory.get_raw(*alloc_id) {\n                if let Some(&(prev_step_count, AllocTracePoint::Changed(ref prev_alloc))) =\n                    alloc_trace.trace_points.last()\n                {\n                    if eq_alloc(alloc, prev_alloc) || *pcx.step_count == prev_step_count {\n                        continue;\n                    }\n                }\n\n                alloc_trace\n                    .trace_points\n                    .push((*pcx.step_count, AllocTracePoint::Changed(alloc.clone())));\n            } else if !matches!(\n                alloc_trace.trace_points.last(),\n                Some(&(_, AllocTracePoint::Deallocated))\n            ) && !alloc_trace.trace_points.is_empty()\n            {\n                alloc_trace\n                    .trace_points\n                    .push((*pcx.step_count, AllocTracePoint::Deallocated));\n            }\n        }\n    }\n\n    stack_trace::step_callback(pcx);\n}\n\npub fn routes() -> Vec<::rocket::Route> {\n    routes![watch::show, watch::continue_and_show, watch::add]\n}\n\n#[get(\"/show\")]\nfn show(sender: rocket::State<'_, crate::PrirodaSender>) -> crate::RResult<Html<String>> {\n    sender.do_work(|pcx| {\n        let mut buf = String::new();\n\n        stack_trace::show(pcx, &mut buf).unwrap();\n\n        let mut alloc_traces = pcx.traces.alloc_traces.iter().collect::<Vec<_>>();\n        alloc_traces.sort_by_key(|(id, _)| id.0);\n        for (alloc_id, alloc_trace) in alloc_traces {\n            if alloc_trace.trace_points.is_empty() {\n                writeln!(buf, \"<h2>Alloc {} has never existed</h2>\", alloc_id.0).unwrap();\n                continue;\n            }\n\n            writeln!(buf, \"<h2>Alloc {}</h2>\\n<table border='1'>\", alloc_id.0).unwrap();\n            for (step_count, trace_point) in &alloc_trace.trace_points {\n                let content = match trace_point {\n                    AllocTracePoint::Changed(alloc) => crate::render::locals::print_alloc(\n                        pcx.ecx.memory.pointer_size().bytes(),\n                        Pointer::new(*alloc_id, Size::from_bytes(0)).with_tag(miri::Tag::Untagged),\n                        alloc,\n                        None,\n                    ),\n                    AllocTracePoint::Deallocated => \"Dealloc\".to_string(),\n                };\n                writeln!(\n                    buf,\n                    \"<tr>\\n<td>{}</td>\\n<td>{}</td>\\n</tr>\",\n                    step_count, content\n                )\n                .unwrap();\n            }\n            writeln!(buf, \"</table>\\n\").unwrap();\n        }\n\n        Html(buf)\n    })\n}\n\n#[get(\"/continue_and_show\")]\npub fn continue_and_show(sender: State<'_, PrirodaSender>) -> RResult<Html<String>> {\n    sender.do_work(move |pcx| {\n        crate::step::step(pcx, |_ecx| crate::step::ShouldContinue::Continue);\n    })?;\n    show(sender)\n}\n\n#[get(\"/add/<id>\")]\npub fn add(\n    sender: rocket::State<'_, crate::PrirodaSender>,\n    id: u64,\n) -> crate::RResult<rocket::response::Redirect> {\n    sender.do_work(move |pcx| {\n        pcx.traces\n            .alloc_traces\n            .insert(AllocId(id), AllocTrace::new());\n        step_callback(pcx);\n        rocket::response::Redirect::to(\"/\")\n    })\n}\n"
  },
  {
    "path": "src/watch/stack_trace.rs",
    "content": "use std::fmt::Write;\nuse std::io::{self, Write as IoWrite};\nuse std::process::{Command, Stdio};\n\nuse rustc_middle::ty::{self, Instance, InstanceDef, ParamEnv};\nuse rustc_mir::interpret::Machine;\n\nuse crate::*;\n\npub(super) fn step_callback(pcx: &mut PrirodaContext<'_, '_>) {\n    let ecx = &pcx.ecx;\n    let traces = &mut pcx.traces;\n\n    let stack_trace = Machine::stack(ecx)\n        .iter()\n        .map(|frame| (frame.instance,))\n        .collect::<Vec<_>>();\n    insert_stack_trace(&mut traces.stack_traces_cpu, stack_trace.clone(), 1);\n\n    let location = if let Some(location) = ecx.frame().current_loc().ok() {\n        location\n    } else {\n        return; // Unwinding, but no cleanup for current frame needed\n    };\n    let mir::Location {\n        block,\n        statement_index: stmt,\n    } = location;\n    let blck = &ecx.frame().body.basic_blocks()[block];\n\n    if stmt == blck.statements.len() {\n        use rustc_middle::mir::TerminatorKind::*;\n        match &blck.terminator().kind {\n            Call { func, args, .. } => {\n                if let Some(instance) = instance_for_call_operand(ecx, &func) {\n                    insert_stack_traces_for_instance(pcx, stack_trace, instance, Some(&args));\n                }\n            }\n            Drop { place, .. } => {\n                let location_ty = place.ty(ecx.frame().body, ecx.tcx.tcx).ty;\n                let location_ty = ecx.tcx.subst_and_normalize_erasing_regions(\n                    ecx.frame().instance.substs,\n                    ParamEnv::reveal_all(),\n                    location_ty,\n                );\n                let instance = Instance::resolve_drop_in_place(ecx.tcx.tcx, location_ty);\n                insert_stack_traces_for_instance(pcx, stack_trace, instance, None);\n            }\n            _ => {}\n        }\n    }\n}\n\nfn instance_for_call_operand<'a, 'tcx: 'a>(\n    ecx: &InterpCx<'tcx>,\n    func: &'tcx rustc_middle::mir::Operand<'_>,\n) -> Option<Instance<'tcx>> {\n    let res: ::miri::InterpResult<'_, Instance<'_>> = try {\n        let func = ecx.eval_operand(func, None)?;\n\n        match func.layout.ty.kind() {\n            ty::FnPtr(_) => {\n                let fn_ptr = ecx.read_scalar(&func)?.check_init()?;\n                if let Ok(instance) = ecx.memory.get_fn(fn_ptr)?.as_instance() {\n                    instance\n                } else {\n                    return None;\n                }\n            }\n            ty::FnDef(def_id, substs) => {\n                let substs = ecx.tcx.subst_and_normalize_erasing_regions(\n                    ecx.frame().instance.substs,\n                    ParamEnv::reveal_all(),\n                    *substs,\n                );\n                ty::Instance::resolve(*ecx.tcx, ParamEnv::reveal_all(), *def_id, substs)\n                    .unwrap()\n                    .unwrap()\n            }\n            _ => {\n                panic!(\"can't handle callee of type {:?}\", func.layout.ty);\n            }\n        }\n    };\n    Some(res.unwrap())\n}\n\nfn insert_stack_traces_for_instance<'a, 'tcx: 'a>(\n    pcx: &mut PrirodaContext<'a, 'tcx>,\n    mut stack_trace: Vec<(Instance<'tcx>,)>,\n    instance: Instance<'tcx>,\n    args: Option<&[mir::Operand<'tcx>]>,\n) {\n    let ecx = &pcx.ecx;\n    let traces = &mut pcx.traces;\n\n    let item_path = ecx.tcx.def_path_str(instance.def_id());\n\n    stack_trace.push((instance,));\n    insert_stack_trace(&mut traces.stack_traces_cpu, stack_trace.clone(), 1);\n\n    let _: ::miri::InterpResult<'_> = try {\n        let args = if let Some(args) = args {\n            args.into_iter()\n                .map(|op| ecx.eval_operand(op, None))\n                .collect::<Result<Vec<_>, _>>()?\n        } else {\n            return;\n        };\n\n        match &item_path[..] {\n            \"alloc::alloc::::__rust_alloc\" | \"alloc::alloc::::__rust_alloc_zeroed\" => {\n                let size = ecx.read_scalar(&args[0])?.to_machine_usize(&ecx.tcx.tcx)?;\n                insert_stack_trace(&mut traces.stack_traces_mem, stack_trace, size as u128);\n            }\n            \"alloc::alloc::::__rust_realloc\" => {\n                let old_size = ecx.read_scalar(&args[1])?.to_machine_usize(&ecx.tcx.tcx)?;\n                let new_size = ecx.read_scalar(&args[3])?.to_machine_usize(&ecx.tcx.tcx)?;\n                if new_size > old_size {\n                    insert_stack_trace(\n                        &mut traces.stack_traces_mem,\n                        stack_trace,\n                        (new_size - old_size) as u128,\n                    );\n                }\n            }\n            _ => {}\n        }\n    };\n}\n\nfn insert_stack_trace<T: Eq>(traces: &mut Vec<(T, u128)>, trace: T, count: u128) {\n    if let Some(t) = traces.last_mut() {\n        if t.0 == trace {\n            t.1 += count;\n            return;\n        }\n    }\n    traces.push((trace, count));\n}\n\npub(super) fn show(pcx: &PrirodaContext<'_, '_>, buf: &mut impl Write) -> io::Result<()> {\n    writeln!(buf, \"{}\\n\", crate::render::refresh_script(pcx)).unwrap();\n    create_flame_graph(\n        &pcx.ecx,\n        &mut *buf,\n        &pcx.traces.stack_traces_cpu,\n        \"Cpu usage\",\n        \"instructions\",\n        \"java\",\n        \"flame_graph_cpu\",\n    )?;\n    create_flame_graph(\n        &pcx.ecx,\n        &mut *buf,\n        &pcx.traces.stack_traces_mem,\n        \"Memory usage\",\n        \"bytes\",\n        \"mem\",\n        \"flame_graph_mem\",\n    )?;\n    print_stack_traces(&pcx.ecx, &mut *buf, &pcx.traces.stack_traces_cpu).unwrap();\n    Ok(())\n}\n\nfn create_flame_graph<'a, 'tcx: 'a>(\n    ecx: &InterpCx<'tcx>,\n    mut buf: impl Write,\n    traces: &[(Vec<(Instance<'tcx>,)>, u128)],\n    name: &str,\n    count_name: &str,\n    color_scheme: &str,\n    _file_name: &str,\n) -> io::Result<()> {\n    let mut flame_data = String::new();\n    for (stack_trace, count) in traces {\n        let mut last_crate = rustc_hir::def_id::LOCAL_CRATE;\n        writeln!(\n            flame_data,\n            \"{} {}\",\n            stack_trace\n                .iter()\n                .map(|(instance,)| {\n                    let mut name = ecx.tcx.def_path_str(instance.def_id());\n                    match instance.def {\n                        InstanceDef::Intrinsic(..) => name.push_str(\"_[k]\"),\n                        InstanceDef::DropGlue(..) => name.push_str(\"_[k]\"),\n                        _ => {\n                            if instance.def_id().is_local() {\n                                name.push_str(\"_[j]\");\n                            }\n                        }\n                    }\n                    if last_crate != instance.def_id().krate {\n                        name = \"-;\".to_string() + &name;\n                        last_crate = instance.def_id().krate;\n                    }\n                    name\n                })\n                .collect::<Vec<_>>()\n                .join(\";\"),\n            count\n        )\n        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;\n    }\n\n    //::std::fs::write(format!(\"./resources/{}.txt\", _file_name), flame_data.as_bytes())?;\n\n    let child = Command::new(\"../FlameGraph/flamegraph.pl\")\n        .arg(\"-\")\n        .arg(\"--title\")\n        .arg(name)\n        .arg(\"--countname\")\n        .arg(count_name)\n        .arg(\"--colors\")\n        .arg(color_scheme)\n        .arg(\"--minwidth\")\n        .arg(\"0.01\")\n        .stdin(Stdio::piped())\n        .stdout(Stdio::piped())\n        .spawn();\n    match child {\n        Ok(mut child) => {\n            child\n                .stdin\n                .as_mut()\n                .unwrap()\n                .write_all(flame_data.as_bytes())?;\n            match child.wait_with_output() {\n                Ok(output) => {\n                    let flame_graph = String::from_utf8(output.stdout).unwrap();\n                    //::std::fs::write(format!(\"./resources/{}.svg\", _file_name), flame_graph.as_bytes())?;\n                    writeln!(buf, \"{}\", flame_graph).unwrap()\n                }\n                Err(err) => writeln!(buf, \"<h1><pre>Wait error: {:?}</pre></h1>\", err).unwrap(),\n            }\n        }\n        Err(err) => writeln!(buf, \"<h1><pre>Spawn error: {:?}</pre></h1>\", err).unwrap(),\n    }\n\n    Ok(())\n}\n\nfn print_stack_traces<'a, 'tcx: 'a>(\n    ecx: &InterpCx<'tcx>,\n    mut buf: impl Write,\n    traces: &[(Vec<(Instance<'tcx>,)>, u128)],\n) -> ::std::fmt::Result {\n    let name_for_instance = |i: Instance<'_>| {\n        ecx.tcx\n            .def_path_str(i.def_id())\n            .replace(\"<\", \"&lt;\")\n            .replace(\">\", \"&gt;\")\n    };\n    writeln!(buf, \"<h1>Stack trace</h1>\\n<ul>\\n\")?;\n    for (stack_trace, count) in traces {\n        writeln!(\n            buf,\n            \"<li>{2}{0} ({1})</li>\\n\",\n            name_for_instance(stack_trace.last().unwrap().0),\n            count,\n            format!(\n                \"{nil: <indent$}\",\n                nil = \"\",\n                indent = 4 * (stack_trace.len() - 1)\n            )\n            .replace(\" \", \"&nbsp;\")\n        )?;\n    }\n    writeln!(buf, \"</ul>\")?;\n    Ok(())\n}\n"
  }
]