[
  {
    "path": "CONTRIBUTING.md",
    "content": "# How to Contribute\n\nWe'd love to accept your patches and contributions to this project. There are\njust a few small guidelines you need to follow.\n\n## Contributor License Agreement\n\nContributions to this project must be accompanied by a Contributor License\nAgreement. You (or your employer) retain the copyright to your contribution;\nthis simply gives us permission to use and redistribute your contributions as\npart of the project. Head over to <https://cla.developers.google.com/> to see\nyour current agreements on file or to sign a new one.\n\nYou generally only need to submit a CLA once, so if you've already submitted one\n(even if it was for a different project), you probably don't need to do it\nagain.\n\n## Code Reviews\n\nAll submissions, including submissions by project members, require review. We\nuse GitHub pull requests for this purpose. Consult\n[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more\ninformation on using pull requests.\n\n## Community Guidelines\n\nThis project follows [Google's Open Source Community\nGuidelines](https://opensource.google/conduct/)."
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. 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\n   2. 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\n   3. 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\n   4. 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\n   5. 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\n   6. 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\n   7. 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\n   8. 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\n   9. 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\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: 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\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Fiber\n\nFiber implements an proof-of-concept Python decorator that rewrites a function\nso that it can be paused and resumed (by moving stack variables to a heap frame\nand adding if statements to simulate jumps/gotos to specific lines of code).\n\nThen, using a trampoline function that simulates the call stack on the heap, we\ncan call functions that recurse arbitrarily deeply without stack overflowing\n(assuming we don't run out of heap memory).\n\n```python3\ncache = {}\n\n@fiber.fiber(locals=locals())\ndef fib(n):\n    assert n >= 0\n    if n in cache:\n        return cache[n]\n    if n == 0:\n        return 0\n    if n == 1:\n        return 1\n    cache[n] = fib(n-1) + fib(n-2)\n    return cache[n]\n\nprint(sys.getrecursionlimit())  # 1000 by default\n\n# https://www.wolframalpha.com/input/?i=fib%281010%29+mod+10**5\nprint(trampoline.run(fib, [1010]) % 10 ** 5) # 74305\n```\n\nPlease do not use this in production.\n\n## TOC\n\n* [Fiber](#fiber)\n   * [How it works](#how-it-works)\n   * [Performance](#performance)\n   * [Limitations](#limitations)\n      * [Possible improvements](#possible-improvements)\n   * [Questions](#questions)\n      * [Why didn't you use Python generators?](#why-didnt-you-use-python-generators)\n      * [Why did you write this?](#why-did-you-write-this)\n   * [Contributing](#contributing)\n   * [License](#license)\n   * [Disclaimer](#disclaimer)\n\n## How it works\n\nA quick refresher on the call stack: normally, when some function A calls\nanother function B, A is \"paused\" while B runs to completion. Then, once B\nfinishes, A is resumed.\n\nIn order to move the call stack to the heap, we need to transform function A\nto (1) store all variables on the heap, and (2) be able to resume execution\nat specific lines of code within the function.\n\nThe first step is easy: we rewrite all local loads and stores to instead load\nand store in a frame dictionary that is passed into the function. The second is\nmore difficult: because Python doesn't support goto statements, we have to\ninsert if statements to skip the code prefix that we don't want to execute.\n\nThere are a variety of [\"special\nforms\"](https://www.gnu.org/software/emacs/manual/html_node/elisp/Special-Forms.html)\nthat cannot be jumped into. These we must handle by rewriting them into a form\nthat we do handle.\n\nFor example, if we recursively call a function inside a for loop, we would like\nto be able to resume execution on the same iteration. However, when Python\nexecutes a for loop on an non-iterator iterable it will create a new iterator\nevery time. To handle this case, we rewrite for loops into the equivalent while\nloop. Similarly, we must rewrite boolean expressions that short circuit (`and`,\n`or`) into the equivalent if statements.\n\nLastly, we must replace all recursive calls and normal returns by instead\nreturning an instruction to a trampoline to call the child function or return\nthe value to the parent function, respectively.\n\nTo recap, here are the AST passes we currently implement:\n\n1. Rewrite special forms:\n   - `for_to_while`: Transforms for loops into the equivalent while loops.\n   - `promote_while_cond`: Rewrites the while conditional to use a temporary\n     variable that is updated every loop iteration so that we can control when\n     it is evaluated (e.g. if the loop condition includes a recursive call).\n   - `bool_exps_to_if`: Converts `and` and `or` expressions into the\n     equivalent if statements.\n1. `promote_to_temporary`: Assigns the results of recursive calls into\n   temporary variables. This is necessary when we make multiple recursive calls\n   in the same statement (e.g. `fib(n-1) + fib(n-2)`): we need to resume\n   execution in the middle of the expression.\n1. `remove_trivial_temporaries`: Removes temporaries that are assigned to only\n   once and are directly assigned to some other variable, replacing subsequent\n   usages with that other variable. This helps us detect tail calls.\n1. `insert_jumps`: Marks the statement after yield points (currently recursive\n   calls and normal returns) with a `pc` index, and inserts if statements so\n   that re-execution of the function will resume at that program counter.\n1. `lift_locals_to_frame`: Replaces loads and stores of local variables to\n   loads and stores in the frame object.\n1. `add_trampoline_returns`: Replaces places where we must yield (recursive\n   calls and normal returns) with returns to the trampoline function.\n1. `fix_fn_def`: Rewrites the function defintion to take a `frame` parameter.\n\nSee the [`examples`](examples) directory for functions and the results after\neach AST pass. Also, see [`src/trampoline_test.py`](src/trampoline_test.py) for\nsome test cases.\n\n## Performance\n\nA simple tail-recursive function that computes the sum of an array takes about\n10-11 seconds to compute with Fiber. 1000 iterations of the equivalent for loop\ntakes 7-8 seconds to compute. So we are slower by roughly a factor of 1000.\n\n```python3\nlst = list(range(1, 100001))\n\n# fiber\n@fiber.fiber(locals=locals())\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    return sum(lst[1:], acc + lst[0])\n\n# for loop\ntotal = 0\nfor i in lst:\n    total += i\n\nprint(total, trampoline.run(sum, [lst, 0]))  # 5000050000, 5000050000\n```\n\nWe could improve the performance of the code by eliminating redundant if\nchecks in the generated code. Also, as we statically know the stack variables,\nwe can use an array for the stack frame and integer indexes (instead of a\ndictionary and string hashes + lookups). This should improve the performance\nsignificantly, but there will still probably be a large amount of overhead.\n\nAnother performance improvement is to inline the stack array: instead of\nstoring a list of frames in the trampoline, we could variables directly in the\nstack. Again, we can compute the frame size statically. Based on some tests in\na handwritten JavaScript implementation, this has the potential to speed up the\ncode by roughly a factor of 2-3, at the cost of a more complex implementation.\n\n## Limitations\n\n- The transformation works on the AST level, so we don't support other\n  decorators (for example, we cannot use\n  [functools.cache](https://docs.python.org/3.10/library/functools.html#functools.cache)\n  in the above Fibonacci example).\n\n- The function can only access variables that are passed in the `locals=`\n  argument. As a consequence of this, to resolve recursive function calls,\n  we maintain a global mapping of all fiber functions by name. This means that\n  fibers must have distinct names.\n\n- We don't support some special forms (ternaries, comprehensions). These can\n  easily be added as a rewrite transformation.\n\n- We don't support exceptions. This would require us to keep track of exception\n  handlers in the trampoline and insert returns to the trampoline to register\n  and deregister handlers.\n\n- We don't support generators. To add support, we would have to modify the\n  trampoline to accept another operation type (yield) that sends a value to the\n  function that called `next()`. Also, the trampoline would have to support\n  multiple call stacks.\n\n\n### Possible improvements\n\n- Improve test coverage on some of the AST transformations.\n  - `remove_trivial_temporaries` may have a bug if the variable that it is\n    replaced with is reassigned to another value.\n- Support more special forms (comprehensions, generators).\n- Support exceptions.\n- Support recursive calls that don't read the return value.\n\n## Questions\n\n### Why didn't you use Python generators?\n\nIt's less interesting as the transformations are easier. Here, we are\neffectively implementing generators in userspace (i.e. not needing VM support);\nsee the answer to the next question for why this is useful.\n\nAlso, people have used generators to do this; see [one recent generator\nexample](https://hurryabit.github.io/blog/stack-safety-for-free/).\n\n### Why did you write this?\n\n- [A+ project for CS 61A at\n  Berkeley.](https://web.archive.org/web/20211208153249/https://cs61a.org/articles/about/#a-grades)\n  During the course, we created a Scheme interpreter. The extra credit\n  question we to replace tail calls in Python with a return to a trampoline,\n  with the goal that tail call optimization in Python would let us evaluate\n  tail calls to arbitrary depth in Scheme, in constant space.\n\n  The test cases for the question checked whether interpreting tail-call\n  recursive functions in Scheme caused a Python stack overflow. Using this\n  Fiber implementation, (1) without tail call optimization in our trampoline,\n  we would still be able to pass the test cases (we just wouldn't use constant\n  space) and (2) we can now evaluate any Scheme expression to arbitrary depth,\n  even if they are not in tail form.\n\n- The React framework has an a bug open which explores a compiler transform to\n  rewrite JavaScript generators to a state machine so that recursive operations\n  (render, reconcilation) can be written more easily. This is necessary because\n  some JavaScript engines still don't support generators.\n\n  This project basically implements a rough version of that compiler transform\n  as a proof of concept, just in Python.\n  https://github.com/facebook/react/pull/18942\n\n## Contributing\n\nSee [`CONTRIBUTING.md`](CONTRIBUTING.md) for more details.\n\n## License\n\nApache 2.0; see [`LICENSE`](LICENSE) for more details.\n\n## Disclaimer\n\nThis is a personal project, not an official Google project. It is not supported\nby Google and Google specifically disclaims all warranties as to its quality,\nmerchantability, or fitness for a particular purpose.\n\n"
  },
  {
    "path": "examples/edit_distance.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Pass (0): Start\n\ndef edit_distance__helper(f, s):\n    if f == len(first):\n        return len(second) - s\n    if s == len(second):\n        return len(first) - f\n\n    if first[f] == second[s]:\n        return edit_distance__helper(f + 1, s + 1)\n\n    del_f = edit_distance__helper(f + 1, s) + 1\n    replace = edit_distance__helper(f + 1, s + 1) + 1\n    del_s = edit_distance__helper(f, s + 1) + 1\n\n    return min(del_f, replace, del_s)\n\n\n# ------------------------------------\n\n\n# Pass (1): for_to_while\n\ndef edit_distance__helper(f, s):\n    if f == len(first):\n        return len(second) - s\n    if s == len(second):\n        return len(first) - f\n\n    if first[f] == second[s]:\n        return edit_distance__helper(f + 1, s + 1)\n\n    del_f = edit_distance__helper(f + 1, s) + 1\n    replace = edit_distance__helper(f + 1, s + 1) + 1\n    del_s = edit_distance__helper(f, s + 1) + 1\n\n    return min(del_f, replace, del_s)\n\n\n# ------------------------------------\n\n\n# Pass (2): promote_while_cond\n\ndef edit_distance__helper(f, s):\n    if f == len(first):\n        return len(second) - s\n    if s == len(second):\n        return len(first) - f\n\n    if first[f] == second[s]:\n        return edit_distance__helper(f + 1, s + 1)\n\n    del_f = edit_distance__helper(f + 1, s) + 1\n    replace = edit_distance__helper(f + 1, s + 1) + 1\n    del_s = edit_distance__helper(f, s + 1) + 1\n\n    return min(del_f, replace, del_s)\n\n\n# ------------------------------------\n\n\n# Pass (3): bool_exps_to_if\n\ndef edit_distance__helper(f, s):\n    if f == len(first):\n        return len(second) - s\n    if s == len(second):\n        return len(first) - f\n\n    if first[f] == second[s]:\n        return edit_distance__helper(f + 1, s + 1)\n\n    del_f = edit_distance__helper(f + 1, s) + 1\n    replace = edit_distance__helper(f + 1, s + 1) + 1\n    del_s = edit_distance__helper(f, s + 1) + 1\n\n    return min(del_f, replace, del_s)\n\n\n# ------------------------------------\n\n\n# Pass (4): promote_to_temporary_m\n\ndef edit_distance__helper(f, s):\n    if f == len(first):\n        return len(second) - s\n    if s == len(second):\n        return len(first) - f\n\n    if first[f] == second[s]:\n        __tmp0__ = edit_distance__helper(f + 1, s + 1)\n        return __tmp0__\n\n    __tmp1__ = edit_distance__helper(f + 1, s)\n    del_f = __tmp1__ + 1\n    __tmp2__ = edit_distance__helper(f + 1, s + 1)\n    replace = __tmp2__ + 1\n    __tmp3__ = edit_distance__helper(f, s + 1)\n    del_s = __tmp3__ + 1\n\n    return min(del_f, replace, del_s)\n\n\n# ------------------------------------\n\n\n# Pass (5): remove_trivial_temporaries\n\ndef edit_distance__helper(f, s):\n    if f == len(first):\n        return len(second) - s\n    if s == len(second):\n        return len(first) - f\n\n    if first[f] == second[s]:\n        return edit_distance__helper(f + 1, s + 1)\n\n    __tmp1__ = edit_distance__helper(f + 1, s)\n    del_f = __tmp1__ + 1\n    __tmp2__ = edit_distance__helper(f + 1, s + 1)\n    replace = __tmp2__ + 1\n    __tmp3__ = edit_distance__helper(f, s + 1)\n    del_s = __tmp3__ + 1\n\n    return min(del_f, replace, del_s)\n\n\n# ------------------------------------\n\n\n# Pass (6): insert_jumps\n\ndef edit_distance__helper(f, s):\n    if __pc == 0:\n        if f == len(first):\n            if __pc == 0:\n                return len(second) - s\n                __pc = 1\n        if s == len(second):\n            if __pc == 0:\n                return len(first) - f\n                __pc = 1\n\n        if first[f] == second[s]:\n            if __pc == 0:\n                return edit_distance__helper(f + 1, s + 1)\n                __pc = 1\n        __pc = 1\n\n    if __pc == 1:\n        __tmp1__ = edit_distance__helper(f + 1, s)\n        __pc = 2\n    if __pc == 2:\n        del_f = __tmp1__ + 1\n        __tmp2__ = edit_distance__helper(f + 1, s + 1)\n        __pc = 3\n    if __pc == 3:\n        replace = __tmp2__ + 1\n        __tmp3__ = edit_distance__helper(f, s + 1)\n        __pc = 4\n\n    if __pc == 4:\n        del_s = __tmp3__ + 1\n        return min(del_f, replace, del_s)\n        __pc = 5\n\n\n# ------------------------------------\n\n\n# Pass (7): lift_locals_to_frame\n\ndef edit_distance__helper(f, s):\n    if frame['__pc'] == 0:\n        if frame['f'] == len(first):\n            if frame['__pc'] == 0:\n                return len(second) - frame['s']\n                frame['__pc'] = 1\n        if frame['s'] == len(second):\n            if frame['__pc'] == 0:\n                return len(first) - frame['f']\n                frame['__pc'] = 1\n\n        if first[frame['f']] == second[frame['s']]:\n            if frame['__pc'] == 0:\n                return edit_distance__helper(frame['f'] + 1, frame['s'] + 1)\n                frame['__pc'] = 1\n        frame['__pc'] = 1\n\n    if frame['__pc'] == 1:\n        frame['__tmp1__'] = edit_distance__helper(frame['f'] + 1, frame['s'])\n        frame['__pc'] = 2\n    if frame['__pc'] == 2:\n        frame['del_f'] = frame['__tmp1__'] + 1\n        frame['__tmp2__'] = edit_distance__helper(frame['f'] + 1, frame['s'] + 1)\n        frame['__pc'] = 3\n    if frame['__pc'] == 3:\n        frame['replace'] = frame['__tmp2__'] + 1\n        frame['__tmp3__'] = edit_distance__helper(frame['f'], frame['s'] + 1)\n        frame['__pc'] = 4\n\n    if frame['__pc'] == 4:\n        frame['del_s'] = frame['__tmp3__'] + 1\n        return min(frame['del_f'], frame['replace'], frame['del_s'])\n        frame['__pc'] = 5\n\n\n# ------------------------------------\n\n\n# Pass (8): add_trampoline_returns\n\ndef edit_distance__helper(f, s):\n    if frame['__pc'] == 0:\n        if frame['f'] == len(first):\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=len(second) - frame['s'])\n        if frame['s'] == len(second):\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=len(first) - frame['f'])\n\n        if first[frame['f']] == second[frame['s']]:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return TailCallOp(func='edit_distance__helper', args=[frame['f'] + 1, frame['s'] + 1], kwargs={})\n        frame['__pc'] = 1\n\n    if frame['__pc'] == 1:\n        frame['__pc'] = 2\n        return CallOp(func='edit_distance__helper', args=[frame['f'] + 1, frame['s']], kwargs={}, ret_variable='__tmp1__')\n    if frame['__pc'] == 2:\n        frame['del_f'] = frame['__tmp1__'] + 1\n        frame['__pc'] = 3\n        return CallOp(func='edit_distance__helper', args=[frame['f'] + 1, frame['s'] + 1], kwargs={}, ret_variable='__tmp2__')\n    if frame['__pc'] == 3:\n        frame['replace'] = frame['__tmp2__'] + 1\n        frame['__pc'] = 4\n        return CallOp(func='edit_distance__helper', args=[frame['f'], frame['s'] + 1], kwargs={}, ret_variable='__tmp3__')\n\n    if frame['__pc'] == 4:\n        frame['del_s'] = frame['__tmp3__'] + 1\n        frame['__pc'] = 5\n        return RetOp(value=min(frame['del_f'], frame['replace'], frame['del_s']))\n\n\n# ------------------------------------\n\n\n# Pass (9): fix_fn_def\n\ndef __fiberfn_edit_distance__helper(frame):\n    if frame['__pc'] == 0:\n        if frame['f'] == len(first):\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=len(second) - frame['s'])\n        if frame['s'] == len(second):\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=len(first) - frame['f'])\n\n        if first[frame['f']] == second[frame['s']]:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return TailCallOp(func='edit_distance__helper', args=[frame['f'] + 1, frame['s'] + 1], kwargs={})\n        frame['__pc'] = 1\n\n    if frame['__pc'] == 1:\n        frame['__pc'] = 2\n        return CallOp(func='edit_distance__helper', args=[frame['f'] + 1, frame['s']], kwargs={}, ret_variable='__tmp1__')\n    if frame['__pc'] == 2:\n        frame['del_f'] = frame['__tmp1__'] + 1\n        frame['__pc'] = 3\n        return CallOp(func='edit_distance__helper', args=[frame['f'] + 1, frame['s'] + 1], kwargs={}, ret_variable='__tmp2__')\n    if frame['__pc'] == 3:\n        frame['replace'] = frame['__tmp2__'] + 1\n        frame['__pc'] = 4\n        return CallOp(func='edit_distance__helper', args=[frame['f'], frame['s'] + 1], kwargs={}, ret_variable='__tmp3__')\n\n    if frame['__pc'] == 4:\n        frame['del_s'] = frame['__tmp3__'] + 1\n        frame['__pc'] = 5\n        return RetOp(value=min(frame['del_f'], frame['replace'], frame['del_s']))\n\n\n# ------------------------------------\n\n\n"
  },
  {
    "path": "examples/fib.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Pass (0): Start\n\ndef fib(n):\n    if n in cache:\n        return cache[n]\n\n    if n == 0:\n        return 0\n    if n == 1:\n        return 1\n\n    cache[n] = fib(n - 1) + fib(n - 2)\n    return cache[n]\n\n\n# ------------------------------------\n\n\n# Pass (1): for_to_while\n\ndef fib(n):\n    if n in cache:\n        return cache[n]\n\n    if n == 0:\n        return 0\n    if n == 1:\n        return 1\n\n    cache[n] = fib(n - 1) + fib(n - 2)\n    return cache[n]\n\n\n# ------------------------------------\n\n\n# Pass (2): promote_while_cond\n\ndef fib(n):\n    if n in cache:\n        return cache[n]\n\n    if n == 0:\n        return 0\n    if n == 1:\n        return 1\n\n    cache[n] = fib(n - 1) + fib(n - 2)\n    return cache[n]\n\n\n# ------------------------------------\n\n\n# Pass (3): bool_exps_to_if\n\ndef fib(n):\n    if n in cache:\n        return cache[n]\n\n    if n == 0:\n        return 0\n    if n == 1:\n        return 1\n\n    cache[n] = fib(n - 1) + fib(n - 2)\n    return cache[n]\n\n\n# ------------------------------------\n\n\n# Pass (4): promote_to_temporary_m\n\ndef fib(n):\n    if n in cache:\n        return cache[n]\n\n    if n == 0:\n        return 0\n    if n == 1:\n        return 1\n\n    __tmp0__ = fib(n - 1)\n    __tmp1__ = fib(n - 2)\n\n    cache[n] = __tmp0__ + __tmp1__\n    return cache[n]\n\n\n# ------------------------------------\n\n\n# Pass (5): remove_trivial_temporaries\n\ndef fib(n):\n    if n in cache:\n        return cache[n]\n\n    if n == 0:\n        return 0\n    if n == 1:\n        return 1\n\n    __tmp0__ = fib(n - 1)\n    __tmp1__ = fib(n - 2)\n\n    cache[n] = __tmp0__ + __tmp1__\n    return cache[n]\n\n\n# ------------------------------------\n\n\n# Pass (6): insert_jumps\n\ndef fib(n):\n    if __pc == 0:\n        if n in cache:\n            if __pc == 0:\n                return cache[n]\n                __pc = 1\n\n        if n == 0:\n            if __pc == 0:\n                return 0\n                __pc = 1\n        if n == 1:\n            if __pc == 0:\n                return 1\n                __pc = 1\n\n        __tmp0__ = fib(n - 1)\n        __pc = 1\n    if __pc == 1:\n        __tmp1__ = fib(n - 2)\n        __pc = 2\n\n    if __pc == 2:\n        cache[n] = __tmp0__ + __tmp1__\n        return cache[n]\n        __pc = 3\n\n\n# ------------------------------------\n\n\n# Pass (7): lift_locals_to_frame\n\ndef fib(n):\n    if frame['__pc'] == 0:\n        if frame['n'] in cache:\n            if frame['__pc'] == 0:\n                return cache[frame['n']]\n                frame['__pc'] = 1\n\n        if frame['n'] == 0:\n            if frame['__pc'] == 0:\n                return 0\n                frame['__pc'] = 1\n        if frame['n'] == 1:\n            if frame['__pc'] == 0:\n                return 1\n                frame['__pc'] = 1\n\n        frame['__tmp0__'] = fib(frame['n'] - 1)\n        frame['__pc'] = 1\n    if frame['__pc'] == 1:\n        frame['__tmp1__'] = fib(frame['n'] - 2)\n        frame['__pc'] = 2\n\n    if frame['__pc'] == 2:\n        cache[frame['n']] = frame['__tmp0__'] + frame['__tmp1__']\n        return cache[frame['n']]\n        frame['__pc'] = 3\n\n\n# ------------------------------------\n\n\n# Pass (8): add_trampoline_returns\n\ndef fib(n):\n    if frame['__pc'] == 0:\n        if frame['n'] in cache:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=cache[frame['n']])\n\n        if frame['n'] == 0:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=0)\n        if frame['n'] == 1:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=1)\n\n        frame['__pc'] = 1\n        return CallOp(func='fib', args=[frame['n'] - 1], kwargs={}, ret_variable='__tmp0__')\n    if frame['__pc'] == 1:\n        frame['__pc'] = 2\n        return CallOp(func='fib', args=[frame['n'] - 2], kwargs={}, ret_variable='__tmp1__')\n\n    if frame['__pc'] == 2:\n        cache[frame['n']] = frame['__tmp0__'] + frame['__tmp1__']\n        frame['__pc'] = 3\n        return RetOp(value=cache[frame['n']])\n\n\n# ------------------------------------\n\n\n# Pass (9): fix_fn_def\n\ndef __fiberfn_fib(frame):\n    if frame['__pc'] == 0:\n        if frame['n'] in cache:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=cache[frame['n']])\n\n        if frame['n'] == 0:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=0)\n        if frame['n'] == 1:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=1)\n\n        frame['__pc'] = 1\n        return CallOp(func='fib', args=[frame['n'] - 1], kwargs={}, ret_variable='__tmp0__')\n    if frame['__pc'] == 1:\n        frame['__pc'] = 2\n        return CallOp(func='fib', args=[frame['n'] - 2], kwargs={}, ret_variable='__tmp1__')\n\n    if frame['__pc'] == 2:\n        cache[frame['n']] = frame['__tmp0__'] + frame['__tmp1__']\n        frame['__pc'] = 3\n        return RetOp(value=cache[frame['n']])\n\n\n# ------------------------------------\n\n\n"
  },
  {
    "path": "examples/matrix_chain_mult.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Pass (0): Start\n\ndef matrix_chain_mult__helper(i, j):\n    if i == j:\n        return 0\n\n    max_profit = float('-inf')\n    for k in range(i, j):\n        profit = matrix_chain_mult__helper(i, k)\n        profit += matrix_chain_mult__helper(k + 1, j)\n        profit += sizes[i - 1] * sizes[k] * sizes[j]\n        max_profit = max(max_profit, profit)\n\n    return max_profit\n\n\n# ------------------------------------\n\n\n# Pass (1): for_to_while\n\ndef matrix_chain_mult__helper(i, j):\n    if i == j:\n        return 0\n\n    max_profit = float('-inf')\n    __tmp0__ = iter(range(i, j))\n    __tmp1__ = True\n    while __tmp1__:\n        try:\n            k = next(__tmp0__)\n        except StopIteration:\n            __tmp1__ = False\n            continue\n        profit = matrix_chain_mult__helper(i, k)\n        profit += matrix_chain_mult__helper(k + 1, j)\n        profit += sizes[i - 1] * sizes[k] * sizes[j]\n        max_profit = max(max_profit, profit)\n\n    return max_profit\n\n\n# ------------------------------------\n\n\n# Pass (2): promote_while_cond\n\ndef matrix_chain_mult__helper(i, j):\n    if i == j:\n        return 0\n\n    max_profit = float('-inf')\n    __tmp0__ = iter(range(i, j))\n    __tmp1__ = True\n    while __tmp1__:\n        try:\n            k = next(__tmp0__)\n        except StopIteration:\n            __tmp1__ = False\n            continue\n        profit = matrix_chain_mult__helper(i, k)\n        profit += matrix_chain_mult__helper(k + 1, j)\n        profit += sizes[i - 1] * sizes[k] * sizes[j]\n        max_profit = max(max_profit, profit)\n\n    return max_profit\n\n\n# ------------------------------------\n\n\n# Pass (3): bool_exps_to_if\n\ndef matrix_chain_mult__helper(i, j):\n    if i == j:\n        return 0\n\n    max_profit = float('-inf')\n    __tmp0__ = iter(range(i, j))\n    __tmp1__ = True\n    while __tmp1__:\n        try:\n            k = next(__tmp0__)\n        except StopIteration:\n            __tmp1__ = False\n            continue\n        profit = matrix_chain_mult__helper(i, k)\n        profit += matrix_chain_mult__helper(k + 1, j)\n        profit += sizes[i - 1] * sizes[k] * sizes[j]\n        max_profit = max(max_profit, profit)\n\n    return max_profit\n\n\n# ------------------------------------\n\n\n# Pass (4): promote_to_temporary_m\n\ndef matrix_chain_mult__helper(i, j):\n    if i == j:\n        return 0\n\n    max_profit = float('-inf')\n    __tmp0__ = iter(range(i, j))\n    __tmp1__ = True\n    while __tmp1__:\n        try:\n            k = next(__tmp0__)\n        except StopIteration:\n            __tmp1__ = False\n            continue\n        __tmp2__ = matrix_chain_mult__helper(i, k)\n        profit = __tmp2__\n        __tmp3__ = matrix_chain_mult__helper(k + 1, j)\n        profit += __tmp3__\n        profit += sizes[i - 1] * sizes[k] * sizes[j]\n        max_profit = max(max_profit, profit)\n\n    return max_profit\n\n\n# ------------------------------------\n\n\n# Pass (5): remove_trivial_temporaries\n\ndef matrix_chain_mult__helper(i, j):\n    if i == j:\n        return 0\n\n    max_profit = float('-inf')\n    __tmp0__ = iter(range(i, j))\n    __tmp1__ = True\n    while __tmp1__:\n        try:\n            k = next(__tmp0__)\n        except StopIteration:\n            __tmp1__ = False\n            continue\n        profit = matrix_chain_mult__helper(i, k)\n        __tmp3__ = matrix_chain_mult__helper(k + 1, j)\n        profit += __tmp3__\n        profit += sizes[i - 1] * sizes[k] * sizes[j]\n        max_profit = max(max_profit, profit)\n\n    return max_profit\n\n\n# ------------------------------------\n\n\n# Pass (6): insert_jumps\n\ndef matrix_chain_mult__helper(i, j):\n    if __pc == 0:\n        if i == j:\n            if __pc == 0:\n                return 0\n                __pc = 1\n\n        max_profit = float('-inf')\n        __tmp0__ = iter(range(i, j))\n        __tmp1__ = True\n        __pc = 1\n    if 1 <= __pc < 4:\n        while __tmp1__:\n            if __pc == 1:\n                try:\n                    k = next(__tmp0__)\n                except StopIteration:\n                    __tmp1__ = False\n                    continue\n                profit = matrix_chain_mult__helper(i, k)\n                __pc = 2\n            if __pc == 2:\n                __tmp3__ = matrix_chain_mult__helper(k + 1, j)\n                __pc = 3\n            if __pc == 3:\n                profit += __tmp3__\n                profit += sizes[i - 1] * sizes[k] * sizes[j]\n                max_profit = max(max_profit, profit)\n                __pc = 4\n            __pc = 1\n        __pc = 4\n\n    if __pc == 4:\n        return max_profit\n        __pc = 5\n\n\n# ------------------------------------\n\n\n# Pass (7): lift_locals_to_frame\n\ndef matrix_chain_mult__helper(i, j):\n    if frame['__pc'] == 0:\n        if frame['i'] == frame['j']:\n            if frame['__pc'] == 0:\n                return 0\n                frame['__pc'] = 1\n\n        frame['max_profit'] = float('-inf')\n        frame['__tmp0__'] = iter(range(frame['i'], frame['j']))\n        frame['__tmp1__'] = True\n        frame['__pc'] = 1\n    if 1 <= frame['__pc'] < 4:\n        while frame['__tmp1__']:\n            if frame['__pc'] == 1:\n                try:\n                    frame['k'] = next(frame['__tmp0__'])\n                except StopIteration:\n                    frame['__tmp1__'] = False\n                    continue\n                frame['profit'] = matrix_chain_mult__helper(frame['i'], frame['k'])\n                frame['__pc'] = 2\n            if frame['__pc'] == 2:\n                frame['__tmp3__'] = matrix_chain_mult__helper(frame['k'] + 1, frame['j'])\n                frame['__pc'] = 3\n            if frame['__pc'] == 3:\n                frame['profit'] += frame['__tmp3__']\n                frame['profit'] += sizes[frame['i'] - 1] * sizes[frame['k']] * sizes[frame['j']]\n                frame['max_profit'] = max(frame['max_profit'], frame['profit'])\n                frame['__pc'] = 4\n            frame['__pc'] = 1\n        frame['__pc'] = 4\n\n    if frame['__pc'] == 4:\n        return frame['max_profit']\n        frame['__pc'] = 5\n\n\n# ------------------------------------\n\n\n# Pass (8): add_trampoline_returns\n\ndef matrix_chain_mult__helper(i, j):\n    if frame['__pc'] == 0:\n        if frame['i'] == frame['j']:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=0)\n\n        frame['max_profit'] = float('-inf')\n        frame['__tmp0__'] = iter(range(frame['i'], frame['j']))\n        frame['__tmp1__'] = True\n        frame['__pc'] = 1\n    if 1 <= frame['__pc'] < 4:\n        while frame['__tmp1__']:\n            if frame['__pc'] == 1:\n                try:\n                    frame['k'] = next(frame['__tmp0__'])\n                except StopIteration:\n                    frame['__tmp1__'] = False\n                    continue\n                frame['__pc'] = 2\n                return CallOp(func='matrix_chain_mult__helper', args=[frame['i'], frame['k']], kwargs={}, ret_variable='profit')\n            if frame['__pc'] == 2:\n                frame['__pc'] = 3\n                return CallOp(func='matrix_chain_mult__helper', args=[frame['k'] + 1, frame['j']], kwargs={}, ret_variable='__tmp3__')\n            if frame['__pc'] == 3:\n                frame['profit'] += frame['__tmp3__']\n                frame['profit'] += sizes[frame['i'] - 1] * sizes[frame['k']] * sizes[frame['j']]\n                frame['max_profit'] = max(frame['max_profit'], frame['profit'])\n                frame['__pc'] = 4\n            frame['__pc'] = 1\n        frame['__pc'] = 4\n\n    if frame['__pc'] == 4:\n        frame['__pc'] = 5\n        return RetOp(value=frame['max_profit'])\n\n\n# ------------------------------------\n\n\n# Pass (9): fix_fn_def\n\ndef __fiberfn_matrix_chain_mult__helper(frame):\n    if frame['__pc'] == 0:\n        if frame['i'] == frame['j']:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=0)\n\n        frame['max_profit'] = float('-inf')\n        frame['__tmp0__'] = iter(range(frame['i'], frame['j']))\n        frame['__tmp1__'] = True\n        frame['__pc'] = 1\n    if 1 <= frame['__pc'] < 4:\n        while frame['__tmp1__']:\n            if frame['__pc'] == 1:\n                try:\n                    frame['k'] = next(frame['__tmp0__'])\n                except StopIteration:\n                    frame['__tmp1__'] = False\n                    continue\n                frame['__pc'] = 2\n                return CallOp(func='matrix_chain_mult__helper', args=[frame['i'], frame['k']], kwargs={}, ret_variable='profit')\n            if frame['__pc'] == 2:\n                frame['__pc'] = 3\n                return CallOp(func='matrix_chain_mult__helper', args=[frame['k'] + 1, frame['j']], kwargs={}, ret_variable='__tmp3__')\n            if frame['__pc'] == 3:\n                frame['profit'] += frame['__tmp3__']\n                frame['profit'] += sizes[frame['i'] - 1] * sizes[frame['k']] * sizes[frame['j']]\n                frame['max_profit'] = max(frame['max_profit'], frame['profit'])\n                frame['__pc'] = 4\n            frame['__pc'] = 1\n        frame['__pc'] = 4\n\n    if frame['__pc'] == 4:\n        frame['__pc'] = 5\n        return RetOp(value=frame['max_profit'])\n\n\n# ------------------------------------\n\n\n"
  },
  {
    "path": "examples/sum.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Pass (0): Start\n\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    return sum(lst[1:], acc + lst[0])\n\n\n# ------------------------------------\n\n\n# Pass (1): for_to_while\n\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    return sum(lst[1:], acc + lst[0])\n\n\n# ------------------------------------\n\n\n# Pass (2): promote_while_cond\n\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    return sum(lst[1:], acc + lst[0])\n\n\n# ------------------------------------\n\n\n# Pass (3): bool_exps_to_if\n\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    return sum(lst[1:], acc + lst[0])\n\n\n# ------------------------------------\n\n\n# Pass (4): promote_to_temporary_m\n\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    __tmp0__ = sum(lst[1:], acc + lst[0])\n    return __tmp0__\n\n\n# ------------------------------------\n\n\n# Pass (5): remove_trivial_temporaries\n\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    return sum(lst[1:], acc + lst[0])\n\n\n# ------------------------------------\n\n\n# Pass (6): insert_jumps\n\ndef sum(lst, acc):\n    if __pc == 0:\n        if not lst:\n            if __pc == 0:\n                return acc\n                __pc = 1\n        return sum(lst[1:], acc + lst[0])\n        __pc = 1\n\n\n# ------------------------------------\n\n\n# Pass (7): lift_locals_to_frame\n\ndef sum(lst, acc):\n    if frame['__pc'] == 0:\n        if not frame['lst']:\n            if frame['__pc'] == 0:\n                return frame['acc']\n                frame['__pc'] = 1\n        return sum(frame['lst'][1:], frame['acc'] + frame['lst'][0])\n        frame['__pc'] = 1\n\n\n# ------------------------------------\n\n\n# Pass (8): add_trampoline_returns\n\ndef sum(lst, acc):\n    if frame['__pc'] == 0:\n        if not frame['lst']:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=frame['acc'])\n        frame['__pc'] = 1\n        return TailCallOp(func='sum', args=[frame['lst'][1:], frame['acc'] + frame['lst'][0]], kwargs={})\n\n\n# ------------------------------------\n\n\n# Pass (9): fix_fn_def\n\ndef __fiberfn_sum(frame):\n    if frame['__pc'] == 0:\n        if not frame['lst']:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=frame['acc'])\n        frame['__pc'] = 1\n        return TailCallOp(func='sum', args=[frame['lst'][1:], frame['acc'] + frame['lst'][0]], kwargs={})\n\n\n# ------------------------------------\n\n\n"
  },
  {
    "path": "examples/tree_recursion.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Pass (0): Start\n\ndef all_zeroes(tree):\n    if tree == 0:\n        return True\n    if not isinstance(tree, Tree):\n        return False\n\n    return all_zeroes(tree.left) and all_zeroes(tree.right)\n\n\n# ------------------------------------\n\n\n# Pass (1): for_to_while\n\ndef all_zeroes(tree):\n    if tree == 0:\n        return True\n    if not isinstance(tree, Tree):\n        return False\n\n    return all_zeroes(tree.left) and all_zeroes(tree.right)\n\n\n# ------------------------------------\n\n\n# Pass (2): promote_while_cond\n\ndef all_zeroes(tree):\n    if tree == 0:\n        return True\n    if not isinstance(tree, Tree):\n        return False\n\n    return all_zeroes(tree.left) and all_zeroes(tree.right)\n\n\n# ------------------------------------\n\n\n# Pass (3): bool_exps_to_if\n\ndef all_zeroes(tree):\n    if tree == 0:\n        return True\n    if not isinstance(tree, Tree):\n        return False\n\n    __tmp0__ = all_zeroes(tree.left)\n    if __tmp0__:\n        __tmp0__ = all_zeroes(tree.right)\n    return __tmp0__\n\n\n# ------------------------------------\n\n\n# Pass (4): promote_to_temporary_m\n\ndef all_zeroes(tree):\n    if tree == 0:\n        return True\n    if not isinstance(tree, Tree):\n        return False\n\n    __tmp1__ = all_zeroes(tree.left)\n    __tmp0__ = __tmp1__\n    if __tmp0__:\n        __tmp2__ = all_zeroes(tree.right)\n        __tmp0__ = __tmp2__\n    return __tmp0__\n\n\n# ------------------------------------\n\n\n# Pass (5): remove_trivial_temporaries\n\ndef all_zeroes(tree):\n    if tree == 0:\n        return True\n    if not isinstance(tree, Tree):\n        return False\n\n    __tmp0__ = all_zeroes(tree.left)\n    if __tmp0__:\n        __tmp0__ = all_zeroes(tree.right)\n    return __tmp0__\n\n\n# ------------------------------------\n\n\n# Pass (6): insert_jumps\n\ndef all_zeroes(tree):\n    if __pc == 0:\n        if tree == 0:\n            if __pc == 0:\n                return True\n                __pc = 1\n        if not isinstance(tree, Tree):\n            if __pc == 0:\n                return False\n                __pc = 1\n\n        __tmp0__ = all_zeroes(tree.left)\n        __pc = 1\n    if __pc == 1:\n        if __tmp0__:\n            if __pc == 1:\n                __tmp0__ = all_zeroes(tree.right)\n                __pc = 2\n        __pc = 2\n    if __pc == 2:\n        return __tmp0__\n        __pc = 3\n\n\n# ------------------------------------\n\n\n# Pass (7): lift_locals_to_frame\n\ndef all_zeroes(tree):\n    if frame['__pc'] == 0:\n        if frame['tree'] == 0:\n            if frame['__pc'] == 0:\n                return True\n                frame['__pc'] = 1\n        if not isinstance(frame['tree'], Tree):\n            if frame['__pc'] == 0:\n                return False\n                frame['__pc'] = 1\n\n        frame['__tmp0__'] = all_zeroes(frame['tree'].left)\n        frame['__pc'] = 1\n    if frame['__pc'] == 1:\n        if frame['__tmp0__']:\n            if frame['__pc'] == 1:\n                frame['__tmp0__'] = all_zeroes(frame['tree'].right)\n                frame['__pc'] = 2\n        frame['__pc'] = 2\n    if frame['__pc'] == 2:\n        return frame['__tmp0__']\n        frame['__pc'] = 3\n\n\n# ------------------------------------\n\n\n# Pass (8): add_trampoline_returns\n\ndef all_zeroes(tree):\n    if frame['__pc'] == 0:\n        if frame['tree'] == 0:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=True)\n        if not isinstance(frame['tree'], Tree):\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=False)\n\n        frame['__pc'] = 1\n        return CallOp(func='all_zeroes', args=[frame['tree'].left], kwargs={}, ret_variable='__tmp0__')\n    if frame['__pc'] == 1:\n        if frame['__tmp0__']:\n            if frame['__pc'] == 1:\n                frame['__pc'] = 2\n                return CallOp(func='all_zeroes', args=[frame['tree'].right], kwargs={}, ret_variable='__tmp0__')\n        frame['__pc'] = 2\n    if frame['__pc'] == 2:\n        frame['__pc'] = 3\n        return RetOp(value=frame['__tmp0__'])\n\n\n# ------------------------------------\n\n\n# Pass (9): fix_fn_def\n\ndef __fiberfn_all_zeroes(frame):\n    if frame['__pc'] == 0:\n        if frame['tree'] == 0:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=True)\n        if not isinstance(frame['tree'], Tree):\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=False)\n\n        frame['__pc'] = 1\n        return CallOp(func='all_zeroes', args=[frame['tree'].left], kwargs={}, ret_variable='__tmp0__')\n    if frame['__pc'] == 1:\n        if frame['__tmp0__']:\n            if frame['__pc'] == 1:\n                frame['__pc'] = 2\n                return CallOp(func='all_zeroes', args=[frame['tree'].right], kwargs={}, ret_variable='__tmp0__')\n        frame['__pc'] = 2\n    if frame['__pc'] == 2:\n        frame['__pc'] = 3\n        return RetOp(value=frame['__tmp0__'])\n\n\n# ------------------------------------\n\n\n"
  },
  {
    "path": "src/expressions.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nfrom collections.abc import Container\nimport utils\nimport itertools\n\n\ndef promote_call_expressions(expression: ast.AST, fns: Container[str], name_iter, assignments):\n    \"\"\"Given a expression, transforms call expressions to functions in fns by\n    promoting them to temporary variables. Appends promoting assignment\n    expressions to assignments. Returns the new expression with call expressions\n    replaced.\"\"\"\n    def map_attributes(field, expression):\n        return promote_call_expressions(expression, fns, name_iter, assignments)\n\n    # Recursively map the expression's attributes (e.g. subexpressions).\n    new_expression = utils.map_expression(expression, map_attributes)\n\n    # If the function is a special function, then lift the expression to a\n    # temporary. Also, replace the current expression with a reference to that\n    # temporary.\n    if isinstance(expression, ast.Call) and isinstance(expression.func, ast.Name) and expression.func.id in fns:\n        name = next(name_iter)\n        assignments.append(utils.make_assign(name, new_expression))\n        return utils.make_lookup(name)\n    return new_expression\n\n\ndef make_and_if(name: str, expression: ast.AST, body):\n    return ast.If(\n        test=utils.make_lookup(name),\n        body=body,\n        orelse=[],\n    )\n\n\ndef make_or_if(name: str, expression: ast.AST, body):\n    return ast.If(\n        test=utils.make_not(utils.make_lookup(name)),\n        body=body,\n        orelse=[],\n    )\n\n\ndef promote_boolean_expression_operands(expression: ast.AST, name_iter, lines):\n    \"\"\"Given a expression, transforms boolean expressions by promoting their\n    operands to temporary values assigned to by if expressions.  Returns the\n    resulting temporary variable, and appends to lines the corresponding if\n    expressions that populate the variable.\n    \"\"\"\n    def map_attributes(field, expression):\n        # If the expression is a boolop, append if statements to lines.\n        if isinstance(expression, ast.BoolOp):\n            assert len(expression.values) > 0\n            maker = make_or_if if isinstance(\n                expression.op, ast.Or) else make_and_if\n            name = next(name_iter)\n            lines.append(utils.make_assign(name, expression.values[0]))\n            for child in itertools.islice(expression.values, 1, None):\n                body = []\n                body.append(promote_boolean_expression_operands(\n                    utils.make_assign(name, child),\n                    name_iter,\n                    body,\n                ))\n                lines.append(maker(name, child, body))\n            return utils.make_lookup(name)\n        return promote_boolean_expression_operands(expression, name_iter, lines)\n\n    # Recursively map the expression's attributes (e.g. subexpressions).\n    return utils.map_expression(expression, map_attributes)\n\n\nFRAME_LOCAL_NAME = \"frame\"\n\n\ndef promote_variable_access(expression: ast.AST, name_fn):\n    def map_attributes(field, expression):\n        if isinstance(expression, ast.Name) and (name := name_fn(expression.id)) is not None:\n            return ast.Subscript(\n                ctx=expression.ctx,\n                slice=ast.Constant(value=name),\n                value=ast.Name(id=FRAME_LOCAL_NAME, ctx=ast.Load())\n            )\n        return promote_variable_access(expression, name_fn)\n    return utils.map_expression(expression, map_attributes)\n"
  },
  {
    "path": "src/fiber.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nfrom collections import ChainMap\nfrom dataclasses import dataclass\nimport inspect\nfrom typing import Any, Container, Dict, List, Set, Union\nimport textwrap\n\nimport jumps\nimport mappers\nimport utils\n\n\ndef get_tree(fn):\n    lines = textwrap.dedent(inspect.getsource(fn)).split(\"\\n\")\n    for i, line in enumerate(lines):\n        if line.startswith(\"def\"):\n            break\n    return ast.parse(\"\\n\".join(lines[i:]))\n\n\ndef fn_call_names(stmt: ast.AST, fns: Container[str]):\n    for node in ast.walk(stmt):\n        if isinstance(node, ast.Call):\n            if isinstance(node.func, ast.Name) and node.func.id in fns:\n                yield node.func.id\n\n\ndef make_prev_dict(block: ast.AST):\n    prev_dict = {}\n\n    def helper(block: ast.AST):\n        assert utils.is_block(block)\n        for i, stmt in enumerate(block.body):\n            if 0 <= i - 1:\n                assert stmt not in prev_dict\n                prev_dict[stmt] = block.body[i - 1]\n        for stmt in block.body:\n            if utils.is_block(stmt):\n                helper(stmt)\n    helper(block)\n    return prev_dict\n\n\n@dataclass\nclass CallOp:\n    func: Any\n    args: List[Any]\n    kwargs: Dict[Any, Any]\n    ret_variable: str\n\n\n@dataclass\nclass TailCallOp:\n    func: Any\n    args: List[Any]\n    kwargs: Dict[Any, Any]\n\n\n@dataclass\nclass RetOp:\n    value: Any\n\n\nOP_MAP = {\n    CallOp.__name__: CallOp,\n    TailCallOp.__name__: TailCallOp,\n    RetOp.__name__: RetOp,\n}\n\n\ndef matches_call(call: Union[ast.expr, None], fns: Container[str]):\n    return isinstance(call, ast.Call) \\\n        and isinstance(call.func, ast.Name) \\\n        and call.func.id in fns\n\n\ndef matches_callop(stmt: ast.AST, fns: Container[str]):\n    return isinstance(stmt, ast.Assign) and \\\n        len(stmt.targets) == 1 and \\\n        isinstance(target := stmt.targets[0], ast.Subscript) and \\\n        isinstance(target.value, ast.Name) and \\\n        target.value.id == \"frame\" and \\\n        matches_call(stmt.value, fns)\n\n\ndef matches_tailcallop(stmt: ast.AST, fns: Container[str]):\n    return isinstance(stmt, ast.Return) and matches_call(stmt.value, fns)\n\n\ndef matches_retop(stmt: ast.AST, fns: Container[str]):\n    return isinstance(stmt, ast.Return)\n\n\ndef is_pc_assign(stmt: ast.AST):\n    return isinstance(stmt, ast.Assign) and \\\n        len(stmt.targets) == 1 and \\\n        isinstance(target := stmt.targets[0], ast.Subscript) and \\\n        isinstance(target.value, ast.Name) and \\\n        target.value.id == \"frame\" and \\\n        isinstance(name := target.slice, ast.Constant) and \\\n        name.value == jumps.PC_LOCAL_NAME and \\\n        isinstance(stmt.value, ast.Constant) and \\\n        isinstance(stmt.value.value, int)\n\n\ndef is_tail_call(stmt: ast.AST):\n    return isinstance(stmt, ast.Return) and \\\n        isinstance(stmt.value, ast.Call)\n\n\ndef make_callop_expr(variable: ast.Constant, call: ast.Call):\n    return ast.Return(\n        value=ast.Call(\n            func=utils.make_lookup(CallOp.__name__),\n            args=[],\n            keywords=[\n                ast.keyword(arg=\"func\", value=ast.Constant(\n                    value=call.func.id)),\n                ast.keyword(arg=\"args\", value=ast.List(\n                    elts=call.args, ctx=ast.Load())),\n                ast.keyword(arg=\"kwargs\", value=ast.Dict(\n                    keys=[ast.Constant(k.arg) for k in call.keywords], values=[k.value for k in call.keywords])),\n                ast.keyword(arg=\"ret_variable\", value=variable),\n            ]\n        )\n    )\n\n\ndef make_tailcallop_expr(call: ast.Call):\n    return ast.Return(\n        value=ast.Call(\n            func=utils.make_lookup(TailCallOp.__name__),\n            args=[],\n            keywords=[\n                ast.keyword(arg=\"func\", value=ast.Constant(\n                    value=call.func.id)),\n                ast.keyword(arg=\"args\", value=ast.List(\n                    elts=call.args, ctx=ast.Load())),\n                ast.keyword(arg=\"kwargs\", value=ast.Dict(\n                    keys=[ast.Constant(k.arg) for k in call.keywords], values=[k.value for k in call.keywords])),\n            ]\n        )\n    )\n\n\ndef make_retop_expr(value: ast.AST):\n    return ast.Return(\n        value=ast.Call(\n            func=utils.make_lookup(RetOp.__name__),\n            args=[],\n            keywords=[\n                ast.keyword(arg=\"value\", value=value)\n            ]\n        )\n    )\n\n\ndef make_arguments():\n    return ast.arguments(\n        posonlyargs=[],\n        args=[ast.arg(arg=\"frame\")],\n        kwonlyargs=[],\n        kwarg=None,\n        vararg=None,\n        defaults=[],\n        kw_defaults=[],\n    )\n\n\ndef fix_fn_def(fn_tree: ast.FunctionDef, fn):\n    fn_tree.name = f\"__fiberfn_{fn.__name__}\"\n    fn_tree.args = make_arguments()\n\n\ndef fiber_locals(fn_tree: ast.FunctionDef):\n    local_vars = utils.local_vars(fn_tree)\n    local_vars.add(jumps.PC_LOCAL_NAME)\n    return local_vars\n\n\ndef insert_jumps(fn_tree: ast.FunctionDef, prev_dict, fns):\n    prev_dict = make_prev_dict(fn_tree)\n    body, _ = jumps.insert_jumps(\n        fn_tree.body, jump_to=lambda stmt: needs_jump(stmt, prev_dict, fns))\n    return body\n\n\ndef lift_locals_to_frame(fn_tree: ast.FunctionDef):\n    local_vars = fiber_locals(fn_tree)\n    return mappers.map_scope(fn_tree, mappers.lift_to_frame_m(\n        name_fn=lambda x: x if x in local_vars else None))\n\n\ndef needs_jump(stmt: ast.AST, prev_dict, fns):\n    if not stmt in prev_dict:\n        return False\n\n    # Check whether the child function is a trampoline.\n    fn_calls = list(fn_call_names(prev_dict[stmt], fns))\n    if not fn_calls:\n        return False\n    for name in fn_calls:\n        if not (name in FIBER_FN_NAME_MAP or name in fns):\n            return False\n\n    return not is_tail_call(prev_dict[stmt])\n\n\ndef compile_tree(tree: ast.AST, fn, local_vars):\n    tree = ast.fix_missing_locations(tree)\n    code = compile(tree, f\"<fiber> {inspect.getfile(fn)}\", \"exec\")\n    results = {}\n    exec(code, dict([*fn.__globals__.items(), *\n         OP_MAP.items(), *local_vars.items()]), results)\n    results[tree.body[0].name].__fibercode__ = ast.unparse(tree)\n    return results[tree.body[0].name]\n\n\n# This is hacky...\n\n@dataclass\nclass FiberMetadata:\n    fn_def: ast.FunctionDef\n    fn: Any\n\n\nFIBER_FN_NAME_MAP = {}\nFIBER_FN_COMPILED_MAP = {}\n\n\ndef add_trampoline_returns(block: ast.AST, fns: Container[str]):\n    \"\"\"Recursively mutates the block by replacing a function call or a return\n    statement with a return to a trampoline. Also moves the PC assignment to\n    before the return to the trampoline.\n\n    We assume that all recursive calls have been lifted to temporaries, and\n    tail calls are in `return call()` form (trivial temporary eliminated).\"\"\"\n    assert utils.is_block(block)\n    # Make a shallow copy, as we mutate the list as we iterate (by swapping).\n    body = block.body\n    for index, stmt in enumerate(list(body)):\n        if utils.is_block(stmt):\n            add_trampoline_returns(stmt, fns)\n            continue\n        if matches_callop(stmt, fns):\n            replaced = make_callop_expr(stmt.targets[0].slice, stmt.value)\n        elif matches_tailcallop(stmt, fns):\n            replaced = make_tailcallop_expr(stmt.value)\n        elif matches_retop(stmt, fns):\n            replaced = make_retop_expr(stmt.value)\n        else:\n            continue\n        assert index + 1 < len(body)\n        assert is_pc_assign(body[index + 1])\n        body[index], body[index + 1] = body[index+1], replaced\n\n\ndef fiber(fns: Container[str] = None, *, locals, recursive=True):\n    \"\"\"Returns a decorator that converts a function to a fiber.\n\n    A fiber is a userspace scheduled thread. In this fiber implementation, we\n    yield to the userspace scheduler whenever a listed function is called.\n\n    Using the trampoline scheduler, we can functions that recurse arbitrarily\n    deep by simulating the call stack on the heap: Suppose we are executing a\n    function A. When A reaches a call to some function B in fns, instead of\n    calling the B directly, A will return a call operation to a trampoline. The\n    trampoline will call the B with the correct arguments. After B finishes\n    executing, the trampoline will resume A, passing B's return value.\n\n    >>> @fiber(locals=locals())\n    ... def fib(n):\n    ...     if n <= 1: return n\n    ...     return fib(n-1) + fib(n-2)\n    ...\n    >>> import trampoline\n    >>> trampoline.run(fib, [10])\n    55\n    \"\"\"\n\n    if fns is None:\n        fns = set()\n    for fiber_fn in FIBER_FN_NAME_MAP:\n        fns = set(fns)\n        fns.add(fiber_fn)\n    if callable(fns):\n        raise ValueError(\"Did you forget to call the fiber decorator?\")\n\n    def make_fiber(fn):\n        if recursive:\n            fns.add(fn.__name__)\n\n        tree = get_tree(fn)\n        name_iter, fn_tree = utils.dunder_names(), tree.body[0]\n        assert isinstance(fn_tree, ast.FunctionDef)\n\n        transforms = [\n            mappers.for_to_while_m(name_iter),\n            mappers.promote_while_cond_m(name_iter),\n            mappers.bool_exps_to_if_m(name_iter),\n            mappers.promote_to_temporary_m(fns, name_iter),\n        ]\n        for t in transforms:\n            fn_tree = mappers.map_scope(fn_tree, t)\n\n        # These mappers need access to the new tree to preprocess variables.\n        fn_tree = mappers.map_scope(fn_tree, mappers.remove_trivial_temporaries_m(fn_tree))\n\n        prev_dict = make_prev_dict(fn_tree)\n        fn_tree.body = insert_jumps(fn_tree, prev_dict, fns)\n        fn_tree = lift_locals_to_frame(fn_tree)\n        add_trampoline_returns(fn_tree, fns)\n        fix_fn_def(fn_tree, fn)\n\n        tree.body[0] = fn_tree\n        fiber_fn = compile_tree(tree, fn, locals)\n\n        lookup = FiberMetadata(get_tree(fn).body[0], fiber_fn)\n        FIBER_FN_NAME_MAP[fn.__name__] = lookup\n        FIBER_FN_COMPILED_MAP[fiber_fn] = lookup\n        return fiber_fn\n\n    return make_fiber\n"
  },
  {
    "path": "src/fiber_test.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nimport fiber\n\n\nclass TestFiber(unittest.TestCase):\n\n    def test_fib(self):\n        @fiber.fiber(locals=locals())\n        def fib(n):\n            if n == 0:\n                return 0\n            if n == 1:\n                return 1\n            return fib(n-1) + fib(n=n-2)\n        self.maxDiff = None\n\n        want = \"\"\"\ndef __fiberfn_fib(frame):\n    if frame['__pc'] == 0:\n        if frame['n'] == 0:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=0)\n        if frame['n'] == 1:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=1)\n        frame['__pc'] = 1\n        return CallOp(func='fib', args=[frame['n'] - 1], kwargs={}, ret_variable='__tmp0__')\n    if frame['__pc'] == 1:\n        frame['__pc'] = 2\n        return CallOp(func='fib', args=[], kwargs={'n': frame['n'] - 2}, ret_variable='__tmp1__')\n    if frame['__pc'] == 2:\n        frame['__pc'] = 3\n        return RetOp(value=frame['__tmp0__'] + frame['__tmp1__'])\n        \"\"\".strip()\n        self.assertEqual(want, fib.__fibercode__)\n\n    def test_sum(self):\n        @fiber.fiber(locals=locals())\n        def sum(lst, acc):\n            if not lst:\n                return acc\n            return sum(lst[1:], acc + lst[0])\n\n        want = \"\"\"\ndef __fiberfn_sum(frame):\n    if frame['__pc'] == 0:\n        if not frame['lst']:\n            if frame['__pc'] == 0:\n                frame['__pc'] = 1\n                return RetOp(value=frame['acc'])\n        frame['__pc'] = 1\n        return TailCallOp(func='sum', args=[frame['lst'][1:], frame['acc'] + frame['lst'][0]], kwargs={})\n        \"\"\".strip()\n        self.assertEqual(want, sum.__fibercode__)\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "src/jumps.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nfrom typing import List, Callable, Iterable\nimport utils\n\nPC_LOCAL_NAME = \"__pc\"\n\n\ndef is_supported_jump_block(b: ast.AST):\n    return any(isinstance(b, t) for t in (ast.While, ast.If))\n\n\ndef block_has_jump_to(block, jump_to: Callable[[ast.AST], bool]):\n    return any(has_jump_to(stmt, jump_to) for stmt in block.body)\n\n\ndef has_jump_to(stmt: ast.AST, jump_to: Callable[[ast.AST], bool]):\n    return jump_to(stmt) or (is_supported_jump_block(stmt) and block_has_jump_to(stmt, jump_to))\n\n\ndef partition_stmts(stmts: Iterable[ast.AST], jump_to: Callable[[ast.AST], bool]):\n    \"\"\"Splits statements into partitions with jump_to statements as dividers.\n    The first statement in each partition is one that needs to be jumped to.\"\"\"\n    current = []\n    for stmt in stmts:\n        if has_jump_to(stmt, jump_to):\n            yield current\n            current = []\n        current.append(stmt)\n    yield current\n\n\ndef transform_if(stmt: ast.If, jump_to: Callable[[ast.AST], bool], next_pc):\n    body, next_pc = insert_jumps(\n        stmt.body, jump_to, next_pc)\n    return ast.If(test=stmt.test, body=body, orelse=stmt.orelse), next_pc\n\n\ndef transform_while(stmt: ast.While, jump_to: Callable[[ast.AST], bool], next_pc):\n    first_pc = next_pc\n    body, next_pc = insert_jumps(stmt.body, jump_to, next_pc)\n    # While loops jump back to the start of the loop.\n    body.append(utils.make_assign(PC_LOCAL_NAME, ast.Constant(first_pc)))\n    return ast.While(test=stmt.test, body=body, orelse=stmt.orelse), next_pc\n\n\ndef make_range_test(start_pc, end_pc):\n    \"\"\"Creates an boolean expression AST that checks whether the pc variable is\n    in range(start, end).\"\"\"\n    if start_pc + 1 == end_pc:\n        return ast.Compare(\n            left=utils.make_lookup(PC_LOCAL_NAME),\n            ops=[ast.Eq()],\n            comparators=[ast.Constant(value=start_pc)]\n        )\n    return ast.Compare(\n        left=ast.Constant(value=start_pc),\n        ops=[ast.LtE(), ast.Lt()],\n        comparators=[utils.make_lookup(\n            PC_LOCAL_NAME), ast.Constant(value=end_pc)],\n    )\n\n\ndef transform_partition(partition, jump_to, next_pc):\n    \"\"\"Recursively transforms the partition, and wraps it in the appropriate if\n    statement. Returns the new AST as well as the next pc value.\"\"\"\n    body = []\n    start_pc = next_pc\n    next_pc += 1  # Need at least one PC for this partition.\n    for stmt in partition:\n        transformed = stmt\n        if isinstance(stmt, ast.If):\n            # For blocks, the first inner PC is the same PC as the outer PC.\n            transformed, next_pc = transform_if(stmt, jump_to, next_pc-1)\n        elif isinstance(stmt, ast.While):\n            transformed, next_pc = transform_while(stmt, jump_to, next_pc-1)\n        body.append(transformed)\n    end_pc = next_pc\n    body.append(utils.make_assign(PC_LOCAL_NAME, ast.Constant(end_pc)))\n\n    return ast.If(test=make_range_test(start_pc, end_pc), body=body, orelse=[]), next_pc\n\n\ndef insert_jumps(stmts: Iterable[ast.AST], jump_to: Callable[[ast.AST], bool], start_pc=0):\n    \"\"\"Inserts ifs into a sequence of statements such that each statement for\n    which jump_to returns True has a pc value where entering the sequence with\n    that value jumps to that statement.\n\n    Only recursively inserts jumps inside child if and for blocks. If your\n    block has for loops, then use for_to_while_m to rewrite them to while.\n\n    Returns a new list of statements and the total number of jumps inserted.\n    \"\"\"\n    new_stmts = []\n    next_pc = start_pc\n    for partition in partition_stmts(stmts, jump_to):\n        if not partition:\n            continue\n        transformed, next_pc = transform_partition(partition, jump_to, next_pc)\n        new_stmts.append(transformed)\n    return new_stmts, next_pc\n"
  },
  {
    "path": "src/jumps_test.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nimport unittest\n\nimport jumps\n\n\nclass TestInsertJumps(unittest.TestCase):\n\n    def test_complex(self):\n        source = \"\"\"\ndef bar(hello, world):\n    for i in range(10):\n        print(hello)\n    a = hello + world\n    while b < a:\n        print()\n        b = a * a\n        a = a + b\n    if True:\n        d = a + b\n        d = d * 2\n    d = d + 1\n    d = d + 2\n    return d\n        \"\"\".strip()\n\n        want = \"\"\"\ndef bar(hello, world):\n    if __pc == 0:\n        for i in range(10):\n            print(hello)\n        __pc = 1\n    if __pc == 1:\n        a = hello + world\n        __pc = 2\n    if 2 <= __pc < 5:\n        while b < a:\n            if __pc == 2:\n                print()\n                __pc = 3\n            if __pc == 3:\n                b = a * a\n                __pc = 4\n            if __pc == 4:\n                a = a + b\n                __pc = 5\n            __pc = 2\n        __pc = 5\n    if 5 <= __pc < 7:\n        if True:\n            if __pc == 5:\n                d = a + b\n                __pc = 6\n            if __pc == 6:\n                d = d * 2\n                __pc = 7\n        __pc = 7\n    if __pc == 7:\n        d = d + 1\n        __pc = 8\n    if __pc == 8:\n        d = d + 2\n        return d\n        __pc = 9\n        \"\"\".strip()\n\n        tree = ast.parse(source)\n        fn_tree = tree.body[0]\n        assert isinstance(fn_tree, ast.FunctionDef)\n        fn_tree.body, _ = jumps.insert_jumps(\n            fn_tree.body, lambda stmt: isinstance(stmt, ast.Assign))\n        tree = ast.fix_missing_locations(tree)\n        result = ast.unparse(tree)\n        self.assertEqual(result, want)\n\n    def test_equivalent(self):\n        source = \"\"\"\ndef fib(__pc, n):\n    curr = 0\n    next = 1\n    for i in range(n):\n        tmp = curr\n        curr = next\n        next = tmp + next\n    return curr\n\"\"\"\n\n        tree = ast.parse(source)\n        fn_tree = tree.body[0]\n        assert isinstance(fn_tree, ast.FunctionDef)\n        fn_tree.body, _ = jumps.insert_jumps(\n            fn_tree.body, lambda stmt: isinstance(stmt, ast.Assign))\n        fn_tree.name = \"fib_transformed\"\n\n        tree = ast.fix_missing_locations(tree)\n        code = compile(tree, \"<string>\", \"exec\")\n        results = {}\n        exec(code, globals(), results)\n        exec(source, globals(), results)\n        fib, fib_transformed = results[\"fib\"], results[\"fib_transformed\"]\n        for i in range(100):\n            self.assertEqual(fib(0, i), fib_transformed(0, i))\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "src/manual.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n\ndef editDistance(first, second):\n    \"\"\"Computes the edit distance between two strings.\n\n    >>> editDistance(\"kitten\", \"sitting\")\n    3\n    \"\"\"\n\n    return editDistanceImpl(first, second, 0, 0)\n\n\ndef editDistanceImpl(first, second, f, s):\n    if f == len(first):\n        return len(second) - s\n    if s == len(second):\n        return len(first) - f\n\n    if first[f] == second[s]:\n        return editDistanceImpl(first, second, f+1, s+1)\n\n    deleteFirst = editDistanceImpl(first, second, f+1, s) + 1\n    deleteSecond = editDistanceImpl(first, second, f, s+1) + 1\n    replace = editDistanceImpl(first, second, f+1, s+1) + 1\n    return min(deleteFirst, deleteSecond, replace)\n\n\n@dataclass\nclass Frame:\n    __pc: int\n    locals: Any\n    child: Any\n\n\n@dataclass\nclass CallOp:\n    fn: Any\n    arguments: Any\n\n\n@dataclass\nclass TailCallOp:\n    callop: CallOp\n\n\n@dataclass\nclass RetOp:\n    pass\n\n\ndef engine(fn, args):\n    stack = []  # make frame fn, args\n    while True:\n        # op = run last function on stack\n        # if op == tailcall\n        # pop the last frame in stack\n        # if op == call or tailcall\n        # bind arguments to corresponding frame locals\n        # push new frame onto stack\n        # if op == ret\n        # pop last frame in stack\n        # if no parent frame, return value\n        # assign new top's child frame pointer to popped frame\n        # next function will read the return value through the pointer\n\n        # ABI: returns put return value into the current frame\n        # We don't support nested functions.\n\n\ndef editDistanceIterImpl(frame):\n    if frame.__pc == 0:\n        if frame.f == len(frame.first):\n            return len(frame.second) - frame.s\n        if frame.s == len(frame.second):\n            return len(frame.first) - frame.s\n\n    if 0 <= frame.__pc <= 1:\n        if frame.first[frame.f] == frame.second[frame.s]:\n            if frame.__pc == 0:\n                frame.__pc = 1\n                # callop editDistanceImpl(frame.first, frame.second, frame.f+1, frame.s+1)\n            # jmp (1)\n            return frame.child.ret\n        frame.__pc = 2\n\n    if frame.__pc == 2:\n        frame.__pc = 3\n        # callop editDistanceImpl(frame.first, frame.second, frame.f+1, frame.s)\n        frame.deleteFirst = frame.child.ret + 1\n    # jmp\n    if frame.__pc == 3:\n        frame.__pc = 4\n        # callop editDistanceImpl(frame.first, frame.second, frame.f, frame.s+1)\n        frame.deleteSecond = frame.child.ret + 1\n    # jmp\n    if frame.__pc == 4:\n        frame.__pc = 5\n        # callop editDistanceImpl(frame.first, frame.second, frame.f+1, frame.s+1)\n        frame.replace = frame.child.ret + 1\n    # jmp\n    if frame.__pc == 5:\n        return min(frame.deleteFirst, frame.deleteSecond, frame.replace)\n\n# transforms\n# mark recursive calls\n# promote nested recursive call results to temporaries\n# change locals to accesses in heap frame\n# add jump points after recursive calls\n# write recursive calls as returning (tail)?call ops\n# write returns as returning return ops\n# write jumps as if statements & pc counter\n"
  },
  {
    "path": "src/mappers.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nfrom collections.abc import Container\n\nimport expressions\nimport utils\n\n\ndef map_scope(scope, fn):\n    \"\"\"Applies the mapping function to every statement in the scope.\n\n    The mapping function should return a list of statements; the returned\n    statements will be flattened together.\"\"\"\n    kwargs = {field: value for field, value in ast.iter_fields(scope)}\n    body = []\n    for stmt in scope.body:\n        body.extend(fn(stmt))\n        # TODO(tylerhou): Should we map all scopes?\n        if utils.is_supported_scope(stmt):\n            body[-1] = map_scope(body[-1], fn)\n    kwargs[\"body\"] = body\n    return type(scope)(**kwargs)\n\n\ndef promote_to_temporary_m(fns: Container[str], name_iter):\n    \"\"\"Creates a function mapper that promotes the results of inner calls to\n    functions in fns to temporary variables.\"\"\"\n    def promote_mapper(stmt):\n        stmts = []\n        stmts.append(expressions.promote_call_expressions(\n            stmt, fns, name_iter, stmts))  # Mutates stmts\n        return stmts\n    return promote_mapper\n\n\ndef remove_trivial_temporaries_m(fn_ast: ast.AST):\n    \"\"\"Creates a function mapper that removes trivial assignments.\"\"\"\n    trivial_temps = set(utils.potentially_trivial_temporaries(fn_ast))\n    first_assignment, last_assignment = utils.find_assignments(fn_ast, trivial_temps)\n    trivial_temps = set(t for t in trivial_temps if last_assignment[t] is first_assignment[t])\n    trivial_assignments = set(last_assignment[t] for t in trivial_temps)\n    to_replace = {temp: last_assignment[temp] for temp in trivial_temps if temp in trivial_temps}\n\n\n    def remove_trivial_mapper(stmt):\n        return [] if stmt in trivial_assignments else [utils.replace_variable(stmt, to_replace)]\n    return remove_trivial_mapper\n\n\ndef for_to_while_m(name_iter):\n    \"\"\"Creates a function mapper that converts for loops to equivalent while loops.\"\"\"\n    def mapper(stmt):\n        if not isinstance(stmt, ast.For):\n            return [stmt]\n        iter_n, test_n = next(name_iter), next(name_iter)\n        body = [utils.make_for_try(stmt.target, iter_n, test_n)] + stmt.body\n        return [\n            utils.make_assign(iter_n, utils.make_call(\"iter\", stmt.iter)),\n            utils.make_assign(test_n, ast.Constant(value=True)),\n            ast.While(test=utils.make_lookup(test_n),\n                      body=body, orelse=stmt.orelse),\n        ]\n    return mapper\n\n\ndef promote_while_cond_m(name_iter):\n    \"\"\"Creates a function mapper that promotes the test in while loops to a variable.\"\"\"\n    def mapper(stmt):\n        if not isinstance(stmt, ast.While):\n            return [stmt]\n        if isinstance(stmt.test, ast.Name):\n            return [stmt]\n            # TODO(tylerhou): Add a test for this.\n        condition_n = next(name_iter)\n        test_assign = utils.make_assign(condition_n, stmt.test)\n        body = stmt.body + [test_assign]\n        return [test_assign, ast.While(test=utils.make_lookup(condition_n), body=body, orelse=stmt.orelse)]\n    return mapper\n\n\ndef bool_exps_to_if_m(name_iter):\n    \"\"\"Creates a function mapper that rewrites boolean expressions as if\n    statements so promotion to temporaries doesn't change evaluation order.\"\"\"\n    def mapper(stmt):\n        stmts = []\n        stmts.append(expressions.promote_boolean_expression_operands(\n            stmt, name_iter, stmts))  # Mutates stmts\n        return stmts\n    return mapper\n\n\ndef lift_to_frame_m(name_fn=lambda x: x):\n    \"\"\"Creates a function mapper that replaces all accesses where name_fn\n    returns not None to loads and stores in a frame object.\"\"\"\n    def mapper(stmt):\n        return [expressions.promote_variable_access(stmt, name_fn)]\n    return mapper\n"
  },
  {
    "path": "src/mappers_test.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nimport unittest\nimport mappers\nimport utils\n\n\ndef map_function(source, mapper):\n    tree = ast.parse(source).body[0]\n    tree = mappers.map_scope(tree, mapper)\n    tree = ast.fix_missing_locations(tree)\n    return ast.unparse(tree)\n\n\nclass TestMappers(unittest.TestCase):\n\n    def test_promote_to_temporary_m(self):\n        source = \"\"\"\ndef foo():\n    t = bar(2)\n    if t == 1:\n        return bar(bar(bar(1), 3), 5) + bar(baz(t), 4)\n    if t == bar(10):\n        return bar(baz(t), 2)\n        \"\"\".strip()\n\n        want = \"\"\"\ndef foo():\n    __tmp0__ = bar(2)\n    t = __tmp0__\n    if t == 1:\n        __tmp1__ = bar(1)\n        __tmp2__ = bar(__tmp1__, 3)\n        __tmp3__ = bar(__tmp2__, 5)\n        __tmp4__ = bar(baz(t), 4)\n        return __tmp3__ + __tmp4__\n    __tmp5__ = bar(10)\n    if t == __tmp5__:\n        __tmp6__ = bar(baz(t), 2)\n        return __tmp6__\n        \"\"\".strip()\n\n        mapper = mappers.promote_to_temporary_m([\"bar\"], utils.dunder_names())\n        result = map_function(source, mapper)\n        self.assertEqual(result, want)\n\n    def test_remove_trivial_temporaries_m(self):\n        source = \"\"\"\ndef foo():\n    __tmp0__ = bar(2)\n    t = __tmp0__\n    if t == 1:\n        __tmp1__ = bar(1)\n        __tmp2__ = bar(__tmp1__, 3)\n        __tmp3__ = bar(__tmp2__, 5)\n        __tmp4__ = bar(baz(t), 4)\n        return __tmp3__ + __tmp4__\n    __tmp5__ = bar(10)\n    if t == __tmp5__:\n        __tmp6__ = bar(baz(t), 2)\n        return __tmp6__\n        \"\"\".strip()\n\n        want = \"\"\"\ndef foo():\n    t = bar(2)\n    if t == 1:\n        __tmp1__ = bar(1)\n        __tmp2__ = bar(__tmp1__, 3)\n        __tmp3__ = bar(__tmp2__, 5)\n        __tmp4__ = bar(baz(t), 4)\n        return __tmp3__ + __tmp4__\n    __tmp5__ = bar(10)\n    if t == __tmp5__:\n        return bar(baz(t), 2)\n        \"\"\".strip()\n\n        tree = ast.parse(source).body[0]\n        # Remove trivial needs to preprocess the tree to find trivial variables.\n        mapper = mappers.remove_trivial_temporaries_m(tree)\n        tree = mappers.map_scope(tree, mapper)\n        tree = ast.fix_missing_locations(tree)\n        result = ast.unparse(tree)\n        self.assertEqual(result, want)\n\n    def test_remove_trivial_temporaries_m_tail_call(self):\n        source = \"\"\"\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    __tmp0__ = sum(lst[1:], acc + lst[0])\n    return __tmp0__\n        \"\"\".strip()\n\n        want = \"\"\"\ndef sum(lst, acc):\n    if not lst:\n        return acc\n    return sum(lst[1:], acc + lst[0])\n        \"\"\".strip()\n        tree = ast.parse(source).body[0]\n        mapper = mappers.remove_trivial_temporaries_m(tree)\n        tree = mappers.map_scope(tree, mapper)\n        tree = ast.fix_missing_locations(tree)\n        result = ast.unparse(tree)\n        self.assertEqual(result, want)\n\n    def test_for_to_while_m(self):\n        source = \"\"\"\ndef bar():\n    pre = 1\n    for i in range(10):\n        print(pre, i)\n        if i == 5:\n            break\n    else:\n        print('else')\n    post = 1\n    return pre + post\n        \"\"\".strip()\n\n        want = \"\"\"\ndef bar():\n    pre = 1\n    __tmp0__ = iter(range(10))\n    __tmp1__ = True\n    while __tmp1__:\n        try:\n            i = next(__tmp0__)\n        except StopIteration:\n            __tmp1__ = False\n            continue\n        print(pre, i)\n        if i == 5:\n            break\n    else:\n        print('else')\n    post = 1\n    return pre + post\n        \"\"\".strip()\n\n        mapper = mappers.for_to_while_m(utils.dunder_names())\n        result = map_function(source, mapper)\n        self.assertEqual(result, want)\n\n    def test_promote_while_cond_m(self):\n        source = \"\"\"\ndef bar():\n    p = [1, 2, 3]\n    while len(p) > 0:\n        t = p.pop()\n    else:\n        print('else')\n    post = 1\n    return t + post\n        \"\"\".strip()\n\n        want = \"\"\"\ndef bar():\n    p = [1, 2, 3]\n    __tmp0__ = len(p) > 0\n    while __tmp0__:\n        t = p.pop()\n        __tmp0__ = len(p) > 0\n    else:\n        print('else')\n    post = 1\n    return t + post\n        \"\"\".strip()\n\n        mapper = mappers.promote_while_cond_m(utils.dunder_names())\n        result = map_function(source, mapper)\n        self.assertEqual(result, want)\n\n    def test_bool_exps_to_if_m(self):\n        source = \"\"\"\ndef bar():\n    a = first() and (second() or third()) and fourth()\n    b = 1 + (foo() or baz())\n    return a or b\n        \"\"\".strip()\n\n        want = \"\"\"\ndef bar():\n    __tmp0__ = first()\n    if __tmp0__:\n        __tmp1__ = second()\n        if not __tmp1__:\n            __tmp1__ = third()\n        __tmp0__ = __tmp1__\n    if __tmp0__:\n        __tmp0__ = fourth()\n    a = __tmp0__\n    __tmp2__ = foo()\n    if not __tmp2__:\n        __tmp2__ = baz()\n    b = 1 + __tmp2__\n    __tmp3__ = a\n    if not __tmp3__:\n        __tmp3__ = b\n    return __tmp3__\n        \"\"\".strip()\n\n        mapper = mappers.bool_exps_to_if_m(utils.dunder_names())\n        result = map_function(source, mapper)\n        self.assertEqual(result, want)\n\n    def test_lift_to_frame_m(self):\n        source = \"\"\"\ndef bar(arg1, arg2):\n    a = arg1 + arg2\n    if a == 2:\n        return arg1 + arg2\n    b = a + (foo() or baz())\n    return a + b\n        \"\"\".strip()\n\n        want = \"\"\"\ndef bar(arg1, arg2):\n    frame['a'] = frame['arg1'] + frame['arg2']\n    if frame['a'] == 2:\n        return frame['arg1'] + frame['arg2']\n    frame['b'] = frame['a'] + (foo() or baz())\n    return frame['a'] + frame['b']\n        \"\"\".strip()\n        mapper = mappers.lift_to_frame_m(\n            lambda x: x if x in (\"a\", \"b\", \"arg1\", \"arg2\") else None)\n        result = map_function(source, mapper)\n        self.assertEqual(result, want)\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "src/trampoline.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Union\nimport itertools\n\nimport fiber\nimport jumps\n\n\n@dataclass\nclass StackFrame:\n    frame: Dict[str, Any]\n    fn: Any\n    ret_variable: Union[str, None]\n\n\ndef pos_with_defaults(args: ast.arguments):\n    num_non_defaults = len(args.posonlyargs) + \\\n        len(args.args) - len(args.defaults)\n    args_iter = itertools.chain(iter(args.posonlyargs), iter(args.args))\n    for _ in range(num_non_defaults):\n        yield next(args_iter), None\n    for default in args.defaults:\n        yield next(args_iter), default\n\n\ndef bind_frame(positional_args, keyword_args, fn_tree: ast.FunctionDef):\n    frame = {}\n    # Reverse the list of args because we pop args from the front of the\n    # original list, which is the back of the reversed list.\n    positional_args, fn_args = list(reversed(positional_args)), fn_tree.args\n    for needed_arg, default in pos_with_defaults(fn_args):\n        name: str = needed_arg.arg\n        if positional_args:  # If we can still take args\n            frame[name] = positional_args.pop()\n            continue\n\n        if name in keyword_args:\n            if needed_arg in fn_tree.args.posonlyargs:\n                raise TypeError(\n                    f\"{fn_tree.name}: got positional only argument {name} as a keyword\")\n            frame[name] = keyword_args[name]\n            del keyword_args[name]\n            continue\n\n        elif not default:\n            raise TypeError(f\"{fn_tree.name} had too few positional arguments\")\n        frame[name] = default\n\n    if fn_args.vararg:\n        # Unreverse the list as from the beginning.\n        frame[fn_args.vararg.arg] = list(reversed(positional_args))\n\n    keyword_arg_names = set(k.arg for k in itertools.chain(\n        fn_args.args, fn_args.kwonlyargs))\n    for kwarg in keyword_args:\n        if kwarg not in keyword_arg_names:\n            raise TypeError(\n                f\"{fn_tree.name} got invalid keyword argument '{kwarg}'\")\n        if kwarg in frame:\n            raise TypeError(\n                f\"{fn_tree.name} got multiple values for argument '{kwarg}'\")\n        frame[kwarg] = keyword_args[kwarg]\n\n    for kwarg, default in zip(fn_args.kwonlyargs, fn_args.kw_defaults):\n        if default is None and kwarg.arg not in frame:\n            raise TypeError(\n                f\"{fn_tree.name} missing required keyword only argument '{kwarg.arg}'\")\n        if default is not None and kwarg.arg not in frame:\n            frame[kwarg.arg] = ast.literal_eval(default)\n\n    frame[jumps.PC_LOCAL_NAME] = 0\n    return frame\n\n\ndef run(fn, args=None, kwargs=None, *, __max_stack_size=float('inf')):\n    if args is None:\n        args = []\n    if kwargs is None:\n        kwargs = {}\n\n    frame = bind_frame(args, kwargs, fiber.FIBER_FN_COMPILED_MAP[fn].fn_def)\n    stack: List[StackFrame] = [StackFrame(frame, fn, None)]\n    while True:\n        assert len(stack) <= __max_stack_size\n        top = stack[-1]\n        op = top.fn(top.frame)\n        if isinstance(op, fiber.CallOp):\n            metadata = fiber.FIBER_FN_NAME_MAP[op.func]\n            top.ret_variable = op.ret_variable\n            frame = bind_frame(op.args, op.kwargs, metadata.fn_def)\n            stack.append(StackFrame(frame, metadata.fn, None))\n        elif isinstance(op, fiber.TailCallOp):\n            stack.pop()  # Tail call, so we can discard the frame.\n            metadata = fiber.FIBER_FN_NAME_MAP[op.func]\n            frame = bind_frame(op.args, op.kwargs, metadata.fn_def)\n            stack.append(StackFrame(frame, metadata.fn, None))\n        elif isinstance(op, fiber.RetOp):\n            stack.pop()\n            if not stack:\n                return op.value\n            top = stack[-1]\n            assert top.ret_variable is not None\n            top.frame[top.ret_variable] = op.value\n"
  },
  {
    "path": "src/trampoline_test.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nimport unittest\n\nimport fiber\nimport trampoline\n\n\nclass TestTrampoline(unittest.TestCase):\n\n    def test_fib(self):\n        cache = {}\n\n        @fiber.fiber(locals=locals())\n        def fib(n):\n            if n in cache:\n                return cache[n]\n            if n == 0:\n                return 0\n            if n == 1:\n                return 1\n            cache[n] = fib(n-1) + fib(n=n-2)\n            return cache[n]\n        self.assertEqual(55, trampoline.run(fib, [10], {}))\n        self.assertLess(0, trampoline.run(fib, [1002], {}))\n\n    def test_sum(self):\n        @fiber.fiber(locals=locals())\n        def sum(lst, acc):\n            if not lst:\n                return acc\n            return sum(lst[1:], acc + lst[0])\n        n = sys.getrecursionlimit() + 1\n        want = n * (n + 1) / 2\n        got = trampoline.run(sum, [list(range(1, n+1)), 0], __max_stack_size=1)\n        self.assertEqual(want, got)\n\n    def test_sum_recursion_exceeded(self):\n        def sum(lst, acc):\n            if not lst:\n                return acc\n            return sum(lst[1:], acc + lst[0])\n        n = sys.getrecursionlimit() + 1\n        self.assertRaises(RecursionError, sum, list(range(1, n+1)), 0)\n\n    def test_sum_non_tailcall(self):\n        @fiber.fiber(locals=locals())\n        def sum(lst, acc):\n            if not lst:\n                return acc\n            return sum(lst[1:], acc + lst[0]) + 1\n        n = sys.getrecursionlimit() + 1\n        want = n * (n + 1) / 2 + n\n        got = trampoline.run(sum, [list(range(1, n+1)), 0])\n        self.assertEqual(want, got)\n\n    def test_mutual_recursion(self):\n        @fiber.fiber([\"b\"], locals=locals())\n        def a(n):\n            if n == 0:\n                return 1\n            return b(n-1) * 2\n\n        @fiber.fiber(locals=locals())\n        def b(n):\n            if n == 0:\n                return 1\n            return a(n-1) * 3\n        got = trampoline.run(a, [10])\n        self.assertEqual(2**5 * 3**5, got)\n\n    def test_edit_distance(self):\n        def edit_distance(first, second):\n            @fiber.fiber(locals=locals())\n            def edit_distance__helper(f, s):\n                if f == len(first):\n                    return len(second) - s\n                if s == len(second):\n                    return len(first) - f\n\n                if first[f] == second[s]:\n                    return edit_distance__helper(f+1, s+1)\n\n                del_f = edit_distance__helper(f+1, s) + 1\n                replace = edit_distance__helper(f+1, s+1) + 1\n                del_s = edit_distance__helper(f, s+1) + 1\n\n                return min(del_f, replace, del_s)\n\n            return trampoline.run(edit_distance__helper, [0, 0])\n        self.assertEqual(3, edit_distance(\"kitten\", \"sitting\"))\n\n    def test_pop_balloons(self):\n        def pop_balloons(balloons):\n            balloons = [1] + balloons + [1]\n\n            @fiber.fiber(locals=locals())\n            def pop_balloons__helper(i, j):\n                if i == j:\n                    return 0\n                max_profit = float('-inf')\n                for k in range(i, j):\n                    profit = pop_balloons__helper(i, k)\n                    profit += pop_balloons__helper(k+1, j)\n                    profit += balloons[i-1] * balloons[k] * balloons[j]\n                    max_profit = max(max_profit, profit)\n                return max_profit\n\n            return trampoline.run(pop_balloons__helper, [1, len(balloons) - 1])\n        self.assertEqual(175, pop_balloons([4, 5, 7]))\n\n    def test_tree_recursion(self):\n        from collections import namedtuple\n        Tree = namedtuple(\"Tree\", [\"left\", \"right\"])\n\n        @fiber.fiber(locals=locals())\n        def all_zeroes(tree):\n            if tree == 0:\n                return True\n            if not isinstance(tree, Tree):\n                return False\n            return all_zeroes(tree.left) and all_zeroes(tree.right)\n\n        zeroes = Tree(Tree(0, 0), Tree(Tree(Tree(0, 0), 0), Tree(0, 0)))\n        one = Tree(Tree(0, 0), Tree(Tree(Tree(1, 0), 0), Tree(0, 0)))\n        self.assertTrue(trampoline.run(all_zeroes, [zeroes]))\n        self.assertFalse(trampoline.run(all_zeroes, [one]))\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "src/utils.py",
    "content": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nimport itertools\nimport re\n\n# We don't support exceptions (ast.Try) or async for/while.\n# Exception support is fairly easy to add; async is harder.\nFN_INNER_SCOPE_NODES = [ast.For, ast.While, ast.If, ast.While]\n\n\ndef dunder_names():\n    for i in itertools.count():\n        yield f\"__tmp{i}__\"\n\n\ndunder_regex = re.compile(r'__tmp\\d+__')\n\n\ndef is_temporary(name):\n    return re.match(dunder_regex, name) != None\n\n\ndef is_supported_scope(tree):\n    return any(isinstance(tree, scope_type) for scope_type in FN_INNER_SCOPE_NODES)\n\n\ndef map_expression(statement: ast.AST, fn):\n    \"\"\"Recursively transforms an expression by applying the mapping function to\n    all attributes that are AST nodes.\n\n    Does not recursively transform scope bodies (while, for, try) as one would\n    usually call this function from a mapper in map_scope, which itself already\n    iterates through scope bodies.\"\"\"\n    kwargs = {}\n    for field, value in ast.iter_fields(statement):\n        result = value\n        if is_supported_scope(statement) and field == \"body\":\n            result = value\n        elif isinstance(value, list):\n            result = [fn(field, v)\n                      for v in value if isinstance(v, ast.AST)]\n        elif isinstance(value, ast.AST):\n            result = fn(field, value)\n        kwargs[field] = result\n    return type(statement)(**kwargs)\n\n\ndef iter_scope(scope):\n    \"\"\"Iterates through every statement in the scope, recursively.\"\"\"\n    for stmt in scope.body:\n        yield stmt\n        if is_supported_scope(stmt):\n            yield from iter_scope(stmt)\n\n\ndef potentially_trivial_temporaries(fn):\n    \"\"\"Yields potentially trivial temporaries.\n\n    Temporaries are trivial if they are directly assigned to another variable\n    or if they are returned; e.g.\n        t = __tmp1__\n        return __tmp2__\n\n    If they are assigned to multiple times, then they are not trivial.\n    \"\"\"\n    for statement in iter_scope(fn):\n        if isinstance(statement, ast.Return) and \\\n                isinstance(statement.value, ast.Name) and \\\n                is_temporary(statement.value.id):\n            yield statement.value.id\n\n        if (isinstance(statement, ast.Assign) or\n                isinstance(statement, ast.AnnAssign)) and \\\n                isinstance(statement.value, ast.Name) and \\\n                is_temporary(statement.value.id):\n            yield statement.value.id\n\n\ndef find_assignments(fn, variables):\n    \"\"\"Finds the first and last assignment for each variable.\"\"\"\n    first_assignment, last_assignment = {}, {}\n    for statement in iter_scope(fn):\n        if isinstance(statement, ast.Assign) and \\\n                len(statement.targets) == 1 and \\\n                isinstance(statement.targets[0], ast.Name) and \\\n                (var := statement.targets[0].id) in variables:\n            if var not in first_assignment:\n                first_assignment[var] = statement\n            last_assignment[var] = statement\n    return first_assignment, last_assignment\n\n\ndef replace_variable(statement, assignments):\n    def mapper(field, expression):\n        if field == \"value\":\n            return assignments[expression.id].value\n        return expression\n\n    if isinstance(statement, ast.Return) and \\\n            isinstance(statement.value, ast.Name) and \\\n            statement.value.id in assignments:\n        return map_expression(statement, mapper)\n\n    if (isinstance(statement, ast.Assign) or\n        isinstance(statement, ast.AnnAssign)) and \\\n        isinstance(statement.value, ast.Name) and \\\n            statement.value.id in assignments:\n        return map_expression(statement, mapper)\n    return statement\n\n\ndef make_assign(target, value):\n    return ast.Assign(targets=[ast.Name(id=target, ctx=ast.Store())], value=value)\n\n\ndef make_call(func: str, *args):\n    return ast.Call(func=ast.Name(id=func, ctx=ast.Load()), args=list(args), keywords=[])\n\n\ndef make_lookup(name: str):\n    return ast.Name(id=name, ctx=ast.Load())\n\n\ndef make_not(exp: ast.AST):\n    return ast.UnaryOp(op=ast.Not(), operand=exp)\n\n\ndef make_for_try(loop_target, iter_n, test_n):\n    return ast.Try(\n        body=[ast.Assign(targets=[loop_target], value=make_call(\n            \"next\", make_lookup(iter_n)))],\n        handlers=[\n            ast.ExceptHandler(type=make_lookup(\"StopIteration\"),\n                              body=[\n                                  make_assign(\n                                      test_n, ast.Constant(value=False)),\n                                  ast.Continue()\n            ])],\n        orelse=[],\n        finalbody=[])\n\n\ndef is_block(block: ast.AST):\n    return hasattr(block, \"body\") and isinstance(block.body, list)\n\n\ndef _locals_impl(fn: ast.AST):\n    assert isinstance(fn, ast.FunctionDef)\n    args = fn.args\n    for arg in itertools.chain(args.posonlyargs, args.args, args.kwonlyargs, (args.vararg, args.kwarg)):\n        if arg is not None:\n            yield arg.arg\n\n    def helper(block: ast.AST):\n        for node in block.body:\n            if isinstance(node, ast.Assign):\n                for target in node.targets:\n                    if isinstance(target, ast.Name):\n                        yield target.id\n            if isinstance(node, ast.AnnAssign) or \\\n                    isinstance(node, ast.AugAssign) or \\\n                    isinstance(node, ast.NamedExpr):\n                if isinstance(node.target, ast.Name):\n                    yield node.target.id\n            if is_block(node) and not isinstance(node, ast.FunctionDef):\n                yield from helper(node)\n    yield from helper(fn)\n\n\ndef local_vars(fn: ast.AST):\n    \"\"\"Returns a set of all function local variables.\"\"\"\n    return set(_locals_impl(fn))\n"
  }
]