SymbolRefExpression.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Antlr4.Runtime.Tree;
  6. using MoonSharp.Interpreter.Execution;
  7. using MoonSharp.Interpreter.Grammar;
  8. namespace MoonSharp.Interpreter.Tree.Expressions
  9. {
  10. class SymbolRefExpression : Expression, IVariable
  11. {
  12. LRef m_Ref;
  13. public SymbolRefExpression(ITerminalNode terminalNode, ScriptLoadingContext lcontext)
  14. : base(terminalNode, lcontext)
  15. {
  16. string varName = terminalNode.GetText();
  17. m_Ref = lcontext.Scope.Find(varName);
  18. if (!m_Ref.IsValid())
  19. {
  20. m_Ref = lcontext.Scope.DefineGlobal(varName);
  21. }
  22. }
  23. public override RValue Eval(RuntimeScope scope)
  24. {
  25. RValue v = scope.Get(m_Ref);
  26. if (v == null)
  27. throw new ScriptRuntimeException(this.TreeNode, "Undefined symbol: {0}", m_Ref.i_Name);
  28. return v;
  29. }
  30. public void SetValue(RuntimeScope scope, RValue rValue)
  31. {
  32. scope.Assign(m_Ref, rValue);
  33. }
  34. public override void Compile(Execution.VM.Chunk bc)
  35. {
  36. bc.Load(m_Ref);
  37. }
  38. public void CompileAssignment(Execution.VM.Chunk bc)
  39. {
  40. bc.Symbol(m_Ref);
  41. }
  42. }
  43. }