Processor_InstructionLoop.cs 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using MoonSharp.Interpreter.DataStructs;
  6. using MoonSharp.Interpreter.Debugging;
  7. namespace MoonSharp.Interpreter.Execution.VM
  8. {
  9. sealed partial class Processor
  10. {
  11. private DynValue Processing_Loop(int instructionPtr)
  12. {
  13. repeat_execution:
  14. try
  15. {
  16. while (true)
  17. {
  18. Instruction i = m_RootChunk.Code[instructionPtr];
  19. if (m_DebuggerAttached != null)
  20. {
  21. ListenDebugger(i, instructionPtr);
  22. }
  23. ++instructionPtr;
  24. switch (i.OpCode)
  25. {
  26. case OpCode.Nop:
  27. case OpCode.Debug:
  28. break;
  29. case OpCode.Pop:
  30. m_ValueStack.RemoveLast(i.NumVal);
  31. break;
  32. case OpCode.Copy:
  33. m_ValueStack.Push(m_ValueStack.Peek(i.NumVal));
  34. break;
  35. case OpCode.Swap:
  36. ExecSwap(i);
  37. break;
  38. case OpCode.Literal:
  39. m_ValueStack.Push(i.Value);
  40. break;
  41. case OpCode.Add:
  42. instructionPtr = ExecAdd(i, instructionPtr);
  43. break;
  44. case OpCode.Concat:
  45. instructionPtr = ExecConcat(i, instructionPtr);
  46. break;
  47. case OpCode.Neg:
  48. instructionPtr = ExecNeg(i, instructionPtr);
  49. break;
  50. case OpCode.Sub:
  51. instructionPtr = ExecSub(i, instructionPtr);
  52. break;
  53. case OpCode.Mul:
  54. instructionPtr = ExecMul(i, instructionPtr);
  55. break;
  56. case OpCode.Div:
  57. instructionPtr = ExecDiv(i, instructionPtr);
  58. break;
  59. case OpCode.Mod:
  60. instructionPtr = ExecMod(i, instructionPtr);
  61. break;
  62. case OpCode.Power:
  63. instructionPtr = ExecPower(i, instructionPtr);
  64. break;
  65. case OpCode.Eq:
  66. instructionPtr = ExecEq(i, instructionPtr);
  67. break;
  68. case OpCode.LessEq:
  69. instructionPtr = ExecLessEq(i, instructionPtr);
  70. break;
  71. case OpCode.Less:
  72. instructionPtr = ExecLess(i, instructionPtr);
  73. break;
  74. case OpCode.Len:
  75. instructionPtr = ExecLen(i, instructionPtr);
  76. break;
  77. case OpCode.Call:
  78. instructionPtr = Internal_ExecCall(i.NumVal, instructionPtr);
  79. break;
  80. case OpCode.Scalar:
  81. m_ValueStack.Push(m_ValueStack.Pop().ToScalar());
  82. break;
  83. case OpCode.Not:
  84. ExecNot(i);
  85. break;
  86. case OpCode.JfOrPop:
  87. case OpCode.JtOrPop:
  88. instructionPtr = ExecShortCircuitingOperator(i, instructionPtr);
  89. break;
  90. case OpCode.JNil:
  91. {
  92. DynValue v = m_ValueStack.Pop();
  93. if (v.Type == DataType.Nil)
  94. instructionPtr = i.NumVal;
  95. }
  96. break;
  97. case OpCode.Jf:
  98. instructionPtr = JumpBool(i, false, instructionPtr);
  99. break;
  100. case OpCode.Jump:
  101. instructionPtr = i.NumVal;
  102. break;
  103. case OpCode.MkTuple:
  104. ExecMkTuple(i);
  105. break;
  106. case OpCode.Enter:
  107. NilifyBlockData(i);
  108. break;
  109. case OpCode.Leave:
  110. case OpCode.Exit:
  111. ClearBlockData(i);
  112. break;
  113. case OpCode.Closure:
  114. ExecClosure(i);
  115. break;
  116. case OpCode.BeginFn:
  117. ExecBeginFn(i);
  118. break;
  119. case OpCode.ToBool:
  120. m_ValueStack.Push(DynValue.NewBoolean(m_ValueStack.Pop().CastToBool()));
  121. break;
  122. case OpCode.Args:
  123. ExecArgs(i);
  124. break;
  125. case OpCode.Ret:
  126. instructionPtr = ExecRet(i);
  127. if (instructionPtr < 0)
  128. goto return_to_native_code;
  129. break;
  130. case OpCode.Incr:
  131. ExecIncr(i);
  132. break;
  133. case OpCode.ToNum:
  134. ExecToNum(i);
  135. break;
  136. case OpCode.JFor:
  137. instructionPtr = ExecJFor(i, instructionPtr);
  138. break;
  139. case OpCode.NewTable:
  140. m_ValueStack.Push(DynValue.NewTable(this.m_Script));
  141. break;
  142. case OpCode.IterPrep:
  143. ExecIterPrep(i);
  144. break;
  145. case OpCode.IterUpd:
  146. ExecIterUpd(i);
  147. break;
  148. case OpCode.ExpTuple:
  149. ExecExpTuple(i);
  150. break;
  151. case OpCode.Local:
  152. m_ValueStack.Push(m_ExecutionStack.Peek().LocalScope[i.Symbol.i_Index]);
  153. break;
  154. case OpCode.Upvalue:
  155. m_ValueStack.Push(m_ExecutionStack.Peek().ClosureScope[i.Symbol.i_Index]);
  156. break;
  157. case OpCode.StoreUpv:
  158. ExecStoreUpv(i);
  159. break;
  160. case OpCode.StoreLcl:
  161. ExecStoreLcl(i);
  162. break;
  163. case OpCode.TblInitN:
  164. ExecTblInitN(i);
  165. break;
  166. case OpCode.TblInitI:
  167. ExecTblInitI(i);
  168. break;
  169. case OpCode.Index:
  170. instructionPtr = ExecIndex(i, instructionPtr);
  171. break;
  172. case OpCode.PushEnv:
  173. m_ValueStack.Push(DynValue.NewTable(m_GlobalTable));
  174. break;
  175. case OpCode.IndexSet:
  176. instructionPtr = ExecIndexSet(i, instructionPtr);
  177. break;
  178. case OpCode.Invalid:
  179. throw new NotImplementedException(string.Format("Invalid opcode : {0}", i.Name));
  180. default:
  181. throw new NotImplementedException(string.Format("Execution for {0} not implented yet!", i.OpCode));
  182. }
  183. }
  184. }
  185. catch (ScriptRuntimeException ex)
  186. {
  187. while (m_ExecutionStack.Count > 0)
  188. {
  189. CallStackItem csi = PopToBasePointer();
  190. CallMode mode = csi.Mode;
  191. if (mode == CallMode.PCall)
  192. {
  193. instructionPtr = csi.ReturnAddress;
  194. var argscnt = (int)(m_ValueStack.Pop().Number);
  195. m_ValueStack.RemoveLast(argscnt + 1);
  196. m_ValueStack.Push(DynValue.NewTuple(DynValue.False, DynValue.NewString(ex.Message)));
  197. goto repeat_execution;
  198. }
  199. }
  200. if (m_ExecutionStack.Count == 0)
  201. {
  202. throw;
  203. }
  204. }
  205. return_to_native_code:
  206. if (m_ValueStack.Count == 1)
  207. return m_ValueStack.Pop();
  208. else if (m_ValueStack.Count == 0)
  209. return DynValue.Nil;
  210. else
  211. throw new InternalErrorException("Unexpected value stack count at program end : {0}", m_ValueStack.Count);
  212. }
  213. private void AssignLocal(SymbolRef symref, DynValue value)
  214. {
  215. var stackframe = m_ExecutionStack.Peek();
  216. DynValue v = stackframe.LocalScope[symref.i_Index];
  217. if (v == null)
  218. stackframe.LocalScope[symref.i_Index] = v = DynValue.NewNil();
  219. v.Assign(value);
  220. }
  221. private void ExecStoreLcl(Instruction i)
  222. {
  223. DynValue value = GetStoreValue(i);
  224. SymbolRef symref = i.Symbol;
  225. AssignLocal(symref, value);
  226. }
  227. private void ExecStoreUpv(Instruction i)
  228. {
  229. DynValue value = GetStoreValue(i);
  230. SymbolRef symref = i.Symbol;
  231. var stackframe = m_ExecutionStack.Peek();
  232. DynValue v = stackframe.ClosureScope[symref.i_Index];
  233. if (v == null)
  234. stackframe.ClosureScope[symref.i_Index] = v = DynValue.NewNil();
  235. v.Assign(value);
  236. }
  237. private void ExecSwap(Instruction i)
  238. {
  239. DynValue v1 = m_ValueStack.Peek(i.NumVal);
  240. DynValue v2 = m_ValueStack.Peek(i.NumVal2);
  241. m_ValueStack.Set(i.NumVal, v2);
  242. m_ValueStack.Set(i.NumVal2, v1);
  243. }
  244. private DynValue GetStoreValue(Instruction i)
  245. {
  246. int stackofs = i.NumVal;
  247. int tupleidx = i.NumVal2;
  248. DynValue v = m_ValueStack.Peek(stackofs);
  249. if (v.Type == DataType.Tuple)
  250. {
  251. return (tupleidx < v.Tuple.Length) ? v.Tuple[tupleidx] : DynValue.NewNil();
  252. }
  253. else
  254. {
  255. return (tupleidx == 0) ? v : DynValue.NewNil();
  256. }
  257. }
  258. private void ExecClosure(Instruction i)
  259. {
  260. Closure c = new Closure(this.m_Script, i.NumVal, i.SymbolList,
  261. i.SymbolList.Select(s => this.GetUpvalueSymbol(s)).ToList());
  262. m_ValueStack.Push(DynValue.NewClosure(c));
  263. }
  264. private DynValue GetUpvalueSymbol(SymbolRef s)
  265. {
  266. if (s.Type == SymbolRefType.Local)
  267. return m_ExecutionStack.Peek().LocalScope[s.i_Index];
  268. else if (s.Type == SymbolRefType.Upvalue)
  269. return m_ExecutionStack.Peek().ClosureScope[s.i_Index];
  270. else
  271. throw new Exception("unsupported symbol type");
  272. }
  273. private void ExecMkTuple(Instruction i)
  274. {
  275. Slice<DynValue> slice = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - i.NumVal, i.NumVal, false);
  276. var v = Internal_AdjustTuple(slice);
  277. m_ValueStack.RemoveLast(i.NumVal);
  278. m_ValueStack.Push(DynValue.NewTuple(v));
  279. }
  280. private void ExecToNum(Instruction i)
  281. {
  282. double? v = m_ValueStack.Pop().CastToNumber();
  283. if (v.HasValue)
  284. m_ValueStack.Push(DynValue.NewNumber(v.Value));
  285. else
  286. throw new ScriptRuntimeException(null, "Can't convert value to number");
  287. }
  288. private void ExecIterUpd(Instruction i)
  289. {
  290. DynValue v = m_ValueStack.Peek(0);
  291. DynValue t = m_ValueStack.Peek(1);
  292. t.Tuple[2] = v;
  293. }
  294. private void ExecExpTuple(Instruction i)
  295. {
  296. DynValue t = m_ValueStack.Peek(i.NumVal);
  297. if (t.Type == DataType.Tuple)
  298. {
  299. for (int idx = 0; idx < t.Tuple.Length; idx++)
  300. m_ValueStack.Push(t.Tuple[idx]);
  301. }
  302. else
  303. {
  304. m_ValueStack.Push(t);
  305. }
  306. }
  307. private void ExecIterPrep(Instruction i)
  308. {
  309. DynValue v = m_ValueStack.Pop();
  310. if (v.Type != DataType.Tuple)
  311. {
  312. v = DynValue.NewTuple(v, DynValue.Nil, DynValue.Nil);
  313. }
  314. else if (v.Tuple.Length > 3)
  315. {
  316. v = DynValue.NewTuple(v.Tuple[0], v.Tuple[1], v.Tuple[2]);
  317. }
  318. else if (v.Tuple.Length == 2)
  319. {
  320. v = DynValue.NewTuple(v.Tuple[0], v.Tuple[1], DynValue.Nil);
  321. }
  322. else if (v.Tuple.Length == 1)
  323. {
  324. v = DynValue.NewTuple(v.Tuple[0], DynValue.Nil, DynValue.Nil);
  325. }
  326. m_ValueStack.Push(v);
  327. }
  328. private int ExecJFor(Instruction i, int instructionPtr)
  329. {
  330. double val = m_ValueStack.Peek(0).Number;
  331. double step = m_ValueStack.Peek(1).Number;
  332. double stop = m_ValueStack.Peek(2).Number;
  333. bool whileCond = (step > 0) ? val <= stop : val >= stop;
  334. if (!whileCond)
  335. return i.NumVal;
  336. else
  337. return instructionPtr;
  338. }
  339. private void ExecIncr(Instruction i)
  340. {
  341. DynValue top = m_ValueStack.Peek(0);
  342. DynValue btm = m_ValueStack.Peek(i.NumVal);
  343. if (top.ReadOnly)
  344. {
  345. m_ValueStack.Pop();
  346. top = top.CloneAsWritable();
  347. m_ValueStack.Push(top);
  348. }
  349. top.AssignNumber(top.Number + btm.Number);
  350. }
  351. private void ExecNot(Instruction i)
  352. {
  353. DynValue v = m_ValueStack.Pop();
  354. m_ValueStack.Push(DynValue.NewBoolean(!(v.CastToBool())));
  355. }
  356. private void ExecBeginFn(Instruction i)
  357. {
  358. CallStackItem c = m_ExecutionStack.Peek();
  359. c.Debug_Symbols = i.SymbolList;
  360. c.LocalScope = new DynValue[i.NumVal];
  361. if (i.NumVal2 >= 0 && i.NumVal > 0)
  362. {
  363. for (int idx = 0; idx < i.NumVal2; idx++)
  364. {
  365. c.LocalScope[idx] = DynValue.NewNil();
  366. }
  367. }
  368. }
  369. private CallStackItem PopToBasePointer()
  370. {
  371. var csi = m_ExecutionStack.Pop();
  372. m_ValueStack.CropAtCount(csi.BasePointer);
  373. return csi;
  374. }
  375. private int PopExecStackAndCheckVStack(int vstackguard)
  376. {
  377. var xs = m_ExecutionStack.Pop();
  378. if (vstackguard != xs.BasePointer)
  379. throw new InternalErrorException("StackGuard violation");
  380. return xs.ReturnAddress;
  381. }
  382. private void ExecArgs(Instruction I)
  383. {
  384. int numargs = (int)m_ValueStack.Peek(0).Number;
  385. for (int i = 0; i < I.SymbolList.Length; i++)
  386. {
  387. if (i >= numargs)
  388. {
  389. this.AssignLocal(I.SymbolList[i], DynValue.NewNil());
  390. }
  391. else if ((i == I.SymbolList.Length - 1) && (I.SymbolList[i].i_Name == "..."))
  392. {
  393. int len = numargs - i;
  394. DynValue[] varargs = new DynValue[len];
  395. for (int ii = 0; ii < len; ii++)
  396. {
  397. varargs[ii] = m_ValueStack.Peek(numargs - i - ii).CloneAsWritable();
  398. }
  399. this.AssignLocal(I.SymbolList[i], DynValue.NewTuple(varargs));
  400. }
  401. else
  402. {
  403. this.AssignLocal(I.SymbolList[i], m_ValueStack.Peek(numargs - i).CloneAsWritable());
  404. }
  405. }
  406. }
  407. private int Internal_ExecCall(int argsCount, int instructionPtr, CallMode mode = CallMode.Normal)
  408. {
  409. DynValue fn = m_ValueStack.Peek(argsCount);
  410. if (fn.Type == DataType.ClrFunction)
  411. {
  412. IList<DynValue> args = new Slice<DynValue>(m_ValueStack, m_ValueStack.Count - argsCount, argsCount, false);
  413. var ret = fn.Callback.Invoke(new ScriptExecutionContext(this, fn.Callback), args);
  414. m_ValueStack.RemoveLast(argsCount + 1);
  415. m_ValueStack.Push(ret);
  416. return Internal_CheckForTailRequests(null, instructionPtr);
  417. }
  418. else if (fn.Type == DataType.Function)
  419. {
  420. m_ValueStack.Push(DynValue.NewNumber(argsCount));
  421. m_ExecutionStack.Push(new CallStackItem()
  422. {
  423. BasePointer = m_ValueStack.Count,
  424. ReturnAddress = instructionPtr,
  425. Debug_EntryPoint = fn.Function.ByteCodeLocation,
  426. ClosureScope = fn.Function.ClosureContext,
  427. Mode = mode,
  428. });
  429. return fn.Function.ByteCodeLocation;
  430. }
  431. else
  432. {
  433. if (fn.MetaTable != null)
  434. {
  435. var m = fn.MetaTable.RawGet("__call");
  436. if (m != null && m.Type != DataType.Nil)
  437. {
  438. DynValue[] tmp = new DynValue[argsCount + 1];
  439. for (int i = 0; i < argsCount + 1; i++)
  440. tmp[i] = m_ValueStack.Pop();
  441. m_ValueStack.Push(m);
  442. for (int i = argsCount; i >= 0; i--)
  443. m_ValueStack.Push(tmp[i]);
  444. return Internal_ExecCall(argsCount + 1, instructionPtr);
  445. }
  446. }
  447. throw new NotImplementedException("Can't call non function - " + fn.ToString());
  448. }
  449. }
  450. private int ExecRet(Instruction i)
  451. {
  452. CallStackItem csi;
  453. int retpoint = 0;
  454. if (i.NumVal == 0)
  455. {
  456. csi = PopToBasePointer();
  457. retpoint = csi.ReturnAddress;
  458. var argscnt = (int)(m_ValueStack.Pop().Number);
  459. m_ValueStack.RemoveLast(argscnt + 1);
  460. m_ValueStack.Push(DynValue.Nil);
  461. }
  462. else if (i.NumVal == 1)
  463. {
  464. var retval = m_ValueStack.Pop();
  465. csi = PopToBasePointer();
  466. retpoint = csi.ReturnAddress;
  467. var argscnt = (int)(m_ValueStack.Pop().Number);
  468. m_ValueStack.RemoveLast(argscnt + 1);
  469. m_ValueStack.Push(retval);
  470. retpoint = Internal_CheckForTailRequests(i, retpoint);
  471. }
  472. else
  473. {
  474. throw new InternalErrorException("RET supports only 0 and 1 ret val scenarios");
  475. }
  476. if (csi.Mode != CallMode.Normal)
  477. AdjustRetValueForMode(csi.Mode);
  478. return retpoint;
  479. }
  480. private void AdjustRetValueForMode(CallMode callMode)
  481. {
  482. DynValue r = m_ValueStack.Pop();
  483. switch (callMode)
  484. {
  485. case CallMode.PCall:
  486. m_ValueStack.Push(DynValue.NewTupleNested(DynValue.True, r));
  487. break;
  488. case CallMode.Require:
  489. break;
  490. case CallMode.Normal:
  491. default:
  492. throw new InternalErrorException("Unreachable case .. reached");
  493. }
  494. }
  495. private int Internal_CheckForTailRequests(Instruction i, int instructionPtr)
  496. {
  497. DynValue tail = m_ValueStack.Peek(0);
  498. if (tail.Type == DataType.TailCallRequest)
  499. {
  500. m_ValueStack.Pop(); // discard tail call request
  501. TailCallData tcd = (TailCallData)tail.UserObject;
  502. m_ValueStack.Push(tcd.Function);
  503. for (int ii = 0; ii < tcd.Args.Length; ii++)
  504. m_ValueStack.Push(tcd.Args[ii]);
  505. //instructionPtr -= 1;
  506. return Internal_ExecCall(tcd.Args.Length, instructionPtr, tcd.Mode);
  507. }
  508. return instructionPtr;
  509. }
  510. private int JumpBool(Instruction i, bool expectedValueForJump, int instructionPtr)
  511. {
  512. DynValue op = m_ValueStack.Pop();
  513. if (op.CastToBool() == expectedValueForJump)
  514. return i.NumVal;
  515. return instructionPtr;
  516. }
  517. private int ExecShortCircuitingOperator(Instruction i, int instructionPtr)
  518. {
  519. bool expectedValToShortCircuit = i.OpCode == OpCode.JtOrPop;
  520. DynValue op = m_ValueStack.Peek();
  521. if (op.CastToBool() == expectedValToShortCircuit)
  522. {
  523. return i.NumVal;
  524. }
  525. else
  526. {
  527. m_ValueStack.Pop();
  528. return instructionPtr;
  529. }
  530. }
  531. private int ExecAdd(Instruction i, int instructionPtr)
  532. {
  533. DynValue r = m_ValueStack.Pop();
  534. DynValue l = m_ValueStack.Pop();
  535. double? rn = r.CastToNumber();
  536. double? ln = l.CastToNumber();
  537. if (ln.HasValue && rn.HasValue)
  538. {
  539. m_ValueStack.Push(DynValue.NewNumber(ln.Value + rn.Value));
  540. return instructionPtr;
  541. }
  542. else
  543. {
  544. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__add", instructionPtr);
  545. if (ip >= 0) return ip;
  546. else throw new ScriptRuntimeException(null, "Arithmetic on non numbers");
  547. }
  548. }
  549. private int ExecSub(Instruction i, int instructionPtr)
  550. {
  551. DynValue r = m_ValueStack.Pop();
  552. DynValue l = m_ValueStack.Pop();
  553. double? rn = r.CastToNumber();
  554. double? ln = l.CastToNumber();
  555. if (ln.HasValue && rn.HasValue)
  556. {
  557. m_ValueStack.Push(DynValue.NewNumber(ln.Value - rn.Value));
  558. return instructionPtr;
  559. }
  560. else
  561. {
  562. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__sub", instructionPtr);
  563. if (ip >= 0) return ip;
  564. else throw new ScriptRuntimeException(null, "Arithmetic on non numbers");
  565. }
  566. }
  567. private int ExecMul(Instruction i, int instructionPtr)
  568. {
  569. DynValue r = m_ValueStack.Pop();
  570. DynValue l = m_ValueStack.Pop();
  571. double? rn = r.CastToNumber();
  572. double? ln = l.CastToNumber();
  573. if (ln.HasValue && rn.HasValue)
  574. {
  575. m_ValueStack.Push(DynValue.NewNumber(ln.Value * rn.Value));
  576. return instructionPtr;
  577. }
  578. else
  579. {
  580. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__mul", instructionPtr);
  581. if (ip >= 0) return ip;
  582. else throw new ScriptRuntimeException(null, "Arithmetic on non numbers");
  583. }
  584. }
  585. private int ExecMod(Instruction i, int instructionPtr)
  586. {
  587. DynValue r = m_ValueStack.Pop();
  588. DynValue l = m_ValueStack.Pop();
  589. double? rn = r.CastToNumber();
  590. double? ln = l.CastToNumber();
  591. if (ln.HasValue && rn.HasValue)
  592. {
  593. m_ValueStack.Push(DynValue.NewNumber(Math.IEEERemainder(ln.Value, rn.Value)));
  594. return instructionPtr;
  595. }
  596. else
  597. {
  598. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__div", instructionPtr);
  599. if (ip >= 0) return ip;
  600. else throw new ScriptRuntimeException(null, "Arithmetic on non numbers");
  601. }
  602. }
  603. private int ExecDiv(Instruction i, int instructionPtr)
  604. {
  605. DynValue r = m_ValueStack.Pop();
  606. DynValue l = m_ValueStack.Pop();
  607. double? rn = r.CastToNumber();
  608. double? ln = l.CastToNumber();
  609. if (ln.HasValue && rn.HasValue)
  610. {
  611. m_ValueStack.Push(DynValue.NewNumber(ln.Value / rn.Value));
  612. return instructionPtr;
  613. }
  614. else
  615. {
  616. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__div", instructionPtr);
  617. if (ip >= 0) return ip;
  618. else throw new ScriptRuntimeException(null, "Arithmetic on non numbers");
  619. }
  620. }
  621. private int ExecPower(Instruction i, int instructionPtr)
  622. {
  623. DynValue r = m_ValueStack.Pop();
  624. DynValue l = m_ValueStack.Pop();
  625. double? rn = r.CastToNumber();
  626. double? ln = l.CastToNumber();
  627. if (ln.HasValue && rn.HasValue)
  628. {
  629. m_ValueStack.Push(DynValue.NewNumber(Math.Pow(ln.Value, rn.Value)));
  630. return instructionPtr;
  631. }
  632. else
  633. {
  634. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__pow", instructionPtr);
  635. if (ip >= 0) return ip;
  636. else throw new ScriptRuntimeException(null, "Arithmetic on non numbers");
  637. }
  638. }
  639. private int ExecNeg(Instruction i, int instructionPtr)
  640. {
  641. DynValue r = m_ValueStack.Pop();
  642. double? rn = r.CastToNumber();
  643. if (rn.HasValue)
  644. {
  645. m_ValueStack.Push(DynValue.NewNumber(-rn.Value));
  646. return instructionPtr;
  647. }
  648. else
  649. {
  650. int ip = Internal_InvokeUnaryMetaMethod(r, "__unm", instructionPtr);
  651. if (ip >= 0) return ip;
  652. else throw new ScriptRuntimeException(null, "Arithmetic on non number");
  653. }
  654. }
  655. private int ExecEq(Instruction i, int instructionPtr)
  656. {
  657. DynValue r = m_ValueStack.Pop();
  658. DynValue l = m_ValueStack.Pop();
  659. if (object.ReferenceEquals(r, l))
  660. {
  661. m_ValueStack.Push(DynValue.True);
  662. }
  663. else if (r.Type != l.Type)
  664. {
  665. m_ValueStack.Push(DynValue.False);
  666. }
  667. else if ((l.Type == DataType.Table || l.Type == DataType.UserData) && (l.MetaTable != null) && (l.MetaTable == r.MetaTable))
  668. {
  669. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__eq", instructionPtr);
  670. if (ip < 0)
  671. m_ValueStack.Push(DynValue.NewBoolean(r.Equals(l)));
  672. else
  673. return ip;
  674. }
  675. else
  676. {
  677. m_ValueStack.Push(DynValue.NewBoolean(r.Equals(l)));
  678. }
  679. return instructionPtr;
  680. }
  681. private int ExecLess(Instruction i, int instructionPtr)
  682. {
  683. DynValue r = m_ValueStack.Pop();
  684. DynValue l = m_ValueStack.Pop();
  685. if (l.Type == DataType.Number && r.Type == DataType.Number)
  686. {
  687. m_ValueStack.Push(DynValue.NewBoolean(l.Number < r.Number));
  688. }
  689. else if (l.Type == DataType.String && r.Type == DataType.String)
  690. {
  691. m_ValueStack.Push(DynValue.NewBoolean(l.String.CompareTo(r.String) < 0));
  692. }
  693. else
  694. {
  695. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__lt", instructionPtr);
  696. if (ip < 0)
  697. throw new ScriptRuntimeException(null, "Can't compare on non number non string");
  698. else
  699. return ip;
  700. }
  701. return instructionPtr;
  702. }
  703. private int ExecLessEq(Instruction i, int instructionPtr)
  704. {
  705. DynValue r = m_ValueStack.Pop();
  706. DynValue l = m_ValueStack.Pop();
  707. if (l.Type == DataType.Number && r.Type == DataType.Number)
  708. {
  709. m_ValueStack.Push(DynValue.NewBoolean(l.Number <= r.Number));
  710. }
  711. else if (l.Type == DataType.String && r.Type == DataType.String)
  712. {
  713. m_ValueStack.Push(DynValue.NewBoolean(l.String.CompareTo(r.String) <= 0));
  714. }
  715. else
  716. {
  717. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__le", instructionPtr);
  718. if (ip < 0)
  719. {
  720. ip = Internal_InvokeBinaryMetaMethod(r, l, "__lt", instructionPtr);
  721. if (ip < 0)
  722. throw new ScriptRuntimeException(null, "Can't compare on non number non string");
  723. else
  724. return ip;
  725. }
  726. else
  727. return ip;
  728. }
  729. return instructionPtr;
  730. }
  731. private int ExecLen(Instruction i, int instructionPtr)
  732. {
  733. DynValue r = m_ValueStack.Pop();
  734. if (r.Type == DataType.String)
  735. m_ValueStack.Push(DynValue.NewNumber(r.String.Length));
  736. else
  737. {
  738. int ip = Internal_InvokeUnaryMetaMethod(r, "__len", instructionPtr);
  739. if (ip >= 0)
  740. return ip;
  741. else if (r.Type == DataType.Table)
  742. m_ValueStack.Push(DynValue.NewNumber(r.Table.Length));
  743. else
  744. throw new ScriptRuntimeException(null, "Arithmetic on non number");
  745. }
  746. return instructionPtr;
  747. }
  748. private int ExecConcat(Instruction i, int instructionPtr)
  749. {
  750. DynValue r = m_ValueStack.Pop();
  751. DynValue l = m_ValueStack.Pop();
  752. string rs = r.CastToString();
  753. string ls = l.CastToString();
  754. if (rs != null && ls != null)
  755. {
  756. m_ValueStack.Push(DynValue.NewString(ls + rs));
  757. return instructionPtr;
  758. }
  759. else
  760. {
  761. int ip = Internal_InvokeBinaryMetaMethod(l, r, "__concat", instructionPtr);
  762. if (ip >= 0) return ip;
  763. else throw new ScriptRuntimeException(null, "Concatenation on non strings");
  764. }
  765. }
  766. private void ExecTblInitI(Instruction i)
  767. {
  768. // stack: tbl - val
  769. DynValue val = m_ValueStack.Pop();
  770. DynValue tbl = m_ValueStack.Peek();
  771. if (tbl.Type != DataType.Table)
  772. throw new InternalErrorException("Unexpected type in table ctor : {0}", tbl);
  773. tbl.Table.InitNextArrayKeys(val);
  774. }
  775. private void ExecTblInitN(Instruction i)
  776. {
  777. // stack: tbl - key - val
  778. DynValue val = m_ValueStack.Pop();
  779. DynValue key = m_ValueStack.Pop();
  780. DynValue tbl = m_ValueStack.Peek();
  781. if (tbl.Type != DataType.Table)
  782. throw new InternalErrorException("Unexpected type in table ctor : {0}", tbl);
  783. tbl.Table[key] = val.ToScalar();
  784. }
  785. private int ExecIndexSet(Instruction i, int instructionPtr)
  786. {
  787. int nestedMetaOps = 100; // sanity check, to avoid potential infinite loop here
  788. // stack: vals.. - base - index
  789. DynValue idx = i.Value ?? m_ValueStack.Pop();
  790. DynValue obj = m_ValueStack.Pop();
  791. var value = GetStoreValue(i);
  792. DynValue h = null;
  793. while (nestedMetaOps > 0)
  794. {
  795. --nestedMetaOps;
  796. if (obj.Type == DataType.Table)
  797. {
  798. if (!obj.Table[idx].IsNil())
  799. {
  800. obj.Table[idx] = value;
  801. return instructionPtr;
  802. }
  803. if (obj.MetaTable != null)
  804. h = obj.MetaTable.RawGet("__newindex");
  805. if (h == null || h.IsNil())
  806. {
  807. obj.Table[idx] = value;
  808. return instructionPtr;
  809. }
  810. }
  811. else
  812. {
  813. h = obj.MetaTable.RawGet("__newindex");
  814. if (h == null || h.IsNil())
  815. throw new ScriptRuntimeException("Can't index non table: {0}", obj);
  816. }
  817. if (h.Type == DataType.Function || h.Type == DataType.ClrFunction)
  818. {
  819. m_ValueStack.Push(h);
  820. m_ValueStack.Push(obj);
  821. m_ValueStack.Push(idx);
  822. m_ValueStack.Push(value);
  823. return Internal_ExecCall(3, instructionPtr);
  824. }
  825. else
  826. {
  827. obj = h;
  828. h = null;
  829. }
  830. }
  831. throw new ScriptRuntimeException("__newindex returning too many nested tables");
  832. }
  833. private int ExecIndex(Instruction i, int instructionPtr)
  834. {
  835. int nestedMetaOps = 100; // sanity check, to avoid potential infinite loop here
  836. // stack: base - index
  837. DynValue idx = i.Value ?? m_ValueStack.Pop();
  838. DynValue obj = m_ValueStack.Pop();
  839. DynValue h = null;
  840. while (nestedMetaOps > 0)
  841. {
  842. --nestedMetaOps;
  843. if (obj.Type == DataType.Table)
  844. {
  845. var v = obj.Table[idx];
  846. if (!v.IsNil())
  847. {
  848. m_ValueStack.Push(v);
  849. return instructionPtr;
  850. }
  851. if (obj.MetaTable != null)
  852. h = obj.MetaTable.RawGet("__index");
  853. if (h == null || h.IsNil())
  854. {
  855. m_ValueStack.Push(DynValue.NewNil());
  856. return instructionPtr;
  857. }
  858. }
  859. else
  860. {
  861. if (obj.MetaTable != null)
  862. h = obj.MetaTable.RawGet("__index");
  863. if (h == null || h.IsNil())
  864. throw new ScriptRuntimeException("Can't index non table: {0}", obj);
  865. }
  866. if (h.Type == DataType.Function || h.Type == DataType.ClrFunction)
  867. {
  868. m_ValueStack.Push(h);
  869. m_ValueStack.Push(obj);
  870. m_ValueStack.Push(idx);
  871. return Internal_ExecCall(2, instructionPtr);
  872. }
  873. else
  874. {
  875. obj = h;
  876. h = null;
  877. }
  878. }
  879. throw new ScriptRuntimeException("__index returning too many nested tables");
  880. }
  881. }
  882. }