From 2f732ef2095e4eae25aa65f070c6ec661fec1e6c Mon Sep 17 00:00:00 2001
From: Vasilii Rogin <vasya@rogin.ru>
Date: Thu, 11 May 2023 18:52:27 +0300
Subject: [PATCH] Add op_arrayexpr

---
 src/sfall_arrays.cc  | 24 ++++++++++++++++++++++--
 src/sfall_arrays.h   |  1 +
 src/sfall_opcodes.cc | 14 ++++++++++++++
 3 files changed, 37 insertions(+), 2 deletions(-)

diff --git a/src/sfall_arrays.cc b/src/sfall_arrays.cc
index aa09bd8..0681f84 100644
--- a/src/sfall_arrays.cc
+++ b/src/sfall_arrays.cc
@@ -13,7 +13,7 @@
 namespace fallout {
 
 static ArrayId nextArrayID = 1;
-static ArrayId stackArrayId = 1;
+static ArrayId stackArrayId = 0;
 
 #define ARRAY_MAX_STRING (255) // maximum length of string to be stored as array key or value
 #define ARRAY_MAX_SIZE (100000) // maximum number of array elements,
@@ -358,7 +358,7 @@ void sfallArraysReset()
     temporaryArrays.clear();
     arrays.clear();
     nextArrayID = 1;
-    stackArrayId = 1;
+    stackArrayId = 0;
 }
 
 void ResizeArray(ArrayId array_id, int newLen)
@@ -369,4 +369,24 @@ void ResizeArray(ArrayId array_id, int newLen)
     };
     arr->ResizeArray(newLen);
 }
+
+int StackArray(const ProgramValue& key, const ProgramValue& val)
+{
+    if (stackArrayId == 0) {
+        return 0;
+    }
+
+    auto arr = get_array_by_id(stackArrayId);
+    if (!arr) {
+        return 0;
+    };
+
+    auto size = arr->size();
+    if (size >= ARRAY_MAX_SIZE) return 0;
+    if (key.asInt() >= size) arr->ResizeArray(size + 1);
+
+    SetArray(stackArrayId, key, val, false);
+    return 0;
+}
+
 }
\ No newline at end of file
diff --git a/src/sfall_arrays.h b/src/sfall_arrays.h
index 3cc59e6..1ee94c3 100644
--- a/src/sfall_arrays.h
+++ b/src/sfall_arrays.h
@@ -24,6 +24,7 @@ void FixArray(ArrayId id);
 void ResizeArray(ArrayId array_id, int newLen);
 void DeleteAllTempArrays();
 void sfallArraysReset();
+int StackArray(const ProgramValue& key, const ProgramValue& val);
 
 }
 #endif /* SFALL_ARRAYS */
\ No newline at end of file
diff --git a/src/sfall_opcodes.cc b/src/sfall_opcodes.cc
index 19556fd..8ab43c6 100644
--- a/src/sfall_opcodes.cc
+++ b/src/sfall_opcodes.cc
@@ -533,6 +533,19 @@ static void opSetArray(Program* program)
     SetArray(arrayId, key, value, true);
 }
 
+
+// arrayexpr
+static void opStackArray(Program* program)
+{
+    auto value = programStackPopValue(program);
+    auto key = programStackPopValue(program);    
+    auto returnValue = StackArray(key, value);
+    programStackPushInteger(program, returnValue);
+}
+
+
+
+
 // get_array
 static void opGetArray(Program* program)
 {
@@ -744,6 +757,7 @@ void sfallOpcodesInit()
     interpreterRegisterOpcode(0x824F, opGetStringLength);
     interpreterRegisterOpcode(0x8253, opTypeOf);
     interpreterRegisterOpcode(0x8256, opGetArrayKey);
+    interpreterRegisterOpcode(0x8257, opStackArray);
     interpreterRegisterOpcode(0x8263, op_power);
     interpreterRegisterOpcode(0x8267, opRound);
     interpreterRegisterOpcode(0x826B, opGetMessage);