Files
hakorune/docs/archive/rust_ownership_question.txt
Moe Charm ef7a0de3b0 feat: Prepare for code modularization and cleanup
- Archive old documentation and test files to `docs/archive/` and `local_tests/`.
- Remove various temporary and old files from the project root.
- Add `nekocode-rust` analysis tool and its output files (`nekocode/`, `.nekocode_sessions/`, `analysis.json`).
- Minor updates to `apps/chip8_nyash/chip8_emulator.nyash` and `local_tests` files.

This commit cleans up the repository and sets the stage for further code modularization efforts, particularly in the `src/interpreter` and `src/parser` modules, based on recent analysis.
2025-08-16 01:30:39 +09:00

44 lines
1.7 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Nyashプログラミング言語のRust実装で困っています。
【現在の問題】
Everything is Box設計で、全てのデータがBox<dyn NyashBox>として管理されています。
しかし以下の3箇所で clone_box() を使って毎回新しいインスタンスを作成してしまい、
ステートフルなオブジェクトSocketBoxなどの状態が保持されない問題が発生しています。
【問題箇所】
1. resolve_variable() - src/interpreter/core.rs:366
```rust
let cloned_value = local_value.clone_box(); // ← 毎回新インスタンス
return Ok(cloned_value);
```
2. get_field() - src/instance.rs:275
```rust
self.fields.lock().unwrap().get(field_name).map(|v| v.clone_box()) // ← フィールド複製
```
3. execute_field_access() - src/interpreter/expressions.rs:779
```rust
let field_value = instance.get_field(field) // ← 上記を呼び出し
```
【現在のデータ構造】
- local_vars: HashMap<String, Box<dyn NyashBox>>
- fields: Arc<Mutex<HashMap<String, Box<dyn NyashBox>>>>
- 全てのBoxは Arc<Mutex> で内部状態を管理
【症状】
me.server.bind() → SocketBox ID=10で成功、is_server=true
me.server.isServer() → SocketBox ID=19で失敗、is_server=false
毎回別インスタンスになってしまう
【質問】
Rustの所有権システムを正しく使って、clone_box()ではなく「同じBoxインスタンスへの参照」を返すにはどう実装すべきでしょうか
考えられるアプローチ:
1. Arc<dyn NyashBox>に統一する
2. Rc<dyn NyashBox>を使う
3. 参照を返す(ライフタイム管理)
4. 他の適切なパターン
具体的なコード例を交えて、Rust的に正しい設計を教えてください。