FunctionDefinitionExpression.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using MoonSharp.Interpreter.Debugging;
  6. using MoonSharp.Interpreter.Execution;
  7. using MoonSharp.Interpreter.Execution.VM;
  8. using MoonSharp.Interpreter.Tree.Statements;
  9. namespace MoonSharp.Interpreter.Tree.Expressions
  10. {
  11. class FunctionDefinitionExpression : Expression, IClosureBuilder
  12. {
  13. SymbolRef[] m_ParamNames = null;
  14. Statement m_Statement;
  15. RuntimeScopeFrame m_StackFrame;
  16. List<SymbolRef> m_Closure = new List<SymbolRef>();
  17. bool m_HasVarArgs = false;
  18. Instruction m_ClosureInstruction = null;
  19. Table m_GlobalEnv;
  20. SymbolRef m_Env;
  21. SourceRef m_Begin, m_End;
  22. public FunctionDefinitionExpression(ScriptLoadingContext lcontext, Table globalContext)
  23. : this(lcontext, false, globalContext, false)
  24. { }
  25. public FunctionDefinitionExpression(ScriptLoadingContext lcontext, bool pushSelfParam, bool isLambda)
  26. : this(lcontext, pushSelfParam, null, isLambda)
  27. { }
  28. private FunctionDefinitionExpression(ScriptLoadingContext lcontext, bool pushSelfParam, Table globalContext, bool isLambda)
  29. : base(lcontext)
  30. {
  31. if (globalContext != null)
  32. CheckTokenType(lcontext, TokenType.Function);
  33. // here lexer should be at the '(' or at the '|'
  34. Token openRound = CheckTokenType(lcontext, isLambda ? TokenType.Lambda : TokenType.Brk_Open_Round);
  35. List<string> paramnames = BuildParamList(lcontext, pushSelfParam, openRound, isLambda);
  36. // here lexer is at first token of body
  37. m_Begin = openRound.GetSourceRefUpTo(lcontext.Lexer.Current);
  38. // create scope
  39. lcontext.Scope.PushFunction(this, m_HasVarArgs);
  40. if (globalContext != null)
  41. {
  42. m_GlobalEnv = globalContext;
  43. m_Env = lcontext.Scope.DefineLocal(WellKnownSymbols.ENV);
  44. }
  45. else
  46. {
  47. lcontext.Scope.ForceEnvUpValue();
  48. }
  49. m_ParamNames = DefineArguments(paramnames, lcontext);
  50. if(isLambda)
  51. m_Statement = CreateLambdaBody(lcontext);
  52. else
  53. m_Statement = CreateBody(lcontext);
  54. m_StackFrame = lcontext.Scope.PopFunction();
  55. lcontext.Source.Refs.Add(m_Begin);
  56. lcontext.Source.Refs.Add(m_End);
  57. }
  58. private Statement CreateLambdaBody(ScriptLoadingContext lcontext)
  59. {
  60. Token start = lcontext.Lexer.Current;
  61. Expression e = Expression.Expr(lcontext);
  62. Token end = lcontext.Lexer.Current;
  63. SourceRef sref = start.GetSourceRefUpTo(end);
  64. Statement s = new ReturnStatement(lcontext, e, sref);
  65. return s;
  66. }
  67. private Statement CreateBody(ScriptLoadingContext lcontext)
  68. {
  69. Statement s = new CompositeStatement(lcontext);
  70. if (lcontext.Lexer.Current.Type != TokenType.End)
  71. throw new SyntaxErrorException(lcontext.Lexer.Current, "'end' expected near '{0}'", lcontext.Lexer.Current.Text)
  72. {
  73. IsPrematureStreamTermination = (lcontext.Lexer.Current.Type == TokenType.Eof)
  74. };
  75. m_End = lcontext.Lexer.Current.GetSourceRef();
  76. lcontext.Lexer.Next();
  77. return s;
  78. }
  79. private List<string> BuildParamList(ScriptLoadingContext lcontext, bool pushSelfParam, Token openBracketToken, bool isLambda)
  80. {
  81. TokenType closeToken = isLambda ? TokenType.Lambda : TokenType.Brk_Close_Round;
  82. List<string> paramnames = new List<string>();
  83. // method decls with ':' must push an implicit 'self' param
  84. if (pushSelfParam)
  85. paramnames.Add("self");
  86. while (lcontext.Lexer.Current.Type != closeToken)
  87. {
  88. Token t = lcontext.Lexer.Current;
  89. if (t.Type == TokenType.Name)
  90. {
  91. paramnames.Add(t.Text);
  92. }
  93. else if (t.Type == TokenType.VarArgs)
  94. {
  95. m_HasVarArgs = true;
  96. paramnames.Add(WellKnownSymbols.VARARGS);
  97. }
  98. else
  99. UnexpectedTokenType(t);
  100. lcontext.Lexer.Next();
  101. t = lcontext.Lexer.Current;
  102. if (t.Type == TokenType.Comma)
  103. {
  104. lcontext.Lexer.Next();
  105. }
  106. else
  107. {
  108. CheckMatch(lcontext, openBracketToken, closeToken, isLambda ? "|" : ")");
  109. break;
  110. }
  111. }
  112. if (lcontext.Lexer.Current.Type == closeToken)
  113. lcontext.Lexer.Next();
  114. return paramnames;
  115. }
  116. private SymbolRef[] DefineArguments(List<string> paramnames, ScriptLoadingContext lcontext)
  117. {
  118. HashSet<string> names = new HashSet<string>();
  119. SymbolRef[] ret = new SymbolRef[paramnames.Count];
  120. for (int i = paramnames.Count - 1; i >= 0; i--)
  121. {
  122. if (!names.Add(paramnames[i]))
  123. paramnames[i] = paramnames[i] + "@" + i.ToString();
  124. ret[i] = lcontext.Scope.DefineLocal(paramnames[i]);
  125. }
  126. return ret;
  127. }
  128. public SymbolRef CreateUpvalue(BuildTimeScope scope, SymbolRef symbol)
  129. {
  130. for (int i = 0; i < m_Closure.Count; i++)
  131. {
  132. if (m_Closure[i].i_Name == symbol.i_Name)
  133. {
  134. return SymbolRef.Upvalue(symbol.i_Name, i);
  135. }
  136. }
  137. m_Closure.Add(symbol);
  138. if (m_ClosureInstruction != null)
  139. {
  140. m_ClosureInstruction.SymbolList = m_Closure.ToArray();
  141. }
  142. return SymbolRef.Upvalue(symbol.i_Name, m_Closure.Count - 1);
  143. }
  144. public override DynValue Eval(ScriptExecutionContext context)
  145. {
  146. throw new DynamicExpressionException("Dynamic Expressions cannot define new functions.");
  147. }
  148. public int CompileBody(ByteCode bc, string friendlyName)
  149. {
  150. string funcName = friendlyName ?? ("<" + this.m_Begin.FormatLocation(bc.Script, true) + ">");
  151. bc.PushSourceRef(m_Begin);
  152. Instruction I = bc.Emit_Jump(OpCode.Jump, -1);
  153. Instruction meta = bc.Emit_FuncMeta(funcName);
  154. int metaip = bc.GetJumpPointForLastInstruction();
  155. bc.Emit_BeginFn(m_StackFrame);
  156. bc.LoopTracker.Loops.Push(new LoopBoundary());
  157. int entryPoint = bc.GetJumpPointForLastInstruction();
  158. if (m_GlobalEnv != null)
  159. {
  160. bc.Emit_Literal(DynValue.NewTable(m_GlobalEnv));
  161. bc.Emit_Store(m_Env, 0, 0);
  162. bc.Emit_Pop();
  163. }
  164. if (m_ParamNames.Length > 0)
  165. bc.Emit_Args(m_ParamNames);
  166. m_Statement.Compile(bc);
  167. bc.PopSourceRef();
  168. bc.PushSourceRef(m_End);
  169. bc.Emit_Ret(0);
  170. bc.LoopTracker.Loops.Pop();
  171. I.NumVal = bc.GetJumpPointForNextInstruction();
  172. meta.NumVal = bc.GetJumpPointForLastInstruction() - metaip;
  173. bc.PopSourceRef();
  174. return entryPoint;
  175. }
  176. public int Compile(ByteCode bc, Func<int> afterDecl, string friendlyName)
  177. {
  178. using (bc.EnterSource(m_Begin))
  179. {
  180. SymbolRef[] symbs = m_Closure
  181. //.Select((s, idx) => s.CloneLocalAndSetFrame(m_ClosureFrames[idx]))
  182. .ToArray();
  183. m_ClosureInstruction = bc.Emit_Closure(symbs, bc.GetJumpPointForNextInstruction());
  184. int ops = afterDecl();
  185. m_ClosureInstruction.NumVal += 2 + ops;
  186. }
  187. return CompileBody(bc, friendlyName);
  188. }
  189. public override void Compile(ByteCode bc)
  190. {
  191. Compile(bc, () => 0, null);
  192. }
  193. }
  194. }