[
  {
    "path": ".gitattributes",
    "content": "docs/* linguist-vendored\nbf/* linguist-vendored\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where the package manifests are located.\n# Please see the documentation for all configuration options:\n# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates\n\nversion: 2\nupdates:\n  - package-ecosystem: \"cargo\" # See documentation for possible values\n    directory: \"/\" # Location of package manifests\n    schedule:\n      interval: \"monthly\"\n    groups:\n      dependencies:\n        patterns:\n          - \"*\"\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches:\n      - main\n      - 'feat/**'\n  pull_request:\n    branches:\n      - main\n      - 'feat/**'\n  schedule:\n    - cron: '0 0 * * 0' # at midnight of each sunday\n  workflow_dispatch:\n\njobs:\n  develop:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: taiki-e/install-action@just\n      - uses: dtolnay/rust-toolchain@nightly\n        with:\n          components: rustfmt, clippy, miri, rust-src\n      - uses: Swatinem/rust-cache@v2\n      - run: just ci\n\n  msrv:\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        toolchain: \n          - 1.78.0 # MSRV\n          - stable\n    steps:\n      - uses: actions/checkout@v4\n      - uses: taiki-e/install-action@just\n      - uses: dtolnay/rust-toolchain@master\n        with:\n          toolchain: ${{ matrix.toolchain }}\n      - uses: Swatinem/rust-cache@v2\n      - run: just test\n  \n  audit:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: taiki-e/install-action@cargo-audit\n      - run: cargo audit -D warnings\n"
  },
  {
    "path": ".github/workflows/deploy.yml",
    "content": "name: Deploy\n\non:\n  push:\n    branches: [\"main\"]\n  workflow_dispatch:\n\npermissions:\n  contents: read\n  pages: write\n  id-token: write\n\nconcurrency:\n  group: \"pages\"\n  cancel-in-progress: false\n\njobs:\n  deploy:\n    environment:\n      name: github-pages\n      url: ${{ steps.deployment.outputs.page_url }}\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: taiki-e/install-action@mdbook\n      - run: cd book && mdbook build\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v3\n        with:\n          path: ./dist\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v4\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\n**/*.rs.bk\n.vscode\n/dist\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"bfjit\"\nversion = \"0.1.4\"\nauthors = [\"Nugine <nugine@foxmail.com>\"]\nedition = \"2021\"\nlicense = \"AGPL-3.0\"\nrepository = \"https://github.com/Nugine/bfjit\"\ndescription = \"Brainfuck JIT VM tutorial\"\nkeywords = [\"brainfuck\", \"jit\", \"tutorial\"]\ncategories = [\"compilers\", \"command-line-utilities\"]\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\nthiserror = \"2.0.18\"\ndynasm = \"5.0.0\"\ndynasmrt = \"5.0.0\"\nclap = { version = \"4.5.60\", features = [\"derive\"] }\n\n[profile.release]\ndebug = \"full\"\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<http://www.gnu.org/licenses/>."
  },
  {
    "path": "README.md",
    "content": "# Brainfuck JIT 虚拟机教程\n\n当我们谈到 JIT 时，通常会想到 V8、JVM 之类的庞然大物，然后望而生畏，觉得 JIT 是一种极其高深复杂的技术。\n\n但 JIT 也可以变得非常简单，我们不需要做完善的优化和分析，只要输入源码，输出机器指令，再执行，这和普通的文本处理程序没什么区别。\n\n在本教程中，我们将用 Rust 语言实现一个简单的 Brainfuck JIT 虚拟机，逐步理解 JIT 技术。\n\n教程地址：<https://nugine.github.io/bfjit>\n\n如果本教程对您有帮助，请[赞助我的开源工作](https://github.com/Nugine#sponsor)。\n"
  },
  {
    "path": "bf/cgbfi2.bf",
    "content": "Brainfuck Self Interpreter: by Clive Gifford \n\nVersion 1: 01 December 2006 (one trip between code and data per op)\nVersion 2: 16 December 2006 (virtual codes for various combinations)\n\nCredits\n\nA large section of code to load the input to the interpreter is copied \nfrom the the 423 byte dbfi interpreter as described in the November 2003\npaper \"A Very Small Interpeter\" by Oleg Mazonka and Daniel B Cristofani\n\nGoals\n\nThe goal for this interpreter was to be efficient rather than small and\nparticularly to allow as many copies of itself as possible to be \"stacked\"\nup with something else on top / In other words to achieve a low \"eigenratio\"\n(See http eigenratios dot blogspot dot com for more information)\n\nThe main idea of the first version was to only make one round trip between\nthe emulated code and emulated data for each instruction executed instead\nof multiple round trips which is what Daniel and Oleg's version does\n\nThe second version does more pre processing of the guest program in order\nto map several common sequences to virtual codes thus reducing the memory\nfootprint and also further reducing the number of round trips between the\nemulated code and data\n\nOther info:\n\nThe input must consist of valid brainfuck code (to be interpreted) which\nmust always be followed by an exclamation mark and then any associated data\nInput can also include \"comments\" (if desired) except for exclamation mark\n\nIf you are stacking multiple copies of this interpreter then each additional\nlevel also has to appear in the input with a trailing exclamation mark and \nthen we finally have the input for the very top level to finish things off\n\nThe underlying brainfuck machine determines the possible range of values in\nthe data cell values and what happens if an attempt is made to go outside the\nsupported range but this interpreter does not more than 8 bit data itself\n\nLoops in the emulated code can be nested up to the maximum cell value in the\nunderlying machine and this interpreter requires that at least 17 levels of\nnesting is supported\n\nBehaviour on end of input is also inherited from the next level down\n\n>>>>                        leave a little extra space before the program code\n+                           start in left hand cell of first program code pair\n[\n  ->>>                      clear flag and move to the starting position\n  ++>+>+++++++              setup differences and read char as per dbfi\n  [<++++>>++<-]++>>+>+>     (by Daniel B Cristofani)\n  +++++[>++>++++++<<-]\n  +>>>,<++\n  [\n    [>[->>]<[>>]<<-]        see section 3 of dbfi paper\n     <[<]<+>>[>]>\n    [                       see section 4 of dbfi paper\n      <+>-\n      [[<+>-]>]             see section 5 of dbfi paper\n      <                     see section 6 of dbfi paper\n      [\n        [[-]<]              scan left and zero the differences\n        ++<-                see section 7 of dbfi paper\n        [\n          <+++++++++>[<->-]>>\n        ]\n        >>\n      ]\n    ]\n    <<\n  ]\n\n a three way switch to handle possibilities and adjust positioning\n \n  >[-]+<<                   set \"done\" flag and position to value\n  [\n    --                      2 means last decode was for a valid instruction\n    [                       so if we still have something left now it was a 9\n      [-]                   originally (meaning input should be ignored)\n      >>- <<<+>             so all we do is set the \"more input\" flag\n    ]\n    >> \n    [\n      -\n      <<<<[>+<-]            for valid input move everything right one\n\n start of processing to find and recode certain combinations of codes   \n\n      +<<+                  set flags to indicate we want to process \n                            the last two instructions in the loop below\n      [                     \n        ->                  clear flag and move to instruction\n        [<+>>>>>>+<<<<<-]   double copy instruction and then\n        <[>+<-]>>>>>>       restore original before moving to copy\n\n map relevant codes to values giving unique pairwise sums and also\n set a flag if we see the end of a loop\n\n        >+<\n        [\n         -[\n           -[\n             -[\n               -[\n                 -[\n                   -[\n                     -[\n                       -[\n                          [-]\n                          >-<\n                        ]>[-<<+++++++>>] <\n                      ]\n                    ]\n                  ]>[-]<\n                ]>[-<<+++>>]<\n              ]>[-<<+>>]<\n            ]>[-]<\n          ]>[-<<<<<<<+>>>>>>>]<   set flag if it is end of loop\n        ]>[-]<\n        <<<<                      goto next instruction flag\n      ]\n\n add values from above together to get unique sum\n\n      >>>[<<+>>-]\n      <+<\n\n setup a switch to figure out what it means\n\n      [\n       -[\n         -[ \n           -[\n             -[\n               -[\n                 -[\n                   -[\n                     -[\n                       -[\n                         -[\n                            [-]\n                            >-<<<[-]<<+>>  change code 8 (add 1) to 9 (add 2)\n                          ]\n                        ]\n                      ]\n                    ]>[-]<\n                  ]>[-<<<[-]<<+++++++>>>]< change code 4 (left) to 11 (left 2)\n                ]\n              ]\n            ]>[-]<\n          ]>[-<<<[-]<<+++++++>>>]<         change code 3 (right) to 10 (right 2)\n        ]\n      ]>[-]<\n\n clear flag set if second to last was end of loop\n and go to similar flag for last instruction\n\n      <<<<<[-]>>\n      [\n        -\n        <<<[>+>>+<<<-]>[<+>-]>>            copy third to last instruction\n \n if it is the start of a loop then we can (in some cases)\n collapse the last three instructions to single virtual code\n\n        [\n         -[\n           -[\n              [-]\n              >>\n            ]\n            >\n            [    Now we are ready to check what code is in the loop (must be at least 1)\n              <<[<+>>+<-]>[<+>-]+<<\n              -\n              [\n               -[\n                 -[\n                   -[\n                     -[\n                       -[\n                         -[\n                           -[\n                             -[\n                               -[\n                                  -\n                                  <+>         fall through & code as 16 (double skip left)\n                                ]<+++++++++++++>>[-]>->-<<   code as 15 (double skip right)\n                              ]                  \n                            ]\n                          ]>>[->>>>>]<<\n                        ]>>[-<<<++++++++++++>>[-]>>-]<<      code as 14 (zero)\n                      ]>>[->>>>>]<<\n                    ]>>[-<<<+++++++++++>>[-]>>-]<<           code as 13 (skip left)\n                  ]>>[-<<<++++++++++>>[-]>>-]<<              code as 12 (skip right)\n                ]                         \n              ]>>[->>>>>]<<\n            ]\n            <\n          ]\n        ]>[>>]<\n        <<\n      ]\n      >>+>>>\n    ] \n    <<\n  ]\n  >> [->+>] <<              end of input so clear \"done\" and set data mark and\n                            finally position to a zero cell ready for next phase\n  \n  <                         move to \"more input\" flag\n  \n]\n\n<<[<<]>>                    go to the first instruction\n\n                            ******** MAIN INTERPRETER LOOPS STARTS HERE ********\n\n[                           start on current instruction code\n                            setup a big switch statement to decode instructions\n  [<+>>+<-]                 move/copy instruction code and set \"done\" flag to\n  +<-                       start with '(i less 1) (1) (i) for i = instruction\n  [\n   -[\n     -[\n       -[\n         -[\n           -[\n             -[\n               -[\n                 -[\n                   -[\n                     -[\n                       -[\n                         -[\n                           -[\n                             -[\n                                -           can't be anything but 1 so bracketing not needed\n                                >->> [>>] >> [>>]< [<-<<-<] <[<<] << [<<]<   double skip left (code 16)\n                              ]\n                              >[->> [>>] >> [>>]< [>+>>+>] <[<<] << [<<]]<   double skip right (code 15)\n                            ]\n                            >[->> [>>] >> [>>] <[-]< [<<] << [<<]]<  zero (code 14)\n                          ]\n                          >[->> [>>] >> [>>]< [<-<] <[<<] << [<<]]<  skip left (code 13)\n                        ]\n                        >[->> [>>] >> [>>]< [>+>] <[<<] << [<<]]<    skip right  (code 12)\n                      ] \n                      >[->> [>>] >> [>>]< <-<<-< <[<<] << [<<]]<  double move left (code 11)\n                    ]\n                    >[->> [>>] >> [>>] +>>+ [<<] << [<<]]<        double move right (code 10)\n                  ]\n                  >[->> [>>] >> [>>]< ++ <[<<] << [<<]]<          add 2 (code 9)\n                ]\n                >[->> [>>] >> [>>]< + <[<<] << [<<]]<       increment\n              ]\n              >[->> [>>] >> [>>]< , <[<<] << [<<]]<         input\n            ]\n            >[->> [>>] >> [>>]< - <[<<] << [<<]]<           decrement\n          ]\n          >[->> [>>] >> [>>]< . <[<<] << [<<]]<             output\n        ]\n        >[->> [>>] >> [>>] <<-<< [<<] << [<<]]<             move left\n      ]\n      >[->> [>>] >> [>>] + [<<] << [<<]]<                   move right\n    ]\n    >\n    [-                      left hand bracket\n      >> [>>] >> [>>]<      move to data cell\n      [>+>>+<<<-]>          make double copy and move to first\n      [<+>-]                restore original data cell value\n      >>[<<+>>[-]]+         This and the following achieves\n      <<[>>-<<-]            x = not x\n      >>                    go to flag cell (0 or 1)\n\n      Some tricky stuff here: set up (not flag) also so we can later choose\n      appropriate instruction sequence to get back to code area in one pass\n      In one case we set flags at the other end (data greater than 0) but\n      for the other we just go back without setting any flags (data equals 0)\n\n      [<<+>>>>+<<-]         make two copies of flag\n      >>[<<+>>-]\n      <<[>>+<<-]+           This and the following achieves\n      >>[<<->>-]<<          x = not x\n\n      <<                    so we now have (data) '(flag) (?) (not flag)\n\n      [                     if flag set then\n        -<< [<<] << [<<]<   clear and return to code section where we save\n        << << ++            a 2 meaning we need (later) to match left bracket\n        >>                  stop in zero cell for now\n      ]\n\n      >>                    if we executed code above then now at switch flag\n                            else it will put us ready to return from data area\n\n      [-<<<<<<[<<]<<[<<]<]  move back to switch flag without setting anything\n\n      >\n    ]\n    <\n  ]\n  >\n  [-                        right hand bracket\n    >> [>>] >> [>>]<        move to data cell\n    [>+>>+<<<-]>            make double copy and move to first\n    [[<+>-]>>[-]+<<]        restore data from one then zero second and set flag\n    >>                      go to flag cell (0 or 1)\n\n    Some tricky stuff here: set up (not flag) also so we can later choose\n    appropriate instruction sequence to get back to code area in one pass\n    In one case we set flags at the other end (data greater than 0) but\n    for the other we just go back without setting any flags (data equals 0)\n\n    [<<+>>>>+<<-]           make two copes of flag\n    >>[<<+>>-]\n    <<[>>+<<-]+             This and the following achieves\n    >>[<<->>-]<<            x = not x\n       \n    <<                      so we now have (data) '(flag) (?) (not flag)\n    \n    [                       if flag set then\n      -<< [<<] << [<<]<     clear and return to code section where we save\n      << << +               a 1 meaning we need (later) to match right bracket\n      >>                    stop in zero cell for now\n    ]\n\n    >>                      if we executed code above then now at switch flag\n                            else it will put us ready to return from data area\n                          \n    [-<<<<<<[<<]<<[<<]<]    move back to switch flag without setting anything\n    \n    >\n  ]\n\n  >[<+>-]                   restore original instruction code\n\n  *** We are positioned in the cell immediately to the right of the   ***\n  *** instruction that has just been \"executed\" in the switch above   ***\n  *** The following code is to handle finding matching brackets       ***\n  *** because code above has only set a cell value to 1 or 2 to show  ***\n  *** what kind of loop scanning is required (1=scan left 2=right)    ***\n  \n  << << <<                  position to cell showing if matching required\n  [                         if non zero we need to find a matching bracket\n    >> +                    set up \"done\" flag for switch and\n    << -                    decrement switch value so now is 0 or 1\n    [                       if 1 we are looking for matching right bracket\n      - >> - >> +           clear switch value & \"done\" & set level to 1\n      [                     while level is more than 0\n        >>>[-<+>>+<]        make double copy of instruction code\n        +<-                 set flag and prepare for switch\n        [\n         -[\n            [-]             clear whatever is left of code\n            > - <           do nothing except clear flag\n          ]\n          > [- <<< + >>>] < increment level\n        ]\n        > [- <<< - >>>]     decrement level\n\n        >[-<+>]<<           restore instruction code\n\n        <<                  go to level\n        [>>+<<-]            if level then move right one instruction\n        >>\n      ]\n      << << <<              go back to switch value cell\n    ]\n    >>                      go to switch done flag and if still set then\n    [                       we must be looking for a matching left bracket\n      - << +                clear switch value & \"done\" & set level to 1\n      [                     repeat while level is more than 0\n        >>>[-<+>>+<]        make double copy of instruction code\n        +<-                 set flag and prepare for switch\n        [\n         -[\n            [-]             clear whatever is left of code\n            > - <           do nothing except clear flag\n          ]\n          > [- <<< - >>>] < decrement level\n        ]\n        > [- <<< + >>>]     increment level\n\n        >[-<+>]<<           restore instruction code\n\n        <<                  go to level\n        [<<+>>-]            if level then move left one instruction\n        <<\n      ]\n    ]\n  ]\n\n  >> >> >>\n\n  >                         move forward to next instruction\n]\n"
  },
  {
    "path": "bf/hello.bf",
    "content": "[ This program prints \"Hello World\" and a newline to the screen, its\n  length is 106 active command characters. [It is not the shortest.]\n\n  This loop is an \"initial comment loop\", a simple way of adding a comment\n  to a BF program such that you don't have to worry about any command\n  characters. Any \".\", \",\", \"+\", \"-\", \"<\" and \">\" characters are simply\n  ignored, the \"[\" and \"]\" characters just have to be balanced. This\n  loop and the commands it contains are ignored because the current cell\n  defaults to a value of 0; the 0 value causes this loop to be skipped.\n]\n++++++++               Set Cell #0 to 8\n[\n    >++++               Add 4 to Cell #1; this will always set Cell #1 to 4\n    [                   as the cell will be cleared by the loop\n        >++             Add 2 to Cell #2\n        >+++            Add 3 to Cell #3\n        >+++            Add 3 to Cell #4\n        >+              Add 1 to Cell #5\n        <<<<-           Decrement the loop counter in Cell #1\n    ]                   Loop till Cell #1 is zero; number of iterations is 4\n    >+                  Add 1 to Cell #2\n    >+                  Add 1 to Cell #3\n    >-                  Subtract 1 from Cell #4\n    >>+                 Add 1 to Cell #6\n    [<]                 Move back to the first zero cell you find; this will\n                        be Cell #1 which was cleared by the previous loop\n    <-                  Decrement the loop Counter in Cell #0\n]                       Loop till Cell #0 is zero; number of iterations is 8\n\nThe result of this is:\nCell No :   0   1   2   3   4   5   6\nContents:   0   0  72 104  88  32   8\nPointer :   ^\n\n>>.                     Cell #2 has value 72 which is 'H'\n>---.                   Subtract 3 from Cell #3 to get 101 which is 'e'\n+++++++..+++.           Likewise for 'llo' from Cell #3\n>>.                     Cell #5 is 32 for the space\n<-.                     Subtract 1 from Cell #4 for 87 to give a 'W'\n<.                      Cell #3 was set to 'o' from the end of 'Hello'\n+++.------.--------.    Cell #3 for 'rl' and 'd'\n>>+.                    Add 1 to Cell #5 gives us an exclamation point\n>++.                    And finally a newline from Cell #6"
  },
  {
    "path": "bf/mendelbrot.bf",
    "content": "[A mandelbrot set fractal viewer in brainf*** written by Erik Bosman]\n+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[\n>>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+\n<<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>>\n>+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[-]>>]<<<<<<<<<[<<<<<<<<<]>>\n>>>>>[-]+<<<<<<++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<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<<[->>>>>>>+<<<<<<<]<+<<<<<<\n<<<]>>>>>>>>-<<<<<[-]+<<<]+>>>>>>>>[-<<<<<<<<->>>>>>>>]+<<<<<<<<[->>>>>>>>->[>>>\n>>>[->>+<<]>>>]<<<<<<<<<[>[-]<->>>>>>>>[-<<<<<<<<+>[<->-<<+>>]<[->+<]>>>>>>>>]<<\n<<<<<[->>>>>>>+<<<<<<<]<+<<<<<<<<<]>+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>\n+>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<[<<<<<<<<<]>>>>>>>>>[>>>>>>[-<<<<<<->>>>>>]+<\n<<<<<[->>>>>>->>[-<<<<<<<<+>>>>>>>>]<<<<<<<<[->>>>>>>>+<<<<<<<<<<<<<<<<<[<<<<<<<\n<<]>>>>[-]+>>>>>[>>>>>>>>>]>+<]]+>>>>>>>>[-<<<<<<<<->>>>>>>>]+<<<<<<<<[->>>>>>>>\n-<<[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>>\n>>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<<<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>[-]<<<++++\n+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<<\n<<<<<]]>>>]\n"
  },
  {
    "path": "book/book.toml",
    "content": "[book]\nauthors = [\"Nugine\"]\nlanguage = \"zh-CN\"\nmultilingual = false\nsrc = \"src\"\ntitle = \"Brainfuck JIT 虚拟机教程\"\n\n[build]\nbuild-dir = \"../dist\"\n"
  },
  {
    "path": "book/src/1.md",
    "content": "# 1. 背景知识\n\n## Brainfuck 简介\n\n<https://en.wikipedia.org/wiki/Brainfuck>\n\nBrainfuck 仅包含八个指令，却是图灵完备的，理论上它可以做到任何用图灵机能做到的事情。\n\n机器模型：一个字节数组，一个数据指针，一个指令指针，输入流，输出流。\n\n数组初始化为全零，数据指针初始时指向数组的第一个字节，指令指针指向第一条指令。\n\n字符 '>'：将数据指针加一。\n\n字符 '<'：将数据指针减一。\n\n字符 '+'：将数据指针所指的单元加一。\n\n字符 '-'：将数据指针所指的单元减一。\n\n字符 ','：从输入流中读取一个字节，存入数据指针所指单元。\n\n字符 '.'：输出数据指针所指单元的字节。\n\n字符 '['：如果当前单元是 0，那么跳转到对应的 ']' 的下一条指令，否则继续执行。\n\n字符 ']'：如果当前单元不是 0，那么跳转到对应的 '[' 的下一条指令，否则继续执行。\n\n\nBrainfuck 可以直接对应到 C 代码，仅用几十行就能写个从 bf 到 c 的编译器。\n\n初始化\n\n```c\nchar array[30000] = {0};\nchar *ptr=array;\n```\n\n| 指令 | C 代码          |\n| ---- | --------------- |\n| >    | ++ptr;          |\n| <    | --ptr;          |\n| +    | ++*ptr;         |\n| -    | --*ptr;         |\n| .    | putchar(*ptr);  |\n| ,    | *ptr=getchar(); |\n| [    | while (*ptr) {  |\n| ]    | }               |\n\nBrainfuck 可视化\n\n<https://ashupk.github.io/Brainfuck/brainfuck-visualizer-master/index.html>\n\n## Rust 资源\n\nRust 官网 <https://www.rust-lang.org/>\n\nRust 一键安装 <https://rustup.rs/>\n\nRust 并不是一个能立即上手的语言，如果您是一位 Rust 新手，最好先全面了解 Rust 语言特性。\n\nRust 官网入门教程 <https://www.rust-lang.org/zh-CN/learn>\n\n中文书《Rust编程之道》 <https://book.douban.com/subject/30418895/>\n"
  },
  {
    "path": "book/src/2.md",
    "content": "# 2. 启动项目\n\n初始化项目\n\n```bash\ncargo new bfjit\ncd bfjit\ncargo run\n```\n\n空白项目默认为 Hello world\n\n```\nFinished dev [unoptimized + debuginfo] target(s) in 0.06s\nRunning `target/debug/bfjit`\nHello, world!\n```\n\n一切就绪。"
  },
  {
    "path": "book/src/3.md",
    "content": "# 3. 中间表示\n\n为了方便后期处理，我们先将 Brainfuck 代码转换为一种中间表示 (IR).\n\n在 src 目录下添加文件 bfir.rs\n\n此时目录结构\n\n```\n.\n├── Cargo.lock\n├── Cargo.toml\n└── src\n   ├── bfir.rs\n   └── main.rs\n```\n\nmain.rs\n\n```rust ,noplaypen\nmod bfir;\n\nfn main() {\n    println!(\"Hello, world!\");\n}\n```\n\n本节以下代码都将写入 bfir.rs\n\n## IR 定义\n\nAddVal, SubVal 表示将当前单元加减某一数值。\n\nAddPtr, SubPtr 表示将数据指针加减某一数值。\n\nJz，Jnz 表示跳转指令，带有跳转地址。\n\n```rust ,noplaypen\n{{#include ../../src/bfir.rs:3:13}}\n```\n\n## 错误处理\n\n\n我们使用 thiserror 库，用来轻松定义错误类型。\n\n<https://github.com/dtolnay/thiserror>\n\n导入第三方库时：\n\n若 Rust 版本 >= 1.62，可直接 [cargo add](https://doc.rust-lang.org/cargo/commands/cargo-add.html) 。\n\n若 Rust 版本 < 1.62，推荐用 cargo-edit 插件。安装 cargo-edit 插件后，可以用命令导入第三方库。\n\n<https://github.com/killercup/cargo-edit>\n\n也可手动编辑 Cargo.toml。\n\n```bash\ncargo install cargo-edit\n```\n\n```bash\ncargo add thiserror\n```\n\n错误定义\n\n```rust ,noplaypen\n{{#include ../../src/bfir.rs:15:28}}\n```\n\n为 CompileError 实现 Display 和 Error，Display 用于对人友好的信息，Error 表明它是一个错误类型。\n\n```rust ,noplaypen\n{{#include ../../src/bfir.rs:23:34}}\n```\n\n## 编译为 IR\n\n\n```rust ,noplaypen\n{{#include ../../src/bfir.rs:38:44}}\n```\n\ncompile 函数接收一个字符串，返回 IR 序列。\n\ncode 存储已解析的 IR，stk 作为栈，存储左括号的IR位置、源代码行位置、源代码列位置，line 和 col 分别记录行号和列号。\n\n主循环结构\n\n```rust ,noplaypen\nfor ch in src.chars() {\n    col += 1;\n    match ch {\n        ...\n    }\n}\n```\n\n处理换行\n\n```rust ,noplaypen\n'\\n' => {\n    line += 1;\n    col = 0;\n}\n```\n\n处理普通指令\n\n```rust ,noplaypen\n'+' => code.push(BfIR::AddVal(1)),\n'-' => code.push(BfIR::SubVal(1)),\n'>' => code.push(BfIR::AddPtr(1)),\n'<' => code.push(BfIR::SubPtr(1)),\n',' => code.push(BfIR::GetByte),\n'.' => code.push(BfIR::PutByte),\n```\n\n处理左括号，将左括号位置入栈。\n\n```rust ,noplaypen\n'[' => {\n    let pos = code.len() as u32;\n    stk.push((pos, line, col));\n    code.push(BfIR::Jz)\n}\n```\n\n处理右括号，从栈中弹出左括号位置，如果栈为空，说明没有匹配的左括号，生成一个编译错误并返回。如果有匹配的左括号，则正常生成 IR。\n\n```rust ,noplaypen\n']' => {\n    stk.pop().ok_or(CompileError {\n        line,\n        col,\n        kind: CompileErrorKind::UnexpectedRightBracket,\n    })?;\n\n    code.push(BfIR::Jnz)\n}\n```\n\n忽略其他字符\n\n```rust ,noplaypen\n_ => {}\n```\n\n循环结束后，如果栈不为空，说明有左括号没有匹配到右括号，弹出左括号位置，生成编译错误。最后返回生成的IR.\n\n```rust ,noplaypen\nif let Some((_, line, col)) = stk.pop() {\n    return Err(CompileError {\n        line,\n        col,\n        kind: CompileErrorKind::UnclosedLeftBracket,\n    });\n}\nOk(code)\n```\n\n完整代码\n\n```rust,noplaypen\n{{#include ../../src/bfir.rs:38:84}}\n```\n\n## 简单优化\n\nbrainfuck 代码中经常有连续的算术加减和指针移动，这些操作完全可以折叠起来。\n\n优化函数直接操作 IR 序列，用一次遍历完成折叠，原地操作。时间复杂度 O(n)，空间复杂度 O(1)。\n\n这里定义两个宏来避免复制粘贴大量同样的代码。\n\n```rust,noplaypen\n{{#include ../../src/bfir.rs:88:132}}\n```\n\n## 简单测试\n\nRust 内置一套单元测试框架，在模块内随手写个函数，标上 `#[test]`，然后运行命令 `cargo test`。cargo 会收集所有测试，逐个运行，并报告结果。\n\n```rust,noplaypen\n{{#include ../../src/bfir.rs:134:161}}\n```\n"
  },
  {
    "path": "book/src/4.md",
    "content": "# 4. Hello, JIT\n\n通常来说，Just In Time (JIT) 编译器 是指在某段高阶代码即将运行时将其编译到机器码再执行的程序。下文中，我们把这样的程序叫做 \"JIT\"。\n\n一个最简单的 JIT 工作方式是这样的：\n\n1. 将源代码编译为机器码。\n2. 申请一段可写可执行内存，写入机器码。\n3. 跳转到这段内存，执行机器码。\n4. 执行完毕，稍作清理，退出。\n\n以下代码引用自 [Hello, JIT World: The Joy of Simple JITs](http://blog.reverberate.org/2012/12/hello-jit-world-joy-of-simple-jits.html)\n\n```c\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/mman.h>\n\nint main(int argc, char *argv[]) {\n  // 机器码：\n  //   mov eax, 0\n  //   ret\n  unsigned char code[] = {0xb8, 0x00, 0x00, 0x00, 0x00, 0xc3};\n\n  if (argc < 2) {\n    fprintf(stderr, \"Usage: jit1 <integer>\\n\");\n    return 1;\n  }\n\n  // 把用户给出的数值写入机器码，覆盖立即数 \"0\"\n  //   mov eax, <user's value>\n  //   ret\n  int num = atoi(argv[1]);\n  memcpy(&code[1], &num, 4);\n\n  // 分配可写可执行内存\n  // 注意：真实的程序不应该映射同时可写可执行的内存，\n  // 这里有安全风险。\n  void *mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC,\n                   MAP_ANON | MAP_PRIVATE, -1, 0);\n  memcpy(mem, code, sizeof(code));\n\n  // 定义一个函数指针指向机器码内存，再执行函数\n  int (*func)() = mem;\n  return func();\n}\n```\n\n编写 JIT 的一大难点是如何生成机器码，这里通常有跨平台问题、可读性消失问题。\n\n最笨的方法：写一段汇编，用汇编器生成机器码，再复制到高级代码里。但这样不具有通用性，开发效率非常低。\n\n## dynasm\n\n[DynAsm](http://luajit.org/dynasm.html) 是 LuaJIT 的一部分，它用预处理器把混合汇编的 C 文件转换成 纯 C 文件，还包含一个微型运行时，用来执行运行时工作。\n\n[dynasm-rs](https://crates.io/crates/dynasm) 是对应的 Rust 实现，用过程宏在编译期解析汇编语法，也包含微型运行时。\n\nRust 过程宏作为编译器插件几乎是万能的，不光是汇编，html、shell、cpp 等语言都能嵌入，转换成对应的 Rust 结构，给人一种相当纯粹的感觉。过程宏还有很多用途，感兴趣的可以自行研究。\n\n```bash\ncargo add dynasm dynasmrt\n```\n\n修改 main.rs，导入 dynasm.\n\n```rust ,noplaypen\nmod bfir;\n\nuse dynasm::dynasm;\nuse dynasmrt::{DynasmApi, DynasmLabelApi};\n\nuse std::io::{stdout, Write};\n```\n\n编写 print 函数，使用 \"sysv64\" ABI。\n\nx86-64 Linux 系统上默认为 System V ABI. [相关文档](https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI)\n\n```rust ,noplaypen\nunsafe extern \"sysv64\" fn print(buf: *const u8, len: u64) -> u8 {\n    let buf = std::slice::from_raw_parts(buf, len as usize);\n    stdout().write_all(buf).is_err() as u8\n}\n```\n\n首先初始化汇编器，指定架构为 x64，全局标签 hello 指向字符串。\n\n\n```rust ,noplaypen\nfn main() {\n    let mut ops = dynasmrt::x64::Assembler::new().unwrap();\n    let string = b\"Hello, JIT!\\n\";\n\n    dynasm!(ops\n        ; .arch x64\n        ; ->hello:\n        ; .bytes string\n    );\n```\n\ndynasm 使用 nasm 的方言，左操作数为目标，右操作数为源。\n\nsysv64 调用约定规定 rdi, rsi, rdx, rcx 存放前四个整数参数，rax 存放返回值。\n\n```rust ,noplaypen\n    let hello = ops.offset();\n    dynasm!(ops\n        ; lea rdi, [->hello]                // 将 hello 字符串地址放入 rdi\n        ; mov rsi, QWORD string.len() as _  // 将 字符串长度放入 rsi\n        ; mov rax, QWORD print as _         // 将 print 函数地址放入 rax\n        ; call rax                          // 调用函数\n        ; ret                               // 返回\n    );\n```\n\n完成汇编，取得可执行缓冲区。根据偏移拿到函数地址，强制转换为函数指针。最后调用机器码，得到结果。\n\n```rust ,noplaypen\n    let buf = ops.finalize().unwrap();\n\n    let hello_fn: unsafe extern \"sysv64\" fn() -> u8 =\n        unsafe { std::mem::transmute(buf.ptr(hello)) };\n\n    let ret = unsafe { hello_fn() };\n\n    assert_eq!(ret, 0);\n}\n```\n\n运行结果\n\n```bash\n$ cargo run\n    Finished dev [unoptimized + debuginfo] target(s) in 1.30s\n     Running `target/debug/bfjit`\nHello, JIT!\n```\n\n\n完整代码\n\n```rust ,noplaypen\nmod bfir;\n\nuse dynasm::dynasm;\nuse dynasmrt::{DynasmApi, DynasmLabelApi};\n\nuse std::io::{stdout, Write};\n\nunsafe extern \"sysv64\" fn print(buf: *const u8, len: u64) -> u8 {\n    let buf = std::slice::from_raw_parts(buf, len as usize);\n    stdout().write_all(buf).is_err() as u8\n}\n\nfn main() {\n    let mut ops = dynasmrt::x64::Assembler::new().unwrap();\n    let string = b\"Hello, JIT!\\n\";\n\n    dynasm!(ops\n        ; .arch x64\n        ; ->hello:\n        ; .bytes string\n    );\n\n    let hello = ops.offset();\n    dynasm!(ops\n        ; lea rdi, [->hello]\n        ; mov rsi, QWORD string.len() as _\n        ; mov rax, QWORD print as _\n        ; call rax\n        ; ret\n    );\n\n    let buf = ops.finalize().unwrap();\n\n    let hello_fn: unsafe extern \"sysv64\" fn() -> u8 =\n        unsafe { std::mem::transmute(buf.ptr(hello)) };\n\n    let ret = unsafe { hello_fn() };\n\n    assert_eq!(ret, 0);\n}\n```\n\n## 如何处理 panic\n\n跨越 Rust 边界的 panic 是未定义行为，我们很难让汇编去匹配 unwind ABI。\n\n暴露给外部调用的 Rust 函数最好捕获 panic，用其他方式去处理。\n\n例如这样 \n\n```rust\nunsafe extern \"sysv64\" fn print(buf: *const u8, len: u64) -> u8 {\n    let ret = std::panic::catch_unwind(|| {\n        let buf = std::slice::from_raw_parts(buf, len as usize);\n        stdout().write_all(buf).is_err()\n    });\n    match ret {\n        Ok(false) => 0,\n        Ok(true) => 1,\n        Err(_) => 2,\n    }\n}\n```"
  },
  {
    "path": "book/src/5.md",
    "content": "# 5. 来点错误\n\n添加一个错误模块\n\nsrc/main.rs\n\n```rust ,noplaypen\nmod error;\n```\n\nsrc/error.rs\n\n```rust ,noplaypen\n{{#include ../../src/error.rs}}\n```\n\n虚拟机运行时可能出现两种错误，IO 错误和指针溢出。\n\n虚拟机首先需要读取源代码，可能出现IO错误，然后将源代码编译为 IR，可能发生编译错误，最后运行程序，可能有运行时错误。\n"
  },
  {
    "path": "book/src/6.md",
    "content": "# 6. 实现虚拟机\n\n添加模块 src/bfjit.rs\n\n导入必要的类型\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:1:9}}\n```\n\n\n虚拟机定义与 Brainfuck 机器模型一致。\n\n机器码缓冲区，起始偏移，字节数组，输入输出流。\n\n字节数组大小至少为 30000，这里设置为 4 MiB.\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:13:19}}\n```\n\n准备汇编可调用的函数，brainfuck 通过 unsafe 函数与虚拟机交互。\n\n为了传出可能的错误，把错误移动到堆上，返回裸指针。您也可以选择其他方式来传出错误。\n\n在 FFI 时完善地处理 panic 和 backtrace 是一个复杂的问题。为了不增加过多处理代码，这里选择忽略 unsafe 函数中的 panic 问题。在代码正确的情况下，panic 应该不会发生。\n\n请注意：跨语言的栈展开 (stack unwind) 是未定义行为，有可能引发段错误，您需要仔细研究 ABI 才能解决它。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:21:52}}\n```\n\n用输入流、输出流、源文件路径初始化虚拟机，优化选项也由外部提供。\n\ncompile 方法暂时留空。\n\n```rust ,noplaypen\nimpl BfVM<'_> {\n    fn compile(code: &[BfIR]) -> Result<(dynasmrt::ExecutableBuffer, dynasmrt::AssemblyOffset)> {\n        todo!()\n    }\n```\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:54:79}}\n```\n\n即时编译出的裸函数接收虚拟机指针和字节数组的边界指针，返回错误指针。\n\n执行函数后检查错误指针，如果非空，就把错误从堆上移动到栈上再返回。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:81:102}}\n```"
  },
  {
    "path": "book/src/7.md",
    "content": "# 7. 生成机器码\n\n完成上一节留空的 compile 方法。\n\n整个 brainfuck 程序将被编译为一个大函数，在上一节的 run 方法中我们已经指定了该函数的签名。\n\n```rust,noplaypen\ntype RawFn = unsafe extern \"sysv64\" fn(\n    this: *mut BfVM<'_>,\n    memory_start: *mut u8,\n    memory_end: *const u8,\n) -> *mut VMError;\n```\n\n在 compile 方法中，首先初始化汇编器，函数起始地址就是最开始的偏移。\n\nloops 作为栈，用来存放动态标签，指引跳转。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:104:110}}\n```\n\nsysv64 调用约定规定 rdi, rsi, rdx, rcx 存放前四个整数参数，rax 存放返回值，这些属于易失性寄存器，在调用子函数时其内容可能丢失。\n\nrbp, rbx, r12 ~ r15 是非易失性寄存器，在调用子函数时不会丢失。如果函数中会占用这些寄存器，也要在开头和结尾相应地保存和恢复它们的内容。\n\n我们在注释里记录函数会用到的所有寄存器。rdi, rsi, rdx 对应函数的三个参数，我们将其保存到 r12, r13, r14 寄存器。函数中需要一个 ptr 变量记录 brainfuck 程序的当前指针，我们使用 r15 寄存器。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:112:115}}\n```\n\n汇编函数开始，首先把 rax 压栈。x86-64-psABI 规定参数区域的结尾按16字节对齐。函数开始时返回地址压栈，此时 栈指针+8 是 16 的倍数，因此再把 rax 压栈，使栈指针对齐，以便之后的函数调用，rax 的内容没有意义。\n\n由于函数中用到 r12 ~ r15 非易失性寄存器，将其压栈保存。注意这里压入 4 个 8 字节寄存器，栈指针仍然对齐。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:117:127}}\n```\n\n每个 IR 依次映射到汇编。\n\n指针移动，需要检查算术溢出和数组边界溢出，出错即跳转到全局标签所指的错误处理区域。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:129:143}}\n```\n\n单个字节的算术加减，允许溢出。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:144:149}}\n```\n\nIO 操作。首先保存当前数据指针寄存器，将虚拟机函数所需的各参数和函数地址放入寄存器，调用函数。\n\n如果函数返回的不是空指针，说明出错，应该跳转到IO错误处理区域。\n\n最后恢复数据指针寄存器。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:150:165}}\n```\n\n跳转指令。利用 dynasm 提供的 api， 创建两个动态标签，分别生成跳转汇编。由于编译到 IR 时已经验证过跳转指令的对应关系，这里的栈可以直接弹出。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:166:186}}\n```\n\n正常退出函数时应该返回空指针，表示没有错误。\n\n溢出时生成一个溢出错误，IO错误时错误指针已经存入 rax，无需处理。\n\n最后退栈，与函数开始时的压栈对应，维持栈平衡。注意退栈时不能破坏 rax 中的返回值。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:188:203}}\n```\n\n完成汇编，取出可执行缓冲区，返回。\n\n```rust,noplaypen\n{{#include ../../src/bfjit.rs:205:210}}\n```\n"
  },
  {
    "path": "book/src/8.md",
    "content": "# 8. 命令行界面\n\n虚拟机已经完成，剩下的就是把它包装成命令行界面 (CLI) 了。\n\n我们使用 clap 库，用结构体定义命令行参数解析。\n\n<https://github.com/clap-rs/clap>\n\n```bash\ncargo add clap --features derive\n```\n\n这就是 main.rs 的全部代码。\n\n```rust,noplaypen\n{{#include ../../src/main.rs}}\n```\n\n把写好的命令行应用安装到系统。\n\n```bash\n$ cargo install --path .\n$ bfjit --help\nUsage: bfjit [OPTIONS] <FILE>\n\nArguments:\n  <FILE>  \n\nOptions:\n  -o, --optimize  Optimize code\n  -h, --help      Print help\n  -V, --version   Print version\n```\n\n从 github 上找一些 brainfuck 程序运行，观察 JIT 与解释器的效率差别。\n\n```bash\n$ bfjit bf/hello.bf\nHello World!\n```\n\n观察折叠操作对速度的影响。\n\n```bash\n$ time bfjit bf/mendelbrot.bf > m.txt\n\nreal    0m5.858s\nuser    0m5.840s\nsys     0m0.012s\n\n$ time bfjit bf/mendelbrot.bf -o > m.txt\n\nreal    0m1.921s\nuser    0m1.903s\nsys     0m0.010s\n```\n\n甚至可以运行一层 brainfuck 自解释器。\n\n注意：多层自解释器的效率会严重下降，短时间内无法得出结果。\n\n<https://github.com/cagataycali/awesome-brainfuck>\n\n<http://homepages.xnet.co.nz/~clive/eigenratios/cgbfi2.b>\n\n"
  },
  {
    "path": "book/src/SUMMARY.md",
    "content": "# Summary\n\n[介绍](introduction.md)\n\n- [背景知识](./1.md)\n- [启动项目](./2.md)\n- [中间表示](./3.md)\n- [Hello, JIT](./4.md)\n- [来点错误](./5.md)\n- [实现虚拟机](./6.md)\n- [生成机器码](./7.md)\n- [命令行界面](./8.md)\n\n[结语](./conclusion.md)\n"
  },
  {
    "path": "book/src/conclusion.md",
    "content": "# 结语\n\n本教程基于 dynasm 实现了一个 Brainfuck JIT 虚拟机，主要功能有 Brainfuck 解析编译、简单优化、动态生成机器码，并提供了友好的命令行界面。\n\n希望本项目对有兴趣深入研究 JIT 技术的人有所帮助。\n\n欢迎 PR 来进一步改进本项目。\n\n第三方依赖：\n\n<https://crates.io/crates/dynasm>\n\n<https://github.com/dtolnay/thiserror>\n\n<https://github.com/clap-rs/clap>\n"
  },
  {
    "path": "book/src/introduction.md",
    "content": "# Brainfuck JIT 虚拟机教程\n\n当我们谈到 JIT 时，通常会想到 V8、JVM 之类的庞然大物，然后望而生畏，觉得 JIT 是一种极其高深复杂的技术。\n\n但 JIT 也可以变得非常简单，我们不需要做完善的优化和分析，只要输入源码，输出机器指令，再执行，这和普通的文本处理程序没什么区别。\n\n在本教程中，我们将用 Rust 语言实现一个简单的 Brainfuck JIT 虚拟机，逐步理解 JIT 技术。\n"
  },
  {
    "path": "justfile",
    "content": "build:\n    cd book && mdbook build\n\nserve:\n    cd book && mdbook serve --open\n\ndev:\n    just fmt\n    just lint\n    just test\n\nfmt *ARGS:\n    cargo fmt --all {{ARGS}}\n\nlint *ARGS:\n    cargo clippy --all-features --tests --benches {{ARGS}}\n\ntest *ARGS:\n    cargo test --all-features {{ARGS}}\n    cargo run --release -- bf/hello.bf\n    cargo run --release -- bf/hello.bf -o\n    cargo run --release -- bf/mendelbrot.bf\n    cargo run --release -- bf/mendelbrot.bf -o\n\nci:\n    just fmt --check\n    just lint -- -D warnings\n    just test\n"
  },
  {
    "path": "src/bfir.rs",
    "content": "use std::fmt;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum BfIR {\n    AddVal(u8),  // +\n    SubVal(u8),  // -\n    AddPtr(u32), // >\n    SubPtr(u32), // <\n    GetByte,     // ,\n    PutByte,     // .\n    Jz,          // [\n    Jnz,         // ]\n}\n\n#[derive(Debug, thiserror::Error)]\npub enum CompileErrorKind {\n    #[error(\"Unclosed left bracket\")]\n    UnclosedLeftBracket,\n    #[error(\"Unexpected right bracket\")]\n    UnexpectedRightBracket,\n}\n\n#[derive(Debug)]\npub struct CompileError {\n    line: u32,\n    col: u32,\n    kind: CompileErrorKind,\n}\n\nimpl fmt::Display for CompileError {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{} at line {}:{}\", self.kind, self.line, self.col)\n    }\n}\n\nimpl std::error::Error for CompileError {}\n\npub fn compile(src: &str) -> Result<Vec<BfIR>, CompileError> {\n    let mut code: Vec<BfIR> = vec![];\n\n    let mut stk: Vec<(u32, u32, u32)> = vec![];\n\n    let mut line: u32 = 1;\n    let mut col: u32 = 0;\n\n    for ch in src.chars() {\n        col += 1;\n        match ch {\n            '\\n' => {\n                line += 1;\n                col = 0;\n            }\n            '+' => code.push(BfIR::AddVal(1)),\n            '-' => code.push(BfIR::SubVal(1)),\n            '>' => code.push(BfIR::AddPtr(1)),\n            '<' => code.push(BfIR::SubPtr(1)),\n            ',' => code.push(BfIR::GetByte),\n            '.' => code.push(BfIR::PutByte),\n            '[' => {\n                let pos = code.len() as u32;\n                stk.push((pos, line, col));\n                code.push(BfIR::Jz)\n            }\n            ']' => {\n                stk.pop().ok_or(CompileError {\n                    line,\n                    col,\n                    kind: CompileErrorKind::UnexpectedRightBracket,\n                })?;\n\n                code.push(BfIR::Jnz)\n            }\n            _ => {}\n        }\n    }\n    if let Some((_, line, col)) = stk.pop() {\n        return Err(CompileError {\n            line,\n            col,\n            kind: CompileErrorKind::UnclosedLeftBracket,\n        });\n    }\n    Ok(code)\n}\n\npub fn optimize(code: &mut Vec<BfIR>) {\n    let len = code.len();\n    let mut i = 0;\n    let mut pc = 0;\n\n    macro_rules! _fold_ir {\n        ($variant:ident, $x:ident) => {{\n            let mut j = i + 1;\n            while j < len {\n                if let $variant(d) = code[j] {\n                    $x = $x.wrapping_add(d);\n                } else {\n                    break;\n                }\n                j += 1;\n            }\n            i = j;\n            code[pc] = $variant($x);\n            pc += 1;\n        }};\n    }\n\n    macro_rules! _normal_ir {\n        () => {{\n            code[pc] = code[i];\n            pc += 1;\n            i += 1;\n        }};\n    }\n\n    use BfIR::*;\n    while i < len {\n        match code[i] {\n            AddPtr(mut x) => _fold_ir!(AddPtr, x),\n            SubPtr(mut x) => _fold_ir!(SubPtr, x),\n            AddVal(mut x) => _fold_ir!(AddVal, x),\n            SubVal(mut x) => _fold_ir!(SubVal, x),\n            GetByte => _normal_ir!(),\n            PutByte => _normal_ir!(),\n            Jz => _normal_ir!(),\n            Jnz => _normal_ir!(),\n        }\n    }\n\n    code.truncate(pc);\n    code.shrink_to_fit();\n}\n\n#[test]\nfn test_compile() {\n    assert_eq!(\n        compile(\"+[,.]\").unwrap(),\n        vec![\n            BfIR::AddVal(1),\n            BfIR::Jz,\n            BfIR::GetByte,\n            BfIR::PutByte,\n            BfIR::Jnz,\n        ]\n    );\n\n    match compile(\"[\").unwrap_err().kind {\n        CompileErrorKind::UnclosedLeftBracket => {}\n        _ => panic!(),\n    };\n\n    match compile(\"]\").unwrap_err().kind {\n        CompileErrorKind::UnexpectedRightBracket => {}\n        _ => panic!(),\n    };\n\n    let mut code = compile(\"[+++++]\").unwrap();\n    optimize(&mut code);\n    assert_eq!(code, vec![BfIR::Jz, BfIR::AddVal(5), BfIR::Jnz]);\n}\n"
  },
  {
    "path": "src/bfjit.rs",
    "content": "use crate::bfir::{self, BfIR};\nuse crate::error::{Result, RuntimeError, VMError};\n\nuse std::io::{Read, Write};\nuse std::path::Path;\nuse std::ptr;\n\nuse dynasm::dynasm;\nuse dynasmrt::{DynasmApi, DynasmLabelApi};\n\nconst MEMORY_SIZE: usize = 4 * 1024 * 1024;\n\npub struct BfVM<'io> {\n    code: dynasmrt::ExecutableBuffer,\n    start: dynasmrt::AssemblyOffset,\n    memory: Box<[u8]>,\n    input: Box<dyn Read + 'io>,\n    output: Box<dyn Write + 'io>,\n}\n\n#[inline(always)]\nfn vm_error(re: RuntimeError) -> *mut VMError {\n    let e = Box::new(VMError::from(re));\n    Box::into_raw(e)\n}\n\nimpl BfVM<'_> {\n    unsafe extern \"sysv64\" fn getbyte(this: *mut Self, ptr: *mut u8) -> *mut VMError {\n        let mut buf = [0_u8];\n        let this = &mut *this;\n        match this.input.read(&mut buf) {\n            Ok(0) => {}\n            Ok(1) => *ptr = buf[0],\n            Err(e) => return vm_error(RuntimeError::IO(e)),\n            _ => unreachable!(),\n        }\n        ptr::null_mut()\n    }\n\n    unsafe extern \"sysv64\" fn putbyte(this: *mut Self, ptr: *const u8) -> *mut VMError {\n        let buf = std::slice::from_ref(&*ptr);\n        let this = &mut *this;\n        match this.output.write_all(buf) {\n            Ok(()) => ptr::null_mut(),\n            Err(e) => vm_error(RuntimeError::IO(e)),\n        }\n    }\n\n    unsafe extern \"sysv64\" fn overflow_error() -> *mut VMError {\n        vm_error(RuntimeError::PointerOverflow)\n    }\n}\n\nimpl<'io> BfVM<'io> {\n    pub fn new(\n        file_path: &Path,\n        input: Box<dyn Read + 'io>,\n        output: Box<dyn Write + 'io>,\n        optimize: bool,\n    ) -> Result<Self> {\n        let src = std::fs::read_to_string(file_path)?;\n        let mut ir = bfir::compile(&src)?;\n        drop(src);\n\n        if optimize {\n            bfir::optimize(&mut ir);\n        }\n        let (code, start) = Self::compile(&ir)?;\n        drop(ir);\n\n        let memory = vec![0; MEMORY_SIZE].into_boxed_slice();\n        Ok(Self {\n            code,\n            start,\n            memory,\n            input,\n            output,\n        })\n    }\n\n    pub fn run(&mut self) -> Result<()> {\n        type RawFn = unsafe extern \"sysv64\" fn(\n            this: *mut BfVM<'_>,\n            memory_start: *mut u8,\n            memory_end: *const u8,\n        ) -> *mut VMError;\n\n        let raw_fn: RawFn = unsafe { std::mem::transmute(self.code.ptr(self.start)) };\n\n        let this: *mut Self = self;\n        let memory_start = self.memory.as_mut_ptr();\n        let memory_end = unsafe { memory_start.add(MEMORY_SIZE) };\n\n        let ret: *mut VMError = unsafe { raw_fn(this, memory_start, memory_end) };\n\n        if ret.is_null() {\n            Ok(())\n        } else {\n            Err(*unsafe { Box::from_raw(ret) })\n        }\n    }\n}\n\nimpl BfVM<'_> {\n    #[allow(clippy::fn_to_numeric_cast)]\n    fn compile(code: &[BfIR]) -> Result<(dynasmrt::ExecutableBuffer, dynasmrt::AssemblyOffset)> {\n        let mut ops = dynasmrt::x64::Assembler::new()?;\n        let start = ops.offset();\n\n        let mut loops = vec![];\n\n        // this:         rdi r12\n        // memory_start: rsi r13\n        // memory_end:   rdx r14\n        // ptr:              r15\n\n        dynasm!(ops\n            ; push rax\n            ; push r12\n            ; push r13\n            ; push r14\n            ; push r15\n            ; mov r12, rdi   // save this\n            ; mov r13, rsi   // save memory_start\n            ; mov r14, rdx   // save memory_end\n            ; mov r15, rsi   // ptr = memory_start\n        );\n\n        use BfIR::*;\n        for &ir in code {\n            match ir {\n                AddPtr(x) => dynasm!(ops\n                    ; add r15, x as i32     // ptr += x\n                    ; jc  ->overflow        // jmp if overflow\n                    ; cmp r15, r14          // ptr - memory_end\n                    ; jnb ->overflow        // jmp if ptr >= memory_end\n                ),\n                SubPtr(x) => dynasm!(ops\n                    ; sub r15, x as i32     // ptr -= x\n                    ; jc  ->overflow        // jmp if overflow\n                    ; cmp r15, r13          // ptr - memory_start\n                    ; jb  ->overflow        // jmp if ptr < memory_start\n                ),\n                AddVal(x) => dynasm!(ops\n                    ; add BYTE [r15], x as i8    // *ptr += x\n                ),\n                SubVal(x) => dynasm!(ops\n                    ; sub BYTE [r15], x as i8    // *ptr -= x\n                ),\n                GetByte => dynasm!(ops\n                    ; mov  rdi, r12         // arg0: this\n                    ; mov  rsi, r15         // arg1: ptr\n                    ; mov  rax, QWORD BfVM::getbyte as *const () as _\n                    ; call rax              // getbyte(this, ptr)\n                    ; test rax, rax\n                    ; jnz  ->io_error       // jmp if rax != 0\n                ),\n                PutByte => dynasm!(ops\n                    ; mov  rdi, r12         // arg0: this\n                    ; mov  rsi, r15         // arg1: ptr\n                    ; mov  rax, QWORD BfVM::putbyte as *const () as _\n                    ; call rax              // putbyte(this, ptr)\n                    ; test rax, rax\n                    ; jnz  ->io_error       // jmp if rax != 0\n                ),\n                Jz => {\n                    let left = ops.new_dynamic_label();\n                    let right = ops.new_dynamic_label();\n                    loops.push((left, right));\n\n                    dynasm!(ops\n                        ; cmp BYTE [r15], 0\n                        ; jz => right       // jmp if *ptr == 0\n                        ; => left\n                    )\n                }\n                Jnz => {\n                    let (left, right) = loops.pop().unwrap();\n                    dynasm!(ops\n                        ; cmp BYTE [r15], 0\n                        ; jnz => left       // jmp if *ptr != 0\n                        ; => right\n                    )\n                }\n            }\n        }\n\n        dynasm!(ops\n            ; xor rax, rax\n            ; jmp >exit\n            ; -> overflow:\n            ; mov rax, QWORD BfVM::overflow_error as *const () as _\n            ; call rax\n            ; jmp >exit\n            ; -> io_error:\n            ; exit:\n            ; pop r15\n            ; pop r14\n            ; pop r13\n            ; pop r12\n            ; pop rdx\n            ; ret\n        );\n\n        let code = ops.finalize().unwrap();\n\n        Ok((code, start))\n    }\n}\n"
  },
  {
    "path": "src/error.rs",
    "content": "#[derive(Debug, thiserror::Error)]\npub enum RuntimeError {\n    #[error(\"IO: {0}\")]\n    IO(#[from] std::io::Error),\n\n    #[error(\"Pointer overflow\")]\n    PointerOverflow,\n}\n\n#[derive(Debug, thiserror::Error)]\npub enum VMError {\n    #[error(\"IO: {0}\")]\n    IO(#[from] std::io::Error),\n\n    #[error(\"Compile: {0}\")]\n    Compile(#[from] crate::bfir::CompileError),\n\n    #[error(\"Runtime: {0}\")]\n    Runtime(#[from] RuntimeError),\n}\n\npub type Result<T> = std::result::Result<T, VMError>;\n"
  },
  {
    "path": "src/main.rs",
    "content": "mod bfir;\nmod bfjit;\nmod error;\n\nuse crate::bfjit::BfVM;\n\nuse std::io::{stdin, stdout};\nuse std::path::PathBuf;\n\nuse clap::Parser;\n\n#[derive(Debug, clap::Parser)]\n#[clap(version)]\nstruct Opt {\n    #[clap(name = \"FILE\")]\n    file_path: PathBuf,\n\n    #[clap(short = 'o', long = \"optimize\", help = \"Optimize code\")]\n    optimize: bool,\n}\n\nfn main() {\n    let opt = Opt::parse();\n\n    let stdin = stdin();\n    let stdout = stdout();\n\n    let ret = BfVM::new(\n        &opt.file_path,\n        Box::new(stdin.lock()),\n        Box::new(stdout.lock()),\n        opt.optimize,\n    )\n    .and_then(|mut vm| vm.run());\n\n    if let Err(e) = &ret {\n        eprintln!(\"bfjit: {e}\");\n    }\n\n    std::process::exit(ret.is_err() as i32)\n}\n"
  }
]