diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index abfaccd..91847e2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -60,6 +60,11 @@ jobs: インストール方法は各OSの手順に従ってください。 (ビルド完了後にアセットが追加されます) + ## License / Source + - License: GPL-2.0-only(`LICENSE`) + - Third-party notices: `THIRD_PARTY_NOTICES.md` + - Corresponding Source: `opcode-logic-${{ steps.version.outputs.version }}-corresponding-source.tar.gz` + # 2. 全プラットフォームで並列ビルド build: needs: create-release @@ -128,4 +133,61 @@ jobs: projectPath: . tagName: v${{ needs.create-release.outputs.version }} releaseId: ${{ needs.create-release.outputs.release_id }} - args: ${{ matrix.args }} \ No newline at end of file + args: ${{ matrix.args }} + + # 3. 対応ソース(Corresponding Source)と告知ファイルをReleaseに添付 + corresponding-source: + needs: create-release + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Checkout tag + run: | + git checkout "v${{ needs.create-release.outputs.version }}" + + - name: Install Rust + uses: dtolnay/rust-toolchain@stable + + - name: Vendor Rust crates (cargo vendor) + working-directory: src-tauri + run: | + cargo vendor vendor + mkdir -p .cargo + cat > .cargo/config.toml <<'EOF' + [source.crates-io] + replace-with = "vendored-sources" + + [source.vendored-sources] + directory = "vendor" + EOF + + - name: Create corresponding source tarball + run: | + VERSION="${{ needs.create-release.outputs.version }}" + NAME="opcode-logic-${VERSION}-corresponding-source" + mkdir -p dist + rsync -a --delete \ + --exclude '.git' \ + --exclude 'node_modules' \ + --exclude 'release' \ + --exclude 'dist' \ + ./ "dist/${NAME}/" + tar -C dist -czf "dist/${NAME}.tar.gz" "${NAME}" + sha256sum "dist/${NAME}.tar.gz" > "dist/${NAME}.tar.gz.sha256" + + - name: Upload corresponding source and notices + uses: softprops/action-gh-release@v2 + with: + tag_name: v${{ needs.create-release.outputs.version }} + files: | + dist/*.tar.gz + dist/*.sha256 + LICENSE + THIRD_PARTY_NOTICES.md + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/LICENSE b/LICENSE index 5645274..d159169 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,339 @@ -MIT License - -Copyright (c) 2026 Saku0512 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/README.md b/README.md index 89bdd49..49e46fe 100644 --- a/README.md +++ b/README.md @@ -161,7 +161,7 @@ npm run check ## ライセンス -MIT License +GPL-2.0-only ## 推奨IDE設定 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e609aef..80f67f9 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -1,16 +1,24 @@ ## Third-party notices +このプロジェクト(OpCode Logic)は **GPL-2.0-only** で配布します。 +デスクトップアプリとして **バイナリ配布**(GitHub Releases / 将来はサイト配布)を行う場合、GPLv2(2-only)の条件に従い、受領者が本プロジェクトの対応ソースコードを入手できる状態にします。 + +- **本プロジェクトのライセンス本文**: `LICENSE`(GPLv2) +- **本プロジェクトの対応ソース**: リポジトリのソース、または配布ページ(Release/サイト)から入手可能にします。 + このプロジェクトは以下のサードパーティソフトウェアに依存します。配布形態(静的/動的リンク、同梱物)によっては、それぞれのライセンス条件に従う必要があります。 ### Unicorn Engine - **Project**: Unicorn CPU Emulator - **Repository**: `https://github.com/unicorn-engine/unicorn` - **Used via**: Rust crate `unicorn-engine` -- **License**: GPL-2.0(詳細は上記リポジトリのLICENSEを参照) +- **Crate version**: `unicorn-engine 2.1.5`(`src-tauri/Cargo.toml` / `src-tauri/Cargo.lock`) +- **License**: GPL-2.0-only(詳細は上記リポジトリのLICENSEを参照) ### Keystone Engine - **Project**: Keystone Assembler Engine - **Repository**: `https://github.com/keystone-engine/keystone` - **Used via**: Rust crate `keystone-engine` -- **License**: GPL-2.0(詳細は上記リポジトリのLICENSEを参照) +- **Crate version**: `keystone-engine 0.1.0`(`src-tauri/Cargo.toml` / `src-tauri/Cargo.lock`) +- **License**: GPL-2.0-only(詳細は上記リポジトリのLICENSEを参照) diff --git a/package-lock.json b/package-lock.json index fc0e794..785f238 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "opcode-logic", "version": "0.1.0", - "license": "MIT", + "license": "GPL-2.0-only", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-opener": "^2" diff --git a/package.json b/package.json index 53bdefd..1d681bd 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "test:coverage": "vitest --coverage", "tauri": "tauri" }, - "license": "MIT", + "license": "GPL-2.0-only", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-opener": "^2" diff --git a/scripts/test-all-stages.sh b/scripts/test-all-stages.sh new file mode 100644 index 0000000..cf2ba05 --- /dev/null +++ b/scripts/test-all-stages.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +failures=0 +failed_list=() + +shopt -s nullglob +tests=( "$ROOT_DIR"/stages/*/*/*/test.sh "$ROOT_DIR"/stages/*/*/*/*/test.sh ) + +if [ ${#tests[@]} -eq 0 ]; then + echo "No stage test.sh found under stages/." + exit 1 +fi + +for t in "${tests[@]}"; do + rel="${t#"$ROOT_DIR"/}" + echo "==> $rel" + if bash "$t"; then + echo "PASS: $rel" + else + echo "FAIL: $rel" >&2 + failures=$((failures + 1)) + failed_list+=( "$rel" ) + fi + echo +done + +if [ "$failures" -ne 0 ]; then + echo "FAILED ($failures):" >&2 + for f in "${failed_list[@]}"; do + echo " - $f" >&2 + done + exit 1 +fi + +echo "All stage tests passed (${#tests[@]})." + diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index a57a065..3800978 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -4,6 +4,8 @@ version = "0.2.0" description = "Assemble Code learning" authors = ["saku0512"] edition = "2021" +license = "GPL-2.0-only" +default-run = "opcode-logic" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src-tauri/src/bin/stage_runner.rs b/src-tauri/src/bin/stage_runner.rs new file mode 100644 index 0000000..75a107f --- /dev/null +++ b/src-tauri/src/bin/stage_runner.rs @@ -0,0 +1,150 @@ +use opcode_logic_lib::levels; +use opcode_logic_lib::vm::Syntax; +use opcode_logic_lib::x86_runtime; + +use std::fs; +use std::path::PathBuf; + +fn print_usage_and_exit() -> ! { + eprintln!( + "Usage:\n stage_runner --level-id --asm [--syntax Intel|Att] [--max-instructions N]\n" + ); + std::process::exit(2); +} + +fn main() { + let mut level_id: Option = None; + let mut asm_path: Option = None; + let mut syntax = Syntax::Intel; + let mut max_instructions: usize = 50_000; + + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + match a.as_str() { + "--level-id" => level_id = args.next(), + "--asm" => asm_path = args.next().map(PathBuf::from), + "--syntax" => { + let s = args.next().unwrap_or_else(|| { + eprintln!("Missing value for --syntax"); + print_usage_and_exit(); + }); + syntax = match s.as_str() { + "Intel" => Syntax::Intel, + "Att" => Syntax::Att, + other => { + eprintln!("Unknown syntax: {}", other); + print_usage_and_exit(); + } + }; + } + "--max-instructions" => { + let s = args.next().unwrap_or_else(|| { + eprintln!("Missing value for --max-instructions"); + print_usage_and_exit(); + }); + max_instructions = s.parse().unwrap_or_else(|_| { + eprintln!("Invalid number for --max-instructions: {}", s); + print_usage_and_exit(); + }); + } + "-h" | "--help" => print_usage_and_exit(), + other => { + eprintln!("Unknown arg: {}", other); + print_usage_and_exit(); + } + } + } + + let level_id = level_id.unwrap_or_else(|| { + eprintln!("Missing --level-id"); + print_usage_and_exit(); + }); + let asm_path = asm_path.unwrap_or_else(|| { + eprintln!("Missing --asm"); + print_usage_and_exit(); + }); + + let level = levels::get_level(&level_id).unwrap_or_else(|| { + eprintln!("Unknown level id: {}", level_id); + std::process::exit(2); + }); + + let code = fs::read_to_string(&asm_path).unwrap_or_else(|e| { + eprintln!("Failed to read asm file {}: {}", asm_path.display(), e); + std::process::exit(2); + }); + + let mut failures = 0usize; + for (idx, (test_in, expected)) in level.test_cases.iter().enumerate() { + let run = + match x86_runtime::run_x86_64(&code, syntax.clone(), test_in.clone(), max_instructions) + { + Ok(r) => r, + Err(e) => { + eprintln!( + "[{}] FAIL: runtime error for input {:?}: {}", + idx + 1, + test_in, + e + ); + failures += 1; + continue; + } + }; + + let state = run.state; + if let Some(err) = state.error.clone() { + eprintln!( + "[{}] FAIL: vm error for input {:?}: {}", + idx + 1, + test_in, + err + ); + failures += 1; + continue; + } + + let got = if !state.output.is_empty() { + state.output.clone() + } else { + // Mirror app behavior: treat RAX as output only if no stream output exists. + let rax = *state + .registers + .get(&opcode_logic_lib::vm::Register::RAX) + .unwrap_or(&0); + if state.exited && rax == 60 && expected.len() == 1 && expected[0] != 60 { + vec![] + } else { + vec![rax] + } + }; + + let ok = if !got.is_empty() { + got.len() >= expected.len() && &got[0..expected.len()] == expected.as_slice() + } else { + expected.is_empty() + }; + + if ok { + eprintln!("[{}] PASS", idx + 1); + } else { + eprintln!( + "[{}] FAIL: input {:?}\n expected: {:?}\n got: {:?}", + idx + 1, + test_in, + expected, + got + ); + failures += 1; + } + } + + if failures != 0 { + eprintln!( + "FAILED {} / {} test case(s).", + failures, + level.test_cases.len() + ); + std::process::exit(1); + } +} diff --git a/src-tauri/src/levels.rs b/src-tauri/src/levels.rs index 33f17a1..4d598d6 100644 --- a/src-tauri/src/levels.rs +++ b/src-tauri/src/levels.rs @@ -20,7 +20,8 @@ pub fn get_levels() -> Vec { Level { id: "01_Mov&Call".to_string(), name: "Mov & Call".to_string(), - description: "Read input (RDI), and return it (RAX).".to_string(), + description: "Read bytes from stdin (syscall 0), write them to stdout (syscall 1)." + .to_string(), test_cases: vec![ (vec![123], vec![123]), (vec![0], vec![0]), @@ -30,87 +31,201 @@ pub fn get_levels() -> Vec { Level { id: "02_Addition".to_string(), name: "Addition".to_string(), - description: "Read A (RDI) and B (RSI), return A + B (RAX).".to_string(), + description: "Read bytes, add 1 to each byte, write result.".to_string(), test_cases: vec![ - (vec![10, 20], vec![30]), - (vec![5, 5], vec![10]), - (vec![-10, 20], vec![10]), + (vec![10, 20], vec![11, 21]), + (vec![5, 5], vec![6, 6]), + (vec![-1, 0], vec![0, 1]), ], }, Level { id: "03_Subtraction".to_string(), name: "Subtraction".to_string(), - description: "Read A (RDI) and B (RSI), return A - B (RAX).".to_string(), + description: "Read bytes, subtract 1 from each byte, write result.".to_string(), test_cases: vec![ - (vec![30, 10], vec![20]), - (vec![10, 20], vec![-10]), - (vec![0, 0], vec![0]), + (vec![10, 20], vec![9, 19]), + (vec![0], vec![-1]), + (vec![-128], vec![127]), ], }, Level { id: "04_TheXORTrick".to_string(), name: "The XOR Trick".to_string(), - description: "Return 0 (RAX). Try using XOR.".to_string(), - test_cases: vec![(vec![123], vec![0]), (vec![999], vec![0])], + description: "Read bytes, XOR each byte with 0x20, write result.".to_string(), + test_cases: vec![ + (vec![('a' as i64)], vec![('A' as i64)]), + (vec![('Z' as i64)], vec![('z' as i64)]), + (vec![0], vec![0x20]), + ], }, Level { id: "05_Inc&Dec".to_string(), name: "Inc & Dec".to_string(), - description: "Read input A (RDI). Output A+1 and A-1 (Stream Output via OUT)." + description: "Read bytes. Inc even-indexed bytes, dec odd-indexed bytes, write result." .to_string(), - test_cases: vec![(vec![10], vec![11, 9]), (vec![0], vec![1, -1])], + test_cases: vec![ + (vec![10, 10, 10, 10], vec![11, 9, 11, 9]), + (vec![0], vec![1]), + ], }, Level { id: "06_Unconditional".to_string(), name: "Unconditional".to_string(), - description: "Output 1 infinitely (Stream). (Test checks for first 5 outputs of 1)." - .to_string(), - test_cases: vec![(vec![0], vec![1, 1, 1, 1, 1])], + description: "Same as stage 01, but use JMP to structure the control flow.".to_string(), + test_cases: vec![ + (vec![1, 2, 3], vec![1, 2, 3]), + (vec![-55], vec![-55]), + ], }, Level { id: "07_ZeroFlag".to_string(), name: "Zero Flag".to_string(), - description: "Read A (RDI). If 0, return 1. Else return 0 (RAX).".to_string(), - test_cases: vec![(vec![0], vec![1]), (vec![5], vec![0]), (vec![-1], vec![0])], + description: "Read bytes, replace 0x00 with 0x20 (space), write result.".to_string(), + test_cases: vec![ + (vec![0, 1, 0], vec![0x20, 1, 0x20]), + (vec![5], vec![5]), + ], }, Level { id: "08_SignFlag".to_string(), name: "Sign Flag".to_string(), - description: "Read A (RDI). If A < 0, return 1. Else return 0 (RAX).".to_string(), - test_cases: vec![(vec![-5], vec![1]), (vec![0], vec![0]), (vec![10], vec![0])], + description: "Read bytes, output '+' if first byte is non-negative, otherwise '-'.".to_string(), + test_cases: vec![ + (vec![0], vec![('+' as i64)]), + (vec![-1], vec![('-' as i64)]), + ], }, Level { id: "09_Comparison".to_string(), name: "Comparison".to_string(), - description: "Read A (RDI), B (RSI). Return the larger value (RAX).".to_string(), + description: + "Read bytes, compare consecutive bytes, output '+', '=', '-' markers (length N-1)." + .to_string(), test_cases: vec![ - (vec![10, 20], vec![20]), - (vec![50, 40], vec![50]), - (vec![30, 30], vec![30]), + ( + vec![1, 2, 2, 1], + vec![('+' as i64), ('=' as i64), ('-' as i64)], + ), + (vec![10], vec![]), ], }, Level { id: "10_Countdown".to_string(), name: "Countdown".to_string(), - description: "Read N (RDI). Output N, N-1... 1 (Stream).".to_string(), - test_cases: vec![(vec![3], vec![3, 2, 1]), (vec![5], vec![5, 4, 3, 2, 1])], + description: "Read one ASCII digit, output a countdown from it to '0'.".to_string(), + test_cases: vec![ + (vec![('3' as i64)], vec![('3' as i64), ('2' as i64), ('1' as i64), ('0' as i64)]), + (vec![('0' as i64)], vec![('0' as i64)]), + ], }, Level { id: "11_Accumulate3".to_string(), name: "Accumulate 3".to_string(), - description: "Read 3 inputs (RDI, RSI, RDX). Return sum (RAX).".to_string(), - test_cases: vec![(vec![1, 2, 3], vec![6]), (vec![10, 10, 10], vec![30])], + description: "Read bytes, sum the first 3 bytes (u8), output 1 byte result.".to_string(), + test_cases: vec![ + (vec![1, 2, 3], vec![6]), + (vec![10, 10, 10], vec![30]), + ], }, Level { id: "12_TheAccumulator".to_string(), name: "The Accumulator (BOSS)".to_string(), description: - "Read inputs using 'IN' until 0 is encountered. Return the total sum in RAX." + "Read bytes and transform: A-Z -> a-z, 0-9 -> increment (wrap 9->0), others unchanged." .to_string(), test_cases: vec![ - (vec![1, 2, 3, 0], vec![6]), - (vec![10, -5, 20, 0], vec![25]), - (vec![0], vec![0]), + ( + vec![('A' as i64), ('z' as i64), ('9' as i64), ('!' as i64)], + vec![('a' as i64), ('z' as i64), ('0' as i64), ('!' as i64)], + ), + (vec![('B' as i64), ('0' as i64)], vec![('b' as i64), ('1' as i64)]), + ], + }, + // GRAND STAGE 02: The Stack + Level { + id: "13_Push&Pop".to_string(), + name: "Push & Pop".to_string(), + description: "Read A, push/pop it, then output A (1 byte).".to_string(), + test_cases: vec![(vec![42], vec![42]), (vec![-1], vec![-1]), (vec![0], vec![0])], + }, + Level { + id: "14_SwapTwo".to_string(), + name: "Swap Two".to_string(), + description: "Read A,B and output B,A (2 bytes).".to_string(), + test_cases: vec![ + (vec![1, 2], vec![2, 1]), + (vec![5, -1], vec![-1, 5]), + ], + }, + Level { + id: "15_Duplicate".to_string(), + name: "Duplicate".to_string(), + description: "Read A and output A,A (2 bytes).".to_string(), + test_cases: vec![(vec![7], vec![7, 7]), (vec![-1], vec![-1, -1])], + }, + Level { + id: "16_Reverse3".to_string(), + name: "Reverse 3".to_string(), + description: "Read A,B,C and output C,B,A (3 bytes).".to_string(), + test_cases: vec![(vec![1, 2, 3], vec![3, 2, 1]), (vec![-1, 0, 1], vec![1, 0, -1])], + }, + Level { + id: "17_ReverseUntil0".to_string(), + name: "Reverse Until 0".to_string(), + description: "Read values until 0, output them reversed (0 not included).".to_string(), + test_cases: vec![ + (vec![1, 2, 3, 0], vec![3, 2, 1]), + (vec![-1, 0], vec![-1]), + (vec![0], vec![]), + ], + }, + Level { + id: "18_SumFromStack".to_string(), + name: "Sum From Stack".to_string(), + description: "Read values until 0, sum them, output 1 byte result.".to_string(), + test_cases: vec![(vec![1, 2, 3, 0], vec![6]), (vec![10, 20, 0], vec![30]), (vec![-1, 1, 0], vec![0])], + }, + Level { + id: "19_SafePop".to_string(), + name: "Safe Pop".to_string(), + description: "Process tokens (push/pop) without underflow; output final depth.".to_string(), + test_cases: vec![ + (vec![1, 5, 1, 6, -1, 0], vec![1]), + (vec![-1, 0], vec![0]), + (vec![1, 1, -1, -1, 0], vec![0]), + ], + }, + Level { + id: "20_RPN_AddOnly".to_string(), + name: "RPN (Add Only)".to_string(), + description: "RPN evaluation: numbers push, -1 add, 0 end; output top.".to_string(), + test_cases: vec![(vec![2, 3, -1, 0], vec![5]), (vec![5, 1, -1, 0], vec![6])], + }, + Level { + id: "21_Sort3".to_string(), + name: "Sort 3".to_string(), + description: "Read 3 values and output them sorted ascending (3 bytes).".to_string(), + test_cases: vec![(vec![3, 1, 2], vec![1, 2, 3]), (vec![-1, 0, 1], vec![-1, 0, 1])], + }, + Level { + id: "22_Rotate3".to_string(), + name: "Rotate 3".to_string(), + description: "Read A,B,C and output B,C,A (3 bytes).".to_string(), + test_cases: vec![(vec![1, 2, 3], vec![2, 3, 1]), (vec![-1, 5, 0], vec![5, 0, -1])], + }, + Level { + id: "23_MinMaxFromStack".to_string(), + name: "Min & Max From Stack".to_string(), + description: "Read values until 0; output min then max (2 bytes).".to_string(), + test_cases: vec![(vec![3, 1, 2, 0], vec![1, 3]), (vec![-1, -5, 2, 0], vec![-5, 2])], + }, + Level { + id: "24_TheStackMachine".to_string(), + name: "The Stack Machine (BOSS)".to_string(), + description: "Token machine: +push, -1 add, -2 sub, -3 xor, 0 end; output top.".to_string(), + test_cases: vec![ + (vec![5, 3, -2, 0], vec![2]), + (vec![1, 2, -1, 3, -3, 0], vec![0]), ], }, ] @@ -151,14 +266,16 @@ mod tests { fn test_level_02_addition() { let level = get_level("02_Addition").unwrap(); assert_eq!(level.test_cases.len(), 3); - assert_eq!(level.test_cases[0], (vec![10, 20], vec![30])); + assert_eq!(level.test_cases[0], (vec![10, 20], vec![11, 21])); } #[test] fn test_level_05_inc_dec() { let level = get_level("05_Inc&Dec").unwrap(); - // Stream output test case - assert_eq!(level.test_cases[0], (vec![10], vec![11, 9])); + assert_eq!( + level.test_cases[0], + (vec![10, 10, 10, 10], vec![11, 9, 11, 9]) + ); } #[test] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 79911da..482a9fe 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -20,33 +20,69 @@ fn get_levels() -> Vec { levels::get_levels() } -#[tauri::command] -fn get_level_explanation(level_id: String) -> Result { - // レベルIDからファイルパスを生成 - // 例: "01_Mov&Call" -> "commnet/1.The-Accumulator/Phase1-Registers&ALU/01_Mov&Call.md" - let file_path = match level_id.as_str() { - "01_Mov&Call" => "commnet/1.The-Accumulator/Phase1-Registers&ALU/01_Mov&Call.md", - "02_Addition" => "commnet/1.The-Accumulator/Phase1-Registers&ALU/02_Addition.md", - "03_Subtraction" => "commnet/1.The-Accumulator/Phase1-Registers&ALU/03_Subtraction.md", - "04_TheXORTrick" => "commnet/1.The-Accumulator/Phase1-Registers&ALU/04_TheXORTrick.md", - "05_Inc&Dec" => "commnet/1.The-Accumulator/Phase1-Registers&ALU/05_Inc&Dec.md", - "06_Unconditional" => "commnet/1.The-Accumulator/Phase2-Flags&Jumps/06_Unconditional.md", - "07_ZeroFlag" => "commnet/1.The-Accumulator/Phase2-Flags&Jumps/07_ZeroFlag.md", - "08_SignFlag" => "commnet/1.The-Accumulator/Phase2-Flags&Jumps/08_SignFlag.md", - "09_Comparison" => "commnet/1.The-Accumulator/Phase2-Flags&Jumps/09_Conmparison.md", - "10_Countdown" => "commnet/1.The-Accumulator/Phase3-LoopStructures/10_Countdown.md", - "11_Accumulate3" => "commnet/1.The-Accumulator/Phase3-LoopStructures/11_Accumulate3.md", - "12_TheAccumulator" => "commnet/1.The-Accumulator/BOSS/TheAccumulator.md", - _ => return Err(format!("Explanation not found for level: {}", level_id)), - }; +fn level_dir_for_id(level_id: &str) -> Option<&'static str> { + match level_id { + "01_Mov&Call" => Some("stages/1.The-Accumulator/Phase1-Registers&ALU/01_Mov&Call"), + "02_Addition" => Some("stages/1.The-Accumulator/Phase1-Registers&ALU/02_Addition"), + "03_Subtraction" => Some("stages/1.The-Accumulator/Phase1-Registers&ALU/03_Subtraction"), + "04_TheXORTrick" => Some("stages/1.The-Accumulator/Phase1-Registers&ALU/04_TheXORTrick"), + "05_Inc&Dec" => Some("stages/1.The-Accumulator/Phase1-Registers&ALU/05_Inc&Dec"), + "06_Unconditional" => Some("stages/1.The-Accumulator/Phase2-Flags&Jumps/06_Unconditional"), + "07_ZeroFlag" => Some("stages/1.The-Accumulator/Phase2-Flags&Jumps/07_ZeroFlag"), + "08_SignFlag" => Some("stages/1.The-Accumulator/Phase2-Flags&Jumps/08_SignFlag"), + "09_Comparison" => Some("stages/1.The-Accumulator/Phase2-Flags&Jumps/09_Comparison"), + "10_Countdown" => Some("stages/1.The-Accumulator/Phase3-LoopStructures/10_Countdown"), + "11_Accumulate3" => Some("stages/1.The-Accumulator/Phase3-LoopStructures/11_Accumulate3"), + "12_TheAccumulator" => Some("stages/1.The-Accumulator/BOSS/12_TheAccumulator"), + // GRAND STAGE 02: The Stack + "13_Push&Pop" => Some("stages/2.The-Stack/Phase1-StackBasics/13_Push&Pop"), + "14_SwapTwo" => Some("stages/2.The-Stack/Phase1-StackBasics/14_SwapTwo"), + "15_Duplicate" => Some("stages/2.The-Stack/Phase1-StackBasics/15_Duplicate"), + "16_Reverse3" => Some("stages/2.The-Stack/Phase2-StackAsBuffer/16_Reverse3"), + "17_ReverseUntil0" => Some("stages/2.The-Stack/Phase2-StackAsBuffer/17_ReverseUntil0"), + "18_SumFromStack" => Some("stages/2.The-Stack/Phase2-StackAsBuffer/18_SumFromStack"), + "19_SafePop" => Some("stages/2.The-Stack/Phase3-StackAlgorithms/19_SafePop"), + "20_RPN_AddOnly" => Some("stages/2.The-Stack/Phase3-StackAlgorithms/20_RPN_AddOnly"), + "21_Sort3" => Some("stages/2.The-Stack/Phase3-StackAlgorithms/21_Sort3"), + "22_Rotate3" => Some("stages/2.The-Stack/Phase3-StackAlgorithms/22_Rotate3"), + "23_MinMaxFromStack" => { + Some("stages/2.The-Stack/Phase3-StackAlgorithms/23_MinMaxFromStack") + } + "24_TheStackMachine" => Some("stages/2.The-Stack/BOSS/24_TheStackMachine"), + _ => None, + } +} +fn read_stage_file(rel_path: &str) -> Result { // プロジェクトルートからの相対パスで読み込む let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.pop(); // src-tauri から出る - path.push(file_path); + path.push(rel_path); + fs::read_to_string(&path).map_err(|e| format!("Failed to read file: {} (path: {:?})", e, path)) +} - fs::read_to_string(&path) - .map_err(|e| format!("Failed to read explanation file: {} (path: {:?})", e, path)) +#[tauri::command] +fn get_level_explanation(level_id: String) -> Result { + let dir = level_dir_for_id(level_id.as_str()) + .ok_or_else(|| format!("Stage files not found for level: {}", level_id))?; + let md = format!("{}/{}.md", dir, level_id); + read_stage_file(&md) +} + +#[tauri::command] +fn get_level_ini(level_id: String) -> Result { + let dir = level_dir_for_id(level_id.as_str()) + .ok_or_else(|| format!("Stage files not found for level: {}", level_id))?; + let p = format!("{}/ini.asm", dir); + read_stage_file(&p) +} + +#[tauri::command] +fn get_level_collect(level_id: String) -> Result { + let dir = level_dir_for_id(level_id.as_str()) + .ok_or_else(|| format!("Stage files not found for level: {}", level_id))?; + let p = format!("{}/collect.asm", dir); + read_stage_file(&p) } #[tauri::command] @@ -139,7 +175,9 @@ pub fn run() { .invoke_handler(tauri::generate_handler![ run_simulation, get_levels, - get_level_explanation + get_level_explanation, + get_level_ini, + get_level_collect ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/src-tauri/src/x86_runtime.rs b/src-tauri/src/x86_runtime.rs index f446dc9..c6a4c7c 100644 --- a/src-tauri/src/x86_runtime.rs +++ b/src-tauri/src/x86_runtime.rs @@ -159,6 +159,59 @@ fn preprocess_text(code: &str, syntax: &Syntax, bss_labels: &HashMap` by rewriting it into a custom syscall. + // This keeps tutorial content readable while still using Keystone+Unicorn. + // + // `in rax` -> `mov rax, 0x3e8; syscall` + // `in rbx` -> `mov rax, 0x3e8; syscall; mov rbx, rax` + let lower = line.trim_start().to_lowercase(); + if lower.starts_with("in ") { + let dst_raw = line.trim_start()[2..].trim(); + let dst = dst_raw.trim_start_matches('%').to_lowercase(); + match syntax { + Syntax::Intel => { + if dst == "rax" { + out.push_str("mov rax, 0x3e8\nsyscall\n"); + } else { + // Preserve RAX across pseudo-IN, because some stages use `in rbx`/`in rcx` + // after having loaded a meaningful value into RAX. + out.push_str("push rax\n"); + out.push_str("mov rax, 0x3e8\nsyscall\n"); + out.push_str(&format!("mov {}, rax\n", dst)); + out.push_str("pop rax\n"); + } + } + Syntax::Att => { + if dst == "rax" { + out.push_str("movq $0x3e8, %rax\nsyscall\n"); + } else { + out.push_str("pushq %rax\n"); + out.push_str("movq $0x3e8, %rax\nsyscall\n"); + out.push_str(&format!("movq %rax, %{}\n", dst)); + out.push_str("popq %rax\n"); + } + } + } + continue; + } + + // Keystone label fixups do not handle `loop