Repository: cutelabnyc/nested-tuplets Branch: master Commit: 3ff1d168ba34 Files: 37 Total size: 163.8 KB Directory structure: gitextract_2qx2o3oy/ ├── .editorconfig ├── .gitignore ├── .npmignore ├── .vscode/ │ └── launch.json ├── LICENSE ├── README.md ├── build/ │ └── grammar.js ├── cli.js ├── grammar/ │ └── grammar.ne ├── grammar.html ├── index.js ├── inputs/ │ ├── avg-test.rhy │ ├── complex.rhy │ ├── easy-empty.rhy │ ├── easy-rest.rhy │ ├── easy.rhy │ ├── four-with6.rhy │ └── nested.rhy ├── package.json ├── src/ │ ├── build/ │ │ └── grammar.js │ ├── container.js │ ├── interval.js │ ├── nestup.js │ ├── onset.js │ ├── parseError.js │ ├── parser.js │ └── trackWriter.js ├── test/ │ ├── comments.test.js │ ├── dividedContainers.test.js │ ├── errors.test.js │ ├── grammar.test.js │ ├── nestup.test.js │ ├── rest.test.js │ ├── rotation.test.js │ └── sizedContainers.test.js ├── undefined.mid └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 indent_style = tab insert_final_newline = true trim_trailing_whitespace = true [package.json] indent_style = space tab_width = 2 [*.yaml] indent_style = space tab_width = 2 [*.md] indent_style = space tab_width = 2 ================================================ FILE: .gitignore ================================================ node_modules output yarn-error.log dist ================================================ FILE: .npmignore ================================================ .vscode img inputs output test ================================================ FILE: .vscode/launch.json ================================================ { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "args": [ "-u", "bdd", "--timeout", "999999", "--colors", "${workspaceFolder}/test" ], "internalConsoleOptions": "openOnSessionStart", "name": "Mocha Tests", "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha", "request": "launch", "skipFiles": [ "/**" ], "type": "pwa-node" }, { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": [ "/**" ], "program": "${workspaceFolder}/index.js", "args": ["-i", "inputs/easy.rhy", "out.mid"] } ] } ================================================ FILE: LICENSE ================================================ The Nestup License Copyright (c) 2021 Sam Tarakajian and Alex Van Gils Nestup has mixed license terms, with different terms for commercial and non-commercial use. For non-commercial use, Nestup is licensed under a modified MIT License which excludes the permission to sublicense or sell copies. For commercial use, contact the copyright holders or instead release your applications under the GNU General Public License v.3, which means, amongst other things, that you must make the source code of your Applications available. Non-Commercial License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, or distribute the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Commercial License: GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS ================================================ FILE: README.md ================================================ # Nestup, the Nested Tuplet Generator [[]_[]] It's Nestup! The domain specific language for describing and generating nested tuplets, just like you've always wanted. It also can divide anything that has dimension. ## Cheat Sheet | Nestup_example_expression | Description | Piano_roll | | ----------- | ----------- | ----------- | | `[4]` | One event, 4 beats long | ![](./img/cheat-01.png) | `[[2] [2]]` | Two events, each 2 beats long | ![](./img/cheat-02.png) | `[3 [2] [3]]` | Two events, squeezed into 3 beats. The first will have length `2/5` of 3 beats, and the second will have length `3/5` of 3 beats. | ![](./img/cheat-03.png) |`[[] []] [2, 3/7 [] []]`|Four events, with the second two events scaled at a ratio of `3:7` to the first two. |![](./img/cheat-scale2.png) | `[4] {3}` | Three events, evenly spaced over 4 beats (aka a triplet over 4 beats) | ![](./img/cheat-04.png) | `[4] {3} [4] {5}` | A 3:4 triplet followed by a 5:4 quintuplet | ![](./img/cheat-05.png) | `[4] {3 2 {3} }` | A triplet, where the second event has been itself subdivided into a triplet. A total of 5 note events | ![](./img/cheat-06.png) | `[4] {3 2:2 {5} }` | A triplet, where the second and third beat have been replaced with a quintuplet over that same time. A total of 6 events | ![](./img/cheat-07.png) | | `[4 [1] ['] [1]]` | Three equally long notes in the space of 4 beats (aka a triplet), where the second note is a rest | ![](./img/cheat-08.png) | | `[4 [1] [1] _ [1] [1]]` | Four notes in the space of four beats, The second note is tied to the third. | ![](./img/cheat-09.png) | | `[4 {5 2 [] _ 3 [] }]` | Five notes in the space of four beats, where the second note is tied to the third. | ![](./img/cheat-10.png) | | `[3] {3 > 1/2}` | Three notes in the space of three beats, offset by half a beat. | ![](./img/cheat-11.png) | | `['4] [2]` | An empty container, four beats long, followed by a note two beats long. | ![](./img/cheat-12.png) | ## Where am I? This repo is the home for the Nestup language and the documentation for the language itself. If you are looking for the Ableton Live device, you can find that [here](https://gum.co/nestup), and if you are looking for the online playground, you can find that [here](https://nestup.cutelab.nyc). ## Why Nestup? Most DAWs and other music software are designed to facilitate creating music with rhythmic subdivisions that divide in twos and into threes. However, there are many types of music in the world, such as tabla rhythms from Indian classical music, rhythms by musicians such as Tigran Hamasyan, drawing from Armenian folk traditions, or the nested tuplets common to "New Complexity" composers like Brian Ferneyhough, that do not divide solely into twos and threes. Most of these rhythms are rather difficult, or at least tedious, to program in any DAW. ![nested quintuplet](img/nested-tup-ex.png "Figure 1") With Nestup, programming such a rhythm can be quite easy: ``` [2] {5 4:2 {3} } ``` ![nested quintuplet](img/nested-tup-ex2.png "Figure 2") In addition, DAWs that employ looping clips, for example Ableton Live or Logic Pro, facilitate the creation of clips that are defined by a number of 16th note subdivisions, making a looping clip of a "[fragmentary rhythm](https://www.instagram.com/p/CFxKMSMAS22/?utm_source=ig_web_copy_link)" very difficult to create. Nestup is designed to be a simple and expressive solution for these and other rhythmic needs. ## Dividing Containers In Nestup, we describe containers which are divided into parts. For the purposes of this documentation, where we are talking about music, those containers are generally periods of time, and those parts are generally experienced as events in time. Music notation, and in particular "western" music notation, has its own conventions for describing the rhythmic subdivion of events in time. The Nestup language is simple in that it ignores many of these conventions. That is, Nestup doesn't care if you are in compound or simple meter, or whether the tuplet is described in sixteenth notes or eighth notes. A musician writing in Nestup simply describes when events (such as musical notes or rhythmic attacks) occur in a given period of time. ![5 against 4 eighth notes, followed by two quarter notes](img/ex-5-4.png "Figure 3") In the above figure, we see a measure of common time, where the first two beats of the measure contain 5 eighth notes in the space of 4 eighth notes, and the second half of the measure contains a quarter note on each beat. This could be rendered in multiple ways in Nestup, depending on the user's preference. One rendering of this rhythm could be: ``` [4 [] {5} [] {2} ] ``` Another way to write it could be: ``` [4] {4 1:2 [] {5} } ``` Nestup doesn't have an explicit notion of beats or time signatures, it simply divides containers (of time) and generates events. So, Nestup could render this rhythm in at least these two ways. Let's take a closer look at what these examples are doing. ## What These Examples Are Doing 1. Here, we specify a **container** `[]`, with a **size** of 4, with `[4]`. 2. A container can contain child containers—in our first example, our container contains two containers, `[]` and `[]`, of equal size. 3. A container can be subvidided equally using the **subdivider** `{}`. In our first example, the first child container is subdivided into 5 subdivisions with `{5}`, and the second child is subdivided into 2 with `{2}`. In our second example, we describe the rhythm a little differently. 1. We start, as in the first example, by specifying a container of size 4 with `[4]`. 2. This container is subdivided into 4 subdivisions with `{4}`. 3. A child container can be placed within those subdivisions, by specifying that container's **range**—where it should start, and how long it should continue. In the second example, the ranged container is placed on the first subdivision, stretched across two subdivisions, with `1:2 []`. 4. Finally, that ranged container is subdivided into 5 subdivisions with `{5}`. Both of these examples gives us the rhythm from Figure 1: five evenly spaced events followed by two evenly spaced events that take up the same amount of time as the first five. ## How Nestup Works We can now take a step back and describe the Nestup language systematically, starting from its most simple expression. ### The Container ``` [] ``` The **container,** specified by the square brackets `[]`, defines a period of time, for example, a beat or a measure. If you are using Nestup to generate musical rhythms in a DAW like Ableton Live, the simple expression `[]` will generate one note spanning one beat in the DAW's global time signature. This is because every container has a **size**, which is by default 1. If you wanted your container to be 4 beats long, like a whole note in a 4/4 time signature, you would define the container size with `[4]`. *The container size can be any positive integer.* Our `[4]` gives us a rhythm like: ![a whole note](img/ex-1.png "Figure 2") or, in the piano roll, ![a whole note in piano roll](img/pno-roll-1.png "Figure 4") #### Flexible Container A container can be divided into child containers, for example, `[[2] [2]]` will divide the container into two. Those child containers have a size of 2, and since the parent container has been given no explicit size, it is **flexible**, and inherits its size from the sum of its children's sizes—in this case, a size of 4. ![two half notes in piano roll](img/pno-roll-2.png "Figure 5") To give another example, `[[3] [2]]` will give us a container of size 5, for example, a five beat long rhythm, with a note spanning three beats and a note spanning two beats, like: ![[[3][2]] in piano roll](img/pno-roll-3.png "Figure 6") #### Fixed Container What if you wanted to specify the size of the parent container to be 4, but keep the 3:2 porportion of the child containers? You can do this by specifying a size of the parent container, making it a **fixed container**, as with ``` [4 [3] [2]] ``` ![[4[3][2]] in piano roll](img/pno-roll-4.png "Figure 7") With a combination of fixed and flexible parent and child containers, we can generate a wide variety of rhythms. #### Container Scale You can also **scale** the size of a container by a ratio of two positive integers. It cannot be a decimal number. For example, ``` [2 [] []] [2, 3/5[] []] ``` would generate a container of size two with two child containers, followed by a second container of size two with two child containers, this second one being 3/5 the size of the first. ![container scale in piano roll](img/pno-roll-6.png "Figure 8") In this way, Nestup facilitates the creation of looping clips with fragmentary meters in DAWs such as Ableton Live. Note that in the figure above, the end point of the loop is off of Ableton's "grid." Note: if you wish to scale a container and want to maintain its flexible size, simply writing a comma `,` followed by the desired ratio will add a container scale while maintaining the container's flexibility. For example, `[,8/3 [] []]`. This would be a container of size 2, because it is a parent container with children whose sizes sum to 2. That size is then multiplied by 8/3 to produce its final size. ### The Subdivider A positive integer wrapped in curly braces `{}` evenly divides a container into that many subdivisions. For example, `[4] {3}` might be rendered in conventional western musical notation as: ![a half-note triplet](img/ex-3.png "Figure 9") In the same way, `[4] {1}` gives us: ![a whole note](img/ex-1.png "Figure 10") And `[4] {13}` gives us: ![a 13-let](img/ex-13.png "Figure 11") *Warning:* A container can only be subdivided with the subdivider if it has no child containers. For example, the expression `[[]] {3}` **is not valid.** If you are subdividing a container of size 1 with no sibling containers, you can leave off the preceding `[]`. For example, `[] {5}` and `{5}` are equivalent. However, `{5} {5}` or `{5} [] {4}` **are not valid.** #### Ranged Containers Once you’ve subdivided a container, you can place more containers within those subdivisions. To place one of these ranged containers, you first specify a **range** for the container. The range includes a **start** and a **length.** The range length, written after the colon `:`, is used to stretch that ranged container across multiple subdivisions, but defaults to 1 subdivision if not otherwise specified. For example, to place the container `[[2] [1]]` on the first beat of a container subdivided into 3 parts, you would write: ``` [] {3 1 [[2] [1]]} ``` ![ranged container](img/pno-roll-7.png "Figure 12") `[] {3 1:2 [[2] [1]]}` would stretch the container across two subdivisions. ![range, length](img/pno-roll-8.png "Figure 13") #### Ranged Container Shorthand If you want to place a ranged container of size 1, you can simply declare the range start, or the range start and length, and the ranged container of size 1 will be implied. For example, the following two expressions are equivalent: ``` [] {8 1 [] 2 [] 3 [] 4:5 [] } ``` and ``` [] {8 1 2 3 4:5 } ``` ![range shorthand](img/pno-shorthand.png "Figure 14") *Warning:* The size of the ranged container will always be determined by its range expression. For this reason, you can not give a ranged container a fixed size: `{3 1 [2]}` **is not valid**. Additionally, a ranged container cannot have siblings: `{3 1 [] []}` **is not valid**, though it can have children, as demonstrated in the examples above. ### Empty Containers Up until this point, we have described containers full of rhythmic events. What if we want to describe a period of time that is empty? ``` ['4] ``` The expression above describes a container of size 4 which is empty. We can see such an empty container in context below: ``` [4] {3} ['4] [2] ``` ![empty](img/pno-empty-1.png "Figure 15") The **Empty Container** shares many characteristics with its non-empty counterpart: it has a container size, it can have a scale expressed as a ratio of two positive integers, and it can be subdivided using `{}` expressions. However, the empty container cannot have children. Why? Because the child containers would fill the empty container and it would no longer be empty. Therefore, if you write `['4[2]['3]]`, this will throw a syntax error. The correct form of this expression is `[4[2]['3]]`. It is perfectly possible to add rhythmic events into an empty container, however. You simply need to use the subdivider `{}`. Take for instance: ``` ['4] {16 1 {2} 8 {3} 16 } ``` ![empty 2](img/pno-empty-2.png "Figure 16") #### Rests A common use for an empty container is for adding rests. For example, ``` [] ['] [3] {5 2 ['] 4:2 ['] } ``` ![rests](img/pno-roll-10.png "Figure 17") ### Ties and Rotations Nestup has two additional features to help you generate rhythms: the ability to combine two adjascent containers, in a manner similar to a "tie" in western classical music notation, and the ability to "rotate" rhythmic events forward or backward in a subdivided container. #### Ties In Nestup, ties are written using the underscore `_` and connect sibling containers. When used, the subdivision before and after are combined. For example: `[3] {5} _ [] {3}` will give us: ![tie](img/pno-roll-9.png "Figure 18") #### Rotation Once you've subdivided a container, you can offset those subdivisions forward or backward using the rotation operators `>` or `<`. The **distance** of a rotation is defined in terms of the number of subdivisions, for example, if you've divided a container into 10 subdivisions, then rotating forward by 5 would have the effect of rotating all subdivisions forward by half of the parent container. You can see this demonstrated in the colored visualizer element along the bottom of the Ableton Live Nestup device in the following example: ![rotate-first](img/first-rotate.gif "Figure 19") Rotating in this subdivided container by 10 would have the same effect as not rotating at all. Rotations can be fractions, so you can rotate by 1/2 of 1 subdivision. This can be a nice way to achieve syncopation. ![rotate-diagram](img/rotationDiagram.png "Figure 20") *It could be helpful to visualize a grid of subdivisions, shifted over by the rotation distance* For example, to place a snare drum on beats "2" and "4" of a 4/4 measure, you might write the following expression: ``` ['4] {4 2 4 } ``` With **Rotation**, you could achieve a snare drum hitting on "2" and "4" with the following expression: ``` [4] {2 > 1/2} ``` In this second example, we've made two subdivisions (rather than four) of the parent container, and then used the character `>` to offset the start of those subdivisions by 1/2 of one subdivision. It is also possible to offset a rhythm backwards with `<`, by any ratio of one subdivision. For example: ``` [4] {3} [4] {3 < 1/3} ``` ![rotate](img/pno-rotate.png "Figure 21") You can see in the preceeding example that it appears as if there is a rest at the beginning of the second container. This is due to the first event of the subdivided second container being pushed past the beginning of the container and wrapping around the end of that container. This wrap-around effect can be seen in the following animation using the Ableton Live Nestup device. As the rotation distance approaches 1 (3/3), the final event in the container gets closer to wrapping around to the beginning of the container. ![rotate-anim](img/rotate.gif "Figure 22") ______ ## Ableton-specific documentation If you are using the [Nestup Max For Live device](https://gum.co/nestup) to parse your Nestup expressions, please visit the Nestup Max for Live Device Reference [here](https://nestup.s3.amazonaws.com/Manual+Versions/Nestup+Max+for+Live+Device+Reference+-+v1.0.1.pdf). You can find the Live device for purchase [here](https://gum.co/nestup). Thank you, have fun, and be in touch! ================================================ FILE: build/grammar.js ================================================ // Generated automatically by nearley, version 2.19.6 // http://github.com/Hardmath123/nearley (function () { function id(x) { return x[0]; } const moo = require("moo"); const lexer = moo.compile({ ws: { match: /\s+/, lineBreaks: true }, number: /[0-9]+/, word: /[a-z]+/, lp: /\(/, comma: /,/, rp: /\)/, lb: /\{/, rb: /\}/ }); var grammar = { Lexer: lexer, ParserRules: [ {"name": "tuple$ebnf$1", "symbols": ["_"], "postprocess": id}, {"name": "tuple$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "tuple$ebnf$2", "symbols": ["_"], "postprocess": id}, {"name": "tuple$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "tuple$ebnf$3", "symbols": ["_"], "postprocess": id}, {"name": "tuple$ebnf$3", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "tuple", "symbols": ["tuple$ebnf$1", "extension", "tuple$ebnf$2", "structure", "tuple$ebnf$3"], "postprocess": d => {return { extension: d[1], structure: d[3] }}}, {"name": "extension$ebnf$1", "symbols": ["_"], "postprocess": id}, {"name": "extension$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "extension$ebnf$2", "symbols": ["_"], "postprocess": id}, {"name": "extension$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "extension$ebnf$3", "symbols": ["_"], "postprocess": id}, {"name": "extension$ebnf$3", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "extension$ebnf$4", "symbols": ["_"], "postprocess": id}, {"name": "extension$ebnf$4", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "extension", "symbols": [(lexer.has("lp") ? {type: "lp"} : lp), "extension$ebnf$1", "index", "extension$ebnf$2", (lexer.has("comma") ? {type: "comma"} : comma), "extension$ebnf$3", "length", "extension$ebnf$4", (lexer.has("rp") ? {type: "rp"} : rp)], "postprocess": d => {return { index: d[2], length: d[6] }}}, {"name": "structure$ebnf$1", "symbols": ["_"], "postprocess": id}, {"name": "structure$ebnf$1", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "structure$ebnf$2", "symbols": ["_"], "postprocess": id}, {"name": "structure$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "structure$ebnf$3", "symbols": []}, {"name": "structure$ebnf$3", "symbols": ["structure$ebnf$3", "tuple"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "structure$ebnf$4", "symbols": ["_"], "postprocess": id}, {"name": "structure$ebnf$4", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "structure$ebnf$5", "symbols": ["_"], "postprocess": id}, {"name": "structure$ebnf$5", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "structure", "symbols": [(lexer.has("lb") ? {type: "lb"} : lb), "structure$ebnf$1", "division", "structure$ebnf$2", "structure$ebnf$3", "structure$ebnf$4", (lexer.has("rb") ? {type: "rb"} : rb), "structure$ebnf$5"], "postprocess": d => {return { division: d[2], subtuples: d[4] }}}, {"name": "index", "symbols": [(lexer.has("number") ? {type: "number"} : number)], "postprocess": d => parseInt(d.join(""))}, {"name": "length", "symbols": [(lexer.has("number") ? {type: "number"} : number)], "postprocess": d => parseInt(d.join(""))}, {"name": "division", "symbols": [(lexer.has("number") ? {type: "number"} : number)], "postprocess": d => parseInt(d.join(""))}, {"name": "_", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)], "postprocess": d => { return null; }} ] , ParserStart: "tuple" } if (typeof module !== 'undefined'&& typeof module.exports !== 'undefined') { module.exports = grammar; } else { window.grammar = grammar; } })(); ================================================ FILE: cli.js ================================================ const fs = require("fs"); const path = require("path"); const { RhythmParser, Nestup } = require("./index"); const writeOnsetsAsMidi = require("./src/trackWriter"); const { program } = require('commander'); program.version('0.1.0'); program .requiredOption('-i, --input ', 'input rhythm file (required)') .option('-w, --watch ', 'output directory for watch mode') .parse(process.argv); function process(text, outputFilePath) { const parser = new RhythmParser(); const parseTree = parser.parse(text); const nestup = new Nestup(parseTree); writeOnsetsAsMidi(nestup, "C3", 512, outputFilePath); } function makeOutName(container, prefix) { if (container) { const outName = `out-${Date.now()}`; return path.join(container, outName); } else { return prefix; } } let outName = makeOutName(program.watch, program.args[0]); let lastModTime = fs.statSync(program.input).mtime; // Process straight through console.log(program.input); fs.readFile(program.input, { encoding: "utf8" }, (err, contents) => { if (err) throw err; process(contents, outName); }); // Watch mode if (program.watch) { let location = path.dirname(program.input); console.log(`Watching ${program.input} for file changes`); fs.watch( program.input, { persistent: true, encoding: "utf8" }, (eventType, filename) => { if (eventType === "change") { const inpath = path.join(location, filename); const nmodtime = fs.statSync(inpath).mtime; if (nmodtime.getTime() !== lastModTime.getTime()) { lastModTime = nmodtime; outName = makeOutName(program.watch, program.args[0]); console.log(`Change detected, writing to ${outName}`); fs.readFile(path.join(location, filename), { encoding: "utf8" }, (err, contents) => { if (err) throw err; try { process(contents, outName); } catch (e) { console.error(e); } }); } } } ) } ================================================ FILE: grammar/grammar.ne ================================================ # Add the moo lexer @{% const moo = require("moo"); const lexer = moo.compile({ ws: { match: /\s+/, lineBreaks: true }, unsigned_integer_tk: /[0-9]+/, word: /[a-z]+/, lp: /\(/, comma: /,/, rp: /\)/, lb: /\{/, rb: /\}/, ls: /\[/, rs: /\]/, underscore: /_/, colon: /:/, prime: /'/, gt: />/, lt: / _:* {% d => [] %} | container_list_or_subdivisions _:* {% d => d[0] %} container_list_or_subdivisions -> _:* subdivisions {% d => { return [{ dimension: undefined, subdivisions: d[1] }] } %} | container_list {% d => d[0] %} # The containers can be tied together container_list -> container | container container_list {% d => { return [d[0]].concat(d[1]) } %} | container _:* %underscore container_list {% d => { d[0].tie = true; return [d[0]].concat(d[3]); } %} # A container can be sized or unsized (necessary for ranged containers) container -> _:* sized_container {% d => d[1] %} | _:* unsized_container {% d => d[1] %} # All containers must have either subcontainers or subdivisions, but not both sized_container -> sized_contents_with_subcontainers {% d => d[0] %} | sized_contents _:* subdivisions {% d => { return { dimension: d[0].dimension, empty: d[0].empty, subdivisions: d[2] }} %} | sized_contents {% d => d[0] %} unsized_container -> unsized_contents_with_subcontainers {% d => d[0] %} | unsized_contents _:* subdivisions {% d => { return { dimension: d[0].dimension, empty: d[0].empty, subdivisions: d[2] }} %} | unsized_contents {% d => d[0] %} # Sized contents have explicit dimension sized_contents -> %ls _:* dimension _:* %rs {% d => { return { dimension: d[2] }} %} | %ls _:* %prime _:* dimension _:* %rs {% d => { return { dimension: d[4], empty: true }} %} sized_contents_with_subcontainers -> %ls _:* dimension container_list_or_subdivisions _:* %rs {% d => { return { dimension: d[2], contents: d[3] }} %} # Unsized contents have no explicit dimension, only contents unsized_contents -> %ls _:* %rs {% d => { return { dimension: undefined, subdivisions: {division: 1} }} %} | %ls _:* %prime _:* %rs {% d => { return { dimension: undefined, empty: true, subdivisions: {division: 1} }} %} unsized_contents_with_subcontainers -> %ls container_list_or_subdivisions _:* %rs {% d => { return { dimension: { proportionality: "+", scale: 1 }, contents: d[1] }} %} # Container dimension must include at least one of proportionality or scale dimension -> integer {% d => { return { proportionality: d[0], scale: new Fraction(1) }} %} | %comma _:* ratio {% d => { return { proportionality: "+", scale: d[2] }} %} | integer _:* %comma _:* ratio {% d => { return { proportionality: d[0], scale: d[4] }} %} # Subdivisions is just a subdivision number followed by a list of ranged containers subdivisions -> %lb _:* integer ranged_container_list:? _:* %rb {% d => {return { division: d[2], ranges: d[3] }} %} | %lb _:* rotation ranged_container_list:? _:* %rb {% d => {return { division: 1, rotation: d[2], ranges: d[3] }} %} | %lb _:* integer _:* rotation ranged_container_list:? _:* %rb {% d => {return { division: d[2], rotation: d[4], ranges: d[5] }} %} rotation -> %lt _:* ratio {% d => d[2].mul(-1) %} | %gt _:* ratio {% d => d[2] %} # Ranged containers can also be tied ranged_container_list -> ranged_container {% d => [d[0]] %} | ranged_container ranged_container_list {% d => [d[0]].concat(d[1]) %} | ranged_container _:* %underscore ranged_container_list {% d => { d[0].container.tie = true; return [d[0]].concat(d[3]); } %} # A ranged container is a range followed by an unsized container, or a range followed by subdivisions ranged_container -> _:* range _:* unsized_container {% d => {return { range: d[1], container: d[3] }} %} | _:* range _:* subdivisions {% d => {return { range: d[1], container: { dimension: undefined, subdivisions: d[3] } }} %} | _:* range {% d => {return { range: d[1], container: { dimension: undefined, subdivisions: {division: 1} } }}%} # A range is an index followed by an optional length (defaults to 1) range -> integer {% d => {return { index: d[0], length: 1 }} %} | integer _:* %colon _:* integer {% d => {return { index: d[0], length: d[4] }} %} # A rational number is two integers separated by a slash ratio -> integer {% d => new Fraction(d[0]) %} | integer _:* %slash _:* integer {% d => new Fraction(d[0], d[4]) %} # An integer is, well, an integer integer -> %unsigned_integer_tk {% d => parseInt(d.join("")) %} # Whitespace _ -> %ws {% d => { return null; } %} | %comment {% d => { return null; } %} ================================================ FILE: grammar.html ================================================

nestup

_ container_list_or_subdivisions _

container_list_or_subdivisions

_ subdivisions container_list

container_list

container container container_list container _ underscore container_list

container

_ sized_container _ unsized_container

sized_container

sized_contents_with_subcontainers sized_contents _ subdivisions

unsized_container

unsized_contents_with_subcontainers unsized_contents _ subdivisions unsized_contents

sized_contents

ls _ dimension _ rs

sized_contents_with_subcontainers

ls _ dimension container_list_or_subdivisions _ rs ls container_list_or_subdivisions _ rs

unsized_contents

ls _ rs

unsized_contents_with_subcontainers

ls container_list_or_subdivisions _ rs

dimension

integer comma _ ratio integer _ comma _ ratio plus plus _ comma _ ratio

subdivisions

lb ranged_container_list _ rb lb _ integer ranged_container_list _ rb

ranged_container_list

ranged_container ranged_container ranged_container_list ranged_container _ underscore ranged_container_list

ranged_container

_ range _ unsized_container _ range _ subdivisions

range

lp _ integer _ rp lp _ integer _ comma _ integer _ rp

ratio

integer integer _ slash _ integer

integer

unsigned_integer_tk

_

ws
================================================ FILE: index.js ================================================ const RhythmParser = require("./src/parser"); const Container = require("./src/container"); const Onset = require("./src/onset"); const Interval = require("./src/interval"); const Nestup = require("./src/nestup"); const ParseError = require("./src/parseError"); module.exports = { Container, Interval, Onset, Nestup, ParseError, RhythmParser, }; ================================================ FILE: inputs/avg-test.rhy ================================================ [] {7 1:3 {5} 4:2 {5} 6 {2} } ================================================ FILE: inputs/complex.rhy ================================================ [4] {5 1:4 {3} 5 {4 4 {2} } } ================================================ FILE: inputs/easy-empty.rhy ================================================ ['4] {3 2 } ================================================ FILE: inputs/easy-rest.rhy ================================================ [4] {3 2 ['] } ================================================ FILE: inputs/easy.rhy ================================================ [4] {3} ================================================ FILE: inputs/four-with6.rhy ================================================ [] {4 3:2 {6} } ================================================ FILE: inputs/nested.rhy ================================================ [] {5 1:4 {3 1 {3 2 {7} } } } ================================================ FILE: package.json ================================================ { "name": "@cutelab/nestup", "version": "0.5.11", "description": "Parse a special hierarchical tuplet syntax, get a bunch of midi notes", "main": "index.js", "contributors": [ "Sam Tarakajian ", "Alex Van Gils " ], "license": "MIT", "private": false, "dependencies": { "chai": "^4.2.0", "commander": "^6.1.0", "fraction.js": "^4.0.12", "memoizee": "^0.4.14", "midi-writer-js": "^1.7.4", "mocha": "^8.2.0", "moo": "^0.5.1", "nearley": "^2.19.6" }, "scripts": { "pretest": "yarn run build-grammar", "prepublishOnly": "yarn run build", "build": "yarn run build-grammar && yarn run build-pack", "build-grammar": "mkdirp src/build && nearleyc grammar/grammar.ne --out ./src/build/grammar.js", "build-pack": "webpack", "start": "node cli.js", "test": "mocha", "test-grammar": "mocha -g Grammar" }, "directories": { "test": "test" }, "devDependencies": { "@babel/core": "^7.12.10", "@babel/preset-env": "^7.12.11", "babel-loader": "^8.2.2", "babel-plugin-transform-class-properties": "^6.24.1", "mkdirp": "^1.0.4", "webpack": "^5.11.0", "webpack-cli": "^4.2.0" }, "repository": { "type": "git", "url": "git+https://github.com/cutelabnyc/nested-tuplets.git" }, "author": "", "bugs": { "url": "https://github.com/cutelabnyc/nested-tuplets/issues" }, "homepage": "https://github.com/cutelabnyc/nested-tuplets#readme" } ================================================ FILE: src/build/grammar.js ================================================ // Generated automatically by nearley, version 2.19.6 // http://github.com/Hardmath123/nearley (function () { function id(x) { return x[0]; } const moo = require("moo"); const lexer = moo.compile({ ws: { match: /\s+/, lineBreaks: true }, unsigned_integer_tk: /[0-9]+/, word: /[a-z]+/, lp: /\(/, comma: /,/, rp: /\)/, lb: /\{/, rb: /\}/, ls: /\[/, rs: /\]/, underscore: /_/, colon: /:/, prime: /'/, gt: />/, lt: / []}, {"name": "nestup$ebnf$2", "symbols": []}, {"name": "nestup$ebnf$2", "symbols": ["nestup$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "nestup", "symbols": ["container_list_or_subdivisions", "nestup$ebnf$2"], "postprocess": d => d[0]}, {"name": "container_list_or_subdivisions$ebnf$1", "symbols": []}, {"name": "container_list_or_subdivisions$ebnf$1", "symbols": ["container_list_or_subdivisions$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "container_list_or_subdivisions", "symbols": ["container_list_or_subdivisions$ebnf$1", "subdivisions"], "postprocess": d => { return [{ dimension: undefined, subdivisions: d[1] }] }}, {"name": "container_list_or_subdivisions", "symbols": ["container_list"], "postprocess": d => d[0]}, {"name": "container_list", "symbols": ["container"]}, {"name": "container_list", "symbols": ["container", "container_list"], "postprocess": d => { return [d[0]].concat(d[1]) }}, {"name": "container_list$ebnf$1", "symbols": []}, {"name": "container_list$ebnf$1", "symbols": ["container_list$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "container_list", "symbols": ["container", "container_list$ebnf$1", (lexer.has("underscore") ? {type: "underscore"} : underscore), "container_list"], "postprocess": d => { d[0].tie = true; return [d[0]].concat(d[3]); }}, {"name": "container$ebnf$1", "symbols": []}, {"name": "container$ebnf$1", "symbols": ["container$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "container", "symbols": ["container$ebnf$1", "sized_container"], "postprocess": d => d[1]}, {"name": "container$ebnf$2", "symbols": []}, {"name": "container$ebnf$2", "symbols": ["container$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "container", "symbols": ["container$ebnf$2", "unsized_container"], "postprocess": d => d[1]}, {"name": "sized_container", "symbols": ["sized_contents_with_subcontainers"], "postprocess": d => d[0]}, {"name": "sized_container$ebnf$1", "symbols": []}, {"name": "sized_container$ebnf$1", "symbols": ["sized_container$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "sized_container", "symbols": ["sized_contents", "sized_container$ebnf$1", "subdivisions"], "postprocess": d => { return { dimension: d[0].dimension, empty: d[0].empty, subdivisions: d[2] }}}, {"name": "sized_container", "symbols": ["sized_contents"], "postprocess": d => d[0]}, {"name": "unsized_container", "symbols": ["unsized_contents_with_subcontainers"], "postprocess": d => d[0]}, {"name": "unsized_container$ebnf$1", "symbols": []}, {"name": "unsized_container$ebnf$1", "symbols": ["unsized_container$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "unsized_container", "symbols": ["unsized_contents", "unsized_container$ebnf$1", "subdivisions"], "postprocess": d => { return { dimension: d[0].dimension, empty: d[0].empty, subdivisions: d[2] }}}, {"name": "unsized_container", "symbols": ["unsized_contents"], "postprocess": d => d[0]}, {"name": "sized_contents$ebnf$1", "symbols": []}, {"name": "sized_contents$ebnf$1", "symbols": ["sized_contents$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "sized_contents$ebnf$2", "symbols": []}, {"name": "sized_contents$ebnf$2", "symbols": ["sized_contents$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "sized_contents", "symbols": [(lexer.has("ls") ? {type: "ls"} : ls), "sized_contents$ebnf$1", "dimension", "sized_contents$ebnf$2", (lexer.has("rs") ? {type: "rs"} : rs)], "postprocess": d => { return { dimension: d[2] }}}, {"name": "sized_contents$ebnf$3", "symbols": []}, {"name": "sized_contents$ebnf$3", "symbols": ["sized_contents$ebnf$3", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "sized_contents$ebnf$4", "symbols": []}, {"name": "sized_contents$ebnf$4", "symbols": ["sized_contents$ebnf$4", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "sized_contents$ebnf$5", "symbols": []}, {"name": "sized_contents$ebnf$5", "symbols": ["sized_contents$ebnf$5", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "sized_contents", "symbols": [(lexer.has("ls") ? {type: "ls"} : ls), "sized_contents$ebnf$3", (lexer.has("prime") ? {type: "prime"} : prime), "sized_contents$ebnf$4", "dimension", "sized_contents$ebnf$5", (lexer.has("rs") ? {type: "rs"} : rs)], "postprocess": d => { return { dimension: d[4], empty: true }}}, {"name": "sized_contents_with_subcontainers$ebnf$1", "symbols": []}, {"name": "sized_contents_with_subcontainers$ebnf$1", "symbols": ["sized_contents_with_subcontainers$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "sized_contents_with_subcontainers$ebnf$2", "symbols": []}, {"name": "sized_contents_with_subcontainers$ebnf$2", "symbols": ["sized_contents_with_subcontainers$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "sized_contents_with_subcontainers", "symbols": [(lexer.has("ls") ? {type: "ls"} : ls), "sized_contents_with_subcontainers$ebnf$1", "dimension", "container_list_or_subdivisions", "sized_contents_with_subcontainers$ebnf$2", (lexer.has("rs") ? {type: "rs"} : rs)], "postprocess": d => { return { dimension: d[2], contents: d[3] }}}, {"name": "unsized_contents$ebnf$1", "symbols": []}, {"name": "unsized_contents$ebnf$1", "symbols": ["unsized_contents$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "unsized_contents", "symbols": [(lexer.has("ls") ? {type: "ls"} : ls), "unsized_contents$ebnf$1", (lexer.has("rs") ? {type: "rs"} : rs)], "postprocess": d => { return { dimension: undefined, subdivisions: {division: 1} }}}, {"name": "unsized_contents$ebnf$2", "symbols": []}, {"name": "unsized_contents$ebnf$2", "symbols": ["unsized_contents$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "unsized_contents$ebnf$3", "symbols": []}, {"name": "unsized_contents$ebnf$3", "symbols": ["unsized_contents$ebnf$3", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "unsized_contents", "symbols": [(lexer.has("ls") ? {type: "ls"} : ls), "unsized_contents$ebnf$2", (lexer.has("prime") ? {type: "prime"} : prime), "unsized_contents$ebnf$3", (lexer.has("rs") ? {type: "rs"} : rs)], "postprocess": d => { return { dimension: undefined, empty: true, subdivisions: {division: 1} }}}, {"name": "unsized_contents_with_subcontainers$ebnf$1", "symbols": []}, {"name": "unsized_contents_with_subcontainers$ebnf$1", "symbols": ["unsized_contents_with_subcontainers$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "unsized_contents_with_subcontainers", "symbols": [(lexer.has("ls") ? {type: "ls"} : ls), "container_list_or_subdivisions", "unsized_contents_with_subcontainers$ebnf$1", (lexer.has("rs") ? {type: "rs"} : rs)], "postprocess": d => { return { dimension: { proportionality: "+", scale: 1 }, contents: d[1] }}}, {"name": "dimension", "symbols": ["integer"], "postprocess": d => { return { proportionality: d[0], scale: new Fraction(1) }}}, {"name": "dimension$ebnf$1", "symbols": []}, {"name": "dimension$ebnf$1", "symbols": ["dimension$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "dimension", "symbols": [(lexer.has("comma") ? {type: "comma"} : comma), "dimension$ebnf$1", "ratio"], "postprocess": d => { return { proportionality: "+", scale: d[2] }}}, {"name": "dimension$ebnf$2", "symbols": []}, {"name": "dimension$ebnf$2", "symbols": ["dimension$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "dimension$ebnf$3", "symbols": []}, {"name": "dimension$ebnf$3", "symbols": ["dimension$ebnf$3", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "dimension", "symbols": ["integer", "dimension$ebnf$2", (lexer.has("comma") ? {type: "comma"} : comma), "dimension$ebnf$3", "ratio"], "postprocess": d => { return { proportionality: d[0], scale: d[4] }}}, {"name": "subdivisions$ebnf$1", "symbols": []}, {"name": "subdivisions$ebnf$1", "symbols": ["subdivisions$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "subdivisions$ebnf$2", "symbols": ["ranged_container_list"], "postprocess": id}, {"name": "subdivisions$ebnf$2", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "subdivisions$ebnf$3", "symbols": []}, {"name": "subdivisions$ebnf$3", "symbols": ["subdivisions$ebnf$3", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "subdivisions", "symbols": [(lexer.has("lb") ? {type: "lb"} : lb), "subdivisions$ebnf$1", "integer", "subdivisions$ebnf$2", "subdivisions$ebnf$3", (lexer.has("rb") ? {type: "rb"} : rb)], "postprocess": d => {return { division: d[2], ranges: d[3] }}}, {"name": "subdivisions$ebnf$4", "symbols": []}, {"name": "subdivisions$ebnf$4", "symbols": ["subdivisions$ebnf$4", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "subdivisions$ebnf$5", "symbols": ["ranged_container_list"], "postprocess": id}, {"name": "subdivisions$ebnf$5", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "subdivisions$ebnf$6", "symbols": []}, {"name": "subdivisions$ebnf$6", "symbols": ["subdivisions$ebnf$6", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "subdivisions", "symbols": [(lexer.has("lb") ? {type: "lb"} : lb), "subdivisions$ebnf$4", "rotation", "subdivisions$ebnf$5", "subdivisions$ebnf$6", (lexer.has("rb") ? {type: "rb"} : rb)], "postprocess": d => {return { division: 1, rotation: d[2], ranges: d[3] }}}, {"name": "subdivisions$ebnf$7", "symbols": []}, {"name": "subdivisions$ebnf$7", "symbols": ["subdivisions$ebnf$7", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "subdivisions$ebnf$8", "symbols": []}, {"name": "subdivisions$ebnf$8", "symbols": ["subdivisions$ebnf$8", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "subdivisions$ebnf$9", "symbols": ["ranged_container_list"], "postprocess": id}, {"name": "subdivisions$ebnf$9", "symbols": [], "postprocess": function(d) {return null;}}, {"name": "subdivisions$ebnf$10", "symbols": []}, {"name": "subdivisions$ebnf$10", "symbols": ["subdivisions$ebnf$10", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "subdivisions", "symbols": [(lexer.has("lb") ? {type: "lb"} : lb), "subdivisions$ebnf$7", "integer", "subdivisions$ebnf$8", "rotation", "subdivisions$ebnf$9", "subdivisions$ebnf$10", (lexer.has("rb") ? {type: "rb"} : rb)], "postprocess": d => {return { division: d[2], rotation: d[4], ranges: d[5] }}}, {"name": "rotation$ebnf$1", "symbols": []}, {"name": "rotation$ebnf$1", "symbols": ["rotation$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "rotation", "symbols": [(lexer.has("lt") ? {type: "lt"} : lt), "rotation$ebnf$1", "ratio"], "postprocess": d => d[2].mul(-1)}, {"name": "rotation$ebnf$2", "symbols": []}, {"name": "rotation$ebnf$2", "symbols": ["rotation$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "rotation", "symbols": [(lexer.has("gt") ? {type: "gt"} : gt), "rotation$ebnf$2", "ratio"], "postprocess": d => d[2]}, {"name": "ranged_container_list", "symbols": ["ranged_container"], "postprocess": d => [d[0]]}, {"name": "ranged_container_list", "symbols": ["ranged_container", "ranged_container_list"], "postprocess": d => [d[0]].concat(d[1])}, {"name": "ranged_container_list$ebnf$1", "symbols": []}, {"name": "ranged_container_list$ebnf$1", "symbols": ["ranged_container_list$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "ranged_container_list", "symbols": ["ranged_container", "ranged_container_list$ebnf$1", (lexer.has("underscore") ? {type: "underscore"} : underscore), "ranged_container_list"], "postprocess": d => { d[0].container.tie = true; return [d[0]].concat(d[3]); }}, {"name": "ranged_container$ebnf$1", "symbols": []}, {"name": "ranged_container$ebnf$1", "symbols": ["ranged_container$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "ranged_container$ebnf$2", "symbols": []}, {"name": "ranged_container$ebnf$2", "symbols": ["ranged_container$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "ranged_container", "symbols": ["ranged_container$ebnf$1", "range", "ranged_container$ebnf$2", "unsized_container"], "postprocess": d => {return { range: d[1], container: d[3] }}}, {"name": "ranged_container$ebnf$3", "symbols": []}, {"name": "ranged_container$ebnf$3", "symbols": ["ranged_container$ebnf$3", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "ranged_container$ebnf$4", "symbols": []}, {"name": "ranged_container$ebnf$4", "symbols": ["ranged_container$ebnf$4", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "ranged_container", "symbols": ["ranged_container$ebnf$3", "range", "ranged_container$ebnf$4", "subdivisions"], "postprocess": d => {return { range: d[1], container: { dimension: undefined, subdivisions: d[3] } }}}, {"name": "ranged_container$ebnf$5", "symbols": []}, {"name": "ranged_container$ebnf$5", "symbols": ["ranged_container$ebnf$5", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "ranged_container", "symbols": ["ranged_container$ebnf$5", "range"], "postprocess": d => {return { range: d[1], container: { dimension: undefined, subdivisions: {division: 1} } }}}, {"name": "range", "symbols": ["integer"], "postprocess": d => {return { index: d[0], length: 1 }}}, {"name": "range$ebnf$1", "symbols": []}, {"name": "range$ebnf$1", "symbols": ["range$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "range$ebnf$2", "symbols": []}, {"name": "range$ebnf$2", "symbols": ["range$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "range", "symbols": ["integer", "range$ebnf$1", (lexer.has("colon") ? {type: "colon"} : colon), "range$ebnf$2", "integer"], "postprocess": d => {return { index: d[0], length: d[4] }}}, {"name": "ratio", "symbols": ["integer"], "postprocess": d => new Fraction(d[0])}, {"name": "ratio$ebnf$1", "symbols": []}, {"name": "ratio$ebnf$1", "symbols": ["ratio$ebnf$1", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "ratio$ebnf$2", "symbols": []}, {"name": "ratio$ebnf$2", "symbols": ["ratio$ebnf$2", "_"], "postprocess": function arrpush(d) {return d[0].concat([d[1]]);}}, {"name": "ratio", "symbols": ["integer", "ratio$ebnf$1", (lexer.has("slash") ? {type: "slash"} : slash), "ratio$ebnf$2", "integer"], "postprocess": d => new Fraction(d[0], d[4])}, {"name": "integer", "symbols": [(lexer.has("unsigned_integer_tk") ? {type: "unsigned_integer_tk"} : unsigned_integer_tk)], "postprocess": d => parseInt(d.join(""))}, {"name": "_", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)], "postprocess": d => { return null; }}, {"name": "_", "symbols": [(lexer.has("comment") ? {type: "comment"} : comment)], "postprocess": d => { return null; }} ] , ParserStart: "nestup" } if (typeof module !== 'undefined'&& typeof module.exports !== 'undefined') { module.exports = grammar; } else { window.grammar = grammar; } })(); ================================================ FILE: src/container.js ================================================ const Interval = require("./interval"); const Onset = require("./onset"); const Fraction = require("fraction.js"); module.exports = class Container { constructor(containerDescription, index) { // Set internal proportionality and scale if (containerDescription.dimension) { const dim = containerDescription.dimension; if (dim.proportionality === "+") { this._proportionality = dim.proportionality; } else { this._proportionality = dim.proportionality ? new Fraction(dim.proportionality) : new Fraction(1); } this._scale = dim.scale ? dim.scale : new Fraction(1); } else { this._proportionality = new Fraction(1); this._scale = new Fraction(1); } if (containerDescription.contents) { this._contents = containerDescription.contents.map((c, idx) => new Container(c, idx + 1)); } else if (containerDescription.subdivisions){ this._division = containerDescription.subdivisions.division; this._rotation = containerDescription.subdivisions.rotation; if (containerDescription.subdivisions.ranges) { this._ranges = containerDescription.subdivisions.ranges.map(({range, container}, idx) => { return { range: new Interval(range.index, range.length), container: new Container(container, idx + 1) } }); } else { this._ranges = []; } } else { this._division = 1; this._ranges = []; } this._index = index; this._tie = !!containerDescription.tie; this._empty = !!containerDescription.empty; } get proportionality() { if (this._proportionality === "+") { if (this._contents) { return this._contents.reduce((prev, c) => { return prev.add(c.proportionality) }, new Fraction(0)).mul(this._scale); } else { return this._scale; } } else { return this._proportionality.mul(this._scale); } } get scale() { return this._scale; } get tie() { return this._tie; } normalizedOnsets() { let out = []; // Special case: if the division is one, we encode a rest. if (this._empty || this._division === 0) { out.push(new Onset( new Fraction(0), Onset.type.OFF, (this._index !== undefined) ? `${this._index}` : undefined )); if (this._division === 0) return out; } if (this._contents) { let runningP = new Fraction(0); const totalP = this._contents.reduce((prev, c) => prev.add(c.proportionality), new Fraction(0)); let lastContainerTied = false; this._contents.forEach(c => { const onsets = c.normalizedOnsets(); if (c.tie) onsets.pop(); // Get rid of the last note off event const scale = c.proportionality.div(totalP); onsets.forEach(o => { if (lastContainerTied && o.type === Onset.type.ON) { lastContainerTied = false; } else { out.push(new Onset( o.time.mul(scale).add(runningP), o.type, (this._index !== undefined) ? `${this._index}${o.path}` : undefined )); } }); runningP = runningP.add(scale); lastContainerTied = c.tie; }); } else { // Add an onset for each position that doesn't intersect a subtuplet if (!this._empty) { for (let i = 0; i < this._division; i++) { let intersector = this._ranges.findIndex(({ range }) => range.intersects(i + 1)); if (intersector === -1) out.push(new Onset( new Fraction(i, this._division), Onset.type.ON, this._index ? `${this._index}` : undefined )); } } // Add onsets from all the other subtuplets let lastContainerTied = false; this._ranges.forEach(({range, container: st}) => { const {index, length} = range; let offset = new Fraction((index - 1), this._division); let scale = new Fraction(length, this._division); let onsets = st.normalizedOnsets(); if (st.tie) onsets.pop(); // Get rid of the last note off event onsets.forEach(onset => { if (lastContainerTied && onset.type === Onset.type.ON) { lastContainerTied = false } else { out.push(new Onset( onset.time.mul(scale).add(offset), onset.type, (this._index !== undefined) ? `${this._index}${onset.path}` : undefined )); } }); lastContainerTied = st.tie; }); // sort out = out.sort((oa, ob) => { return oa.time.compare(ob.time); }); } // Rotate the onsets if there is a rotation if (!!this._rotation) { let normalizedRotation = this._rotation; if (normalizedRotation.compare(0) < 0) { normalizedRotation = normalizedRotation.mod(this._division).add(this._division).mod(this._division); } else { normalizedRotation = normalizedRotation.mod(this._division); } normalizedRotation = normalizedRotation.mul(new Fraction(1, this._division)); out.forEach(o => { o._time = o._time.add(normalizedRotation).mod(1); }); // sort out = out.sort((oa, ob) => { return oa.time.compare(ob.time); }); } // Add an off event at the end, if there are any on events if (out.findIndex(o => o.type === Onset.type.ON) !== -1) { out.push(new Onset( new Fraction(1.0), Onset.type.OFF, this._index ? `${this._index}` : undefined )); } // Filter duplicates let i = 0; while (i < out.length) { if (i >= (out.length - 1)) break; if (out[i].time.equals(out[i + 1].time)) { if (out[i].type === Onset.type.OFF && out[i + 1].type === Onset.type.ON) { out.splice(i, 1); } else if (out[i].type === Onset.type.ON && out[i + 1].type === Onset.type.OFF) { out.splice(i + 1, 1); } else { if (out[i].path && out[i + 1].path && out[i].path.length > out[i + 1].path.length) { out.splice(i + 1, 1); } else { out.splice(i, 1); } } } else { i++; } } return out; } } ================================================ FILE: src/interval.js ================================================ module.exports = class Interval{ constructor(index, length) { this._index = index; this._length = length; } get index() { return this._index; } get length() { return this._length; } intersects(index) { return index >= this.index && index < (this.index + this.length); } } ================================================ FILE: src/nestup.js ================================================ const Container = require("./container"); const Onset = require("./onset"); const Fraction = require("fraction.js"); const memoize = require("memoizee"); module.exports = class Nestup { constructor(parseTree) { // Nestup roots everything in a single, additive container const rootContainerDescripiton = { dimension: { proportionality: "+", scale: 1 }, contents: parseTree }; this._rootContainer = new Container(rootContainerDescripiton, 1); } get beatLength() { return this._inherentLength().valueOf(); } onOffEvents(gridsize) { let events = this._onOffEvents(); if (gridsize) { events = this._snapToGrid(events, gridsize); } return this._toFloats(events); } _inherentLength = memoize(() => { return this._rootContainer.proportionality; }); _normalizedOnsets = memoize(() => { return this._rootContainer.normalizedOnsets(); }); _snapToGrid = memoize((events, tickDuration) => { return events.map(e => { return { time: Math.round(e.time.mul(tickDuration).valueOf()), on: e.on, path: e.path }; }); }); _onOffEvents = memoize(() => { const onsets = this._normalizedOnsets(); let lastOnset = null; let outEvents = []; onsets.forEach(e => { if (e.type === Onset.type.ON) { if (lastOnset && lastOnset.type === Onset.type.ON) { outEvents.push({ time: e.time, on: false, path: e.path }); } outEvents.push({ time: e.time, on: true, path: e.path }); } else { if (lastOnset && lastOnset.type === Onset.type.ON) { outEvents.push({ time: e.time, on: false, path: e.path }); } } lastOnset = e; }); if (lastOnset && lastOnset.type === Onset.type.ON) { outEvents.push({ time: new Fraction(1), on: false, path: lastOnset.path }); } return outEvents; }); _toFloats = memoize((events) => { return events.map(e => Object.assign({}, e, { time: e.time.valueOf() })); }); } ================================================ FILE: src/onset.js ================================================ class Onset { constructor(time, type, path) { this._time = time; this._type = type; this._path = path; } get time() { return this._time; } get type() { return this._type; } get path() { return this._path; } } Onset.type = Object.freeze({ ON: "ON", OFF: "OFF", }); module.exports = Onset; ================================================ FILE: src/parseError.js ================================================ module.exports = class ParseError { constructor(rawNearleyError) { const errormessage = rawNearleyError.message; const splitByLine = errormessage.split("\n"); const line1 = splitByLine[0]; const dreg = /\d+/; let lineAnchor = line1.indexOf("line"); let colAnchor = line1.indexOf("col"); let line = Number.parseInt(dreg.exec(line1.substr(lineAnchor))); let col = Number.parseInt(dreg.exec(line1.substr(colAnchor))); this._line = line; this._col = col; const line5 = splitByLine[4]; const periodAnchor = line5.indexOf(". "); const shortMessage = line5.substr(0, periodAnchor + 1); this._shortMessage = shortMessage; if (rawNearleyError.token) { this._token = rawNearleyError.token.text; } else if (this.col !== undefined) { this._token = splitByLine[2].charAt(col + 1); } } get line() { return this._line; } get col() { return this._col; } get message() { return this._shortMessage; } get token() { return this._token; } } ================================================ FILE: src/parser.js ================================================ const nearley = require("nearley"); const grammar = require("./build/grammar.js"); module.exports = class RhythmParser { constructor() { this._parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar)); } parse(text) { this._parser.feed(text); // First result, just in case the grammar is ambiguous, which it shouldn't be return this._parser.results[0]; } } ================================================ FILE: src/trackWriter.js ================================================ const midiWriter = require("midi-writer-js"); module.exports = function writeOnsetsAsMidi(nestup, pitch, ticks, outfile) { // Assume 4 beats to one measure const track = new midiWriter.Track(); const midiLikeEvents = nestup.onOffEvents(ticks); let lastEvent = null; let tickCounter = 0; let noteStartTick = 0; midiLikeEvents.forEach((event) => { if (event.on) { noteStartTick = event.time; } else { const duration = event.time - noteStartTick; const wait = noteStartTick - tickCounter; track.addEvent(new midiWriter.NoteEvent({ pitch: pitch, duration: "T" + duration, wait: "T" + wait })); tickCounter += (wait + duration); } }); const write = new midiWriter.Writer(track); write.saveMIDI(outfile); } ================================================ FILE: test/comments.test.js ================================================ require("mocha"); const { expect } = require("chai"); const { RhythmParser, Nestup } = require("../index"); const Fraction = require("fraction.js"); describe("Comments", () => { it("encodes right rotation, with a comment", () => { const input = `[2 // This is a comment ] {1 > 1/4}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(nestup.beatLength).to.equal(2); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(2); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(25); expect(midiLikeEvents[1].time).to.equal(100); }); it("encodes left rotation, with comments", () => { const input = `// This is a comment // And another [2] {1 < 1/4} // One more comment for the road`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(nestup.beatLength).to.equal(2); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(2); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(75); expect(midiLikeEvents[1].time).to.equal(100); }); }); ================================================ FILE: test/dividedContainers.test.js ================================================ require("mocha"); const { expect } = require("chai"); const { RhythmParser, Container, Onset } = require("../index"); const Fraction = require("fraction.js"); describe("Subdivided Containers", () => { it("parses a basic tuplet", () => { const input = `{3}`; const parseTree = new RhythmParser().parse(input); const containerDescription = parseTree[0]; const tup = new Container(containerDescription); const onsets = tup.normalizedOnsets(); expect(onsets).to.have.length(4); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[1].time.equals(new Fraction(1, 3))).to.be.true; expect(onsets[2].time.equals(new Fraction(2, 3))).to.be.true; expect(onsets[3].time.equals(new Fraction(1))).to.be.true; }); it("parses a nested tuplet", () => { const input = `{3 1:1 {3} }`; const parseTree = new RhythmParser().parse(input); const containerDescription = parseTree[0]; const tup = new Container(containerDescription); const onsets = tup.normalizedOnsets(); expect(onsets).to.have.length(6); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[1].time.equals(new Fraction(1, 9))).to.be.true; expect(onsets[2].time.equals(new Fraction(2, 9))).to.be.true; expect(onsets[3].time.equals(new Fraction(1, 3))).to.be.true; expect(onsets[4].time.equals(new Fraction(2, 3))).to.be.true; expect(onsets[5].time.equals(new Fraction(1))).to.be.true; }); it("handles rests", () => { const input = `[4] {0}`; const parseTree = new RhythmParser().parse(input); const containerDescription = parseTree[0]; const tup = new Container(containerDescription); const onsets = tup.normalizedOnsets(); expect(onsets[0].type).to.equal(Onset.type.OFF); }); it("handles subtuples with rests", () => { const input = `[4] {3 2:1 {0} }`; const parseTree = new RhythmParser().parse(input); const containerDescription = parseTree[0]; const tup = new Container(containerDescription); const onsets = tup.normalizedOnsets(); expect(onsets[1].type).to.equal(Onset.type.OFF); }); it("handles overlapped rests", () => { const input = `[4] {3 1:3 {0} 2:1 {1} }`; const parseTree = new RhythmParser().parse(input); const containerDescription = parseTree[0]; const tup = new Container(containerDescription); const onsets = tup.normalizedOnsets(); expect(onsets).to.have.length(4); expect(onsets[0].type).to.equal(Onset.type.OFF); expect(onsets[1].type).to.equal(Onset.type.ON); expect(onsets[2].type).to.equal(Onset.type.OFF); expect(onsets[3].type).to.equal(Onset.type.OFF); }); }); ================================================ FILE: test/errors.test.js ================================================ require("mocha"); const { expect, assert } = require("chai"); const { RhythmParser, ParseError } = require("../index"); describe("Parse errors", () => { it("identifies obvious line errors", () => { const input = `{1} a`; const parser = new RhythmParser(); try { const result = parser.parse(input); assert.fail("Should have thrown an error"); } catch (e) { const pe = new ParseError(e); expect(pe.line).to.equal(1); expect(pe.col).to.equal(5); expect(pe.message).to.contain("Unexpected word token: \"a\"."); expect(pe.token).to.equals("a"); } }); it("identifies lexer errors", () => { const input = `[2, 3 * 4] {5}`; const parser = new RhythmParser(); try { const result = parser.parse(input); assert.fail("Should have thrown an error"); } catch (e) { const pe = new ParseError(e); expect(pe.line).to.equal(1); expect(pe.col).to.equal(7); expect(pe.message).to.contain("Unexpected input (lexer error)."); expect(pe.token).to.equals("*"); } }); }); ================================================ FILE: test/grammar.test.js ================================================ require("mocha"); const { expect } = require("chai"); const { RhythmParser, ParseError } = require("../index"); const Fraction = require("fraction.js"); describe("Grammar: Bare minimum", () => { it("loads the grammar", () => { expect(RhythmParser).not.to.be.undefined; }); }); describe("Grammar: Generating parse trees", () => { it("parses an empty string", () => { const input = ""; const parser = new RhythmParser(); const result = parser.parse(input); expect(result).to.be.an.instanceOf(Array); expect(result).to.have.length(0); }); it("parses a simple rhythm", () => { const input = ` {3} `; const parser = new RhythmParser(); const result = parser.parse(input); expect(result).to.be.an.instanceOf(Array); expect(result).to.have.length(1); const container = result[0]; expect(container).to.haveOwnProperty("dimension"); expect(container).to.haveOwnProperty("subdivisions"); expect(container.dimension).to.equal(undefined); const subdivisions = container.subdivisions; expect(subdivisions).to.have.property("division").that.is.a("number"); expect(subdivisions).to.have.property("ranges").that.is.null; }); it("parses a nested rhythm", () => { const input = ` {3 1:2 {3}} `; const parser = new RhythmParser(); const result = parser.parse(input); const container = result[0]; expect(container).to.haveOwnProperty("subdivisions"); const subdivisions = container.subdivisions; expect(subdivisions).to.have.property("division").that.equals(3); expect(subdivisions).to.have.property("ranges").that.is.an.instanceOf(Array).that.has.length(1); const rangedContainer = subdivisions.ranges[0]; expect(rangedContainer).to.have.property("range").that.is.a("object"); expect(rangedContainer).to.have.property("container").that.is.a("object"); const range = rangedContainer.range; const subcontainer = rangedContainer.container; expect(range).to.have.property("index").that.equals(1); expect(range).to.have.property("length").that.equals(2); expect(subcontainer).to.have.property("subdivisions").that.is.a("object"); expect(subcontainer.subdivisions.division).to.equal(3); }); it("handles multiple ranged containers", () => { const input = ` {2 1 {3} 2 {4} } `; const parser = new RhythmParser(); const result = parser.parse(input); const container = result[0]; expect(container).to.haveOwnProperty("subdivisions"); expect(container.subdivisions).to.have.property("division").that.equals(2); expect(container.subdivisions).to.haveOwnProperty("ranges").with.length(2); expect(container.subdivisions.ranges[0].container.subdivisions.division).to.equal(3); expect(container.subdivisions.ranges[1].container.subdivisions.division).to.equal(4); }); it("parses a rhythm with container dimensions", () => { const input = ` [4, 2] {3} `; const parser = new RhythmParser(); const result = parser.parse(input); const container = result[0]; expect(container).to.haveOwnProperty("dimension"); expect(container.dimension).to.have.property("proportionality").that.equals(4); expect(container.dimension).to.have.property("scale").that.is.an.instanceOf(Fraction); expect(container.dimension.scale.equals(2)).to.be.true; expect(container).to.haveOwnProperty("subdivisions"); expect(container.subdivisions).to.have.property("division").that.equals(3); }); it("parses a rhythm with multiple containers", () => { const input = ` []{3} []{4} `; const parser = new RhythmParser(); const result = parser.parse(input); expect(result).to.have.length(2); expect(result[0]).to.have.property("subdivisions").with.property("division").that.equals(3); expect(result[1]).to.have.property("subdivisions").with.property("division").that.equals(4); }); it("parses a rhythm with a rational scale", () => { const input = ` [2, 2/3] {3} `; const parser = new RhythmParser(); const result = parser.parse(input); expect(result).to.have.length(1); const container = result[0]; expect(container).to.haveOwnProperty("dimension"); expect(container.dimension).to.have.property("proportionality").that.equals(2); expect(container.dimension).to.have.property("scale").that.is.an.instanceOf(Fraction); expect(container.dimension.scale.equals(new Fraction(2, 3))).to.be.true; }); it("handles subcontainers", () => { const input = `[[1] [1]]`; const parser = new RhythmParser(); const result = parser.parse(input); expect(result).to.have.length(1); const container = result[0]; expect(container).to.haveOwnProperty("contents").that.is.an.instanceOf(Array).with.length(2); }); it("handles a container with additive proportionality", () => { const input = ` [ [1] [1] ] `; const parser = new RhythmParser(); const result = parser.parse(input); expect(result).to.have.length(1); const container = result[0]; expect(container).to.haveOwnProperty("dimension"); expect(container.dimension).to.have.property("proportionality").that.equals("+"); }); it("handles ties between containers", () => { const input = ` [[1] _ [1]] `; const parser = new RhythmParser(); const result = parser.parse(input); expect(result).to.have.length(1); const container = result[0]; expect(container).to.haveOwnProperty("contents").that.is.an.instanceOf(Array).with.length(2); expect(container.contents[0]).to.haveOwnProperty("tie").that.equals(true); }); it("handles ties between ranged containers", () => { const input = ` [] {3 1 [] _ 2 [] } `; const parser = new RhythmParser(); const result = parser.parse(input); expect(result).to.have.length(1); const container = result[0]; expect(container).to.haveOwnProperty("subdivisions"); expect(container.subdivisions).to.haveOwnProperty("ranges").that.is.an.instanceOf(Array).with.length(2); expect(container.subdivisions.ranges[0].container).to.haveOwnProperty("tie").that.equals(true); }); it("rejects ties at the beginning or end of a list of containers", () => { try { const input = `_[1]` const parser = new RhythmParser(); parser.parse(input); expect.fail("Should have thrown a parse error"); } catch (e) {} try { const input = `[1]_` const parser = new RhythmParser(); parser.parse(input); expect.fail("Should have thrown a parse error"); } catch (e) {} }); }); ================================================ FILE: test/nestup.test.js ================================================ require("mocha"); const { expect } = require("chai"); const { default: Fraction } = require("fraction.js"); const { RhythmParser, Nestup, Onset } = require("../index"); describe("Nestup", () => { it("finds the correct proportionality", () => { const input = `[4] {1}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); expect(nestup.beatLength).to.equal(4); }); it("finds the correct proportionality for a more complex expression", () => { const input = `[4] {1} [,1/2] [ [] [] ]`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); expect(nestup.beatLength).to.equal(6.5); }); it("generates events", () => { const input = `[4] {1}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const tickedEvents = nestup.onOffEvents(); expect(tickedEvents).to.be.an.instanceOf(Array); expect(tickedEvents).to.have.length(2); expect(tickedEvents[0]).to.haveOwnProperty("time").that.is.a("number"); expect(tickedEvents[0]).to.haveOwnProperty("on").that.is.a("boolean"); expect(tickedEvents[0]).to.haveOwnProperty("path").that.is.a("string"); }); it("aligns events with a tick grid", () => { const input = `[4] {3}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const divisibleTickedEvents = nestup.onOffEvents(300); const onsets = nestup._normalizedOnsets(); expect(divisibleTickedEvents).to.be.an.instanceOf(Array); expect(divisibleTickedEvents).to.have.length(6); expect(divisibleTickedEvents[0].on).to.equal(true); expect(divisibleTickedEvents[0].time).to.equal(0); expect(divisibleTickedEvents[0].path).to.equal(onsets[0].path); expect(divisibleTickedEvents[1].on).to.equal(false); expect(divisibleTickedEvents[1].time).to.equal(100); expect(divisibleTickedEvents[1].path).to.equal(onsets[0].path); expect(divisibleTickedEvents[2].on).to.equal(true); expect(divisibleTickedEvents[2].time).to.equal(100); expect(divisibleTickedEvents[2].path).to.equal(onsets[1].path); expect(divisibleTickedEvents[3].on).to.equal(false); expect(divisibleTickedEvents[3].time).to.equal(200); expect(divisibleTickedEvents[3].path).to.equal(onsets[1].path); expect(divisibleTickedEvents[4].on).to.equal(true); expect(divisibleTickedEvents[4].time).to.equal(200); expect(divisibleTickedEvents[4].path).to.equal(onsets[2].path); expect(divisibleTickedEvents[5].on).to.equal(false); expect(divisibleTickedEvents[5].time).to.equal(300); expect(divisibleTickedEvents[5].path).to.equal(onsets[2].path); }); it("rounds event times to the nearest tick", () => { const input = `[4] {3}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const tickedEvents = nestup.onOffEvents(100); expect(tickedEvents).to.be.an.instanceOf(Array); expect(tickedEvents).to.have.length(6); expect(tickedEvents[0].time).to.equal(0); expect(tickedEvents[1].time).to.equal(33); expect(tickedEvents[2].time).to.equal(33); expect(tickedEvents[3].time).to.equal(67); expect(tickedEvents[4].time).to.equal(67); expect(tickedEvents[5].time).to.equal(100); }); it("handles rests", () => { const input = `[4] {3 2:1 {0} }`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const tickEvents = nestup.onOffEvents(30); expect(tickEvents).to.be.an.instanceOf(Array); expect(tickEvents).to.have.length(4); expect(tickEvents[0].on).to.equal(true); expect(tickEvents[1].on).to.equal(false); expect(tickEvents[1].time).to.equal(10); expect(tickEvents[2].on).to.equal(true); expect(tickEvents[2].time).to.equal(20); expect(tickEvents[3].on).to.equal(false); expect(tickEvents[3].time).to.equal(30); }); it("generates midi-like events", () => { const input = `[4] {4 3:1 {0} }`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(midiLikeEvents).to.be.an.instanceOf(Array); expect(midiLikeEvents).to.have.length(6); expect(midiLikeEvents[0].on).to.equal(true); expect(midiLikeEvents[0].time).to.equal(0); expect(midiLikeEvents[1].on).to.equal(false); expect(midiLikeEvents[1].time).to.equal(25); expect(midiLikeEvents[2].on).to.equal(true); expect(midiLikeEvents[2].time).to.equal(25); expect(midiLikeEvents[3].on).to.equal(false); expect(midiLikeEvents[3].time).to.equal(50); expect(midiLikeEvents[4].on).to.equal(true); expect(midiLikeEvents[4].time).to.equal(75); expect(midiLikeEvents[5].on).to.equal(false); expect(midiLikeEvents[5].time).to.equal(100); }); it("handles funky on/off overlap", () => { const input = `[4] {4 2:3 {1} 3 {0} }`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(midiLikeEvents).to.be.an.instanceOf(Array); expect(midiLikeEvents).to.have.length(4); expect(midiLikeEvents[0].on).to.equal(true); expect(midiLikeEvents[0].time).to.equal(0); expect(midiLikeEvents[1].on).to.equal(false); expect(midiLikeEvents[1].time).to.equal(25); expect(midiLikeEvents[2].on).to.equal(true); expect(midiLikeEvents[2].time).to.equal(25); expect(midiLikeEvents[3].on).to.equal(false); expect(midiLikeEvents[3].time).to.equal(50); }); it("handles a flexible container inside a fixed container", () => { const input = `[2 [ [4] [] ] ] `; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const onsets = nestup._normalizedOnsets(); expect(onsets).to.be.an.instanceOf(Array).with.length(3); expect(onsets[0].type).to.equal(Onset.type.ON); expect(onsets[1].type).to.equal(Onset.type.ON); expect(onsets[2].type).to.equal(Onset.type.OFF); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[1].time.equals(new Fraction(4, 5))).to.be.true; expect(onsets[2].time.equals(new Fraction(1))).to.be.true; const midiLikeEvents = nestup.onOffEvents(100); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(4); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[2].on).to.be.true; expect(midiLikeEvents[3].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(0); expect(midiLikeEvents[1].time).to.equal(80); expect(midiLikeEvents[2].time).to.equal(80); expect(midiLikeEvents[3].time).to.equal(100); }); it("handles quick ranges", () => { const input = `['4] {10 1 4 6:2 } `; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(6); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[2].on).to.be.true; expect(midiLikeEvents[3].on).to.be.false; expect(midiLikeEvents[4].on).to.be.true; expect(midiLikeEvents[5].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(0); expect(midiLikeEvents[1].time).to.equal(10); expect(midiLikeEvents[2].time).to.equal(30); expect(midiLikeEvents[3].time).to.equal(40); expect(midiLikeEvents[4].time).to.equal(50); expect(midiLikeEvents[5].time).to.equal(70); }); it("rejects a container that is both a parent as well as subdivided", () => { const input = ` [ [] [] ] {2} ` try { const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); expect.fail("Should have produced a parse error"); } catch (e) {} }); it("rejects a list of two or more subcontainers without explicit containers", () => { const input = ` [ {2} {2} ] ` try { const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); expect.fail("Should have produced a parse error"); } catch (e) {} }); it("parses a slightly complex expression", () => { const input = ` [8] {8 2:3 {6 3 ['] } 5 ['] 7 {4} } ` try { const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); expect(nestup).not.to.be.undefined(); } catch (e) {} }); }); ================================================ FILE: test/rest.test.js ================================================ require("mocha"); const { expect } = require("chai"); const { Container, RhythmParser, Nestup, Onset } = require("../index"); const Fraction = require("fraction.js"); describe("Rests", () => { it("encodes a lagging rest", () => { const input = `[[2] ['2]]`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(parseTree).to.be.an.instanceOf(Array).with.length(1); const container = new Container(parseTree[0]); const onsets = container.normalizedOnsets(); expect(onsets).to.have.length(3); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[1].time.equals(new Fraction(1, 2))).to.be.true; expect(onsets[2].time.equals(new Fraction(1))).to.be.true; expect(nestup.beatLength).to.equal(4); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(2); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(0); expect(midiLikeEvents[1].time).to.equal(50); }); it("encodes a leading rest", () => { const input = `[['2] [2]]`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(parseTree).to.be.an.instanceOf(Array).with.length(1); const container = new Container(parseTree[0]); const onsets = container.normalizedOnsets(); expect(onsets).to.have.length(3); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[1].time.equals(new Fraction(1, 2))).to.be.true; expect(onsets[2].time.equals(new Fraction(1))).to.be.true; expect(nestup.beatLength).to.equal(4); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(2); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(50); expect(midiLikeEvents[1].time).to.equal(100); }); it("handles an awkward double rest", () => { const input = `[['2] ['2]]`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(parseTree).to.be.an.instanceOf(Array).with.length(1); const container = new Container(parseTree[0]); const onsets = container.normalizedOnsets(); expect(onsets).to.have.length(2); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[1].time.equals(new Fraction(1, 2))).to.be.true; expect(nestup.beatLength).to.equal(4); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(0); }); it("handles pure rest", () => { const input = `['4]`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(parseTree).to.be.an.instanceOf(Array).with.length(1); const container = new Container(parseTree[0]); const onsets = container.normalizedOnsets(); expect(onsets).to.have.length(1); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(nestup.beatLength).to.equal(4); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(0); }); it("handles the thing we made rests for", () => { const input = `['4] {10 6 []}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(nestup.beatLength).to.equal(4); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(2); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(50); expect(midiLikeEvents[1].time).to.equal(60); }); it("handles another easy rest thing", () => { const input = `['4] {4 2 [] 4 []}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(nestup.beatLength).to.equal(4); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(4); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[2].on).to.be.true; expect(midiLikeEvents[3].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(25); expect(midiLikeEvents[1].time).to.equal(50); expect(midiLikeEvents[2].time).to.equal(75); expect(midiLikeEvents[3].time).to.equal(100); }); }); ================================================ FILE: test/rotation.test.js ================================================ require("mocha"); const { expect } = require("chai"); const { Container, RhythmParser, Nestup, Onset } = require("../index"); const Fraction = require("fraction.js"); describe("Rotations", () => { it("encodes right rotation", () => { const input = `[2] {1 > 1/4}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(nestup.beatLength).to.equal(2); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(2); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(25); expect(midiLikeEvents[1].time).to.equal(100); }); it("encodes left rotation", () => { const input = `[2] {1 < 1/4}`; const parseTree = new RhythmParser().parse(input); const nestup = new Nestup(parseTree); const midiLikeEvents = nestup.onOffEvents(100); expect(nestup.beatLength).to.equal(2); expect(midiLikeEvents).to.be.an.instanceOf(Array).with.length(2); expect(midiLikeEvents[0].on).to.be.true; expect(midiLikeEvents[1].on).to.be.false; expect(midiLikeEvents[0].time).to.equal(75); expect(midiLikeEvents[1].time).to.equal(100); }); }); ================================================ FILE: test/sizedContainers.test.js ================================================ require("mocha"); const { expect } = require("chai"); const { Container, RhythmParser, Nestup, Onset } = require("../index"); const Fraction = require("fraction.js"); describe("Sized Containers", () => { it("parses a container with a beat ratio", () => { const input = `[2, 2/3] {3}`; const parseTree = new RhythmParser().parse(input); expect(parseTree).to.be.an.instanceOf(Array).with.length(1); const container = new Container(parseTree[0]); expect(container).to.have.property("proportionality"); expect(container.proportionality.equals(new Fraction(4, 3))).to.be.true; expect(container).to.have.property("scale"); expect(container.scale.equals(new Fraction(2, 3))).to.be.true; const onsets = container.normalizedOnsets(); expect(onsets).to.have.length(4); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[1].time.equals(new Fraction(1, 3))).to.be.true; expect(onsets[2].time.equals(new Fraction(2, 3))).to.be.true; expect(onsets[3].time.equals(new Fraction(1))).to.be.true; }); it("normalizes containers by beat ratio", () => { const input = `[1, 1/3] {2} [1] {2}`; const parseTree = new RhythmParser().parse(input); expect(parseTree).to.be.an.instanceOf(Array).with.length(2); const nestup = new Nestup(parseTree); const onsets = nestup._normalizedOnsets(); expect(onsets).to.be.an.instanceOf(Array).with.length(5); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[1].time.equals(new Fraction(1, 8))).to.be.true; expect(onsets[2].time.equals(new Fraction(1, 4))).to.be.true; expect(onsets[3].time.equals(new Fraction(5, 8))).to.be.true; expect(onsets[4].time.equals(new Fraction(1))).to.be.true; }); it("handles onset paths", () => { const input = `{2 2:1 {2 2:1 {2}}}`; const parseTree = new RhythmParser().parse(input); expect(parseTree).to.be.an.instanceOf(Array).with.length(1); const nestup = new Nestup(parseTree); const onsets = nestup._normalizedOnsets(); expect(onsets).to.be.an.instanceOf(Array).with.length(5); expect(onsets[0].path).to.equal("11"); expect(onsets[1].path).to.equal("111"); expect(onsets[2].path).to.equal("1111"); expect(onsets[3].path).to.equal("1111"); }); it("handles ties between subcontainers", () => { const input = `[[] _ []]`; const parseTree = new RhythmParser().parse(input); expect(parseTree).to.be.an.instanceOf(Array).with.length(1); const nestup = new Nestup(parseTree); const onsets = nestup._normalizedOnsets(); expect(onsets).to.be.an.instanceOf(Array).with.length(2); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[0].type).equals(Onset.type.ON); expect(onsets[1].time.equals(new Fraction(1))).to.be.true; expect(onsets[1].type).equals(Onset.type.OFF); }); it("handles ties between ranged containers", () => { const input = `[] {2 1 [] _ 2 []}`; const parseTree = new RhythmParser().parse(input); expect(parseTree).to.be.an.instanceOf(Array).with.length(1); const nestup = new Nestup(parseTree); const onsets = nestup._normalizedOnsets(); expect(onsets).to.be.an.instanceOf(Array).with.length(2); expect(onsets[0].time.equals(new Fraction(0))).to.be.true; expect(onsets[0].type).equals(Onset.type.ON); expect(onsets[1].time.equals(new Fraction(1))).to.be.true; expect(onsets[1].type).equals(Onset.type.OFF); }); }); ================================================ FILE: webpack.config.js ================================================ const path = require('path'); module.exports = { entry: './index.js', module: { rules: [ { loader: 'babel-loader', test: /\.js$/, exclude: /node_modules/, options: { plugins: ['transform-class-properties'] } } ] }, output: { path: path.resolve(__dirname, 'dist'), filename: 'nestup.bundle.js', libraryTarget: "umd", library: "Nestup" } };