Allow assigning to array in initialization from function (#624, #728)

dev-time-step
krzys-h 2016-03-13 20:17:10 +01:00
parent 4d99a62d37
commit 967aa22330
2 changed files with 71 additions and 1 deletions

View File

@ -23,6 +23,7 @@
#include "CBot/CBotInstr/CBotExpression.h"
#include "CBot/CBotInstr/CBotListArray.h"
#include "CBot/CBotInstr/CBotEmpty.h"
#include "CBot/CBotInstr/CBotTwoOpExpr.h"
#include "CBot/CBotStack.h"
#include "CBot/CBotCStack.h"
@ -95,7 +96,18 @@ CBotInstr* CBotDefArray::Compile(CBotToken* &p, CBotCStack* pStack, CBotTypResul
if (IsOfType(p, ID_ASS)) // with an assignment
{
inst->m_listass = CBotListArray::Compile(p, pStk, type.GetTypElem());
if ((inst->m_listass = CBotTwoOpExpr::Compile(p, pStk)) != nullptr)
{
if (!pStk->GetTypResult().Compare(type)) // compatible type ?
{
pStk->SetError(CBotErrBadType1, p->GetStart());
goto error;
}
}
else
{
inst->m_listass = CBotListArray::Compile(p, pStk, type.GetTypElem());
}
}
if (pStk->IsOk()) return pStack->Return(inst, pStk);

View File

@ -995,3 +995,61 @@ TEST_F(CBotUT, DISABLED_TestNANParam_Issue642)
"}\n"
);
}
TEST_F(CBotUT, TestArrayInitialization)
{
ExecuteTest(
"extern void TestArrayInitialization() {\n"
" int[] a = {1, 2, 3};\n"
" ASSERT(sizeof(a) == 3);\n"
" ASSERT(a[0] == 1);\n"
" ASSERT(a[1] == 2);\n"
" ASSERT(a[2] == 3);\n"
"}\n"
);
ExecuteTest(
"extern void TestArrayInitializationOutOfRange() {\n"
" int a[2] = {1, 2, 3};\n"
"}\n",
CBotErrOutArray
);
ExecuteTest(
"extern void TestArrayInitializationSmallerThanRange() {\n"
" int a[4] = {1, 2, 3};\n"
" ASSERT(sizeof(a) == 3);\n"
" ASSERT(a[0] == 1);\n"
" ASSERT(a[1] == 2);\n"
" ASSERT(a[2] == 3);\n"
" a[3] = 4;\n"
" ASSERT(sizeof(a) == 4);\n"
" ASSERT(a[3] == 4);\n"
"}\n"
);
ExecuteTest(
"extern void TestArrayInitializationLimitUnchanged() {\n"
" int a[4] = {1, 2, 3};\n"
" a[4] = 5;\n"
"}\n",
CBotErrOutArray
);
}
TEST_F(CBotUT, TestArrayFunctionReturn)
{
ExecuteTest(
"int[] test() {\n"
" int[] a = {1, 2, 3};\n"
" return a;"
"}\n"
"extern void TestArrayFunctionReturn() {\n"
" int[] b = test();\n"
" ASSERT(sizeof(b) == 3);\n"
" ASSERT(b[0] == 1);\n"
" ASSERT(b[1] == 2);\n"
" ASSERT(b[2] == 3);\n"
"}\n"
);
}