JintFunctionDefinition.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. using System;
  2. using System.Collections.Generic;
  3. using Esprima.Ast;
  4. using Jint.Native;
  5. using Jint.Native.Function;
  6. using Jint.Runtime.Interpreter.Expressions;
  7. namespace Jint.Runtime.Interpreter
  8. {
  9. /// <summary>
  10. /// Works as memento for function execution. Optimization to cache things that don't change.
  11. /// </summary>
  12. internal sealed class JintFunctionDefinition
  13. {
  14. private readonly Engine _engine;
  15. private JintExpression _bodyExpression;
  16. private JintStatementList _bodyStatementList;
  17. public readonly string Name;
  18. public readonly bool Strict;
  19. public readonly IFunction Function;
  20. private State _state;
  21. public JintFunctionDefinition(
  22. Engine engine,
  23. IFunction function)
  24. {
  25. _engine = engine;
  26. Function = function;
  27. Name = !string.IsNullOrEmpty(function.Id?.Name) ? function.Id.Name : null;
  28. Strict = function.Strict;
  29. }
  30. public FunctionThisMode ThisMode => Strict ? FunctionThisMode.Strict : FunctionThisMode.Global;
  31. /// <summary>
  32. /// https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
  33. /// </summary>
  34. internal Completion EvaluateBody(EvaluationContext context, FunctionInstance functionObject, JsValue[] argumentsList)
  35. {
  36. Completion result;
  37. if (Function.Expression)
  38. {
  39. result = EvaluateConciseBody(context, functionObject, argumentsList);
  40. }
  41. else if (Function.Generator)
  42. {
  43. result = EvaluateFunctionBody(context, functionObject, argumentsList);
  44. // TODO generators
  45. // result = EvaluateGeneratorBody(functionObject, argumentsList);
  46. }
  47. else
  48. {
  49. result = EvaluateFunctionBody(context, functionObject, argumentsList);
  50. }
  51. return new Completion(result.Type, result.GetValueOrDefault().Clone(), result.Target, result.Location);
  52. }
  53. /// <summary>
  54. /// https://tc39.es/ecma262/#sec-runtime-semantics-evaluategeneratorbody
  55. /// </summary>
  56. private Completion EvaluateGeneratorBody(FunctionInstance functionObject, JsValue[] argumentsList)
  57. {
  58. ExceptionHelper.ThrowNotImplementedException("generators not implemented");
  59. return default;
  60. }
  61. /// <summary>
  62. /// https://tc39.es/ecma262/#sec-runtime-semantics-evaluateconcisebody
  63. /// </summary>
  64. private Completion EvaluateConciseBody(EvaluationContext context, FunctionInstance functionObject, JsValue[] argumentsList)
  65. {
  66. var argumentsInstance = _engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  67. _bodyExpression ??= JintExpression.Build(_engine, (Expression) Function.Body);
  68. var jsValue = _bodyExpression?.GetValue(context).Value ?? Undefined.Instance;
  69. argumentsInstance?.FunctionWasCalled();
  70. return new Completion(CompletionType.Return, jsValue, null, Function.Body.Location);
  71. }
  72. /// <summary>
  73. /// https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody
  74. /// </summary>
  75. private Completion EvaluateFunctionBody(EvaluationContext context, FunctionInstance functionObject, JsValue[] argumentsList)
  76. {
  77. var argumentsInstance = _engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  78. _bodyStatementList ??= new JintStatementList(Function);
  79. var completion = _bodyStatementList.Execute(context);
  80. argumentsInstance?.FunctionWasCalled();
  81. return completion;
  82. }
  83. internal State Initialize(FunctionInstance functionInstance)
  84. {
  85. return _state ??= DoInitialize(functionInstance);
  86. }
  87. internal sealed class State
  88. {
  89. public bool HasRestParameter;
  90. public int Length;
  91. public Key[] ParameterNames;
  92. public bool HasDuplicates;
  93. public bool IsSimpleParameterList;
  94. public bool HasParameterExpressions;
  95. public bool ArgumentsObjectNeeded;
  96. public List<Key> VarNames;
  97. public LinkedList<JintFunctionDefinition> FunctionsToInitialize;
  98. public readonly HashSet<Key> FunctionNames = new();
  99. public LexicalVariableDeclaration[] LexicalDeclarations = Array.Empty<LexicalVariableDeclaration>();
  100. public HashSet<Key> ParameterBindings;
  101. public List<VariableValuePair> VarsToInitialize;
  102. internal struct VariableValuePair
  103. {
  104. public Key Name;
  105. public JsValue InitialValue;
  106. }
  107. internal struct LexicalVariableDeclaration
  108. {
  109. public bool IsConstantDeclaration;
  110. public List<string> BoundNames;
  111. }
  112. }
  113. private State DoInitialize(FunctionInstance functionInstance)
  114. {
  115. var state = new State();
  116. ProcessParameters(Function, state, out var hasArguments);
  117. var hoistingScope = HoistingScope.GetFunctionLevelDeclarations(Function, collectVarNames: true, collectLexicalNames: true);
  118. var functionDeclarations = hoistingScope._functionDeclarations;
  119. var lexicalNames = hoistingScope._lexicalNames;
  120. state.VarNames = hoistingScope._varNames;
  121. LinkedList<JintFunctionDefinition> functionsToInitialize = null;
  122. if (functionDeclarations != null)
  123. {
  124. functionsToInitialize = new LinkedList<JintFunctionDefinition>();
  125. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  126. {
  127. var d = functionDeclarations[i];
  128. var fn = d.Id.Name;
  129. if (state.FunctionNames.Add(fn))
  130. {
  131. functionsToInitialize.AddFirst(new JintFunctionDefinition(_engine, d));
  132. }
  133. }
  134. }
  135. state.FunctionsToInitialize = functionsToInitialize;
  136. const string ParameterNameArguments = "arguments";
  137. state.ArgumentsObjectNeeded = true;
  138. if (functionInstance._thisMode == FunctionThisMode.Lexical)
  139. {
  140. state.ArgumentsObjectNeeded = false;
  141. }
  142. else if (hasArguments)
  143. {
  144. state.ArgumentsObjectNeeded = false;
  145. }
  146. else if (!state.HasParameterExpressions)
  147. {
  148. if (state.FunctionNames.Contains(ParameterNameArguments)
  149. || lexicalNames?.Contains(ParameterNameArguments) == true)
  150. {
  151. state.ArgumentsObjectNeeded = false;
  152. }
  153. }
  154. var parameterBindings = new HashSet<Key>(state.ParameterNames);
  155. if (state.ArgumentsObjectNeeded)
  156. {
  157. parameterBindings.Add(KnownKeys.Arguments);
  158. }
  159. state.ParameterBindings = parameterBindings;
  160. var varsToInitialize = new List<State.VariableValuePair>();
  161. if (!state.HasParameterExpressions)
  162. {
  163. var instantiatedVarNames = state.VarNames != null
  164. ? new HashSet<Key>(state.ParameterBindings)
  165. : new HashSet<Key>();
  166. for (var i = 0; i < state.VarNames?.Count; i++)
  167. {
  168. var n = state.VarNames[i];
  169. if (instantiatedVarNames.Add(n))
  170. {
  171. varsToInitialize.Add(new State.VariableValuePair
  172. {
  173. Name = n
  174. });
  175. }
  176. }
  177. }
  178. else
  179. {
  180. var instantiatedVarNames = state.VarNames != null
  181. ? new HashSet<Key>(state.ParameterBindings)
  182. : null;
  183. for (var i = 0; i < state.VarNames?.Count; i++)
  184. {
  185. var n = state.VarNames[i];
  186. if (instantiatedVarNames.Add(n))
  187. {
  188. JsValue initialValue = null;
  189. if (!state.ParameterBindings.Contains(n) || state.FunctionNames.Contains(n))
  190. {
  191. initialValue = JsValue.Undefined;
  192. }
  193. varsToInitialize.Add(new State.VariableValuePair
  194. {
  195. Name = n,
  196. InitialValue = initialValue
  197. });
  198. }
  199. }
  200. }
  201. state.VarsToInitialize = varsToInitialize;
  202. if (hoistingScope._lexicalDeclarations != null)
  203. {
  204. var _lexicalDeclarations = hoistingScope._lexicalDeclarations;
  205. var lexicalDeclarationsCount = _lexicalDeclarations.Count;
  206. var declarations = new State.LexicalVariableDeclaration[lexicalDeclarationsCount];
  207. for (var i = 0; i < lexicalDeclarationsCount; i++)
  208. {
  209. var d = _lexicalDeclarations[i];
  210. var boundNames = new List<string>();
  211. d.GetBoundNames(boundNames);
  212. declarations[i] = new State.LexicalVariableDeclaration
  213. {
  214. IsConstantDeclaration = d.IsConstantDeclaration(),
  215. BoundNames = boundNames
  216. };
  217. }
  218. state.LexicalDeclarations = declarations;
  219. }
  220. return state;
  221. }
  222. private static void GetBoundNames(
  223. Expression parameter,
  224. List<Key> target,
  225. bool checkDuplicates,
  226. ref bool _hasRestParameter,
  227. ref bool _hasParameterExpressions,
  228. ref bool _hasDuplicates,
  229. ref bool hasArguments)
  230. {
  231. if (parameter is Identifier identifier)
  232. {
  233. _hasDuplicates |= checkDuplicates && target.Contains(identifier.Name);
  234. target.Add(identifier.Name);
  235. hasArguments |= identifier.Name == "arguments";
  236. return;
  237. }
  238. while (true)
  239. {
  240. if (parameter is RestElement restElement)
  241. {
  242. _hasRestParameter = true;
  243. _hasParameterExpressions = true;
  244. parameter = restElement.Argument;
  245. continue;
  246. }
  247. if (parameter is ArrayPattern arrayPattern)
  248. {
  249. _hasParameterExpressions = true;
  250. ref readonly var arrayPatternElements = ref arrayPattern.Elements;
  251. for (var i = 0; i < arrayPatternElements.Count; i++)
  252. {
  253. var expression = arrayPatternElements[i];
  254. GetBoundNames(
  255. expression,
  256. target,
  257. checkDuplicates,
  258. ref _hasRestParameter,
  259. ref _hasParameterExpressions,
  260. ref _hasDuplicates,
  261. ref hasArguments);
  262. }
  263. }
  264. else if (parameter is ObjectPattern objectPattern)
  265. {
  266. _hasParameterExpressions = true;
  267. ref readonly var objectPatternProperties = ref objectPattern.Properties;
  268. for (var i = 0; i < objectPatternProperties.Count; i++)
  269. {
  270. var property = objectPatternProperties[i];
  271. if (property is Property p)
  272. {
  273. GetBoundNames(
  274. p.Value,
  275. target,
  276. checkDuplicates,
  277. ref _hasRestParameter,
  278. ref _hasParameterExpressions,
  279. ref _hasDuplicates,
  280. ref hasArguments);
  281. }
  282. else
  283. {
  284. _hasRestParameter = true;
  285. _hasParameterExpressions = true;
  286. parameter = ((RestElement) property).Argument;
  287. continue;
  288. }
  289. }
  290. }
  291. else if (parameter is AssignmentPattern assignmentPattern)
  292. {
  293. _hasParameterExpressions = true;
  294. parameter = assignmentPattern.Left;
  295. continue;
  296. }
  297. break;
  298. }
  299. }
  300. private static void ProcessParameters(
  301. IFunction function,
  302. State state,
  303. out bool hasArguments)
  304. {
  305. hasArguments = false;
  306. state.IsSimpleParameterList = true;
  307. ref readonly var functionDeclarationParams = ref function.Params;
  308. var count = functionDeclarationParams.Count;
  309. var parameterNames = new List<Key>(count);
  310. for (var i = 0; i < count; i++)
  311. {
  312. var parameter = functionDeclarationParams[i];
  313. if (parameter is Identifier id)
  314. {
  315. state.HasDuplicates |= parameterNames.Contains(id.Name);
  316. hasArguments = id.Name == "arguments";
  317. parameterNames.Add(id.Name);
  318. if (state.IsSimpleParameterList)
  319. {
  320. state.Length++;
  321. }
  322. }
  323. else if (parameter.Type != Nodes.Literal)
  324. {
  325. state.IsSimpleParameterList = false;
  326. GetBoundNames(
  327. parameter,
  328. parameterNames,
  329. checkDuplicates: true,
  330. ref state.HasRestParameter,
  331. ref state.HasParameterExpressions,
  332. ref state.HasDuplicates,
  333. ref hasArguments);
  334. }
  335. }
  336. state.ParameterNames = parameterNames.ToArray();
  337. }
  338. }
  339. }