[
  {
    "path": "LICENSE",
    "content": "Creative Commons Attribution 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n  wiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More_considerations\n     for the public:\n  wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution 4.0 International Public License (\"Public License\"). To the\nextent this Public License may be interpreted as a contract, You are\ngranted the Licensed Rights in consideration of Your acceptance of\nthese terms and conditions, and the Licensor grants You such rights in\nconsideration of benefits the Licensor receives from making the\nLicensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  j. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  k. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part; and\n\n            b. produce, reproduce, and Share Adapted Material.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public licenses.\nNotwithstanding, Creative Commons may elect to apply one of its public\nlicenses to material it publishes and in those instances will be\nconsidered the \"Licensor.\" Except for the limited purpose of indicating\nthat material is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the public\nlicenses.\n\nCreative Commons may be contacted at creativecommons.org.\n"
  },
  {
    "path": "README.md",
    "content": "[![The Super Tiny Compiler](https://cloud.githubusercontent.com/assets/952783/21579290/5755288a-cf75-11e6-90e0-029529a44a38.png)](the-super-tiny-compiler.js)\n\n***Welcome to The Super Tiny Compiler!***\n\nThis is an ultra-simplified example of all the major pieces of a modern compiler\nwritten in easy to read JavaScript.\n\nReading through the guided code will help you learn about how *most* compilers\nwork from end to end.\n\n### [Want to jump into the code? Click here](the-super-tiny-compiler.js)\n\n### [You can also check it out on Glitch](https://the-super-tiny-compiler.glitch.me/)\n\n---\n\n### Why should I care?\n\nThat's fair, most people don't really have to think about compilers in their day\njobs. However, compilers are all around you, tons of the tools you use are based\non concepts borrowed from compilers.\n\n### But compilers are scary!\n\nYes, they are. But that's our fault (the people who write compilers), we've\ntaken something that is reasonably straightforward and made it so scary that\nmost think of it as this totally unapproachable thing that only the nerdiest of\nthe nerds are able to understand.\n\n### Okay so where do I begin?\n\nAwesome! Head on over to the [the-super-tiny-compiler.js](the-super-tiny-compiler.js)\nfile.\n\n### I'm back, that didn't make sense\n\nOuch, I'm really sorry. Let me know how it can be improved.\n\n### Tests\n\nRun with `node test.js`\n\n---\n\n[![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/)\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"the-super-tiny-compiler\",\n  \"version\": \"1.0.0\",\n  \"author\": \"James Kyle <me@thejameskyle.com> (thejameskyle.com)\",\n  \"license\": \"CC-BY-4.0\",\n  \"main\": \"./the-super-tiny-compiler.js\"\n}\n"
  },
  {
    "path": "test.js",
    "content": "const {\n  tokenizer,\n  parser,\n  transformer,\n  codeGenerator,\n  compiler,\n} = require('./the-super-tiny-compiler');\nconst assert = require('assert');\n\nconst input  = '(add 2 (subtract 4 2))';\nconst output = 'add(2, subtract(4, 2));';\n\nconst tokens = [\n  { type: 'paren',  value: '('        },\n  { type: 'name',   value: 'add'      },\n  { type: 'number', value: '2'        },\n  { type: 'paren',  value: '('        },\n  { type: 'name',   value: 'subtract' },\n  { type: 'number', value: '4'        },\n  { type: 'number', value: '2'        },\n  { type: 'paren',  value: ')'        },\n  { type: 'paren',  value: ')'        }\n];\n\nconst ast = {\n  type: 'Program',\n  body: [{\n    type: 'CallExpression',\n    name: 'add',\n    params: [{\n      type: 'NumberLiteral',\n      value: '2'\n    }, {\n      type: 'CallExpression',\n      name: 'subtract',\n      params: [{\n        type: 'NumberLiteral',\n        value: '4'\n      }, {\n        type: 'NumberLiteral',\n        value: '2'\n      }]\n    }]\n  }]\n};\n\nconst newAst = {\n  type: 'Program',\n  body: [{\n    type: 'ExpressionStatement',\n    expression: {\n      type: 'CallExpression',\n      callee: {\n        type: 'Identifier',\n        name: 'add'\n      },\n      arguments: [{\n        type: 'NumberLiteral',\n        value: '2'\n      }, {\n        type: 'CallExpression',\n        callee: {\n          type: 'Identifier',\n          name: 'subtract'\n        },\n        arguments: [{\n          type: 'NumberLiteral',\n          value: '4'\n        }, {\n          type: 'NumberLiteral',\n          value: '2'\n        }]\n      }]\n    }\n  }]\n};\n\nassert.deepStrictEqual(tokenizer(input), tokens, 'Tokenizer should turn `input` string into `tokens` array');\nassert.deepStrictEqual(parser(tokens), ast, 'Parser should turn `tokens` array into `ast`');\nassert.deepStrictEqual(transformer(ast), newAst, 'Transformer should turn `ast` into a `newAst`');\nassert.deepStrictEqual(codeGenerator(newAst), output, 'Code Generator should turn `newAst` into `output` string');\nassert.deepStrictEqual(compiler(input), output, 'Compiler should turn `input` into `output`');\n\nconsole.log('All Passed!');\n"
  },
  {
    "path": "the-super-tiny-compiler.js",
    "content": "'use strict';\n\n/**\n * TTTTTTTTTTTTTTTTTTTTTTTHHHHHHHHH     HHHHHHHHHEEEEEEEEEEEEEEEEEEEEEE\n * T:::::::::::::::::::::TH:::::::H     H:::::::HE::::::::::::::::::::E\n * T:::::::::::::::::::::TH:::::::H     H:::::::HE::::::::::::::::::::E\n * T:::::TT:::::::TT:::::THH::::::H     H::::::HHEE::::::EEEEEEEEE::::E\n * TTTTTT  T:::::T  TTTTTT  H:::::H     H:::::H    E:::::E       EEEEEE\n *         T:::::T          H:::::H     H:::::H    E:::::E\n *         T:::::T          H::::::HHHHH::::::H    E::::::EEEEEEEEEE\n *         T:::::T          H:::::::::::::::::H    E:::::::::::::::E\n *         T:::::T          H:::::::::::::::::H    E:::::::::::::::E\n *         T:::::T          H::::::HHHHH::::::H    E::::::EEEEEEEEEE\n *         T:::::T          H:::::H     H:::::H    E:::::E\n *         T:::::T          H:::::H     H:::::H    E:::::E       EEEEEE\n *       TT:::::::TT      HH::::::H     H::::::HHEE::::::EEEEEEEE:::::E\n *       T:::::::::T      H:::::::H     H:::::::HE::::::::::::::::::::E\n *       T:::::::::T      H:::::::H     H:::::::HE::::::::::::::::::::E\n *       TTTTTTTTTTT      HHHHHHHHH     HHHHHHHHHEEEEEEEEEEEEEEEEEEEEEE\n *\n *    SSSSSSSSSSSSSSS UUUUUUUU     UUUUUUUUPPPPPPPPPPPPPPPPP   EEEEEEEEEEEEEEEEEEEEEERRRRRRRRRRRRRRRRR\n *  SS:::::::::::::::SU::::::U     U::::::UP::::::::::::::::P  E::::::::::::::::::::ER::::::::::::::::R\n * S:::::SSSSSS::::::SU::::::U     U::::::UP::::::PPPPPP:::::P E::::::::::::::::::::ER::::::RRRRRR:::::R\n * S:::::S     SSSSSSSUU:::::U     U:::::UUPP:::::P     P:::::PEE::::::EEEEEEEEE::::ERR:::::R     R:::::R\n * S:::::S             U:::::U     U:::::U   P::::P     P:::::P  E:::::E       EEEEEE  R::::R     R:::::R\n * S:::::S             U:::::U     U:::::U   P::::P     P:::::P  E:::::E               R::::R     R:::::R\n *  S::::SSSS          U:::::U     U:::::U   P::::PPPPPP:::::P   E::::::EEEEEEEEEE     R::::RRRRRR:::::R\n *   SS::::::SSSSS     U:::::U     U:::::U   P:::::::::::::PP    E:::::::::::::::E     R:::::::::::::RR\n *     SSS::::::::SS   U:::::U     U:::::U   P::::PPPPPPPPP      E:::::::::::::::E     R::::RRRRRR:::::R\n *        SSSSSS::::S  U:::::U     U:::::U   P::::P              E::::::EEEEEEEEEE     R::::R     R:::::R\n *             S:::::S U:::::U     U:::::U   P::::P              E:::::E               R::::R     R:::::R\n *             S:::::S U::::::U   U::::::U   P::::P              E:::::E       EEEEEE  R::::R     R:::::R\n * SSSSSSS     S:::::S U:::::::UUU:::::::U PP::::::PP          EE::::::EEEEEEEE:::::ERR:::::R     R:::::R\n * S::::::SSSSSS:::::S  UU:::::::::::::UU  P::::::::P          E::::::::::::::::::::ER::::::R     R:::::R\n * S:::::::::::::::SS     UU:::::::::UU    P::::::::P          E::::::::::::::::::::ER::::::R     R:::::R\n *  SSSSSSSSSSSSSSS         UUUUUUUUU      PPPPPPPPPP          EEEEEEEEEEEEEEEEEEEEEERRRRRRRR     RRRRRRR\n *\n * TTTTTTTTTTTTTTTTTTTTTTTIIIIIIIIIINNNNNNNN        NNNNNNNNYYYYYYY       YYYYYYY\n * T:::::::::::::::::::::TI::::::::IN:::::::N       N::::::NY:::::Y       Y:::::Y\n * T:::::::::::::::::::::TI::::::::IN::::::::N      N::::::NY:::::Y       Y:::::Y\n * T:::::TT:::::::TT:::::TII::::::IIN:::::::::N     N::::::NY::::::Y     Y::::::Y\n * TTTTTT  T:::::T  TTTTTT  I::::I  N::::::::::N    N::::::NYYY:::::Y   Y:::::YYY\n *         T:::::T          I::::I  N:::::::::::N   N::::::N   Y:::::Y Y:::::Y\n *         T:::::T          I::::I  N:::::::N::::N  N::::::N    Y:::::Y:::::Y\n *         T:::::T          I::::I  N::::::N N::::N N::::::N     Y:::::::::Y\n *         T:::::T          I::::I  N::::::N  N::::N:::::::N      Y:::::::Y\n *         T:::::T          I::::I  N::::::N   N:::::::::::N       Y:::::Y\n *         T:::::T          I::::I  N::::::N    N::::::::::N       Y:::::Y\n *         T:::::T          I::::I  N::::::N     N:::::::::N       Y:::::Y\n *       TT:::::::TT      II::::::IIN::::::N      N::::::::N       Y:::::Y\n *       T:::::::::T      I::::::::IN::::::N       N:::::::N    YYYY:::::YYYY\n *       T:::::::::T      I::::::::IN::::::N        N::::::N    Y:::::::::::Y\n *       TTTTTTTTTTT      IIIIIIIIIINNNNNNNN         NNNNNNN    YYYYYYYYYYYYY\n *\n *         CCCCCCCCCCCCC     OOOOOOOOO     MMMMMMMM               MMMMMMMMPPPPPPPPPPPPPPPPP   IIIIIIIIIILLLLLLLLLLL             EEEEEEEEEEEEEEEEEEEEEERRRRRRRRRRRRRRRRR\n *      CCC::::::::::::C   OO:::::::::OO   M:::::::M             M:::::::MP::::::::::::::::P  I::::::::IL:::::::::L             E::::::::::::::::::::ER::::::::::::::::R\n *    CC:::::::::::::::C OO:::::::::::::OO M::::::::M           M::::::::MP::::::PPPPPP:::::P I::::::::IL:::::::::L             E::::::::::::::::::::ER::::::RRRRRR:::::R\n *   C:::::CCCCCCCC::::CO:::::::OOO:::::::OM:::::::::M         M:::::::::MPP:::::P     P:::::PII::::::IILL:::::::LL             EE::::::EEEEEEEEE::::ERR:::::R     R:::::R\n *  C:::::C       CCCCCCO::::::O   O::::::OM::::::::::M       M::::::::::M  P::::P     P:::::P  I::::I    L:::::L                 E:::::E       EEEEEE  R::::R     R:::::R\n * C:::::C              O:::::O     O:::::OM:::::::::::M     M:::::::::::M  P::::P     P:::::P  I::::I    L:::::L                 E:::::E               R::::R     R:::::R\n * C:::::C              O:::::O     O:::::OM:::::::M::::M   M::::M:::::::M  P::::PPPPPP:::::P   I::::I    L:::::L                 E::::::EEEEEEEEEE     R::::RRRRRR:::::R\n * C:::::C              O:::::O     O:::::OM::::::M M::::M M::::M M::::::M  P:::::::::::::PP    I::::I    L:::::L                 E:::::::::::::::E     R:::::::::::::RR\n * C:::::C              O:::::O     O:::::OM::::::M  M::::M::::M  M::::::M  P::::PPPPPPPPP      I::::I    L:::::L                 E:::::::::::::::E     R::::RRRRRR:::::R\n * C:::::C              O:::::O     O:::::OM::::::M   M:::::::M   M::::::M  P::::P              I::::I    L:::::L                 E::::::EEEEEEEEEE     R::::R     R:::::R\n * C:::::C              O:::::O     O:::::OM::::::M    M:::::M    M::::::M  P::::P              I::::I    L:::::L                 E:::::E               R::::R     R:::::R\n *  C:::::C       CCCCCCO::::::O   O::::::OM::::::M     MMMMM     M::::::M  P::::P              I::::I    L:::::L         LLLLLL  E:::::E       EEEEEE  R::::R     R:::::R\n *   C:::::CCCCCCCC::::CO:::::::OOO:::::::OM::::::M               M::::::MPP::::::PP          II::::::IILL:::::::LLLLLLLLL:::::LEE::::::EEEEEEEE:::::ERR:::::R     R:::::R\n *    CC:::::::::::::::C OO:::::::::::::OO M::::::M               M::::::MP::::::::P          I::::::::IL::::::::::::::::::::::LE::::::::::::::::::::ER::::::R     R:::::R\n *      CCC::::::::::::C   OO:::::::::OO   M::::::M               M::::::MP::::::::P          I::::::::IL::::::::::::::::::::::LE::::::::::::::::::::ER::::::R     R:::::R\n *         CCCCCCCCCCCCC     OOOOOOOOO     MMMMMMMM               MMMMMMMMPPPPPPPPPP          IIIIIIIIIILLLLLLLLLLLLLLLLLLLLLLLLEEEEEEEEEEEEEEEEEEEEEERRRRRRRR     RRRRRRR\n *\n * =======================================================================================================================================================================\n * =======================================================================================================================================================================\n * =======================================================================================================================================================================\n * =======================================================================================================================================================================\n */\n\n/**\n * Today we're going to write a compiler together. But not just any compiler... A\n * super duper teeny tiny compiler! A compiler that is so small that if you\n * remove all the comments this file would only be ~200 lines of actual code.\n *\n * We're going to compile some lisp-like function calls into some C-like\n * function calls.\n *\n * If you are not familiar with one or the other. I'll just give you a quick intro.\n *\n * If we had two functions `add` and `subtract` they would be written like this:\n *\n *                  LISP                      C\n *\n *   2 + 2          (add 2 2)                 add(2, 2)\n *   4 - 2          (subtract 4 2)            subtract(4, 2)\n *   2 + (4 - 2)    (add 2 (subtract 4 2))    add(2, subtract(4, 2))\n *\n * Easy peezy right?\n *\n * Well good, because this is exactly what we are going to compile. While this\n * is neither a complete LISP or C syntax, it will be enough of the syntax to\n * demonstrate many of the major pieces of a modern compiler.\n */\n\n/**\n * Most compilers break down into three primary stages: Parsing, Transformation,\n * and Code Generation\n *\n * 1. *Parsing* is taking raw code and turning it into a more abstract\n *    representation of the code.\n *\n * 2. *Transformation* takes this abstract representation and manipulates to do\n *    whatever the compiler wants it to.\n *\n * 3. *Code Generation* takes the transformed representation of the code and\n *    turns it into new code.\n */\n\n/**\n * Parsing\n * -------\n *\n * Parsing typically gets broken down into two phases: Lexical Analysis and\n * Syntactic Analysis.\n *\n * 1. *Lexical Analysis* takes the raw code and splits it apart into these things\n *    called tokens by a thing called a tokenizer (or lexer).\n *\n *    Tokens are an array of tiny little objects that describe an isolated piece\n *    of the syntax. They could be numbers, labels, punctuation, operators,\n *    whatever.\n *\n * 2. *Syntactic Analysis* takes the tokens and reformats them into a\n *    representation that describes each part of the syntax and their relation\n *    to one another. This is known as an intermediate representation or\n *    Abstract Syntax Tree.\n *\n *    An Abstract Syntax Tree, or AST for short, is a deeply nested object that\n *    represents code in a way that is both easy to work with and tells us a lot\n *    of information.\n *\n * For the following syntax:\n *\n *   (add 2 (subtract 4 2))\n *\n * Tokens might look something like this:\n *\n *   [\n *     { type: 'paren',  value: '('        },\n *     { type: 'name',   value: 'add'      },\n *     { type: 'number', value: '2'        },\n *     { type: 'paren',  value: '('        },\n *     { type: 'name',   value: 'subtract' },\n *     { type: 'number', value: '4'        },\n *     { type: 'number', value: '2'        },\n *     { type: 'paren',  value: ')'        },\n *     { type: 'paren',  value: ')'        },\n *   ]\n *\n * And an Abstract Syntax Tree (AST) might look like this:\n *\n *   {\n *     type: 'Program',\n *     body: [{\n *       type: 'CallExpression',\n *       name: 'add',\n *       params: [{\n *         type: 'NumberLiteral',\n *         value: '2',\n *       }, {\n *         type: 'CallExpression',\n *         name: 'subtract',\n *         params: [{\n *           type: 'NumberLiteral',\n *           value: '4',\n *         }, {\n *           type: 'NumberLiteral',\n *           value: '2',\n *         }]\n *       }]\n *     }]\n *   }\n */\n\n/**\n * Transformation\n * --------------\n *\n * The next type of stage for a compiler is transformation. Again, this just\n * takes the AST from the last step and makes changes to it. It can manipulate\n * the AST in the same language or it can translate it into an entirely new\n * language.\n *\n * Let’s look at how we would transform an AST.\n *\n * You might notice that our AST has elements within it that look very similar.\n * There are these objects with a type property. Each of these are known as an\n * AST Node. These nodes have defined properties on them that describe one\n * isolated part of the tree.\n *\n * We can have a node for a \"NumberLiteral\":\n *\n *   {\n *     type: 'NumberLiteral',\n *     value: '2',\n *   }\n *\n * Or maybe a node for a \"CallExpression\":\n *\n *   {\n *     type: 'CallExpression',\n *     name: 'subtract',\n *     params: [...nested nodes go here...],\n *   }\n *\n * When transforming the AST we can manipulate nodes by\n * adding/removing/replacing properties, we can add new nodes, remove nodes, or\n * we could leave the existing AST alone and create an entirely new one based\n * on it.\n *\n * Since we’re targeting a new language, we’re going to focus on creating an\n * entirely new AST that is specific to the target language.\n *\n * Traversal\n * ---------\n *\n * In order to navigate through all of these nodes, we need to be able to\n * traverse through them. This traversal process goes to each node in the AST\n * depth-first.\n *\n *   {\n *     type: 'Program',\n *     body: [{\n *       type: 'CallExpression',\n *       name: 'add',\n *       params: [{\n *         type: 'NumberLiteral',\n *         value: '2'\n *       }, {\n *         type: 'CallExpression',\n *         name: 'subtract',\n *         params: [{\n *           type: 'NumberLiteral',\n *           value: '4'\n *         }, {\n *           type: 'NumberLiteral',\n *           value: '2'\n *         }]\n *       }]\n *     }]\n *   }\n *\n * So for the above AST we would go:\n *\n *   1. Program - Starting at the top level of the AST\n *   2. CallExpression (add) - Moving to the first element of the Program's body\n *   3. NumberLiteral (2) - Moving to the first element of CallExpression's params\n *   4. CallExpression (subtract) - Moving to the second element of CallExpression's params\n *   5. NumberLiteral (4) - Moving to the first element of CallExpression's params\n *   6. NumberLiteral (2) - Moving to the second element of CallExpression's params\n *\n * If we were manipulating this AST directly, instead of creating a separate AST,\n * we would likely introduce all sorts of abstractions here. But just visiting\n * each node in the tree is enough for what we're trying to do.\n *\n * The reason I use the word \"visiting\" is because there is this pattern of how\n * to represent operations on elements of an object structure.\n *\n * Visitors\n * --------\n *\n * The basic idea here is that we are going to create a “visitor” object that\n * has methods that will accept different node types.\n *\n *   var visitor = {\n *     NumberLiteral() {},\n *     CallExpression() {},\n *   };\n *\n * When we traverse our AST, we will call the methods on this visitor whenever we\n * \"enter\" a node of a matching type.\n *\n * In order to make this useful we will also pass the node and a reference to\n * the parent node.\n *\n *   var visitor = {\n *     NumberLiteral(node, parent) {},\n *     CallExpression(node, parent) {},\n *   };\n *\n * However, there also exists the possibility of calling things on \"exit\". Imagine\n * our tree structure from before in list form:\n *\n *   - Program\n *     - CallExpression\n *       - NumberLiteral\n *       - CallExpression\n *         - NumberLiteral\n *         - NumberLiteral\n *\n * As we traverse down, we're going to reach branches with dead ends. As we\n * finish each branch of the tree we \"exit\" it. So going down the tree we\n * \"enter\" each node, and going back up we \"exit\".\n *\n *   -> Program (enter)\n *     -> CallExpression (enter)\n *       -> Number Literal (enter)\n *       <- Number Literal (exit)\n *       -> Call Expression (enter)\n *          -> Number Literal (enter)\n *          <- Number Literal (exit)\n *          -> Number Literal (enter)\n *          <- Number Literal (exit)\n *       <- CallExpression (exit)\n *     <- CallExpression (exit)\n *   <- Program (exit)\n *\n * In order to support that, the final form of our visitor will look like this:\n *\n *   var visitor = {\n *     NumberLiteral: {\n *       enter(node, parent) {},\n *       exit(node, parent) {},\n *     }\n *   };\n */\n\n/**\n * Code Generation\n * ---------------\n *\n * The final phase of a compiler is code generation. Sometimes compilers will do\n * things that overlap with transformation, but for the most part code\n * generation just means take our AST and string-ify code back out.\n *\n * Code generators work several different ways, some compilers will reuse the\n * tokens from earlier, others will have created a separate representation of\n * the code so that they can print nodes linearly, but from what I can tell most\n * will use the same AST we just created, which is what we’re going to focus on.\n *\n * Effectively our code generator will know how to “print” all of the different\n * node types of the AST, and it will recursively call itself to print nested\n * nodes until everything is printed into one long string of code.\n */\n\n/**\n * And that's it! That's all the different pieces of a compiler.\n *\n * Now that isn’t to say every compiler looks exactly like I described here.\n * Compilers serve many different purposes, and they might need more steps than\n * I have detailed.\n *\n * But now you should have a general high-level idea of what most compilers look\n * like.\n *\n * Now that I’ve explained all of this, you’re all good to go write your own\n * compilers right?\n *\n * Just kidding, that's what I'm here to help with :P\n *\n * So let's begin...\n */\n\n/**\n * ============================================================================\n *                                   (/^▽^)/\n *                                THE TOKENIZER!\n * ============================================================================\n */\n\n/**\n * We're gonna start off with our first phase of parsing, lexical analysis, with\n * the tokenizer.\n *\n * We're just going to take our string of code and break it down into an array\n * of tokens.\n *\n *   (add 2 (subtract 4 2))   =>   [{ type: 'paren', value: '(' }, ...]\n */\n\n// We start by accepting an input string of code, and we're gonna set up two\n// things...\nfunction tokenizer(input) {\n\n  // A `current` variable for tracking our position in the code like a cursor.\n  let current = 0;\n\n  // And a `tokens` array for pushing our tokens to.\n  let tokens = [];\n\n  // We start by creating a `while` loop where we are setting up our `current`\n  // variable to be incremented as much as we want `inside` the loop.\n  //\n  // We do this because we may want to increment `current` many times within a\n  // single loop because our tokens can be any length.\n  while (current < input.length) {\n\n    // We're also going to store the `current` character in the `input`.\n    let char = input[current];\n\n    // The first thing we want to check for is an open parenthesis. This will\n    // later be used for `CallExpression` but for now we only care about the\n    // character.\n    //\n    // We check to see if we have an open parenthesis:\n    if (char === '(') {\n\n      // If we do, we push a new token with the type `paren` and set the value\n      // to an open parenthesis.\n      tokens.push({\n        type: 'paren',\n        value: '(',\n      });\n\n      // Then we increment `current`\n      current++;\n\n      // And we `continue` onto the next cycle of the loop.\n      continue;\n    }\n\n    // Next we're going to check for a closing parenthesis. We do the same exact\n    // thing as before: Check for a closing parenthesis, add a new token,\n    // increment `current`, and `continue`.\n    if (char === ')') {\n      tokens.push({\n        type: 'paren',\n        value: ')',\n      });\n      current++;\n      continue;\n    }\n\n    // Moving on, we're now going to check for whitespace. This is interesting\n    // because we care that whitespace exists to separate characters, but it\n    // isn't actually important for us to store as a token. We would only throw\n    // it out later.\n    //\n    // So here we're just going to test for existence and if it does exist we're\n    // going to just `continue` on.\n    let WHITESPACE = /\\s/;\n    if (WHITESPACE.test(char)) {\n      current++;\n      continue;\n    }\n\n    // The next type of token is a number. This is different than what we have\n    // seen before because a number could be any number of characters and we\n    // want to capture the entire sequence of characters as one token.\n    //\n    //   (add 123 456)\n    //        ^^^ ^^^\n    //        Only two separate tokens\n    //\n    // So we start this off when we encounter the first number in a sequence.\n    let NUMBERS = /[0-9]/;\n    if (NUMBERS.test(char)) {\n\n      // We're going to create a `value` string that we are going to push\n      // characters to.\n      let value = '';\n\n      // Then we're going to loop through each character in the sequence until\n      // we encounter a character that is not a number, pushing each character\n      // that is a number to our `value` and incrementing `current` as we go.\n      while (NUMBERS.test(char)) {\n        value += char;\n        char = input[++current];\n      }\n\n      // After that we push our `number` token to the `tokens` array.\n      tokens.push({ type: 'number', value });\n\n      // And we continue on.\n      continue;\n    }\n\n    // We'll also add support for strings in our language which will be any\n    // text surrounded by double quotes (\").\n    //\n    //   (concat \"foo\" \"bar\")\n    //            ^^^   ^^^ string tokens\n    //\n    // We'll start by checking for the opening quote:\n    if (char === '\"') {\n      // Keep a `value` variable for building up our string token.\n      let value = '';\n\n      // We'll skip the opening double quote in our token.\n      char = input[++current];\n\n      // Then we'll iterate through each character until we reach another\n      // double quote.\n      while (char !== '\"') {\n        value += char;\n        char = input[++current];\n      }\n\n      // Skip the closing double quote.\n      char = input[++current];\n\n      // And add our `string` token to the `tokens` array.\n      tokens.push({ type: 'string', value });\n\n      continue;\n    }\n\n    // The last type of token will be a `name` token. This is a sequence of\n    // letters instead of numbers, that are the names of functions in our lisp\n    // syntax.\n    //\n    //   (add 2 4)\n    //    ^^^\n    //    Name token\n    //\n    let LETTERS = /[a-z]/i;\n    if (LETTERS.test(char)) {\n      let value = '';\n\n      // Again we're just going to loop through all the letters pushing them to\n      // a value.\n      while (LETTERS.test(char)) {\n        value += char;\n        char = input[++current];\n      }\n\n      // And pushing that value as a token with the type `name` and continuing.\n      tokens.push({ type: 'name', value });\n\n      continue;\n    }\n\n    // Finally if we have not matched a character by now, we're going to throw\n    // an error and completely exit.\n    throw new TypeError('I dont know what this character is: ' + char);\n  }\n\n  // Then at the end of our `tokenizer` we simply return the tokens array.\n  return tokens;\n}\n\n/**\n * ============================================================================\n *                                 ヽ/❀o ل͜ o\\ﾉ\n *                                THE PARSER!!!\n * ============================================================================\n */\n\n/**\n * For our parser we're going to take our array of tokens and turn it into an\n * AST.\n *\n *   [{ type: 'paren', value: '(' }, ...]   =>   { type: 'Program', body: [...] }\n */\n\n// Okay, so we define a `parser` function that accepts our array of `tokens`.\nfunction parser(tokens) {\n\n  // Again we keep a `current` variable that we will use as a cursor.\n  let current = 0;\n\n  // But this time we're going to use recursion instead of a `while` loop. So we\n  // define a `walk` function.\n  function walk() {\n\n    // Inside the walk function we start by grabbing the `current` token.\n    let token = tokens[current];\n\n    // We're going to split each type of token off into a different code path,\n    // starting off with `number` tokens.\n    //\n    // We test to see if we have a `number` token.\n    if (token.type === 'number') {\n\n      // If we have one, we'll increment `current`.\n      current++;\n\n      // And we'll return a new AST node called `NumberLiteral` and setting its\n      // value to the value of our token.\n      return {\n        type: 'NumberLiteral',\n        value: token.value,\n      };\n    }\n\n    // If we have a string we will do the same as number and create a\n    // `StringLiteral` node.\n    if (token.type === 'string') {\n      current++;\n\n      return {\n        type: 'StringLiteral',\n        value: token.value,\n      };\n    }\n\n    // Next we're going to look for CallExpressions. We start this off when we\n    // encounter an open parenthesis.\n    if (\n      token.type === 'paren' &&\n      token.value === '('\n    ) {\n\n      // We'll increment `current` to skip the parenthesis since we don't care\n      // about it in our AST.\n      token = tokens[++current];\n\n      // We create a base node with the type `CallExpression`, and we're going\n      // to set the name as the current token's value since the next token after\n      // the open parenthesis is the name of the function.\n      let node = {\n        type: 'CallExpression',\n        name: token.value,\n        params: [],\n      };\n\n      // We increment `current` *again* to skip the name token.\n      token = tokens[++current];\n\n      // And now we want to loop through each token that will be the `params` of\n      // our `CallExpression` until we encounter a closing parenthesis.\n      //\n      // Now this is where recursion comes in. Instead of trying to parse a\n      // potentially infinitely nested set of nodes we're going to rely on\n      // recursion to resolve things.\n      //\n      // To explain this, let's take our Lisp code. You can see that the\n      // parameters of the `add` are a number and a nested `CallExpression` that\n      // includes its own numbers.\n      //\n      //   (add 2 (subtract 4 2))\n      //\n      // You'll also notice that in our tokens array we have multiple closing\n      // parenthesis.\n      //\n      //   [\n      //     { type: 'paren',  value: '('        },\n      //     { type: 'name',   value: 'add'      },\n      //     { type: 'number', value: '2'        },\n      //     { type: 'paren',  value: '('        },\n      //     { type: 'name',   value: 'subtract' },\n      //     { type: 'number', value: '4'        },\n      //     { type: 'number', value: '2'        },\n      //     { type: 'paren',  value: ')'        }, <<< Closing parenthesis\n      //     { type: 'paren',  value: ')'        }, <<< Closing parenthesis\n      //   ]\n      //\n      // We're going to rely on the nested `walk` function to increment our\n      // `current` variable past any nested `CallExpression`.\n\n      // So we create a `while` loop that will continue until it encounters a\n      // token with a `type` of `'paren'` and a `value` of a closing\n      // parenthesis.\n      while (\n        (token.type !== 'paren') ||\n        (token.type === 'paren' && token.value !== ')')\n      ) {\n        // we'll call the `walk` function which will return a `node` and we'll\n        // push it into our `node.params`.\n        node.params.push(walk());\n        token = tokens[current];\n      }\n\n      // Finally we will increment `current` one last time to skip the closing\n      // parenthesis.\n      current++;\n\n      // And return the node.\n      return node;\n    }\n\n    // Again, if we haven't recognized the token type by now we're going to\n    // throw an error.\n    throw new TypeError(token.type);\n  }\n\n  // Now, we're going to create our AST which will have a root which is a\n  // `Program` node.\n  let ast = {\n    type: 'Program',\n    body: [],\n  };\n\n  // And we're going to kickstart our `walk` function, pushing nodes to our\n  // `ast.body` array.\n  //\n  // The reason we are doing this inside a loop is because our program can have\n  // `CallExpression` after one another instead of being nested.\n  //\n  //   (add 2 2)\n  //   (subtract 4 2)\n  //\n  while (current < tokens.length) {\n    ast.body.push(walk());\n  }\n\n  // At the end of our parser we'll return the AST.\n  return ast;\n}\n\n/**\n * ============================================================================\n *                                 ⌒(❀>◞౪◟<❀)⌒\n *                               THE TRAVERSER!!!\n * ============================================================================\n */\n\n/**\n * So now we have our AST, and we want to be able to visit different nodes with\n * a visitor. We need to be able to call the methods on the visitor whenever we\n * encounter a node with a matching type.\n *\n *   traverse(ast, {\n *     Program: {\n *       enter(node, parent) {\n *         // ...\n *       },\n *       exit(node, parent) {\n *         // ...\n *       },\n *     },\n *\n *     CallExpression: {\n *       enter(node, parent) {\n *         // ...\n *       },\n *       exit(node, parent) {\n *         // ...\n *       },\n *     },\n *\n *     NumberLiteral: {\n *       enter(node, parent) {\n *         // ...\n *       },\n *       exit(node, parent) {\n *         // ...\n *       },\n *     },\n *   });\n */\n\n// So we define a traverser function which accepts an AST and a\n// visitor. Inside we're going to define two functions...\nfunction traverser(ast, visitor) {\n\n  // A `traverseArray` function that will allow us to iterate over an array and\n  // call the next function that we will define: `traverseNode`.\n  function traverseArray(array, parent) {\n    array.forEach(child => {\n      traverseNode(child, parent);\n    });\n  }\n\n  // `traverseNode` will accept a `node` and its `parent` node. So that it can\n  // pass both to our visitor methods.\n  function traverseNode(node, parent) {\n\n    // We start by testing for the existence of a method on the visitor with a\n    // matching `type`.\n    let methods = visitor[node.type];\n\n    // If there is an `enter` method for this node type we'll call it with the\n    // `node` and its `parent`.\n    if (methods && methods.enter) {\n      methods.enter(node, parent);\n    }\n\n    // Next we are going to split things up by the current node type.\n    switch (node.type) {\n\n      // We'll start with our top level `Program`. Since Program nodes have a\n      // property named body that has an array of nodes, we will call\n      // `traverseArray` to traverse down into them.\n      //\n      // (Remember that `traverseArray` will in turn call `traverseNode` so  we\n      // are causing the tree to be traversed recursively)\n      case 'Program':\n        traverseArray(node.body, node);\n        break;\n\n      // Next we do the same with `CallExpression` and traverse their `params`.\n      case 'CallExpression':\n        traverseArray(node.params, node);\n        break;\n\n      // In the cases of `NumberLiteral` and `StringLiteral` we don't have any\n      // child nodes to visit, so we'll just break.\n      case 'NumberLiteral':\n      case 'StringLiteral':\n        break;\n\n      // And again, if we haven't recognized the node type then we'll throw an\n      // error.\n      default:\n        throw new TypeError(node.type);\n    }\n\n    // If there is an `exit` method for this node type we'll call it with the\n    // `node` and its `parent`.\n    if (methods && methods.exit) {\n      methods.exit(node, parent);\n    }\n  }\n\n  // Finally we kickstart the traverser by calling `traverseNode` with our ast\n  // with no `parent` because the top level of the AST doesn't have a parent.\n  traverseNode(ast, null);\n}\n\n/**\n * ============================================================================\n *                                   ⁽(◍˃̵͈̑ᴗ˂̵͈̑)⁽\n *                              THE TRANSFORMER!!!\n * ============================================================================\n */\n\n/**\n * Next up, the transformer. Our transformer is going to take the AST that we\n * have built and pass it to our traverser function with a visitor and will\n * create a new ast.\n *\n * ----------------------------------------------------------------------------\n *   Original AST                     |   Transformed AST\n * ----------------------------------------------------------------------------\n *   {                                |   {\n *     type: 'Program',               |     type: 'Program',\n *     body: [{                       |     body: [{\n *       type: 'CallExpression',      |       type: 'ExpressionStatement',\n *       name: 'add',                 |       expression: {\n *       params: [{                   |         type: 'CallExpression',\n *         type: 'NumberLiteral',     |         callee: {\n *         value: '2'                 |           type: 'Identifier',\n *       }, {                         |           name: 'add'\n *         type: 'CallExpression',    |         },\n *         name: 'subtract',          |         arguments: [{\n *         params: [{                 |           type: 'NumberLiteral',\n *           type: 'NumberLiteral',   |           value: '2'\n *           value: '4'               |         }, {\n *         }, {                       |           type: 'CallExpression',\n *           type: 'NumberLiteral',   |           callee: {\n *           value: '2'               |             type: 'Identifier',\n *         }]                         |             name: 'subtract'\n *       }]                           |           },\n *     }]                             |           arguments: [{\n *   }                                |             type: 'NumberLiteral',\n *                                    |             value: '4'\n * ---------------------------------- |           }, {\n *                                    |             type: 'NumberLiteral',\n *                                    |             value: '2'\n *                                    |           }]\n *  (sorry the other one is longer.)  |         }\n *                                    |       }\n *                                    |     }]\n *                                    |   }\n * ----------------------------------------------------------------------------\n */\n\n// So we have our transformer function which will accept the lisp ast.\nfunction transformer(ast) {\n\n  // We'll create a `newAst` which like our previous AST will have a program\n  // node.\n  let newAst = {\n    type: 'Program',\n    body: [],\n  };\n\n  // Next I'm going to cheat a little and create a bit of a hack. We're going to\n  // use a property named `context` on our parent nodes that we're going to push\n  // nodes to their parent's `context`. Normally you would have a better\n  // abstraction than this, but for our purposes this keeps things simple.\n  //\n  // Just take note that the context is a reference *from* the old ast *to* the\n  // new ast.\n  ast._context = newAst.body;\n\n  // We'll start by calling the traverser function with our ast and a visitor.\n  traverser(ast, {\n\n    // The first visitor method accepts any `NumberLiteral`\n    NumberLiteral: {\n      // We'll visit them on enter.\n      enter(node, parent) {\n        // We'll create a new node also named `NumberLiteral` that we will push to\n        // the parent context.\n        parent._context.push({\n          type: 'NumberLiteral',\n          value: node.value,\n        });\n      },\n    },\n\n    // Next we have `StringLiteral`\n    StringLiteral: {\n      enter(node, parent) {\n        parent._context.push({\n          type: 'StringLiteral',\n          value: node.value,\n        });\n      },\n    },\n\n    // Next up, `CallExpression`.\n    CallExpression: {\n      enter(node, parent) {\n\n        // We start creating a new node `CallExpression` with a nested\n        // `Identifier`.\n        let expression = {\n          type: 'CallExpression',\n          callee: {\n            type: 'Identifier',\n            name: node.name,\n          },\n          arguments: [],\n        };\n\n        // Next we're going to define a new context on the original\n        // `CallExpression` node that will reference the `expression`'s arguments\n        // so that we can push arguments.\n        node._context = expression.arguments;\n\n        // Then we're going to check if the parent node is a `CallExpression`.\n        // If it is not...\n        if (parent.type !== 'CallExpression') {\n\n          // We're going to wrap our `CallExpression` node with an\n          // `ExpressionStatement`. We do this because the top level\n          // `CallExpression` in JavaScript are actually statements.\n          expression = {\n            type: 'ExpressionStatement',\n            expression: expression,\n          };\n        }\n\n        // Last, we push our (possibly wrapped) `CallExpression` to the `parent`'s\n        // `context`.\n        parent._context.push(expression);\n      },\n    }\n  });\n\n  // At the end of our transformer function we'll return the new ast that we\n  // just created.\n  return newAst;\n}\n\n/**\n * ============================================================================\n *                               ヾ（〃＾∇＾）ﾉ♪\n *                            THE CODE GENERATOR!!!!\n * ============================================================================\n */\n\n/**\n * Now let's move onto our last phase: The Code Generator.\n *\n * Our code generator is going to recursively call itself to print each node in\n * the tree into one giant string.\n */\n\nfunction codeGenerator(node) {\n\n  // We'll break things down by the `type` of the `node`.\n  switch (node.type) {\n\n    // If we have a `Program` node. We will map through each node in the `body`\n    // and run them through the code generator and join them with a newline.\n    case 'Program':\n      return node.body.map(codeGenerator)\n        .join('\\n');\n\n    // For `ExpressionStatement` we'll call the code generator on the nested\n    // expression and we'll add a semicolon...\n    case 'ExpressionStatement':\n      return (\n        codeGenerator(node.expression) +\n        ';' // << (...because we like to code the *correct* way)\n      );\n\n    // For `CallExpression` we will print the `callee`, add an open\n    // parenthesis, we'll map through each node in the `arguments` array and run\n    // them through the code generator, joining them with a comma, and then\n    // we'll add a closing parenthesis.\n    case 'CallExpression':\n      return (\n        codeGenerator(node.callee) +\n        '(' +\n        node.arguments.map(codeGenerator)\n          .join(', ') +\n        ')'\n      );\n\n    // For `Identifier` we'll just return the `node`'s name.\n    case 'Identifier':\n      return node.name;\n\n    // For `NumberLiteral` we'll just return the `node`'s value.\n    case 'NumberLiteral':\n      return node.value;\n\n    // For `StringLiteral` we'll add quotations around the `node`'s value.\n    case 'StringLiteral':\n      return '\"' + node.value + '\"';\n\n    // And if we haven't recognized the node, we'll throw an error.\n    default:\n      throw new TypeError(node.type);\n  }\n}\n\n/**\n * ============================================================================\n *                                  (۶* ‘ヮ’)۶”\n *                         !!!!!!!!THE COMPILER!!!!!!!!\n * ============================================================================\n */\n\n/**\n * FINALLY! We'll create our `compiler` function. Here we will link together\n * every part of the pipeline.\n *\n *   1. input  => tokenizer   => tokens\n *   2. tokens => parser      => ast\n *   3. ast    => transformer => newAst\n *   4. newAst => generator   => output\n */\n\nfunction compiler(input) {\n  let tokens = tokenizer(input);\n  let ast    = parser(tokens);\n  let newAst = transformer(ast);\n  let output = codeGenerator(newAst);\n\n  // and simply return the output!\n  return output;\n}\n\n/**\n * ============================================================================\n *                                   (๑˃̵ᴗ˂̵)و\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!YOU MADE IT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n * ============================================================================\n */\n\n// Now I'm just exporting everything...\nmodule.exports = {\n  tokenizer,\n  parser,\n  traverser,\n  transformer,\n  codeGenerator,\n  compiler,\n};\n"
  }
]