🔥 feat: Arc<Mutex> Revolution完全達成 - 全Box型統一実装

## 🎯 主要な変更
- ArrayBoxをArc<Mutex>パターンで完全再実装
- 全メソッドが`&self`で統一(push, pop, get, set等)
- Box<dyn NyashBox>引数対応でNyashから使用可能に

##  修正内容
- ArrayBox: 完全なArc<Mutex>実装に置き換え
- BufferBox: ArrayBoxとの連携修正、デバッグ出力削除
- StringBox: 新しいArrayBoxインポートに修正
- RandomBox: 新しいArrayBoxインポートに修正
- box_trait.rs: 古いArrayBox定義を削除しre-export追加

## 🧪 テスト追加
- test_buffer_box.nyash: BufferBox動作確認
- test_random_box.nyash: RandomBox動作確認
- test_new_boxes.nyash: 包括的Box機能テスト修正

##  確認済み動作
- ArrayBox: push/pop/get/set/join等全メソッド
- BufferBox: write/readAll/length
- RandomBox: choice/shuffle等配列操作
- JSONBox/RegexBox: 既に正しく実装済み

🚀 全Box型がArc<Mutex>パターンで統一完了!

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Moe Charm
2025-08-10 16:46:39 +09:00
parent dff165db8d
commit 0c786a8ac6
8 changed files with 146 additions and 182 deletions

View File

@ -123,7 +123,7 @@ impl StringBox {
/// Join array elements using this string as delimiter /// Join array elements using this string as delimiter
pub fn join(&self, array_box: Box<dyn NyashBox>) -> Box<dyn NyashBox> { pub fn join(&self, array_box: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
if let Some(array) = array_box.as_any().downcast_ref::<ArrayBox>() { if let Some(array) = array_box.as_any().downcast_ref::<ArrayBox>() {
let strings: Vec<String> = array.elements.lock().unwrap() let strings: Vec<String> = array.items.lock().unwrap()
.iter() .iter()
.map(|element| element.to_string_box().value) .map(|element| element.to_string_box().value)
.collect(); .collect();
@ -363,147 +363,8 @@ impl Display for VoidBox {
} }
} }
/// Array values in Nyash - dynamic arrays of Box values // ArrayBox is now defined in boxes::array module
#[derive(Debug)] pub use crate::boxes::array::ArrayBox;
pub struct ArrayBox {
pub elements: Arc<Mutex<Vec<Box<dyn NyashBox>>>>,
id: u64,
}
impl Clone for ArrayBox {
fn clone(&self) -> Self {
Self {
elements: Arc::clone(&self.elements), // Arcをクローンして同じデータを共有
id: self.id, // 同じIDを保持
}
}
}
impl ArrayBox {
pub fn new() -> Self {
static mut COUNTER: u64 = 0;
let id = unsafe {
COUNTER += 1;
COUNTER
};
Self {
elements: Arc::new(Mutex::new(Vec::new())),
id,
}
}
pub fn new_with_elements(elements: Vec<Box<dyn NyashBox>>) -> Self {
static mut COUNTER: u64 = 0;
let id = unsafe {
COUNTER += 1;
COUNTER
};
Self {
elements: Arc::new(Mutex::new(elements)),
id,
}
}
// ===== Array Methods for Nyash =====
/// Add element to end of array
pub fn push(&self, element: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
self.elements.lock().unwrap().push(element);
Box::new(VoidBox::new())
}
/// Remove and return last element
pub fn pop(&self) -> Box<dyn NyashBox> {
match self.elements.lock().unwrap().pop() {
Some(element) => element,
None => Box::new(VoidBox::new()),
}
}
/// Get array length
pub fn length(&self) -> Box<dyn NyashBox> {
Box::new(IntegerBox::new(self.elements.lock().unwrap().len() as i64))
}
/// Join array elements with delimiter into string
pub fn join(&self, delimiter: &str) -> Box<dyn NyashBox> {
let strings: Vec<String> = self.elements.lock().unwrap()
.iter()
.map(|element| element.to_string_box().value)
.collect();
Box::new(StringBox::new(strings.join(delimiter)))
}
/// Get element at index
pub fn get(&self, index: usize) -> Option<Box<dyn NyashBox>> {
self.elements.lock().unwrap().get(index).map(|e| e.clone_box())
}
/// Set element at index
pub fn set(&self, index: usize, value: Box<dyn NyashBox>) -> Result<(), String> {
let mut elements = self.elements.lock().unwrap();
if index < elements.len() {
elements[index] = value;
Ok(())
} else {
Err(format!("Index {} out of bounds for array of length {}", index, elements.len()))
}
}
}
impl NyashBox for ArrayBox {
fn to_string_box(&self) -> StringBox {
let elements_str: Vec<String> = self.elements.lock().unwrap()
.iter()
.map(|e| e.to_string_box().value)
.collect();
StringBox::new(format!("[{}]", elements_str.join(", ")))
}
fn equals(&self, other: &dyn NyashBox) -> BoolBox {
if let Some(other_array) = other.as_any().downcast_ref::<ArrayBox>() {
let self_elements = self.elements.lock().unwrap();
let other_elements = other_array.elements.lock().unwrap();
if self_elements.len() != other_elements.len() {
return BoolBox::new(false);
}
for (a, b) in self_elements.iter().zip(other_elements.iter()) {
if !a.equals(b.as_ref()).value {
return BoolBox::new(false);
}
}
BoolBox::new(true)
} else {
BoolBox::new(false)
}
}
fn type_name(&self) -> &'static str {
"ArrayBox"
}
fn clone_box(&self) -> Box<dyn NyashBox> {
Box::new(self.clone()) // 同じインスタンスを共有
}
fn as_any(&self) -> &dyn Any {
self
}
fn box_id(&self) -> u64 {
self.id
}
}
impl Display for ArrayBox {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_string_box().value)
}
}
/// File values in Nyash - file system operations /// File values in Nyash - file system operations
#[derive(Debug, Clone)] #[derive(Debug, Clone)]

View File

@ -26,6 +26,19 @@ impl ArrayBox {
} }
} }
/// 要素を持つArrayBoxを作成
pub fn new_with_elements(elements: Vec<Box<dyn NyashBox>>) -> Self {
static mut COUNTER: u64 = 0;
let id = unsafe {
COUNTER += 1;
COUNTER
};
ArrayBox {
items: Arc::new(Mutex::new(elements)),
id,
}
}
/// 要素を追加 /// 要素を追加
pub fn push(&self, item: Box<dyn NyashBox>) -> Box<dyn NyashBox> { pub fn push(&self, item: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
self.items.lock().unwrap().push(item); self.items.lock().unwrap().push(item);
@ -46,36 +59,55 @@ impl ArrayBox {
} }
/// インデックスで要素を取得 /// インデックスで要素を取得
pub fn get(&self, index: usize) -> Option<Box<dyn NyashBox>> { pub fn get(&self, index: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
self.items.lock().unwrap().get(index).map(|item| item.clone_box()) if let Some(idx_box) = index.as_any().downcast_ref::<IntegerBox>() {
let idx = idx_box.value as usize;
let items = self.items.lock().unwrap();
match items.get(idx) {
Some(item) => item.clone_box(),
None => Box::new(crate::boxes::null_box::NullBox::new()),
}
} else {
Box::new(StringBox::new("Error: get() requires integer index"))
}
} }
/// インデックスで要素を設定 /// インデックスで要素を設定
pub fn set(&self, index: usize, value: Box<dyn NyashBox>) -> Result<(), String> { pub fn set(&self, index: Box<dyn NyashBox>, value: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
if let Some(idx_box) = index.as_any().downcast_ref::<IntegerBox>() {
let idx = idx_box.value as usize;
let mut items = self.items.lock().unwrap(); let mut items = self.items.lock().unwrap();
if index < items.len() { if idx < items.len() {
items[index] = value; items[idx] = value;
Ok(()) Box::new(StringBox::new("ok"))
} else { } else {
Err(format!("Index {} out of bounds", index)) Box::new(StringBox::new("Error: index out of bounds"))
}
} else {
Box::new(StringBox::new("Error: set() requires integer index"))
} }
} }
/// 要素を削除 /// 要素を削除
pub fn remove(&self, index: usize) -> Option<Box<dyn NyashBox>> { pub fn remove(&self, index: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
if let Some(idx_box) = index.as_any().downcast_ref::<IntegerBox>() {
let idx = idx_box.value as usize;
let mut items = self.items.lock().unwrap(); let mut items = self.items.lock().unwrap();
if index < items.len() { if idx < items.len() {
Some(items.remove(index)) items.remove(idx)
} else { } else {
None Box::new(crate::boxes::null_box::NullBox::new())
}
} else {
Box::new(StringBox::new("Error: remove() requires integer index"))
} }
} }
/// 指定された値のインデックスを検索 /// 指定された値のインデックスを検索
pub fn indexOf(&self, value: &dyn NyashBox) -> Box<dyn NyashBox> { pub fn indexOf(&self, value: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
let items = self.items.lock().unwrap(); let items = self.items.lock().unwrap();
for (i, item) in items.iter().enumerate() { for (i, item) in items.iter().enumerate() {
if item.equals(value).value { if item.equals(value.as_ref()).value {
return Box::new(IntegerBox::new(i as i64)); return Box::new(IntegerBox::new(i as i64));
} }
} }
@ -83,10 +115,10 @@ impl ArrayBox {
} }
/// 指定された値が含まれているか確認 /// 指定された値が含まれているか確認
pub fn contains(&self, value: &dyn NyashBox) -> Box<dyn NyashBox> { pub fn contains(&self, value: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
let items = self.items.lock().unwrap(); let items = self.items.lock().unwrap();
for item in items.iter() { for item in items.iter() {
if item.equals(value).value { if item.equals(value.as_ref()).value {
return Box::new(BoolBox::new(true)); return Box::new(BoolBox::new(true));
} }
} }
@ -100,12 +132,17 @@ impl ArrayBox {
} }
/// 文字列結合 /// 文字列結合
pub fn join(&self, delimiter: &str) -> Box<dyn NyashBox> { pub fn join(&self, delimiter: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
if let Some(sep_box) = delimiter.as_any().downcast_ref::<StringBox>() {
let items = self.items.lock().unwrap(); let items = self.items.lock().unwrap();
let strings: Vec<String> = items.iter() let parts: Vec<String> = items
.iter()
.map(|item| item.to_string_box().value) .map(|item| item.to_string_box().value)
.collect(); .collect();
Box::new(StringBox::new(&strings.join(delimiter))) Box::new(StringBox::new(&parts.join(&sep_box.value)))
} else {
Box::new(StringBox::new("Error: join() requires string separator"))
}
} }
} }

View File

@ -67,8 +67,8 @@ impl BufferBox {
/// データを書き込む /// データを書き込む
pub fn write(&self, data: Box<dyn NyashBox>) -> Box<dyn NyashBox> { pub fn write(&self, data: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
// ArrayBoxから変換 // ArrayBoxから変換 - use crate::boxes::array::ArrayBox directly
if let Some(array_box) = data.as_any().downcast_ref::<ArrayBox>() { if let Some(array_box) = data.as_any().downcast_ref::<crate::boxes::array::ArrayBox>() {
let mut buffer = self.data.lock().unwrap(); let mut buffer = self.data.lock().unwrap();
let items = array_box.items.lock().unwrap(); let items = array_box.items.lock().unwrap();
for item in items.iter() { for item in items.iter() {
@ -80,7 +80,8 @@ impl BufferBox {
} }
Box::new(IntegerBox::new(buffer.len() as i64)) Box::new(IntegerBox::new(buffer.len() as i64))
} else { } else {
Box::new(StringBox::new("Error: write() requires ArrayBox of integers")) let type_name = data.type_name();
Box::new(StringBox::new(&format!("Error: write() requires ArrayBox of integers, got {}", type_name)))
} }
} }

View File

@ -67,7 +67,8 @@
* - 大きな配列のshuffleは処理時間が長い場合あり * - 大きな配列のshuffleは処理時間が長い場合あり
*/ */
use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, ArrayBox}; use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox};
use crate::boxes::array::ArrayBox;
use crate::boxes::math_box::FloatBox; use crate::boxes::math_box::FloatBox;
use std::fmt::{Debug, Display}; use std::fmt::{Debug, Display};
use std::any::Any; use std::any::Any;
@ -159,10 +160,8 @@ impl RandomBox {
} }
let index = self.next_random() % (length as u64); let index = self.next_random() % (length as u64);
match array_box.get(index as usize) { // 新しいArrayBox.get()は既にBox<dyn NyashBox>を返すので、直接使用
Some(element) => element, array_box.get(Box::new(IntegerBox::new(index as i64)))
None => Box::new(StringBox::new("Error: index out of bounds")),
}
} else { } else {
Box::new(StringBox::new("Error: choice() requires array input")) Box::new(StringBox::new("Error: choice() requires array input"))
} }
@ -181,7 +180,9 @@ impl RandomBox {
// 元の配列の要素を全て新しい配列にコピー // 元の配列の要素を全て新しい配列にコピー
for i in 0..length { for i in 0..length {
if let Some(element) = array_box.get(i as usize) { let element = array_box.get(Box::new(IntegerBox::new(i as i64)));
// NullBoxでなければ追加
if element.type_name() != "NullBox" {
shuffled.push(element); shuffled.push(element);
} }
} }
@ -194,7 +195,9 @@ impl RandomBox {
while !remaining_indices.is_empty() { while !remaining_indices.is_empty() {
let random_idx = (self.next_random() % remaining_indices.len() as u64) as usize; let random_idx = (self.next_random() % remaining_indices.len() as u64) as usize;
let actual_idx = remaining_indices.remove(random_idx); let actual_idx = remaining_indices.remove(random_idx);
if let Some(element) = array_box.get(actual_idx) { let element = array_box.get(Box::new(IntegerBox::new(actual_idx as i64)));
// NullBoxでなければ追加
if element.type_name() != "NullBox" {
result.push(element); result.push(element);
} }
} }

View File

@ -60,12 +60,16 @@ impl StringBox {
/// Split string by delimiter and return ArrayBox /// Split string by delimiter and return ArrayBox
pub fn split(&self, delimiter: &str) -> Box<dyn NyashBox> { pub fn split(&self, delimiter: &str) -> Box<dyn NyashBox> {
use crate::box_trait::ArrayBox; use crate::boxes::array::ArrayBox;
let parts: Vec<String> = self.value.split(delimiter).map(|s| s.to_string()).collect(); let parts: Vec<String> = self.value.split(delimiter).map(|s| s.to_string()).collect();
let array_elements: Vec<Box<dyn NyashBox>> = parts.into_iter() let array_elements: Vec<Box<dyn NyashBox>> = parts.into_iter()
.map(|s| Box::new(StringBox::new(s)) as Box<dyn NyashBox>) .map(|s| Box::new(StringBox::new(s)) as Box<dyn NyashBox>)
.collect(); .collect();
Box::new(ArrayBox::new_with_elements(array_elements)) let result = ArrayBox::new();
for element in array_elements {
result.push(element);
}
Box::new(result)
} }
/// Find substring and return position (or -1 if not found) /// Find substring and return position (or -1 if not found)
@ -117,9 +121,9 @@ impl StringBox {
/// Join array elements using this string as delimiter /// Join array elements using this string as delimiter
pub fn join(&self, array_box: Box<dyn NyashBox>) -> Box<dyn NyashBox> { pub fn join(&self, array_box: Box<dyn NyashBox>) -> Box<dyn NyashBox> {
use crate::box_trait::ArrayBox; use crate::boxes::array::ArrayBox;
if let Some(array) = array_box.as_any().downcast_ref::<ArrayBox>() { if let Some(array) = array_box.as_any().downcast_ref::<ArrayBox>() {
let strings: Vec<String> = array.elements.lock().unwrap() let strings: Vec<String> = array.items.lock().unwrap()
.iter() .iter()
.map(|element| element.to_string_box().value) .map(|element| element.to_string_box().value)
.collect(); .collect();

27
test_buffer_box.nyash Normal file
View File

@ -0,0 +1,27 @@
// 🧪 BufferBoxのテスト
print("=== BufferBox Test ===")
local buffer, data, result
// BufferBox作成
buffer = new BufferBox()
// データ配列作成
data = new ArrayBox()
data.push(72) // 'H'
data.push(101) // 'e'
data.push(108) // 'l'
data.push(108) // 'l'
data.push(111) // 'o'
// データ書き込み
result = buffer.write(data)
print("Write result: " + result)
print("Buffer length: " + buffer.length())
// データ読み取り
local readData
readData = buffer.readAll()
print("Read data: " + readData)
print("BufferBox test completed!")

View File

@ -47,9 +47,8 @@ print("Read data length: " + readData.length())
// 3. JSONBoxのテスト // 3. JSONBoxのテスト
print("\n=== JSONBox Test ===") print("\n=== JSONBox Test ===")
local json, parsed local parsed
json = new JSONBox() parsed = new JSONBox("{\"name\": \"Nyash\", \"version\": 1.0}")
parsed = json.parse('{"name": "Nyash", "version": 1.0}')
print("JSON stringify: " + parsed.stringify()) print("JSON stringify: " + parsed.stringify())
print("Name from JSON: " + parsed.get("name")) print("Name from JSON: " + parsed.get("name"))

32
test_random_box.nyash Normal file
View File

@ -0,0 +1,32 @@
// 🎲 RandomBoxのテスト
print("=== RandomBox Test ===")
local random, result, array
// RandomBox作成
random = new RandomBox()
// 基本乱数テスト
result = random.random()
print("Random float: " + result)
result = random.randInt(1, 6)
print("Dice roll (1-6): " + result)
result = random.randBool()
print("Random bool: " + result)
// 配列テスト
array = new ArrayBox()
array.push("apple")
array.push("banana")
array.push("cherry")
result = random.choice(array)
print("Random choice: " + result)
// 文字列生成テスト
result = random.randString(5)
print("Random string (5 chars): " + result)
print("RandomBox test completed!")