From 587dd5bb80364688419bb43aba4afc044ac0ef48 Mon Sep 17 00:00:00 2001 From: Miquel Sabaté Solà Date: Fri, 17 May 2024 07:39:05 +0200 Subject: Initial commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A lot is missing and there is a long road ahead to make the assembler even work. Signed-off-by: Miquel Sabaté Solà --- .gitignore | 2 + CHANGELOG.md | 3 + CONTRIBUTING.md | 24 + Cargo.lock | 251 ++++++ Cargo.toml | 12 + LICENSE | 674 ++++++++++++++++ README.md | 1 + crates/nasm/Cargo.toml | 9 + crates/nasm/src/main.rs | 80 ++ crates/ncount/TODO | 0 crates/nfind/TODO | 0 lib/xixanta/Cargo.toml | 14 + lib/xixanta/src/assembler.rs | 1711 ++++++++++++++++++++++++++++++++++++++++ lib/xixanta/src/context.rs | 66 ++ lib/xixanta/src/errors.rs | 25 + lib/xixanta/src/instruction.rs | 277 +++++++ lib/xixanta/src/lib.rs | 10 + lib/xixanta/src/opcodes.rs | 631 +++++++++++++++ 18 files changed, 3790 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 crates/nasm/Cargo.toml create mode 100644 crates/nasm/src/main.rs create mode 100644 crates/ncount/TODO create mode 100644 crates/nfind/TODO create mode 100644 lib/xixanta/Cargo.toml create mode 100644 lib/xixanta/src/assembler.rs create mode 100644 lib/xixanta/src/context.rs create mode 100644 lib/xixanta/src/errors.rs create mode 100644 lib/xixanta/src/instruction.rs create mode 100644 lib/xixanta/src/lib.rs create mode 100644 lib/xixanta/src/opcodes.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5e66057 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +*.nes diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6919793 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +# 0.1 + +- Under development diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..467dca7 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,24 @@ +This project uses [Rust](https://www.rust-lang.org/), so use the usual +[cargo](https://doc.rust-lang.org/cargo/) commands in order to build and run + +## Issue reporting + +I'm using Github in order to host the code. Thus, in order to report issues you +can do it on its [issue tracker](https://github.com/mssola/ntools/issues). A +couple of notes on reports: + +- Check that the issue has not already been reported or fixed in the `main` + branch. +- Try to be concise and precise in your description of the problem. +- Provide a step by step guide on how to reproduce this problem. +- Provide the version you are using (git commit SHA). + +## Pull requests + +- Write a [good commit message](https://chris.beams.io/posts/git-commit/). +- Run the tests (`cargo test`). +- Update the [changelog](./CHANGELOG.md). +- Open a pull request with *only* one subject and a clear title and description. + Refrain from submitting pull requests with tons of different unrelated + commits. + diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..debcc84 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,251 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "anstream" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" + +[[package]] +name = "anstyle-parse" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" +dependencies = [ + "anstyle", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" + +[[package]] +name = "clap" +version = "4.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" + +[[package]] +name = "colorchoice" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "nasm" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "xixanta", +] + +[[package]] +name = "proc-macro2" +version = "1.0.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "utf8parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" + +[[package]] +name = "xixanta" +version = "0.1.0" +dependencies = [ + "lazy_static", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..183a9f1 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,12 @@ +[workspace] +members = ["lib/*", "crates/*"] +resolver = "2" + +[workspace.package] +rust-version = "1.73" +edition = "2021" +license = "GPLv3+" +authors = ["Miquel Sabaté Solà"] + +[workspace.dependencies] +xixanta = { path = "./lib/xixanta", version = "0.1.0" } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + 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 + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..91d2ed7 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +Under development diff --git a/crates/nasm/Cargo.toml b/crates/nasm/Cargo.toml new file mode 100644 index 0000000..e1f3e88 --- /dev/null +++ b/crates/nasm/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "nasm" +version = "0.1.0" +edition = "2021" + +[dependencies] +anyhow = "1.0.82" +clap = { version = "4.5.4", features = ["derive"] } +xixanta.workspace = true diff --git a/crates/nasm/src/main.rs b/crates/nasm/src/main.rs new file mode 100644 index 0000000..9f26417 --- /dev/null +++ b/crates/nasm/src/main.rs @@ -0,0 +1,80 @@ +use anyhow::Result; +use clap::Parser as ClapParser; +use std::fs::File; +use std::io::{self, Read, Write}; +use xixanta::assembler::Assembler; + +/// Assembler for the 6502 microprocessor that targets the NES. +#[derive(ClapParser, Debug)] +#[command(version, about, long_about = None)] +struct Args { + /// Assemble the instructions given on this file. The standard input is used + /// when this argument is not given. + file: Option, + + /// Disassemble instead of assembling. Disabled by default. + #[arg(short, long, default_value_t = false)] + disassemble: bool, + + /// Place the output into the given file. Ignored if the `stdout` flag + /// is provided. Defaults to `out.nes` when assembling, and to `out.s` when + /// disassembling. + #[arg(short = 'o', long)] + out: Option, + + /// Spit the output into the standard output instead. This ignores any given + /// `out` flag. Disabled by default. + #[arg(long, default_value_t = false)] + stdout: bool, +} + +fn main() -> Result<()> { + let args = Args::parse(); + let mut assembler = Assembler::new(); + + // Select the input stream. + let input: Box = match args.file { + Some(file) => Box::new(File::open(file)?), + None => Box::new(std::io::stdin()), + }; + + // Select the output stream. + let mut output: Box = if args.stdout { + Box::new(io::stdout()) + } else { + match args.out { + Some(file) => Box::new(File::create(file)?), + None => Box::new(File::create(if args.disassemble { + "out.s" + } else { + "out.nes" + })?), + } + }; + + // After the parse operation, just print the results. + if args.disassemble { + let instructions = assembler.disassemble(input)?; + + for instr in instructions { + output.write_all(instr.to_human().as_bytes())?; + output.write_all("\n".as_bytes())?; + } + } else { + let instructions = assembler.assemble(input)?; + + for instr in instructions { + let bs = instr.to_bytes(); + + if instr.size() == 1 { + output.write_all(&[bs[0]])?; + } else if instr.size() == 2 { + output.write_all(&[bs[0], bs[1]])?; + } else { + output.write_all(&[bs[0], bs[1], bs[2]])?; + } + } + } + + Ok(()) +} diff --git a/crates/ncount/TODO b/crates/ncount/TODO new file mode 100644 index 0000000..e69de29 diff --git a/crates/nfind/TODO b/crates/nfind/TODO new file mode 100644 index 0000000..e69de29 diff --git a/lib/xixanta/Cargo.toml b/lib/xixanta/Cargo.toml new file mode 100644 index 0000000..76a0660 --- /dev/null +++ b/lib/xixanta/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "xixanta" +version = "0.1.0" +description = "TBD" + +authors.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +lazy_static = "1.4.0" diff --git a/lib/xixanta/src/assembler.rs b/lib/xixanta/src/assembler.rs new file mode 100644 index 0000000..5d03186 --- /dev/null +++ b/lib/xixanta/src/assembler.rs @@ -0,0 +1,1711 @@ +use crate::context::Context; +use crate::errors::ParseError; +use crate::instruction::{ + AddressingMode, Encodable, Generic, Instruction, Literal, Node, PString, Scoped, +}; +use crate::opcodes::{INSTRUCTIONS, OPCODES}; +use std::collections::hash_map::Entry; +use std::io::{self, BufRead, Read}; +use std::ops::Range; + +type Result = std::result::Result; + +pub struct Assembler { + line: usize, + column: usize, + offset_address: usize, + context: Context, + + // TODO: segments instead + nodes: Vec, +} + +impl Default for Assembler { + fn default() -> Self { + Assembler::new() + } +} + +impl Assembler { + pub fn new() -> Self { + Self { + line: 0, + column: 0, + offset_address: 0, + context: Context::new(), + nodes: vec![], + } + } + + pub fn reset(&mut self) { + self.line = 0; + self.column = 0; + self.offset_address = 0; + self.nodes = vec![]; + self.context = Context::new(); + } + + pub fn to_nodes(&mut self, reader: impl Read) -> Result<&Vec> { + self.from_reader(reader)?; + self.context.reset(); + self.evaluate()?; + + Ok(&self.nodes) + } + + pub fn assemble(&mut self, reader: impl Read) -> Result> { + let mut instructions: Vec<&dyn Encodable> = vec![]; + + for node in self.to_nodes(reader)? { + match node { + Node::Instruction(instr) => instructions.push(instr), + Node::Literal(lit) => instructions.push(lit), + _ => {} + } + } + + Ok(instructions) + } + + pub fn disassemble(&mut self, reader: impl Read) -> Result> { + self.from_byte_reader(reader)?; + + let mut instructions: Vec<&dyn Encodable> = vec![]; + for node in &self.nodes { + match node { + Node::Instruction(instr) => instructions.push(instr), + Node::Literal(lit) => instructions.push(lit), + _ => {} + } + } + + Ok(instructions) + } + + pub fn from_reader(&mut self, reader: R) -> Result<()> { + for line in io::BufReader::new(reader).lines() { + // TODO: instead of this, accumulate errors so to give as many + // errors as possible. + self.parse_line(line?.as_str())?; + self.line += 1; + } + Ok(()) + } + + pub fn parse_line(&mut self, line: &str) -> Result<()> { + self.column = 0; + + if !self.skip_whitespace(line) { + return Ok(()); + } + + match self.parse_identifier(line) { + Some(identifier) => self.parse_from_identifier(identifier, line), + None => Ok(()), + } + } + + pub fn evaluate(&mut self) -> Result<()> { + for node in &mut self.nodes { + match node { + Node::Instruction(instr) => { + Self::update_instruction_with_context(instr, &self.context)? + } + Node::Scoped(scope) => { + if scope.start { + self.context.push(&scope.identifier.value); + } else { + _ = self.context.pop(); + } + } + Node::Literal(literal) => { + Self::update_literal_with_context(literal, &self.context)? + } + _ => {} + } + } + + Ok(()) + } + + fn update_instruction_with_context(instr: &mut Instruction, context: &Context) -> Result<()> { + // To keep things simple, we remove out the `implied` case and we parse + // further with a known `Some` value for the base algorithm implemented + // in `update_instruction_and_bytes`. + if instr.left.is_some() { + Self::update_addressing_and_bytes(instr, context)?; + } else { + instr.mode = AddressingMode::Implied; + } + + // Now that we have the addressing mode and the bytes, we can fill out + // the rest of it by fetching the values on `INSTRUCTIONS`. + match INSTRUCTIONS.get(&instr.mnemonic.value.to_lowercase()) { + Some(entries) => match entries.get(&instr.mode) { + Some(values) => { + instr.cycles = values.cycles; + instr.opcode = values.opcode; + instr.size = values.size; + instr.affected_on_page = values.affected_on_page; + } + None => { + return Err(instr.mnemonic.parser_error( + format!( + "bad addressing mode '{}' for the instruction '{}'", + &instr.mode, &instr.mnemonic.value + ) + .as_str(), + )); + } + }, + None => { + return Err(instr.mnemonic.parser_error( + format!("unknown instruction '{}'", &instr.mnemonic.value).as_str(), + )); + } + } + + Ok(()) + } + + fn update_addressing_and_bytes(instr: &mut Instruction, context: &Context) -> Result<()> { + // `unwrap()` is guaranteed to work by the caller. + let left = instr.left.as_ref().unwrap(); + + // We will first try to check if there's any variable involved on the + // left arm and replace the string if so. This will greatly simplify + // things down the line. That being said, there is a special reserved + // case, which is the implied addressing by using "a". In this case, we + // want to ensure that we assume an implied addressing and not a + // variable named "a". + if left.value.to_lowercase() == "a" { + instr.mode = AddressingMode::Implied; + } else { + let nleft = Self::replace_variable(left, context)?; + + if nleft.value.starts_with('$') { + // This is an address. At this point we should assume that the + // left node contains the address itself, and that the right one + // will contain whether there is indexing. + + let string = nleft.value.chars().as_str(); + instr.bytes = Self::parse_hex_from(string, &nleft, true, false, true)?; + + match &instr.right { + Some(xy) => match xy.value.to_lowercase().as_str() { + "x" => { + if string.len() == 3 { + instr.mode = AddressingMode::ZeropageIndexedX; + } else { + instr.mode = AddressingMode::IndexedX; + } + } + "y" => { + if string.len() == 3 { + instr.mode = AddressingMode::ZeropageIndexedY; + } else { + instr.mode = AddressingMode::IndexedY; + } + } + _ => return Err(xy.parser_error("index is neither X nor Y")), + }, + None => { + if string.len() == 3 { + instr.mode = AddressingMode::RelativeOrZeropage; + } else { + instr.mode = AddressingMode::Absolute; + } + } + } + } else if nleft.value.starts_with('#') { + // Immediate addressing in any case: hexadecimal, binary or + // decimal. Hence, just figure out the character being used and + // call the right function for it. + + let mut chars = nleft.value.chars(); + chars.next(); + let string = chars.as_str(); + + instr.bytes = Self::parse_numeric(string, &nleft, false)?; + instr.mode = AddressingMode::Immediate; + } else if nleft.value.starts_with('(') { + // Indirect addressing. In this case the left arm can be further + // subdivided. That is, indirect X-indexing is represented like + // so: `instr ($NN, x)`. Hence, first of all we have to figure + // out whether there is a subdivision. + + let (left1, oleft2) = Self::split_left_arm(&nleft)?; + match oleft2 { + Some(left2) => { + // There is subdivision. Thus, we have to assume + // indirect X-indexing, which means that the right arm + // should be None and that the right side of the left + // node must match the X register. Other than that, the + // address being referenced must be zero page. + if instr.right.is_some() { + return Err(instr.right.as_ref().unwrap().parser_error( + "bad indirect mode, expecting an indirect X-indexed addressing mode" + )); + } + if left2.value.to_lowercase() != "x" { + return Err(left2.parser_error( + "the index in indirect X-indexed addressing must be X", + )); + } + match Self::parse_hex_from(&left1.value, &left1, false, false, true) { + Ok(bytes) => instr.bytes = bytes, + Err(e) => { + let msg = String::from( + "when parsing an instruction with indirect X-indexed addressing: ", + ) + &e.message; + return Err(left1.parser_error(msg.as_str())); + } + } + instr.mode = AddressingMode::IndirectX; + } + None => { + // There is no subdivision on the left arm. Hence, if + // there is something on the right arm then we must + // assume indirect Y-index addressing, and if not then + // it's indirect addressing with no indices involvved. + if instr.right.is_some() { + if instr.right.as_ref().unwrap().value.to_lowercase() != "y" { + return Err(instr.right.as_ref().unwrap().parser_error( + "the index in indirect Y-indexed addressing must be Y", + )); + } + match Self::parse_hex_from(&left1.value, &left1, false, false, true) { + Ok(bytes) => instr.bytes = bytes, + Err(e) => { + let msg = String::from( + "when parsing an instruction with indirect Y-indexed addressing: ", + ) + &e.message; + return Err(left1.parser_error(msg.as_str())); + } + } + instr.mode = AddressingMode::IndirectY; + } else { + instr.bytes = + Self::parse_hex_from(&left1.value, &left1, true, true, true)?; + instr.mode = AddressingMode::Indirect; + } + } + } + } else { + // At this point all of the syntax cases have been exhausted: + // the programmer messed up. From this point on we try to figure + // out how they messed up. + + if nleft.value.starts_with('=') { + return Err(instr.mnemonic.parser_error( + format!( + "cannot use '{}' in an assignment because it's a word reserved for an instruction mnemonic", + instr.mnemonic.value + ).as_str(), + )); + } + return Err(instr.mnemonic.parser_error( + format!( + "unknown addressing mode for instruction '{}'", + instr.mnemonic.value + ) + .as_str(), + )); + } + } + + Ok(()) + } + + fn update_literal_with_context(literal: &mut Literal, context: &Context) -> Result<()> { + // Evaluate any possible variable being used inside of this literal. + let evaled = Self::replace_variable(&literal.identifier, context)?; + + // Parse the numeric value after a possible variable has been replaced. + let two_bytes_allowed = literal.size == 2; + let res = Self::parse_numeric( + evaled.value.as_str(), + &literal.identifier, + two_bytes_allowed, + ); + + // And finally assign the computed bytes. + match res { + Ok(bytes) => { + literal.bytes = bytes; + Ok(()) + } + Err(e) => { + let msg = String::from("when parsing a data literal: ") + &e.message; + Err(literal.identifier.parser_error(msg.as_str())) + } + } + } + + fn parse_numeric(string: &str, node: &PString, two_bytes_allowed: bool) -> Result<[u8; 2]> { + if string.starts_with('$') { + Ok(Self::parse_hex_from( + string, + node, + two_bytes_allowed, + false, + true, + )?) + } else if string.starts_with('%') { + Ok([Self::parse_binary_from(string, node)?, 0]) + } else { + Ok([Self::parse_decimal_from(string, node)?, 0]) + } + } + + fn split_left_arm(node: &PString) -> Result<(PString, Option)> { + let mut chars = node.value.chars(); + chars.next(); + let string = chars.as_str(); + + match string.find(|c: char| c == ',') { + Some(idx) => { + let left1 = string.get(..idx).unwrap_or("").trim(); + let left2 = string.get(idx + 1..).unwrap_or("").trim(); + + Ok(( + PString { + value: left1.to_string(), + line: node.line, + range: Range { + start: node.range.start + 1, + end: node.range.start + 1 + left1.len(), + }, + }, + Some(PString { + value: left2.to_string(), + line: node.line, + range: Range { + start: node.range.start + 1 + idx, + end: node.range.start + 1 + idx + left2.len(), + }, + }), + )) + } + None => Ok(( + PString { + value: string.to_string(), + line: node.line, + range: Range { + start: node.range.start + 1, + end: node.range.end, + }, + }, + None, + )), + } + } + + fn parse_binary_from(string: &str, node: &PString) -> Result { + let mut value = 0; + let mut shift = 0; + + for c in string.get(1..).unwrap_or("").chars().rev() { + if c == '1' { + let val = 1 << shift; + value += val; + } else if c != '0' { + return Err( + node.parser_error(format!("bad binary format for '{}'", string).as_str()) + ); + } + + shift += 1; + } + + if shift < 8 { + Err(node.parser_error("missing binary digits to get a full byte")) + } else if shift > 8 { + Err(node.parser_error("too many binary digits for a single byte")) + } else { + Ok(value) + } + } + + fn replace_variable(node: &PString, context: &Context) -> Result { + match node.value.find(|c: char| c.is_alphabetic() || c == '_') { + Some(idx) => { + // Before doing any replacement, let's check the character + // before the one that was found. In this case, if it was a + // proper ASCII digit, then it cannot be a variable but it's + // part of a numeric literal (e.g. '1A'): then just let the + // different numeric parsing functions do their job. + if idx > 0 { + let prev = node.value.chars().nth(idx - 1).unwrap_or(' '); + if prev.is_ascii_digit() { + return Ok(node.clone()); + } + } + + // The variable might still be before an inner comma (e.g. + // sta ($20, x)). We will assume that variables can happen + // only before that. + let end = node.value.find(',').unwrap_or(node.value.len()); + let mut string = node.value.get(idx..end).unwrap_or(""); + let tail = node.value.get(end..).unwrap_or(""); + + // Get the context that might be being referenced. + let ctxt = match string.find("::") { + Some(_) => { + let tctxt = string.rsplit_once("::").unwrap_or(("", "")); + if tctxt.0.is_empty() { + context.current() + } else { + string = tctxt.1; + context.find(tctxt.0) + } + } + None => context.current(), + }; + + match ctxt { + Some(hash) => { + // If there was a comma before the "variable" (i.e. idx > + // end and hence string == ""), or this is just the regular + // X or Y index, just return early. + match string.to_lowercase().as_str() { + "x" | "y" | "" => return Ok(node.clone()), + _ => {} + } + + // It's not any of the indices, let's look for a match on + // the current scope. + match hash.get(string) { + Some(var) => { + let value = String::from(node.value.get(..idx).unwrap_or("")) + + var.value.as_str(); + Ok(PString { + value: value.clone() + tail, + line: node.line, + range: Range { + start: node.range.start, + end: node.range.start + value.len(), + }, + }) + } + None => { + // If a variable could not be found, check that + // this is not a purely hexadecimal number (e.g. + // 'AA'). If that's the case, then just return + // its value. + if Self::parse_hex_from(string, node, true, false, false).is_ok() { + return Ok(node.clone()); + } + + // We've tried hard to not assume the programmer + // messing up, but there's no other way around + // it: it's an "unknown variable" error. + return Err(node.parser_error( + format!("unknown variable '{}'", string).as_str(), + )); + } + } + } + None => { + Err(node.parser_error(format!("unknown scope '{}'", "Global").as_str())) + } + } + } + None => Ok(node.clone()), + } + } + + // Parse an hexadecimal value from the given `string`. A `node` must also be + // supplied so a ParseError can be pushed inside of it in case anything goes + // wrong. Other than that, there are three boolean parameters that have to + // be passed: + // - `two_bytes_allowed`: the value can be 8-bit or 16-bit long. + // - `exactly_two_bytes`: the value has to be exactly 16-bit long. + // - `char_given`: whether the string starts with a '$' character or not. + fn parse_hex_from( + string: &str, + node: &PString, + two_bytes_allowed: bool, + exactly_two_bytes: bool, + char_given: bool, + ) -> Result<[u8; 2]> { + let mut chars = string.chars(); + let len = if char_given { + chars.next(); + string.len() - 1 + } else { + string.len() + }; + + match len { + 2 => { + if exactly_two_bytes { + return Err(node.parser_error("expecting a full 16-bit address")); + } + let mut i = Self::char_to_hex(node, chars.next())? * 16; + i += Self::char_to_hex(node, chars.next())?; + + Ok([i, 0]) + } + 4 => { + if !two_bytes_allowed { + return Err(node.parser_error("only one byte of data is allowed here")); + } + + let mut hi = Self::char_to_hex(node, chars.next())? * 16; + hi += Self::char_to_hex(node, chars.next())?; + + let mut lo = Self::char_to_hex(node, chars.next())? * 16; + lo += Self::char_to_hex(node, chars.next())?; + + Ok([lo, hi]) + } + _ => { + if two_bytes_allowed { + Err(node.parser_error("expecting a number of 2/4 hexadecimal digits")) + } else if exactly_two_bytes { + Err(node.parser_error("expecting a number of 4 hexadecimal digits")) + } else { + Err(node.parser_error("expecting a number of 2 hexadecimal digits")) + } + } + } + } + + fn char_to_hex(node: &PString, oc: Option) -> Result { + match oc { + Some(c) => match c.to_digit(16) { + Some(c) => Ok(c as u8), + None => Err(node.parser_error("could not convert digit to hexadecimal")), + }, + None => Err(node.parser_error("digit out of bounds")), + } + } + + fn parse_decimal_from(string: &str, node: &PString) -> Result { + let mut value = 0; + let mut shift = 1; + + if string.is_empty() { + return Err(node.parser_error("empty decimal literal")); + } + + for c in string.chars().rev() { + if shift > 100 { + return Err(node.parser_error("decimal value is too big")); + } + if c != '0' { + match c.to_digit(10) { + Some(digit) => { + value += digit * shift; + } + None => { + return Err( + node.parser_error(format!("'{}' is not a decimal value", c).as_str()) + ) + } + } + } + + shift *= 10; + } + if value > 255 { + return Err(node.parser_error("decimal value is too big")); + } + + Ok(value as u8) + } + + // Advances `self.column` until a non-whitespace character is found. Returns + // false if the line can be skipped entirely, true otherwise. + fn skip_whitespace(&mut self, line: &str) -> bool { + for c in line.get(self.column..).unwrap_or("").chars() { + if !c.is_whitespace() { + if c == ';' { + return false; + } + return true; + } + + self.column += 1; + } + + true + } + + // Returns a PString object which holds the information for an identifier. + // + // NOTE: this function assumes that `self.column` points to a non-whitespace + // character. + fn parse_identifier(&mut self, line: &str) -> Option { + let column = self.column; + + // For the general case we just need to iterate until a whitespace + // character or an inline comment is found. Then our PString object + // is merely whatever is on the column..self.column range. + for c in line.get(column..).unwrap_or("").chars() { + if c.is_whitespace() || c == ';' { + let range = Range { + start: column, + end: self.column, + }; + + return Some(PString { + value: String::from(line.get(range.clone()).unwrap_or("").trim()), + line: self.line, + range, + }); + } + + self.column += 1; + } + + // Otherwise, we might be at a point whether there is nothing (e.g. an + // empty line), or the line is merely the identifier (e.g. instruction + // with implied addressing). + let range = Range { + start: column, + end: line.len(), + }; + let id = String::from(line.get(range.clone()).unwrap_or("").trim()); + if id.is_empty() { + None + } else { + Some(PString { + value: id, + line: self.line, + range, + }) + } + } + + // Given a PString object which acts as the identifier, try to parse the + // rest of the line depending on whether it's an instruction (e.g. `adc + // $20`), a control statement (e.g. `.macro whatever`) or a general + // statement (e.g. `Var = $10`). + fn parse_from_identifier(&mut self, id: PString, line: &str) -> Result<()> { + if id.value.starts_with('.') { + // If the statement starts with a '.', it's guaranteed to be a + // control statement. + self.parse_control(id, line) + } else { + // Otherwise, we will parse it either as an instruction or a general + // statement depending on whether the parsed identifier is a valid + // instruction mnemonic or not. + match INSTRUCTIONS.get(&id.value) { + Some(_instr) => self.parse_instruction(id, line), + None => self.parse_statement(id, line), + } + } + } + + // TODO: + // - functions + // - macros + fn parse_control(&mut self, id: PString, line: &str) -> Result<()> { + match id.value.to_lowercase().as_str() { + ".scope" => self.parse_scope_definition(&id, line), + ".endscope" => self.parse_scope_end(&id), + ".byte" | ".db" => self.parse_literal_bytes(&id, line, false), + ".word" | ".dw" => self.parse_literal_bytes(&id, line, true), + _ => { + return Err( + id.parser_error(format!("unknown control statement '{}'", id.value).as_str()) + ) + } + } + } + + fn parse_scope_definition(&mut self, id: &PString, line: &str) -> Result<()> { + self.skip_whitespace(line); + + let identifier = self.fetch_identifier(id, line)?; + if identifier.is_reserved() { + return Err(identifier.parser_error( + format!("cannot use reserved name '{}'", identifier.value).as_str(), + )); + } + self.context.push(&identifier.value); + self.nodes.push(Node::Scoped(Scoped { + identifier, + start: true, + })); + + Ok(()) + } + + fn parse_scope_end(&mut self, id: &PString) -> Result<()> { + if !self.context.pop() { + return Err(id.parser_error("missmatched '.endscope': there is no scope to end")); + } + self.nodes.push(Node::Scoped(Scoped { + identifier: PString::new(), + start: false, + })); + + Ok(()) + } + + fn parse_literal_bytes( + &mut self, + node: &PString, + line: &str, + two_bytes_allowed: bool, + ) -> Result<()> { + loop { + self.skip_whitespace(line); + + match line.chars().nth(self.column) { + Some(byte) => { + let needle = if byte == '\'' { + self.column += 1; + self.skip_whitespace(line); + '\'' + } else if byte == '"' { + self.column += 1; + self.skip_whitespace(line); + '"' + } else { + ',' + }; + + let idx = line + .get(self.column..) + .unwrap_or("") + .find(|c: char| c == needle) + .unwrap_or(line.len() - self.column); + + // If this is the last character, the needle was a quote and + // the last char is not the needle, then it means that the + // quote was left open. Complain about this as well. + if idx == line.len() - self.column { + if line.chars().nth(idx).unwrap_or(' ') != needle + && (needle == '"' || needle == '\'') + { + return Err(node.parser_error("non-terminated quote for byte literal")); + } + } + + // NOTE: for now we push an incomplete literal. We need the + // first pass to fill the context and then a second pass + // will evaluate each literal as needed (e.g. replacing + // values from variables being used in this literal). + let string = line.get(self.column..self.column + idx).unwrap_or(" "); + self.nodes.push(Node::Literal(Literal { + identifier: PString { + value: string.to_owned(), + line: self.line, + range: Range { + start: self.column, + end: self.column + idx, + }, + }, + size: if two_bytes_allowed { 2 } else { 1 }, + bytes: [0, 0], + })); + + self.column += idx; + for c in line.get(self.column..).unwrap_or(" ").chars() { + if c == ',' { + break; + } + if c == ';' { + return Ok(()); + } + self.column += 1; + } + self.column += 1; + self.skip_whitespace(line); + } + None => break, + }; + } + + Ok(()) + } + + fn fetch_identifier(&mut self, id: &PString, line: &str) -> Result { + let idx = line + .get(self.column..) + .unwrap_or(" ") + .find(|c: char| c.is_whitespace()); + + match idx { + Some(offset) => { + let end = self.column + offset; + let rest = line.get(end..).unwrap_or("").trim(); + if !rest.is_empty() { + if rest.chars().nth(0).unwrap_or(' ') != ';' { + return Err(id.parser_error( + "there should not be any further content besides the identifier", + )); + } + } + Ok(PString { + value: line.get(self.column..end).unwrap_or(" ").trim().to_string(), + line: self.line, + range: Range { + start: self.column, + end, + }, + }) + } + None => Ok(PString { + value: line.get(self.column..).unwrap_or(" ").trim().to_string(), + line: self.line, + range: Range { + start: self.column, + end: line.len(), + }, + }), + } + } + + fn parse_statement(&mut self, id: PString, line: &str) -> Result<()> { + if line.chars().nth(self.column).unwrap_or(' ') == ':' { + self.parse_label(id, line) + } else { + self.parse_assignment(id, line) + } + } + + fn parse_label(&mut self, _id: PString, _line: &str) -> Result<()> { + // TODO: + + Ok(()) + } + + fn parse_assignment(&mut self, id: PString, line: &str) -> Result<()> { + // You cannot assign into a name which is reserved. + if id.is_reserved() { + return Err( + id.parser_error(format!("cannot use reserved name '{}'", id.value).as_str()) + ); + } + + // To avoid problems down the line, you cannot assign into names which + // are proper hexadecimal values. + if Self::parse_hex_from(&id.value, &id, true, false, false).is_ok() { + return Err(id.parser_error( + format!( + "cannot use names which are valid hexadecimal values such as '{}'", + id.value + ) + .as_str(), + )); + } + + // You cannot assign into scoped names: declare them into their + // respective scopes instead. + if id.value.contains("::") { + return Err(id.parser_error( + format!( + "the name '{}' is scoped: do not declare variables this way", + id.value + ) + .as_str(), + )); + } + + // Skip whitespaces and make sure that we have a '=' sign. + self.skip_whitespace(line); + if line.chars().nth(self.column).unwrap_or(' ') != '=' { + return Err(self.parser_error(format!("unknown instruction '{}'", id.value).as_str())); + } + + // Skip the '=' sign and any possible whitespaces. + self.column += 1; + if !self.skip_whitespace(line) { + return Err(self.parser_error("incomplete assignment")); + } + + let l = String::from(line.get(self.column..).unwrap_or("").trim()); + if l.is_empty() { + return Err(self.parser_error("incomplete assignment")); + } + + // The `Context` struct pretty much guarantees that `current` and + // `current_mut` will return something, so it's safe to ignore a + // `None`. + if let Some(entry) = self.context.current_mut() { + match entry.entry(id.value.clone()) { + Entry::Occupied(e) => { + return Err(ParseError { + line: self.line, + message: format!( + "variable '{}' is being re-assigned: it was previously defined in line {}", + id.value, e.get().clone().line), + }) + } + Entry::Vacant(e) => e.insert(PString { + value: l, + line: self.line, + range: Range { + start: id.range.start, + end: line.len(), + }, + }), + }; + } + + Ok(()) + } + + fn parse_instruction(&mut self, id: PString, line: &str) -> Result<()> { + // Parse the instruction into a `Generic` node. + let node = self.get_generic_instruction_node(id, line)?; + + // Make sure that there is no dangling content. + for c in line.get(self.column..).unwrap_or("").chars() { + if c == ';' { + break; + } + if !c.is_whitespace() { + return Err(self.parser_error("only one statement is allowed per line")); + } + self.column += 1; + } + + // And push a new `Instruction` object based on the parsed node. Note + // that this instruction will be incomplete: we first need to evaluate + // variables first in this context to be able to fully parse this + // object. + self.push_incomplete_instruction_from(node) + } + + // Returns a `Generic` node with the contents that can be parsed with the + // rest of the `line` and assuming that this is an assembly instruction + // which is identified by `id`. + fn get_generic_instruction_node(&mut self, id: PString, line: &str) -> Result { + // First of all, make sure that we are at a non-whitespace character. + self.skip_whitespace(line); + + // Instructions have a character which split the left and the right arms + // of the instruction. This is the character that we will use in order + // to stop on the first loop. + let needle_char = match line.chars().nth(self.column) { + Some(c) => { + if c == '(' { + ')' + } else { + ',' + } + } + None => ',', + }; + + let mut column = self.column; + let mut left = None; + let mut right = None; + let mut found = false; + + // First of the two loops: fetch the left arm. It iterates + // until the needle_char is found and then initializes the `left` + // variable with the fetched contents. + for c in line.get(column..).unwrap_or("").chars() { + if c == ';' { + break; + } + if c == needle_char { + self.init_positioned_maybe(&mut left, line, column, self.column); + + for inner in line.get(self.column..).unwrap_or("").chars() { + if inner.is_whitespace() || inner == ';' { + break; + } + self.column += 1; + } + + found = true; + break; + } + + self.column += 1; + } + + // If the previous loop found the needle, the we might have a right arm. + // Otherwise, if the needle was not found but the end of the line was + // reached, we might still need to pick up the contents that were not + // saved in the previous loop. + if found { + // Ready the `column` for the right arm. + self.skip_whitespace(line); + column = self.column; + + // Second loop: fetch the right arm. This time it iterates until a + // whitespace character or ';' is found. + for c in line.get(column..).unwrap_or("").chars() { + if c == ';' { + self.init_positioned_maybe(&mut right, line, column, self.column); + break; + } + self.column += 1; + } + + // Similarly to the first loop, if this second one reached the end + // without finding a whitespace or a ';' character, make sure that this + // content is not ignored. + self.init_positioned_maybe(&mut right, line, column, self.column); + } else { + self.init_positioned_maybe(&mut left, line, column, self.column); + } + + Ok(Generic { + identifier: id, + left, + right, + }) + } + + // Initialize the PString object `p` with the contents of + // `line.get(left..right)` unless it has already a `Some` value or the + // fetched contents would result in an empty string. + fn init_positioned_maybe( + &mut self, + p: &mut Option, + line: &str, + left: usize, + right: usize, + ) { + if !p.is_none() || left == right { + return; + } + + let string = String::from(line.get(left..right).unwrap_or("").trim()); + if !string.is_empty() { + *p = Some(PString { + value: string, + line: self.line, + range: Range { + start: left, + end: right, + }, + }); + } + } + + fn push_incomplete_instruction_from(&mut self, node: Generic) -> Result<()> { + let mut instr = Instruction::from(&node.identifier.value); + instr.left = node.left; + instr.right = node.right; + + self.nodes.push(Node::Instruction(instr)); + Ok(()) + } + + fn parser_error(&self, msg: &str) -> ParseError { + ParseError { + message: String::from(msg), + line: self.line, + } + } + + pub fn from_byte_reader(&mut self, mut reader: R) -> Result<()> { + loop { + let mut buf = [0; 1]; + let n = reader.read(&mut buf)?; + if n == 0 { + break; + } + + match OPCODES.get(&buf[0]) { + Some(v) => { + let mut bs = [0; 2]; + for i in 0..v.size - 1 { + let nn = reader.read(&mut buf)?; + if nn == 0 { + break; + } + bs[i as usize] = buf[0]; + } + self.nodes.push(Node::Instruction(Instruction { + mnemonic: PString::from(&v.mnemonic), + opcode: v.opcode, + size: v.size, + bytes: bs, + left: None, + right: None, + mode: v.mode.to_owned(), + cycles: v.cycles, + affected_on_page: v.affected_on_page, + })) + } + + None => { + return Err( + self.parser_error(format!("unknown byte '0x{:02X}'", buf[0]).as_str()) + ) + } + } + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::instruction::Node::Instruction; + + fn assert_hex(one: &dyn Encodable, expected: &[u8]) { + assert_eq!( + one.to_hex(), + expected + .iter() + .map(|x| format!("{:02X}", x)) + .collect::>() + ); + } + + fn instruction_test( + line: &str, + hex: &[u8], + cycles: u8, + affected: bool, + skip_disassemble: bool, + ) { + let mut parser = Assembler::new(); + let res = parser.to_nodes(line.as_bytes()); + + if res.is_err() { + if let Err(e) = res.clone() { + assert_eq!( + e, + ParseError { + line: 0, + message: String::from("") + } + ) + } + } + + let vec = res.unwrap(); + assert_eq!(vec.len(), 1); + + if let Instruction(instr) = &vec[0] { + assert_hex(instr, hex); + assert_eq!(instr.cycles, cycles); + assert_eq!(instr.affected_on_page, affected); + } else { + println!("Not an instruction!"); + assert!(false); + } + + // Now disassemble. + + if skip_disassemble { + return; + } + + parser.reset(); + let dis = parser.disassemble(hex); + assert!(dis.is_ok()); + + let dvec = dis.unwrap(); + assert_eq!(dvec.len(), 1); + + let dinstr = dvec[0]; + assert_eq!(dinstr.to_human(), line); + } + + fn instruction_err(line: &str, message: &str) { + let mut parser = Assembler::new(); + let err = parser.assemble(line.as_bytes()); + + assert!(err.is_err()); + if let Err(e) = err { + assert_eq!(e.message, message); + } + } + + // Mainly errors. + + #[test] + fn bad_addressing() { + instruction_err("unknown #$20", "unknown instruction 'unknown'"); + instruction_err( + "adc ($2002, x)", + "when parsing an instruction with indirect X-indexed addressing: only one byte of data is allowed here", + ); + instruction_err( + "adc ($2002, x), y", + "bad indirect mode, expecting an indirect X-indexed addressing mode", + ); + instruction_err( + "adc ($2002), y", + "when parsing an instruction with indirect Y-indexed addressing: only one byte of data is allowed here", + ); + instruction_err( + "adc ($20, y)", + "the index in indirect X-indexed addressing must be X", + ); + instruction_err( + "adc ($20), x", + "the index in indirect Y-indexed addressing must be Y", + ); + instruction_err("jmp ($20)", "expecting a full 16-bit address"); + instruction_err("adc $20, z", "index is neither X nor Y"); + instruction_err( + "adc ($2000)", + "bad addressing mode 'indirect' for the instruction 'adc'", + ); + } + + #[test] + fn parse_binary() { + instruction_err("adc #%", "missing binary digits to get a full byte"); + instruction_err("adc #%0001", "missing binary digits to get a full byte"); + instruction_err("adc #%0001000", "missing binary digits to get a full byte"); + instruction_err( + "adc #%000100001", + "too many binary digits for a single byte", + ); + instruction_test("adc #%10100010", &[0x69, 0xA2], 2, false, true); + } + + #[test] + fn parse_hexadecimal() { + instruction_err("adc $", "expecting a number of 2/4 hexadecimal digits"); + instruction_err("adc #$", "expecting a number of 2 hexadecimal digits"); + instruction_err("adc $AW", "unknown variable 'AW'"); + instruction_test("adc $AA", &[0x65, 0xAA], 3, false, false); + instruction_test("adc $10", &[0x65, 0x10], 3, false, false); + instruction_test("adc $10AB", &[0x6D, 0xAB, 0x10], 4, false, false); + } + + #[test] + fn parse_decimal() { + instruction_err("adc #", "empty decimal literal"); + instruction_err("adc #256", "decimal value is too big"); + instruction_err("adc #2000", "decimal value is too big"); + instruction_err("adc #2A", "'A' is not a decimal value"); + instruction_test("adc #1", &[0x69, 0x01], 2, false, true); + } + + // Individual instructions. + + #[test] + fn adc() { + instruction_test("adc #20", &[0x69, 0x14], 2, false, true); + instruction_test("adc #$20", &[0x69, 0x20], 2, false, false); + instruction_test("adc $2002", &[0x6D, 0x02, 0x20], 4, false, false); + instruction_test("adc $20", &[0x65, 0x20], 3, false, false); + instruction_test("adc $20, x", &[0x75, 0x20], 4, false, false); + instruction_test("adc $2002, x", &[0x7D, 0x02, 0x20], 4, true, false); + instruction_test("adc $2002, y", &[0x79, 0x02, 0x20], 4, true, false); + instruction_test("adc ($20, x)", &[0x61, 0x20], 6, false, false); + instruction_test("adc ($20), y", &[0x71, 0x20], 5, true, false); + } + + #[test] + fn sbc() { + instruction_test("sbc #$20", &[0xE9, 0x20], 2, false, false); + instruction_test("sbc $2002", &[0xED, 0x02, 0x20], 4, false, false); + instruction_test("sbc $20", &[0xE5, 0x20], 3, false, false); + instruction_test("sbc $20, x", &[0xF5, 0x20], 4, false, false); + instruction_test("sbc $2002, x", &[0xFD, 0x02, 0x20], 4, true, false); + instruction_test("sbc $2002, y", &[0xF9, 0x02, 0x20], 4, true, false); + instruction_test("sbc ($20, x)", &[0xE1, 0x20], 6, false, false); + instruction_test("sbc ($20), y", &[0xF1, 0x20], 5, true, false); + } + + #[test] + fn shift() { + // asl + instruction_test("asl", &[0x0A], 2, false, false); + instruction_test("asl a", &[0x0A], 2, false, true); + instruction_test("asl $20", &[0x06, 0x20], 5, false, false); + instruction_test("asl $20, x", &[0x16, 0x20], 6, false, false); + instruction_test("asl $2002", &[0x0E, 0x02, 0x20], 6, false, false); + instruction_test("asl $2002, x", &[0x1E, 0x02, 0x20], 7, false, false); + + // lsr + instruction_test("lsr", &[0x4A], 2, false, false); + instruction_test("lsr a", &[0x4A], 2, false, true); + instruction_test("lsr $20", &[0x46, 0x20], 5, false, false); + instruction_test("lsr $20, x", &[0x56, 0x20], 6, false, false); + instruction_test("lsr $2002", &[0x4E, 0x02, 0x20], 6, false, false); + instruction_test("lsr $2002, x", &[0x5E, 0x02, 0x20], 7, false, false); + } + + #[test] + fn rotate() { + // rol + instruction_test("rol", &[0x2A], 2, false, false); + instruction_test("rol a", &[0x2A], 2, false, true); + instruction_test("rol $20", &[0x26, 0x20], 5, false, false); + instruction_test("rol $20, x", &[0x36, 0x20], 6, false, false); + instruction_test("rol $2002", &[0x2E, 0x02, 0x20], 6, false, false); + instruction_test("rol $2002, x", &[0x3E, 0x02, 0x20], 7, false, false); + + // ror + instruction_test("ror", &[0x6A], 2, false, false); + instruction_test("ror a", &[0x6A], 2, false, true); + instruction_test("ror $20", &[0x66, 0x20], 5, false, false); + instruction_test("ror $20, x", &[0x76, 0x20], 6, false, false); + instruction_test("ror $2002", &[0x6E, 0x02, 0x20], 6, false, false); + instruction_test("ror $2002, x", &[0x7E, 0x02, 0x20], 7, false, false); + } + + #[test] + fn and() { + instruction_test("and #$20", &[0x29, 0x20], 2, false, false); + instruction_test("and $2002", &[0x2D, 0x02, 0x20], 4, false, false); + instruction_test("and $20", &[0x25, 0x20], 3, false, false); + instruction_test("and $20, x", &[0x35, 0x20], 4, false, false); + instruction_test("and $2002, x", &[0x3D, 0x02, 0x20], 4, true, false); + instruction_test("and $2002, y", &[0x39, 0x02, 0x20], 4, true, false); + instruction_test("and ($20, x)", &[0x21, 0x20], 6, false, false); + instruction_test("and ($20), y", &[0x31, 0x20], 5, true, false); + } + + #[test] + fn or() { + // eor + instruction_test("eor #$20", &[0x49, 0x20], 2, false, false); + instruction_test("eor $20", &[0x45, 0x20], 3, false, false); + instruction_test("eor $20, x", &[0x55, 0x20], 4, false, false); + instruction_test("eor $2002", &[0x4D, 0x02, 0x20], 4, false, false); + instruction_test("eor $2002, x", &[0x5D, 0x02, 0x20], 4, true, false); + instruction_test("eor $2002, y", &[0x59, 0x02, 0x20], 4, true, false); + instruction_test("eor ($20, x)", &[0x41, 0x20], 6, false, false); + instruction_test("eor ($20), y", &[0x51, 0x20], 5, true, false); + + // ora + instruction_test("ora #$20", &[0x09, 0x20], 2, false, false); + instruction_test("ora $20", &[0x05, 0x20], 3, false, false); + instruction_test("ora $20, x", &[0x15, 0x20], 4, false, false); + instruction_test("ora $2002", &[0x0D, 0x02, 0x20], 4, false, false); + instruction_test("ora $2002, x", &[0x1D, 0x02, 0x20], 4, true, false); + instruction_test("ora $2002, y", &[0x19, 0x02, 0x20], 4, true, false); + instruction_test("ora ($20, x)", &[0x01, 0x20], 6, false, false); + instruction_test("ora ($20), y", &[0x11, 0x20], 5, true, false); + } + + #[test] + fn jump() { + instruction_test("jsr $2002", &[0x20, 0x02, 0x20], 6, false, false); + + instruction_test("jmp $2002", &[0x4C, 0x02, 0x20], 3, false, false); + instruction_test("jmp ($2002)", &[0x6C, 0x02, 0x20], 5, false, false); + } + + #[test] + fn inc_dec_instructions() { + // inc + instruction_test("inc $10", &[0xE6, 0x10], 5, false, false); + instruction_test("inc $1000", &[0xEE, 0x00, 0x10], 6, false, false); + instruction_test("inc $10, x", &[0xF6, 0x10], 6, false, false); + instruction_test("inc $1000, x", &[0xFE, 0x00, 0x10], 7, false, false); + + instruction_test("inx", &[0xE8], 2, false, false); + + instruction_test("iny", &[0xC8], 2, false, false); + + // dec + instruction_test("dec $10", &[0xC6, 0x10], 5, false, false); + instruction_test("dec $1000", &[0xCE, 0x00, 0x10], 6, false, false); + instruction_test("dec $10, x", &[0xD6, 0x10], 6, false, false); + instruction_test("dec $1000, x", &[0xDE, 0x00, 0x10], 7, false, false); + + instruction_test("dex", &[0xCA], 2, false, false); + + instruction_test("dey", &[0x88], 2, false, false); + } + + #[test] + fn transfer_instructions() { + instruction_test("tax", &[0xAA], 2, false, false); + instruction_test("tay", &[0xA8], 2, false, false); + instruction_test("tsx", &[0xBA], 2, false, false); + instruction_test("txa", &[0x8A], 2, false, false); + instruction_test("txs", &[0x9A], 2, false, false); + instruction_test("tya", &[0x98], 2, false, false); + } + + #[test] + fn return_instructions() { + instruction_test("rti", &[0x40], 6, false, false); + instruction_test("rts", &[0x60], 6, false, false); + } + + #[test] + fn set_clear_instructions() { + instruction_test("clc", &[0x18], 2, false, false); + instruction_test("cld", &[0xD8], 2, false, false); + instruction_test("cli", &[0x58], 2, false, false); + instruction_test("clv", &[0xB8], 2, false, false); + + instruction_test("sec", &[0x38], 2, false, false); + instruction_test("sed", &[0xF8], 2, false, false); + instruction_test("sei", &[0x78], 2, false, false); + } + + #[test] + fn push_pull_instructions() { + instruction_test("pha", &[0x48], 3, false, false); + instruction_test("php", &[0x08], 3, false, false); + instruction_test("pla", &[0x68], 4, false, false); + instruction_test("plp", &[0x28], 4, false, false); + } + + #[test] + fn nop_brk() { + instruction_test("nop", &[0xEA], 2, false, false); + instruction_test("brk", &[0x00], 7, false, false); + } + + #[test] + fn cmp() { + // cmp + instruction_test("cmp #$20", &[0xC9, 0x20], 2, false, false); + instruction_test("cmp $2002", &[0xCD, 0x02, 0x20], 4, false, false); + instruction_test("cmp $20", &[0xC5, 0x20], 3, false, false); + instruction_test("cmp $20, x", &[0xD5, 0x20], 4, false, false); + instruction_test("cmp $2002, x", &[0xDD, 0x02, 0x20], 4, true, false); + instruction_test("cmp $2002, y", &[0xD9, 0x02, 0x20], 4, true, false); + instruction_test("cmp ($20, x)", &[0xC1, 0x20], 6, false, false); + instruction_test("cmp ($20), y", &[0xD1, 0x20], 5, true, false); + + // cpx + instruction_test("cpx #$20", &[0xE0, 0x20], 2, false, false); + instruction_test("cpx $2002", &[0xEC, 0x02, 0x20], 4, false, false); + instruction_test("cpx $20", &[0xE4, 0x20], 3, false, false); + + // cpy + instruction_test("cpy #$20", &[0xC0, 0x20], 2, false, false); + instruction_test("cpy $2002", &[0xCC, 0x02, 0x20], 4, false, false); + instruction_test("cpy $20", &[0xC4, 0x20], 3, false, false); + } + + #[test] + fn load() { + // lda + instruction_test("lda #$20", &[0xA9, 0x20], 2, false, false); + instruction_test("lda $20", &[0xA5, 0x20], 3, false, false); + instruction_test("lda $20, x", &[0xB5, 0x20], 4, false, false); + instruction_test("lda $2002", &[0xAD, 0x02, 0x20], 4, false, false); + instruction_test("lda $2002, x", &[0xBD, 0x02, 0x20], 4, true, false); + instruction_test("lda $2002, y", &[0xB9, 0x02, 0x20], 4, true, false); + instruction_test("lda ($20, x)", &[0xA1, 0x20], 6, false, false); + instruction_test("lda ($20), y", &[0xB1, 0x20], 5, true, false); + + // ldx + instruction_test("ldx #$20", &[0xA2, 0x20], 2, false, false); + instruction_test("ldx $20", &[0xA6, 0x20], 3, false, false); + instruction_test("ldx $20, y", &[0xB6, 0x20], 4, false, false); + instruction_test("ldx $2002", &[0xAE, 0x02, 0x20], 4, false, false); + instruction_test("ldx $2002, y", &[0xBE, 0x02, 0x20], 4, true, false); + + // ldy + instruction_test("ldy #$20", &[0xA0, 0x20], 2, false, false); + instruction_test("ldy $20", &[0xA4, 0x20], 3, false, false); + instruction_test("ldy $20, x", &[0xB4, 0x20], 4, false, false); + instruction_test("ldy $2002", &[0xAC, 0x02, 0x20], 4, false, false); + instruction_test("ldy $2002, x", &[0xBC, 0x02, 0x20], 4, true, false); + } + + #[test] + fn store_instructions() { + //sta + instruction_test("sta $20", &[0x85, 0x20], 3, false, false); + instruction_test("sta $20, x", &[0x95, 0x20], 4, false, false); + instruction_test("sta $2002", &[0x8D, 0x02, 0x20], 4, false, false); + instruction_test("sta $2002, x", &[0x9D, 0x02, 0x20], 5, false, false); + instruction_test("sta $2002, y", &[0x99, 0x02, 0x20], 5, false, false); + instruction_test("sta ($20, x)", &[0x81, 0x20], 6, false, false); + instruction_test("sta ($20), y", &[0x91, 0x20], 6, false, false); + + // stx + instruction_test("stx $20", &[0x86, 0x20], 3, false, false); + instruction_test("stx $20, y", &[0x96, 0x20], 4, false, false); + instruction_test("stx $2002", &[0x8E, 0x02, 0x20], 4, false, false); + + // sty + instruction_test("sty $20", &[0x84, 0x20], 3, false, false); + instruction_test("sty $20, x", &[0x94, 0x20], 4, false, false); + instruction_test("sty $2002", &[0x8C, 0x02, 0x20], 4, false, false); + } + + #[test] + fn bit() { + instruction_test("bit $10", &[0x24, 0x10], 3, false, false); + instruction_test("bit $1001", &[0x2C, 0x01, 0x10], 4, false, false); + } + + // Variables & scopes. + + #[test] + fn scoped_variable() { + let mut parser = Assembler::new(); + let res = parser + .assemble( + r#" +.scope One ; This is a comment + adc #Variable + + Variable = $20 +.endscope + +.scope Another + Variable = $40 +.endscope + +Variable = $30 +adc #Variable + +adc #One::Variable +adc #Another::Variable +"# + .as_bytes(), + ) + .unwrap(); + + assert_eq!(res.len(), 4); + let instrs: Vec<[u8; 2]> = vec![[0x69, 0x20], [0x69, 0x30], [0x69, 0x20], [0x69, 0x40]]; + + for i in 0..4 { + assert_eq!( + res[i].to_hex(), + instrs[i] + .iter() + .map(|x| format!("{:02X}", x)) + .collect::>() + ); + } + } + + #[test] + fn redefined_variable() { + let mut parser = Assembler::new(); + let res = parser.assemble( + r#" +.scope One + Variable = 1 +.endscope + +Variable = 1 +Yet = 3 +Yet = 4 +"# + .as_bytes(), + ); + + assert!(res.is_err()); + if let Err(e) = res { + assert_eq!( + e.message, + "variable 'Yet' is being re-assigned: it was previously defined in line 6" + ); + } + } + + #[test] + fn bad_variable_names() { + instruction_err("a = 2", "cannot use reserved name 'a'"); + instruction_err("X = 2", "cannot use reserved name 'X'"); + + instruction_err( + "AA = 2", + "cannot use names which are valid hexadecimal values such as 'AA'", + ); + + instruction_err( + "Scope::Variable = 2", + "the name 'Scope::Variable' is scoped: do not declare variables this way", + ); + } + + #[test] + fn bad_assignment() { + instruction_err("Variable =", "incomplete assignment"); + instruction_err("Variable = ; comment", "incomplete assignment"); + instruction_err("adc = $12", "cannot use 'adc' in an assignment because it's a word reserved for an instruction mnemonic"); + } + + // Literals + + #[test] + fn byte_literals_errors() { + instruction_err( + ".byte $0102", + "when parsing a data literal: only one byte of data is allowed here", + ); + instruction_err(".byte '$01", "non-terminated quote for byte literal"); + instruction_err(".byte '$01, $02", "non-terminated quote for byte literal"); + } + + #[test] + fn byte_literals() { + let mut asm = Assembler::new(); + + let mut res = asm.assemble(".byte $01".as_bytes()).unwrap(); + assert_eq!(res.len(), 1); + assert_hex(res[0], &[0x01]); + + asm.reset(); + res = asm.assemble(".db $01, $02".as_bytes()).unwrap(); + assert_eq!(res.len(), 2); + assert_hex(res[0], &[0x01]); + assert_hex(res[1], &[0x02]); + + asm.reset(); + res = asm + .assemble(".byte $01, 2, '%00000011', \"$04\"".as_bytes()) + .unwrap(); + assert_eq!(res.len(), 4); + assert_hex(res[0], &[0x01]); + assert_hex(res[1], &[0x02]); + assert_hex(res[2], &[0x03]); + assert_hex(res[3], &[0x04]); + } + + #[test] + fn word_literals() { + let mut asm = Assembler::new(); + + let mut res = asm.assemble(".word $01".as_bytes()).unwrap(); + assert_eq!(res.len(), 1); + assert_hex(res[0], &[0x01, 0x00]); + + asm.reset(); + res = asm.assemble(".dw $0102, $02".as_bytes()).unwrap(); + assert_eq!(res.len(), 2); + assert_hex(res[0], &[0x02, 0x01]); + assert_hex(res[1], &[0x02, 0x00]); + + asm.reset(); + res = asm + .assemble(".word $0102, $0204, '$0308', \"$0410\"".as_bytes()) + .unwrap(); + assert_eq!(res.len(), 4); + assert_hex(res[0], &[0x02, 0x01]); + assert_hex(res[1], &[0x04, 0x02]); + assert_hex(res[2], &[0x08, 0x03]); + assert_hex(res[3], &[0x10, 0x04]); + } + + #[test] + fn variables_in_literals() { + let mut asm = Assembler::new(); + let res = asm + .assemble( + r#" +.scope One + Variable = $01 +.endscope + +Variable = $02 +.byte One::Variable, Variable, $03 +"# + .as_bytes(), + ) + .unwrap(); + + assert_eq!(res.len(), 3); + assert_hex(res[0], &[0x01]); + assert_hex(res[1], &[0x02]); + assert_hex(res[2], &[0x03]); + } +} diff --git a/lib/xixanta/src/context.rs b/lib/xixanta/src/context.rs new file mode 100644 index 0000000..62ec7e0 --- /dev/null +++ b/lib/xixanta/src/context.rs @@ -0,0 +1,66 @@ +use crate::instruction::PString; +use std::collections::HashMap; + +const GLOBAL_CONTEXT: &str = "Global"; + +#[derive(Debug)] +pub struct Context { + stack: Vec, + map: HashMap>, +} + +impl Default for Context { + fn default() -> Self { + Context::new() + } +} + +impl Context { + pub fn new() -> Self { + Context { + stack: vec![], + map: HashMap::from([(String::from(GLOBAL_CONTEXT), HashMap::new())]), + } + } + + pub fn reset(&mut self) { + self.stack = vec![]; + } + + pub fn find(&self, name: &str) -> Option<&HashMap> { + self.map.get(name) + } + + pub fn current(&self) -> Option<&HashMap> { + match self.stack.last() { + Some(name) => self.map.get(name), + None => self.map.get(GLOBAL_CONTEXT), + } + } + + pub fn current_mut(&mut self) -> Option<&mut HashMap> { + match self.stack.last() { + Some(name) => self.map.get_mut(name), + None => self.map.get_mut(GLOBAL_CONTEXT), + } + } + + pub fn push(&mut self, identifier: &String) { + let name = match self.stack.last() { + Some(n) => n.to_owned() + &String::from("::") + identifier, + None => identifier.to_string(), + }; + + self.stack.push(name.clone()); + self.map.entry(name).or_default(); + } + + pub fn pop(&mut self) -> bool { + if self.stack.is_empty() { + return false; + } + + self.stack.truncate(self.stack.len() - 1); + true + } +} diff --git a/lib/xixanta/src/errors.rs b/lib/xixanta/src/errors.rs new file mode 100644 index 0000000..48f7286 --- /dev/null +++ b/lib/xixanta/src/errors.rs @@ -0,0 +1,25 @@ +use std::fmt; + +#[derive(Debug, Clone, PartialEq)] +pub struct ParseError { + pub line: usize, + pub message: String, +} + +impl std::error::Error for ParseError {} + +impl From for ParseError { + fn from(err: std::io::Error) -> Self { + // TODO + ParseError { + line: 0, + message: err.to_string(), + } + } +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "parser (line {}): {}.", self.line + 1, self.message) + } +} diff --git a/lib/xixanta/src/instruction.rs b/lib/xixanta/src/instruction.rs new file mode 100644 index 0000000..fac6d8e --- /dev/null +++ b/lib/xixanta/src/instruction.rs @@ -0,0 +1,277 @@ +use crate::errors::ParseError; +use std::fmt; +use std::ops::Range; + +/// PString is a String with position information. +#[derive(Debug, Clone, PartialEq)] +pub struct PString { + pub value: String, + pub line: usize, + pub range: Range, +} + +impl PString { + pub fn new() -> Self { + PString { + value: String::from(""), + line: 0, + range: Range { start: 0, end: 0 }, + } + } + + pub fn from(value: &str) -> Self { + PString { + value: String::from(value), + line: 0, + range: Range { start: 0, end: 0 }, + } + } + + pub fn parser_error(&self, message: &str) -> ParseError { + // TODO: we can go further :) + ParseError { + line: self.line, + message: String::from(message), + } + } + + pub fn is_reserved(&self) -> bool { + matches!(self.value.to_lowercase().as_str(), "x" | "y" | "a") + } +} + +#[derive(Eq, Hash, PartialEq, Debug, Clone)] +pub enum AddressingMode { + Unknown, + Implied, + Immediate, + Absolute, + RelativeOrZeropage, + IndexedX, + IndexedY, + ZeropageIndexedX, + ZeropageIndexedY, + Indirect, + IndirectX, + IndirectY, +} + +impl fmt::Display for AddressingMode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + AddressingMode::Implied => write!(f, "implied"), + AddressingMode::Immediate => write!(f, "immediate"), + AddressingMode::Absolute => write!(f, "absolute"), + AddressingMode::RelativeOrZeropage => write!(f, "relative or zeropage"), + AddressingMode::IndexedX => write!(f, "indexed by x"), + AddressingMode::IndexedY => write!(f, "indexed by y"), + AddressingMode::ZeropageIndexedX => write!(f, "zeropage indexed by x"), + AddressingMode::ZeropageIndexedY => write!(f, "zeropage indexed by y"), + AddressingMode::Indirect => write!(f, "indirect"), + AddressingMode::IndirectX => write!(f, "indirect indexed by x"), + AddressingMode::IndirectY => write!(f, "indirect indexed by y"), + _ => write!(f, "unknown"), + } + } +} + +/// Encodable is a trait to be implemented by those structs that might need to +/// be encoded into the outside world. That is, structures that make sense to +/// output into files or other output streams. +pub trait Encodable { + /// Returns a fixed array of bytes which belong to an encodable object. Note + /// that the capacity is fixed, but the actual size must be checked with the + /// `size` trait function, otherwise elements beyond that size might contain + /// junk. + fn to_bytes(&self) -> [u8; 3]; + + /// Returns the actual size of the data returned by `to_bytes`. + fn size(&self) -> u8; + + /// Returns a vector which contains the exact byte data for the given + /// object. In contrast with `to_bytes`, the caller does not need to check + /// for `size`: the returned vector is tailored to the exact amount of + /// bytes for the object. + fn to_hex(&self) -> Vec; + + /// Returns a string representation which makes sense to a human (e.g. + /// instead of providing the byte encoded opcode for an instruction, show + /// the mnemonic). + fn to_human(&self) -> String; + + /// Returns a string representation with higher verbosity than `to_human`. + fn to_verbose(&self) -> String; +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Instruction { + pub mnemonic: PString, + pub opcode: u8, + pub bytes: [u8; 2], + pub size: u8, + pub left: Option, + pub right: Option, + pub mode: AddressingMode, + pub cycles: u8, + pub affected_on_page: bool, +} + +impl Instruction { + pub fn unknown() -> Instruction { + Instruction { + mnemonic: PString::new(), + opcode: 0, + bytes: [0, 0], + size: 0, + left: None, + right: None, + mode: AddressingMode::Unknown, + cycles: 0, + affected_on_page: false, + } + } + + pub fn from(mnemonic: &str) -> Instruction { + Instruction { + mnemonic: PString::from(mnemonic), + opcode: 0, + bytes: [0, 0], + size: 0, + left: None, + right: None, + mode: AddressingMode::Unknown, + cycles: 0, + affected_on_page: false, + } + } +} + +impl Encodable for Instruction { + fn size(&self) -> u8 { + self.size + } + + fn to_hex(&self) -> Vec { + let mut ret = vec![]; + + ret.push(format!("{:02X}", self.opcode)); + if self.size > 1 { + ret.push(format!("{:02X}", self.bytes[0])); + } + if self.size == 3 { + ret.push(format!("{:02X}", self.bytes[1])); + } + + ret + } + + fn to_bytes(&self) -> [u8; 3] { + [self.opcode.to_le_bytes()[0], self.bytes[0], self.bytes[1]] + } + + fn to_human(&self) -> String { + match self.mode { + AddressingMode::Implied => self.mnemonic.value.clone(), + AddressingMode::Immediate => format!("{} #${:02X}", self.mnemonic.value, self.bytes[0]), + AddressingMode::Absolute => format!( + "{} ${:02X}{:02X}", + self.mnemonic.value, self.bytes[1], self.bytes[0] + ), + AddressingMode::RelativeOrZeropage => { + format!("{} ${:02X}", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::IndexedX => format!( + "{} ${:02X}{:02X}, x", + self.mnemonic.value, self.bytes[1], self.bytes[0] + ), + AddressingMode::IndexedY => format!( + "{} ${:02X}{:02X}, y", + self.mnemonic.value, self.bytes[1], self.bytes[0] + ), + AddressingMode::ZeropageIndexedX => { + format!("{} ${:02X}, x", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::ZeropageIndexedY => { + format!("{} ${:02X}, y", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::Indirect => format!( + "{} (${:02X}{:02X})", + self.mnemonic.value, self.bytes[1], self.bytes[0] + ), + AddressingMode::IndirectX => { + format!("{} (${:02X}, x)", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::IndirectY => { + format!("{} (${:02X}), y", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::Unknown => String::from("unknown instruction"), + } + } + + fn to_verbose(&self) -> String { + format!("{:#?}", self) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Generic { + pub identifier: PString, + pub left: Option, + pub right: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Scoped { + pub identifier: PString, + pub start: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Literal { + pub identifier: PString, + pub bytes: [u8; 2], + pub size: u8, +} + +impl Encodable for Literal { + fn size(&self) -> u8 { + self.size + } + + fn to_hex(&self) -> Vec { + let mut ret = vec![]; + + ret.push(format!("{:02X}", self.bytes[0])); + if self.size == 2 { + ret.push(format!("{:02X}", self.bytes[1])); + } else if self.size != 1 { + panic!("size for literal should be either 1 or 2"); + } + + ret + } + + fn to_bytes(&self) -> [u8; 3] { + [self.bytes[0], self.bytes[1], 0] + } + + fn to_human(&self) -> String { + match self.size { + 1 => format!(".byte ${:02X}", self.bytes[0]), + 2 => format!(".byte ${:02X}{:02X}", self.bytes[1], self.bytes[0]), + _ => String::from("unknown literal"), + } + } + + fn to_verbose(&self) -> String { + format!("{:#?}", self) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Node { + Generic(Generic), + Instruction(Instruction), + Scoped(Scoped), + Literal(Literal), +} diff --git a/lib/xixanta/src/lib.rs b/lib/xixanta/src/lib.rs new file mode 100644 index 0000000..fc8ca96 --- /dev/null +++ b/lib/xixanta/src/lib.rs @@ -0,0 +1,10 @@ +#[macro_use] +extern crate lazy_static; + +// TODO: be more mindful on what's exported outside. + +pub mod assembler; +mod context; +mod errors; +pub mod instruction; +mod opcodes; diff --git a/lib/xixanta/src/opcodes.rs b/lib/xixanta/src/opcodes.rs new file mode 100644 index 0000000..bca8104 --- /dev/null +++ b/lib/xixanta/src/opcodes.rs @@ -0,0 +1,631 @@ +use crate::instruction::AddressingMode; +use std::collections::HashMap; + +#[derive(Debug)] +pub struct ShortEntry { + pub cycles: u8, + pub opcode: u8, + pub size: u8, + pub affected_on_page: bool, +} + +#[derive(Debug)] +pub struct Entry { + pub mode: AddressingMode, + pub mnemonic: String, + pub cycles: u8, + pub opcode: u8, + pub size: u8, + pub affected_on_page: bool, +} + +lazy_static! { + // TODO + pub static ref INSTRUCTIONS: HashMap> = { + let mut instrs = HashMap::new(); + + // adc + let mut adc = HashMap::new(); + adc.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0x69, affected_on_page: false }); + adc.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x65, affected_on_page: false }); + adc.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x75, affected_on_page: false }); + adc.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x6D, affected_on_page: false }); + adc.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0x7D, affected_on_page: true }); + adc.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0x79, affected_on_page: true }); + adc.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x61, affected_on_page: false }); + adc.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0x71, affected_on_page: true }); + instrs.insert(String::from("adc"), adc); + + // and + let mut and = HashMap::new(); + and.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0x29, affected_on_page: false }); + and.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x25, affected_on_page: false }); + and.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x35, affected_on_page: false }); + and.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x2D, affected_on_page: false }); + and.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0x3D, affected_on_page: true }); + and.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0x39, affected_on_page: true }); + and.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x21, affected_on_page: false }); + and.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0x31, affected_on_page: true }); + instrs.insert(String::from("and"), and); + + // asl + let mut asl = HashMap::new(); + asl.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x0A, affected_on_page: false }); + asl.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0x06, affected_on_page: false }); + asl.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0x16, affected_on_page: false }); + asl.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x0E, affected_on_page: false }); + asl.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0x1E, affected_on_page: false }); + instrs.insert(String::from("asl"), asl); + + // BCC: TODO + // BCS: TODO + // BEQ: TODO + + // bit + let mut bit = HashMap::new(); + bit.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x24, affected_on_page: false }); + bit.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x2C, affected_on_page: false }); + instrs.insert(String::from("bit"), bit); + + // BMI: TODO + // BNE: TODO + // BPL: TODO + + // brk + let mut brk = HashMap::new(); + brk.insert(AddressingMode::Implied, ShortEntry{ cycles: 7, size: 1, opcode: 0x00, affected_on_page: false }); + instrs.insert(String::from("brk"), brk); + + // BVC: TODO + // BVS: TODO + + // clc + let mut clc = HashMap::new(); + clc.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x18, affected_on_page: false }); + instrs.insert(String::from("clc"), clc); + + // cld + let mut cld = HashMap::new(); + cld.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xD8, affected_on_page: false }); + instrs.insert(String::from("cld"), cld); + + // cli + let mut cli = HashMap::new(); + cli.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x58, affected_on_page: false }); + instrs.insert(String::from("cli"), cli); + + // clv + let mut clv = HashMap::new(); + clv.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xB8, affected_on_page: false }); + instrs.insert(String::from("clv"), clv); + + // cmp + let mut cmp = HashMap::new(); + cmp.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xC9, affected_on_page: false }); + cmp.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xC5, affected_on_page: false }); + cmp.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0xD5, affected_on_page: false }); + cmp.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xCD, affected_on_page: false }); + cmp.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0xDD, affected_on_page: true }); + cmp.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0xD9, affected_on_page: true }); + cmp.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0xC1, affected_on_page: false }); + cmp.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0xD1, affected_on_page: true }); + instrs.insert(String::from("cmp"), cmp); + + // cpx + let mut cpx = HashMap::new(); + cpx.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xE0, affected_on_page: false }); + cpx.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xE4, affected_on_page: false }); + cpx.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xEC, affected_on_page: false }); + instrs.insert(String::from("cpx"), cpx); + + // cpy + let mut cpy = HashMap::new(); + cpy.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xC0, affected_on_page: false }); + cpy.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xC4, affected_on_page: false }); + cpy.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xCC, affected_on_page: false }); + instrs.insert(String::from("cpy"), cpy); + + // dec + let mut dec = HashMap::new(); + dec.insert(AddressingMode::RelativeOrZeropage, ShortEntry { cycles: 5, size: 2, opcode: 0xC6, affected_on_page: false }); + dec.insert(AddressingMode::ZeropageIndexedX, ShortEntry { cycles: 6, size: 2, opcode: 0xD6, affected_on_page: false }); + dec.insert(AddressingMode::Absolute, ShortEntry { cycles: 6, size: 3, opcode: 0xCE, affected_on_page: false }); + dec.insert(AddressingMode::IndexedX, ShortEntry { cycles: 7, size: 3, opcode: 0xDE, affected_on_page: false }); + instrs.insert(String::from("dec"), dec); + + // dex + let mut dex = HashMap::new(); + dex.insert(AddressingMode::Implied, ShortEntry { cycles: 2, size: 1, opcode: 0xCA, affected_on_page: false }); + instrs.insert(String::from("dex"), dex); + + // dey + let mut dey = HashMap::new(); + dey.insert(AddressingMode::Implied, ShortEntry { cycles: 2, size: 1, opcode: 0x88, affected_on_page: false }); + instrs.insert(String::from("dey"), dey); + + // eor + let mut eor = HashMap::new(); + eor.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0x49, affected_on_page: false }); + eor.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x45, affected_on_page: false }); + eor.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x55, affected_on_page: false }); + eor.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x4D, affected_on_page: false }); + eor.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0x5D, affected_on_page: true }); + eor.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0x59, affected_on_page: true }); + eor.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x41, affected_on_page: false }); + eor.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0x51, affected_on_page: true }); + instrs.insert(String::from("eor"), eor); + + // inc + let mut inc = HashMap::new(); + inc.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0xE6, affected_on_page: false }); + inc.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0xF6, affected_on_page: false }); + inc.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0xEE, affected_on_page: false }); + inc.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0xFE, affected_on_page: false }); + instrs.insert(String::from("inc"), inc); + + // inx + let mut inx = HashMap::new(); + inx.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xE8, affected_on_page: false }); + instrs.insert(String::from("inx"), inx); + + // iny + let mut iny = HashMap::new(); + iny.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xC8, affected_on_page: false }); + instrs.insert(String::from("iny"), iny); + + // jmp + let mut jmp = HashMap::new(); + jmp.insert(AddressingMode::Absolute, ShortEntry{ cycles: 3, size: 3, opcode: 0x4C, affected_on_page: false }); + jmp.insert(AddressingMode::Indirect, ShortEntry{ cycles: 5, size: 3, opcode: 0x6C, affected_on_page: false }); + instrs.insert(String::from("jmp"), jmp); + + // jsr + let mut jsr = HashMap::new(); + jsr.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x20, affected_on_page: false }); + instrs.insert(String::from("jsr"), jsr); + + // lda + let mut lda = HashMap::new(); + lda.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xA9, affected_on_page: false }); + lda.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xA5, affected_on_page: false }); + lda.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0xB5, affected_on_page: false }); + lda.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xAD, affected_on_page: false }); + lda.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0xBD, affected_on_page: true }); + lda.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0xB9, affected_on_page: true }); + lda.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0xA1, affected_on_page: false }); + lda.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0xB1, affected_on_page: true }); + instrs.insert(String::from("lda"), lda); + + // ldx + let mut ldx = HashMap::new(); + ldx.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xA2, affected_on_page: false }); + ldx.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xA6, affected_on_page: false }); + ldx.insert(AddressingMode::ZeropageIndexedY, ShortEntry{ cycles: 4, size: 2, opcode: 0xB6, affected_on_page: false }); + ldx.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xAE, affected_on_page: false }); + ldx.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0xBE, affected_on_page: true }); + instrs.insert(String::from("ldx"), ldx); + + // ldy + let mut ldy = HashMap::new(); + ldy.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xA0, affected_on_page: false }); + ldy.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xA4, affected_on_page: false }); + ldy.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0xB4, affected_on_page: false }); + ldy.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xAC, affected_on_page: false }); + ldy.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0xBC, affected_on_page: true }); + instrs.insert(String::from("ldy"), ldy); + + // lsr + let mut lsr = HashMap::new(); + lsr.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x4A, affected_on_page: false }); + lsr.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0x46, affected_on_page: false }); + lsr.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0x56, affected_on_page: false }); + lsr.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x4E, affected_on_page: false }); + lsr.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0x5E, affected_on_page: false }); + instrs.insert(String::from("lsr"), lsr); + + // nop + let mut nop = HashMap::new(); + nop.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xEA, affected_on_page: false }); + instrs.insert(String::from("nop"), nop); + + // ora + let mut ora = HashMap::new(); + ora.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0x09, affected_on_page: false }); + ora.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x05, affected_on_page: false }); + ora.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x15, affected_on_page: false }); + ora.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x0D, affected_on_page: false }); + ora.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0x1D, affected_on_page: true }); + ora.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0x19, affected_on_page: true }); + ora.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x01, affected_on_page: false }); + ora.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0x11, affected_on_page: true }); + instrs.insert(String::from("ora"), ora); + + // pha + let mut pha = HashMap::new(); + pha.insert(AddressingMode::Implied, ShortEntry{ cycles: 3, size: 1, opcode: 0x48, affected_on_page: false }); + instrs.insert(String::from("pha"), pha); + + // php + let mut php = HashMap::new(); + php.insert(AddressingMode::Implied, ShortEntry{ cycles: 3, size: 1, opcode: 0x08, affected_on_page: false }); + instrs.insert(String::from("php"), php); + + // pla + let mut pla = HashMap::new(); + pla.insert(AddressingMode::Implied, ShortEntry{ cycles: 4, size: 1, opcode: 0x68, affected_on_page: false }); + instrs.insert(String::from("pla"), pla); + + // plp + let mut plp = HashMap::new(); + plp.insert(AddressingMode::Implied, ShortEntry{ cycles: 4, size: 1, opcode: 0x28, affected_on_page: false }); + instrs.insert(String::from("plp"), plp); + + // rol + let mut rol = HashMap::new(); + rol.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x2A, affected_on_page: false }); + rol.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0x26, affected_on_page: false }); + rol.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0x36, affected_on_page: false }); + rol.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x2E, affected_on_page: false }); + rol.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0x3E, affected_on_page: false }); + instrs.insert(String::from("rol"), rol); + + // ror + let mut ror = HashMap::new(); + ror.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x6A, affected_on_page: false }); + ror.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0x66, affected_on_page: false }); + ror.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0x76, affected_on_page: false }); + ror.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x6E, affected_on_page: false }); + ror.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0x7E, affected_on_page: false }); + instrs.insert(String::from("ror"), ror); + + // rti + let mut rti = HashMap::new(); + rti.insert(AddressingMode::Implied, ShortEntry{ cycles: 6, size: 1, opcode: 0x40, affected_on_page: false }); + instrs.insert(String::from("rti"), rti); + + // rts + let mut rts = HashMap::new(); + rts.insert(AddressingMode::Implied, ShortEntry{ cycles: 6, size: 1, opcode: 0x60, affected_on_page: false }); + instrs.insert(String::from("rts"), rts); + + // sbc + let mut sbc = HashMap::new(); + sbc.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xE9, affected_on_page: false }); + sbc.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xE5, affected_on_page: false }); + sbc.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0xF5, affected_on_page: false }); + sbc.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xED, affected_on_page: false }); + sbc.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0xFD, affected_on_page: true }); + sbc.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0xF9, affected_on_page: true }); + sbc.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0xE1, affected_on_page: false }); + sbc.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0xF1, affected_on_page: true }); + instrs.insert(String::from("sbc"), sbc); + + // sec + let mut sec = HashMap::new(); + sec.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x38, affected_on_page: false }); + instrs.insert(String::from("sec"), sec); + + // sed + let mut sed = HashMap::new(); + sed.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xF8, affected_on_page: false }); + instrs.insert(String::from("sed"), sed); + + // sei + let mut sei = HashMap::new(); + sei.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x78, affected_on_page: false }); + instrs.insert(String::from("sei"), sei); + + // sta + let mut sta = HashMap::new(); + sta.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x85, affected_on_page: false }); + sta.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x95, affected_on_page: false }); + sta.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x8D, affected_on_page: false }); + sta.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 5, size: 3, opcode: 0x9D, affected_on_page: false }); + sta.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 5, size: 3, opcode: 0x99, affected_on_page: false }); + sta.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x81, affected_on_page: false }); + sta.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 6, size: 2, opcode: 0x91, affected_on_page: false }); + instrs.insert(String::from("sta"), sta); + + // stx + let mut stx = HashMap::new(); + stx.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x86, affected_on_page: false }); + stx.insert(AddressingMode::ZeropageIndexedY, ShortEntry{ cycles: 4, size: 2, opcode: 0x96, affected_on_page: false }); + stx.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x8E, affected_on_page: false }); + instrs.insert(String::from("stx"), stx); + + // sty + let mut sty = HashMap::new(); + sty.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x84, affected_on_page: false }); + sty.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x94, affected_on_page: false }); + sty.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x8C, affected_on_page: false }); + instrs.insert(String::from("sty"), sty); + + // tax + let mut tax = HashMap::new(); + tax.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xAA, affected_on_page: false }); + instrs.insert(String::from("tax"), tax); + + // tay + let mut tay = HashMap::new(); + tay.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xA8, affected_on_page: false }); + instrs.insert(String::from("tay"), tay); + + // tsx + let mut tsx = HashMap::new(); + tsx.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xBA, affected_on_page: false }); + instrs.insert(String::from("tsx"), tsx); + + // txa + let mut txa = HashMap::new(); + txa.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x8A, affected_on_page: false }); + instrs.insert(String::from("txa"), txa); + + // txs + let mut txs = HashMap::new(); + txs.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x9A, affected_on_page: false }); + instrs.insert(String::from("txs"), txs); + + // tya + let mut tya = HashMap::new(); + tya.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x98, affected_on_page: false }); + instrs.insert(String::from("tya"), tya); + + instrs + }; + + pub static ref OPCODES: HashMap = { + let mut opcodes = HashMap::new(); + + // adc + opcodes.insert(0x69, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("adc"), cycles: 2, size: 2, opcode: 0x69, affected_on_page: false }); + opcodes.insert(0x65, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("adc"), cycles: 3, size: 2, opcode: 0x65, affected_on_page: false }); + opcodes.insert(0x75, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("adc"), cycles: 4, size: 2, opcode: 0x75, affected_on_page: false }); + opcodes.insert(0x7D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("adc"), cycles: 4, size: 3, opcode: 0x7D, affected_on_page: true }); + opcodes.insert(0x79, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("adc"), cycles: 4, size: 3, opcode: 0x79, affected_on_page: true }); + opcodes.insert(0x61, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("adc"), cycles: 6, size: 2, opcode: 0x61, affected_on_page: false }); + opcodes.insert(0x71, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("adc"), cycles: 5, size: 2, opcode: 0x71, affected_on_page: true }); + opcodes.insert(0x6D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("adc"), cycles: 4, size: 3, opcode: 0x6D, affected_on_page: false }); + + // and + opcodes.insert(0x29, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("and"), cycles: 2, size: 2, opcode: 0x29, affected_on_page: false }); + opcodes.insert(0x25, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("and"), cycles: 3, size: 2, opcode: 0x25, affected_on_page: false }); + opcodes.insert(0x35, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("and"), cycles: 4, size: 2, opcode: 0x35, affected_on_page: false }); + opcodes.insert(0x2D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("and"), cycles: 4, size: 3, opcode: 0x2D, affected_on_page: false }); + opcodes.insert(0x3D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("and"), cycles: 4, size: 3, opcode: 0x3D, affected_on_page: true }); + opcodes.insert(0x39, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("and"), cycles: 4, size: 3, opcode: 0x39, affected_on_page: true }); + opcodes.insert(0x21, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("and"), cycles: 6, size: 2, opcode: 0x21, affected_on_page: false }); + opcodes.insert(0x31, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("and"), cycles: 5, size: 2, opcode: 0x31, affected_on_page: true }); + + // asl + opcodes.insert(0x0A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("asl"), cycles: 2, size: 1, opcode: 0x0A, affected_on_page: false }); + opcodes.insert(0x06, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("asl"), cycles: 5, size: 2, opcode: 0x06, affected_on_page: false }); + opcodes.insert(0x16, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("asl"), cycles: 6, size: 2, opcode: 0x16, affected_on_page: false }); + opcodes.insert(0x0E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("asl"), cycles: 6, size: 3, opcode: 0x0E, affected_on_page: false }); + opcodes.insert(0x1E, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("asl"), cycles: 7, size: 3, opcode: 0x1E, affected_on_page: false }); + + // BCC + // BCS + // BEQ + + // bit + opcodes.insert(0x24, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("bit"), cycles: 3, size: 2, opcode: 0x24, affected_on_page: false }); + opcodes.insert(0x2C, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("bit"), cycles: 4, size: 3, opcode: 0x2C, affected_on_page: false }); + + // BMI + // BNE + // BPL + + // brk + opcodes.insert(0x00, Entry { mode: AddressingMode::Implied, mnemonic: String::from("brk"), cycles: 7, size: 1, opcode: 0x00, affected_on_page: false }); + + // BVC + // BVS + + // clc + opcodes.insert(0x18, Entry { mode: AddressingMode::Implied, mnemonic: String::from("clc"), cycles: 2, size: 1, opcode: 0x18, affected_on_page: false }); + + // cld + opcodes.insert(0xD8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("cld"), cycles: 2, size: 1, opcode: 0xD8, affected_on_page: false }); + + // cli + opcodes.insert(0x58, Entry { mode: AddressingMode::Implied, mnemonic: String::from("cli"), cycles: 2, size: 1, opcode: 0x58, affected_on_page: false }); + + // clv + opcodes.insert(0xB8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("clv"), cycles: 2, size: 1, opcode: 0xB8, affected_on_page: false }); + + // cmp + opcodes.insert(0xC9, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("cmp"), cycles: 2, size: 2, opcode: 0xC9, affected_on_page: false }); + opcodes.insert(0xC5, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("cmp"), cycles: 3, size: 2, opcode: 0xC5, affected_on_page: false }); + opcodes.insert(0xD5, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("cmp"), cycles: 4, size: 2, opcode: 0xD5, affected_on_page: false }); + opcodes.insert(0xCD, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("cmp"), cycles: 4, size: 3, opcode: 0xCD, affected_on_page: false }); + opcodes.insert(0xDD, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("cmp"), cycles: 4, size: 3, opcode: 0xDD, affected_on_page: true }); + opcodes.insert(0xD9, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("cmp"), cycles: 4, size: 3, opcode: 0xD9, affected_on_page: true }); + opcodes.insert(0xC1, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("cmp"), cycles: 6, size: 2, opcode: 0xC1, affected_on_page: false }); + opcodes.insert(0xD1, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("cmp"), cycles: 5, size: 2, opcode: 0xD1, affected_on_page: true }); + + // cpx + opcodes.insert(0xE0, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("cpx"), cycles: 2, size: 2, opcode: 0xE0, affected_on_page: false }); + opcodes.insert(0xE4, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("cpx"), cycles: 3, size: 2, opcode: 0xE4, affected_on_page: false }); + opcodes.insert(0xEC, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("cpx"), cycles: 4, size: 3, opcode: 0xEC, affected_on_page: false }); + + // cpy + opcodes.insert(0xC0, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("cpy"), cycles: 2, size: 2, opcode: 0xC0, affected_on_page: false }); + opcodes.insert(0xC4, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("cpy"), cycles: 3, size: 2, opcode: 0xC4, affected_on_page: false }); + opcodes.insert(0xCC, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("cpy"), cycles: 4, size: 3, opcode: 0xCC, affected_on_page: false }); + + // dec + opcodes.insert(0xC6, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("dec"), cycles: 5, size: 2, opcode: 0xC6, affected_on_page: false }); + opcodes.insert(0xD6, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("dec"), cycles: 6, size: 2, opcode: 0xD6, affected_on_page: false }); + opcodes.insert(0xCE, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("dec"), cycles: 6, size: 3, opcode: 0xCE, affected_on_page: false }); + opcodes.insert(0xDE, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("dec"), cycles: 7, size: 3, opcode: 0xDE, affected_on_page: false }); + + // dex + opcodes.insert(0xCA, Entry { mode: AddressingMode::Implied, mnemonic: String::from("dex"), cycles: 2, size: 1, opcode: 0xCA, affected_on_page: false }); + + // dey + opcodes.insert(0x88, Entry { mode: AddressingMode::Implied, mnemonic: String::from("dey"), cycles: 2, size: 1, opcode: 0x88, affected_on_page: false }); + + // eor + opcodes.insert(0x49, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("eor"), cycles: 2, size: 2, opcode: 0x49, affected_on_page: false }); + opcodes.insert(0x45, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("eor"), cycles: 3, size: 2, opcode: 0x45, affected_on_page: false }); + opcodes.insert(0x55, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("eor"), cycles: 4, size: 2, opcode: 0x55, affected_on_page: false }); + opcodes.insert(0x4D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("eor"), cycles: 4, size: 3, opcode: 0x4D, affected_on_page: false }); + opcodes.insert(0x5D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("eor"), cycles: 4, size: 3, opcode: 0x5D, affected_on_page: true }); + opcodes.insert(0x59, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("eor"), cycles: 4, size: 3, opcode: 0x59, affected_on_page: true }); + opcodes.insert(0x41, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("eor"), cycles: 6, size: 2, opcode: 0x41, affected_on_page: false }); + opcodes.insert(0x51, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("eor"), cycles: 5, size: 2, opcode: 0x51, affected_on_page: true }); + + // inc + opcodes.insert(0xE6, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("inc"), cycles: 5, size: 2, opcode: 0xE6, affected_on_page: false }); + opcodes.insert(0xF6, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("inc"), cycles: 6, size: 2, opcode: 0xF6, affected_on_page: false }); + opcodes.insert(0xEE, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("inc"), cycles: 6, size: 3, opcode: 0xEE, affected_on_page: false }); + opcodes.insert(0xFE, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("inc"), cycles: 7, size: 3, opcode: 0xFE, affected_on_page: false }); + + // inx + opcodes.insert(0xE8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("inx"), cycles: 2, size: 1, opcode: 0xE8, affected_on_page: false }); + + // iny + opcodes.insert(0xC8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("iny"), cycles: 2, size: 1, opcode: 0xC8, affected_on_page: false }); + + // jmp + opcodes.insert(0x4C, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("jmp"), cycles: 3, size: 3, opcode: 0x4C, affected_on_page: false }); + opcodes.insert(0x6C, Entry { mode: AddressingMode::Indirect, mnemonic: String::from("jmp"), cycles: 5, size: 3, opcode: 0x6C, affected_on_page: false }); + + // jsr + opcodes.insert(0x20, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("jsr"), cycles: 6, size: 3, opcode: 0x20, affected_on_page: false }); + + // lda + opcodes.insert(0xA9, Entry{ mode: AddressingMode::Immediate, mnemonic: String::from("lda"), cycles: 2, size: 2, opcode: 0xA9, affected_on_page: false }); + opcodes.insert(0xA5, Entry{ mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("lda"), cycles: 3, size: 2, opcode: 0xA5, affected_on_page: false }); + opcodes.insert(0xB5, Entry{ mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("lda"), cycles: 4, size: 2, opcode: 0xB5, affected_on_page: false }); + opcodes.insert(0xAD, Entry{ mode: AddressingMode::Absolute, mnemonic: String::from("lda"), cycles: 4, size: 3, opcode: 0xAD, affected_on_page: false }); + opcodes.insert(0xBD, Entry{ mode: AddressingMode::IndexedX, mnemonic: String::from("lda"), cycles: 4, size: 3, opcode: 0xBD, affected_on_page: true }); + opcodes.insert(0xB9, Entry{ mode: AddressingMode::IndexedY, mnemonic: String::from("lda"), cycles: 4, size: 3, opcode: 0xB9, affected_on_page: true }); + opcodes.insert(0xA1, Entry{ mode: AddressingMode::IndirectX, mnemonic: String::from("lda"), cycles: 6, size: 2, opcode: 0xA1, affected_on_page: false }); + opcodes.insert(0xB1, Entry{ mode: AddressingMode::IndirectY, mnemonic: String::from("lda"), cycles: 5, size: 2, opcode: 0xB1, affected_on_page: true }); + + // ldx + opcodes.insert(0xA2, Entry{ mode: AddressingMode::Immediate, mnemonic: String::from("ldx"), cycles: 2, size: 2, opcode: 0xA2, affected_on_page: false }); + opcodes.insert(0xA6, Entry{ mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("ldx"), cycles: 3, size: 2, opcode: 0xA6, affected_on_page: false }); + opcodes.insert(0xB6, Entry{ mode: AddressingMode::ZeropageIndexedY, mnemonic: String::from("ldx"), cycles: 4, size: 2, opcode: 0xB6, affected_on_page: false }); + opcodes.insert(0xAE, Entry{ mode: AddressingMode::Absolute, mnemonic: String::from("ldx"), cycles: 4, size: 3, opcode: 0xAE, affected_on_page: false }); + opcodes.insert(0xBE, Entry{ mode: AddressingMode::IndexedY, mnemonic: String::from("ldx"), cycles: 4, size: 3, opcode: 0xBE, affected_on_page: true }); + + // ldy + opcodes.insert(0xA0, Entry{ mode: AddressingMode::Immediate, mnemonic: String::from("ldy"), cycles: 2, size: 2, opcode: 0xA0, affected_on_page: false }); + opcodes.insert(0xA4, Entry{ mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("ldy"), cycles: 3, size: 2, opcode: 0xA4, affected_on_page: false }); + opcodes.insert(0xB4, Entry{ mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("ldy"), cycles: 4, size: 2, opcode: 0xB4, affected_on_page: false }); + opcodes.insert(0xAC, Entry{ mode: AddressingMode::Absolute, mnemonic: String::from("ldy"), cycles: 4, size: 3, opcode: 0xAC, affected_on_page: false }); + opcodes.insert(0xBC, Entry{ mode: AddressingMode::IndexedX, mnemonic: String::from("ldy"), cycles: 4, size: 3, opcode: 0xBC, affected_on_page: true }); + + // lsr + opcodes.insert(0x4A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("lsr"), cycles: 2, size: 1, opcode: 0x4A, affected_on_page: false }); + opcodes.insert(0x46, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("lsr"), cycles: 5, size: 2, opcode: 0x46, affected_on_page: false }); + opcodes.insert(0x56, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("lsr"), cycles: 6, size: 2, opcode: 0x56, affected_on_page: false }); + opcodes.insert(0x4E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("lsr"), cycles: 6, size: 3, opcode: 0x4E, affected_on_page: false }); + opcodes.insert(0x5E, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("lsr"), cycles: 7, size: 3, opcode: 0x5E, affected_on_page: false }); + + // nop + opcodes.insert(0xEA, Entry { mode: AddressingMode::Implied, mnemonic: String::from("nop"), cycles: 2, size: 1, opcode: 0xEA, affected_on_page: false }); + + // ora + opcodes.insert(0x09, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("ora"), cycles: 2, size: 2, opcode: 0x09, affected_on_page: false }); + opcodes.insert(0x05, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("ora"), cycles: 3, size: 2, opcode: 0x05, affected_on_page: false }); + opcodes.insert(0x15, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("ora"), cycles: 4, size: 2, opcode: 0x15, affected_on_page: false }); + opcodes.insert(0x0D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("ora"), cycles: 4, size: 3, opcode: 0x0D, affected_on_page: false }); + opcodes.insert(0x1D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("ora"), cycles: 4, size: 3, opcode: 0x1D, affected_on_page: true }); + opcodes.insert(0x19, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("ora"), cycles: 4, size: 3, opcode: 0x19, affected_on_page: true }); + opcodes.insert(0x01, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("ora"), cycles: 6, size: 2, opcode: 0x01, affected_on_page: false }); + opcodes.insert(0x11, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("ora"), cycles: 5, size: 2, opcode: 0x11, affected_on_page: true }); + + // pha + opcodes.insert(0x48, Entry { mode: AddressingMode::Implied, mnemonic: String::from("pha"), cycles: 3, size: 1, opcode: 0x48, affected_on_page: false }); + + // php + opcodes.insert(0x08, Entry { mode: AddressingMode::Implied, mnemonic: String::from("php"), cycles: 3, size: 1, opcode: 0x08, affected_on_page: false }); + + // pla + opcodes.insert(0x68, Entry { mode: AddressingMode::Implied, mnemonic: String::from("pla"), cycles: 4, size: 1, opcode: 0x68, affected_on_page: false }); + + // plp + opcodes.insert(0x28, Entry { mode: AddressingMode::Implied, mnemonic: String::from("plp"), cycles: 4, size: 1, opcode: 0x28, affected_on_page: false }); + + // rol + opcodes.insert(0x2A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("rol"), cycles: 2, size: 1, opcode: 0x2A, affected_on_page: false }); + opcodes.insert(0x26, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("rol"), cycles: 5, size: 2, opcode: 0x26, affected_on_page: false }); + opcodes.insert(0x36, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("rol"), cycles: 6, size: 2, opcode: 0x36, affected_on_page: false }); + opcodes.insert(0x2E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("rol"), cycles: 6, size: 3, opcode: 0x2E, affected_on_page: false }); + opcodes.insert(0x3E, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("rol"), cycles: 7, size: 3, opcode: 0x3E, affected_on_page: false }); + + // ror + opcodes.insert(0x6A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("ror"), cycles: 2, size: 1, opcode: 0x6A, affected_on_page: false }); + opcodes.insert(0x66, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("ror"), cycles: 5, size: 2, opcode: 0x66, affected_on_page: false }); + opcodes.insert(0x76, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("ror"), cycles: 6, size: 2, opcode: 0x76, affected_on_page: false }); + opcodes.insert(0x6E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("ror"), cycles: 6, size: 3, opcode: 0x6E, affected_on_page: false }); + opcodes.insert(0x7E, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("ror"), cycles: 7, size: 3, opcode: 0x7E, affected_on_page: false }); + + // rti + opcodes.insert(0x40, Entry { mode: AddressingMode::Implied, mnemonic: String::from("rti"), cycles: 6, size: 1, opcode: 0x40, affected_on_page: false }); + + // rts + opcodes.insert(0x60, Entry { mode: AddressingMode::Implied, mnemonic: String::from("rts"), cycles: 6, size: 1, opcode: 0x60, affected_on_page: false }); + + // sbc + opcodes.insert(0xE9, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("sbc"), cycles: 2, size: 2, opcode: 0xE9, affected_on_page: false }); + opcodes.insert(0xE5, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("sbc"), cycles: 3, size: 2, opcode: 0xE5, affected_on_page: false }); + opcodes.insert(0xF5, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("sbc"), cycles: 4, size: 2, opcode: 0xF5, affected_on_page: false }); + opcodes.insert(0xED, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("sbc"), cycles: 4, size: 3, opcode: 0xED, affected_on_page: false }); + opcodes.insert(0xFD, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("sbc"), cycles: 4, size: 3, opcode: 0xFD, affected_on_page: true }); + opcodes.insert(0xF9, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("sbc"), cycles: 4, size: 3, opcode: 0xF9, affected_on_page: true }); + opcodes.insert(0xE1, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("sbc"), cycles: 6, size: 2, opcode: 0xE1, affected_on_page: false }); + opcodes.insert(0xF1, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("sbc"), cycles: 5, size: 2, opcode: 0xF1, affected_on_page: true }); + + // sec + opcodes.insert(0x38, Entry{ mode: AddressingMode::Implied, mnemonic: String::from("sec"), cycles: 2, size: 1, opcode: 0x38, affected_on_page: false }); + + // sed + opcodes.insert(0xF8, Entry{ mode: AddressingMode::Implied, mnemonic: String::from("sed"), cycles: 2, size: 1, opcode: 0xF8, affected_on_page: false }); + + // sei + opcodes.insert(0x78, Entry{ mode: AddressingMode::Implied, mnemonic: String::from("sei"), cycles: 2, size: 1, opcode: 0x78, affected_on_page: false }); + + // sta + opcodes.insert(0x85, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("sta"), cycles: 3, size: 2, opcode: 0x85, affected_on_page: false }); + opcodes.insert(0x95, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("sta"), cycles: 4, size: 2, opcode: 0x95, affected_on_page: false }); + opcodes.insert(0x8D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("sta"), cycles: 4, size: 3, opcode: 0x8D, affected_on_page: false }); + opcodes.insert(0x9D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("sta"), cycles: 5, size: 3, opcode: 0x9D, affected_on_page: false }); + opcodes.insert(0x99, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("sta"), cycles: 5, size: 3, opcode: 0x99, affected_on_page: false }); + opcodes.insert(0x81, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("sta"), cycles: 6, size: 2, opcode: 0x81, affected_on_page: false }); + opcodes.insert(0x91, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("sta"), cycles: 6, size: 2, opcode: 0x91, affected_on_page: false }); + + // stx + opcodes.insert(0x86, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("stx"), cycles: 3, size: 2, opcode: 0x86, affected_on_page: false }); + opcodes.insert(0x96, Entry { mode: AddressingMode::ZeropageIndexedY, mnemonic: String::from("stx"), cycles: 4, size: 2, opcode: 0x96, affected_on_page: false }); + opcodes.insert(0x8E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("stx"), cycles: 4, size: 3, opcode: 0x8E, affected_on_page: false }); + + // sty + opcodes.insert(0x84, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("sty"), cycles: 3, size: 2, opcode: 0x84, affected_on_page: false }); + opcodes.insert(0x94, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("sty"), cycles: 4, size: 2, opcode: 0x94, affected_on_page: false }); + opcodes.insert(0x8C, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("sty"), cycles: 4, size: 3, opcode: 0x8C, affected_on_page: false }); + + // tax + opcodes.insert(0xAA, Entry{ mode: AddressingMode::Implied, mnemonic: String::from("tax"), cycles: 2, size: 1, opcode: 0xAA, affected_on_page: false }); + + // tay + opcodes.insert(0xA8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("tay"), cycles: 2, size: 1, opcode: 0xA8, affected_on_page: false }); + + // tsx + opcodes.insert(0xBA, Entry { mode: AddressingMode::Implied, mnemonic: String::from("tsx"), cycles: 2, size: 1, opcode: 0xBA, affected_on_page: false }); + + // txa + opcodes.insert(0x8A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("txa"), cycles: 2, size: 1, opcode: 0x8A, affected_on_page: false }); + + // txs + opcodes.insert(0x9A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("txs"), cycles: 2, size: 1, opcode: 0x9A, affected_on_page: false }); + + // tya + opcodes.insert(0x98, Entry { mode: AddressingMode::Implied, mnemonic: String::from("tya"), cycles: 2, size: 1, opcode: 0x98, affected_on_page: false }); + + opcodes + }; +} -- cgit v1.2.3