JintFunctionDefinition.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. using System.Runtime.CompilerServices;
  2. using Esprima.Ast;
  3. using Jint.Native;
  4. using Jint.Native.Argument;
  5. using Jint.Native.Function;
  6. using Jint.Native.Promise;
  7. using Jint.Runtime.Environments;
  8. using Jint.Runtime.Interpreter.Expressions;
  9. namespace Jint.Runtime.Interpreter;
  10. /// <summary>
  11. /// Works as memento for function execution. Optimization to cache things that don't change.
  12. /// </summary>
  13. internal sealed class JintFunctionDefinition
  14. {
  15. private JintExpression? _bodyExpression;
  16. private JintStatementList? _bodyStatementList;
  17. public readonly string? Name;
  18. public readonly IFunction Function;
  19. public JintFunctionDefinition(IFunction function)
  20. {
  21. Function = function;
  22. Name = !string.IsNullOrEmpty(function.Id?.Name) ? function.Id!.Name : null;
  23. }
  24. public bool Strict => Function.Strict;
  25. public FunctionThisMode ThisMode => Function.Strict ? FunctionThisMode.Strict : FunctionThisMode.Global;
  26. /// <summary>
  27. /// https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  28. /// </summary>
  29. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  30. internal Completion EvaluateBody(EvaluationContext context, FunctionInstance functionObject, JsValue[] argumentsList)
  31. {
  32. Completion result;
  33. ArgumentsInstance? argumentsInstance = null;
  34. if (Function.Expression)
  35. {
  36. // https://tc39.es/ecma262/#sec-runtime-semantics-evaluateconcisebody
  37. _bodyExpression ??= JintExpression.Build((Expression) Function.Body);
  38. if (Function.Async)
  39. {
  40. var promiseCapability = PromiseConstructor.NewPromiseCapability(context.Engine, context.Engine.Realm.Intrinsics.Promise);
  41. AsyncFunctionStart(context, promiseCapability, context =>
  42. {
  43. context.Engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  44. return new Completion(CompletionType.Return, _bodyExpression.GetValue(context), _bodyExpression._expression);
  45. });
  46. result = new Completion(CompletionType.Return, promiseCapability.PromiseInstance, Function.Body);
  47. }
  48. else
  49. {
  50. argumentsInstance = context.Engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  51. var jsValue = _bodyExpression.GetValue(context).Clone();
  52. result = new Completion(CompletionType.Return, jsValue, Function.Body);
  53. }
  54. }
  55. else if (Function.Generator)
  56. {
  57. // TODO generators
  58. // result = EvaluateGeneratorBody(functionObject, argumentsList);
  59. argumentsInstance = context.Engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  60. _bodyStatementList ??= new JintStatementList(Function);
  61. result = _bodyStatementList.Execute(context);
  62. }
  63. else
  64. {
  65. if (Function.Async)
  66. {
  67. var promiseCapability = PromiseConstructor.NewPromiseCapability(context.Engine, context.Engine.Realm.Intrinsics.Promise);
  68. _bodyStatementList ??= new JintStatementList(Function);
  69. AsyncFunctionStart(context, promiseCapability, context =>
  70. {
  71. context.Engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  72. return _bodyStatementList.Execute(context);
  73. });
  74. result = new Completion(CompletionType.Return, promiseCapability.PromiseInstance, Function.Body);
  75. }
  76. else
  77. {
  78. // https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody
  79. argumentsInstance = context.Engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  80. _bodyStatementList ??= new JintStatementList(Function);
  81. result = _bodyStatementList.Execute(context);
  82. }
  83. }
  84. argumentsInstance?.FunctionWasCalled();
  85. return result;
  86. }
  87. /// <summary>
  88. /// https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
  89. /// </summary>
  90. private static void AsyncFunctionStart(EvaluationContext context, PromiseCapability promiseCapability, Func<EvaluationContext, Completion> asyncFunctionBody)
  91. {
  92. var runningContext = context.Engine.ExecutionContext;
  93. var asyncContext = runningContext;
  94. AsyncBlockStart(context, promiseCapability, asyncFunctionBody, asyncContext);
  95. }
  96. /// <summary>
  97. /// https://tc39.es/ecma262/#sec-asyncblockstart
  98. /// </summary>
  99. private static void AsyncBlockStart(EvaluationContext context, PromiseCapability promiseCapability, Func<EvaluationContext, Completion> asyncBody, in ExecutionContext asyncContext)
  100. {
  101. var runningContext = context.Engine.ExecutionContext;
  102. // Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution contxt the following steps will be performed:
  103. Completion result;
  104. try
  105. {
  106. result = asyncBody(context);
  107. }
  108. catch (JavaScriptException e)
  109. {
  110. promiseCapability.Reject.Call(JsValue.Undefined, new[] { e.Error });
  111. return;
  112. }
  113. if (result.Type == CompletionType.Normal)
  114. {
  115. promiseCapability.Resolve.Call(JsValue.Undefined, new[] { JsValue.Undefined });
  116. }
  117. else if (result.Type == CompletionType.Return)
  118. {
  119. promiseCapability.Resolve.Call(JsValue.Undefined, new[] { result.Value });
  120. }
  121. else
  122. {
  123. promiseCapability.Reject.Call(JsValue.Undefined, new[] { result.Value });
  124. }
  125. /*
  126. 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  127. 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
  128. 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context.
  129. 7. Assert: result is a normal completion with a value of unused. The possible sources of this value are Await or, if the async function doesn't await anything, step 3.g above.
  130. 8. Return unused.
  131. */
  132. }
  133. /// <summary>
  134. /// https://tc39.es/ecma262/#sec-runtime-semantics-evaluategeneratorbody
  135. /// </summary>
  136. private Completion EvaluateGeneratorBody(FunctionInstance functionObject, JsValue[] argumentsList)
  137. {
  138. ExceptionHelper.ThrowNotImplementedException("generators not implemented");
  139. return default;
  140. }
  141. internal State Initialize()
  142. {
  143. var node = (Node) Function;
  144. var state = (State) (node.AssociatedData ??= BuildState(Function));
  145. return state;
  146. }
  147. internal sealed class State
  148. {
  149. public bool HasRestParameter;
  150. public int Length;
  151. public Key[] ParameterNames = null!;
  152. public bool HasDuplicates;
  153. public bool IsSimpleParameterList;
  154. public bool HasParameterExpressions;
  155. public bool ArgumentsObjectNeeded;
  156. public List<Key>? VarNames;
  157. public LinkedList<JintFunctionDefinition>? FunctionsToInitialize;
  158. public readonly HashSet<Key> FunctionNames = new();
  159. public LexicalVariableDeclaration[] LexicalDeclarations = Array.Empty<LexicalVariableDeclaration>();
  160. public HashSet<Key>? ParameterBindings;
  161. public List<VariableValuePair>? VarsToInitialize;
  162. internal struct VariableValuePair
  163. {
  164. public Key Name;
  165. public JsValue? InitialValue;
  166. }
  167. internal struct LexicalVariableDeclaration
  168. {
  169. public bool IsConstantDeclaration;
  170. public List<string> BoundNames;
  171. }
  172. }
  173. internal static State BuildState(IFunction function)
  174. {
  175. var state = new State();
  176. ProcessParameters(function, state, out var hasArguments);
  177. var hoistingScope = HoistingScope.GetFunctionLevelDeclarations(function.Strict, function);
  178. var functionDeclarations = hoistingScope._functionDeclarations;
  179. var lexicalNames = hoistingScope._lexicalNames;
  180. state.VarNames = hoistingScope._varNames;
  181. LinkedList<JintFunctionDefinition>? functionsToInitialize = null;
  182. if (functionDeclarations != null)
  183. {
  184. functionsToInitialize = new LinkedList<JintFunctionDefinition>();
  185. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  186. {
  187. var d = functionDeclarations[i];
  188. var fn = d.Id!.Name;
  189. if (state.FunctionNames.Add(fn))
  190. {
  191. functionsToInitialize.AddFirst(new JintFunctionDefinition(d));
  192. }
  193. }
  194. }
  195. state.FunctionsToInitialize = functionsToInitialize;
  196. const string ParameterNameArguments = "arguments";
  197. state.ArgumentsObjectNeeded = true;
  198. var thisMode = function.Strict ? FunctionThisMode.Strict : FunctionThisMode.Global;
  199. if (function.Type == Nodes.ArrowFunctionExpression)
  200. {
  201. thisMode = FunctionThisMode.Lexical;
  202. }
  203. if (thisMode == FunctionThisMode.Lexical)
  204. {
  205. state.ArgumentsObjectNeeded = false;
  206. }
  207. else if (hasArguments)
  208. {
  209. state.ArgumentsObjectNeeded = false;
  210. }
  211. else if (!state.HasParameterExpressions)
  212. {
  213. if (state.FunctionNames.Contains(ParameterNameArguments)
  214. || lexicalNames?.Contains(ParameterNameArguments) == true)
  215. {
  216. state.ArgumentsObjectNeeded = false;
  217. }
  218. }
  219. if (state.ArgumentsObjectNeeded)
  220. {
  221. // just one extra check...
  222. state.ArgumentsObjectNeeded = ArgumentsUsageAstVisitor.HasArgumentsReference(function);
  223. }
  224. var parameterBindings = new HashSet<Key>(state.ParameterNames);
  225. if (state.ArgumentsObjectNeeded)
  226. {
  227. parameterBindings.Add(KnownKeys.Arguments);
  228. }
  229. state.ParameterBindings = parameterBindings;
  230. var varsToInitialize = new List<State.VariableValuePair>();
  231. if (!state.HasParameterExpressions)
  232. {
  233. var instantiatedVarNames = state.VarNames != null
  234. ? new HashSet<Key>(state.ParameterBindings)
  235. : new HashSet<Key>();
  236. for (var i = 0; i < state.VarNames?.Count; i++)
  237. {
  238. var n = state.VarNames[i];
  239. if (instantiatedVarNames.Add(n))
  240. {
  241. varsToInitialize.Add(new State.VariableValuePair
  242. {
  243. Name = n
  244. });
  245. }
  246. }
  247. }
  248. else
  249. {
  250. var instantiatedVarNames = state.VarNames != null
  251. ? new HashSet<Key>(state.ParameterBindings)
  252. : null;
  253. for (var i = 0; i < state.VarNames?.Count; i++)
  254. {
  255. var n = state.VarNames[i];
  256. if (instantiatedVarNames!.Add(n))
  257. {
  258. JsValue? initialValue = null;
  259. if (!state.ParameterBindings.Contains(n) || state.FunctionNames.Contains(n))
  260. {
  261. initialValue = JsValue.Undefined;
  262. }
  263. varsToInitialize.Add(new State.VariableValuePair
  264. {
  265. Name = n,
  266. InitialValue = initialValue
  267. });
  268. }
  269. }
  270. }
  271. state.VarsToInitialize = varsToInitialize;
  272. if (hoistingScope._lexicalDeclarations != null)
  273. {
  274. var _lexicalDeclarations = hoistingScope._lexicalDeclarations;
  275. var lexicalDeclarationsCount = _lexicalDeclarations.Count;
  276. var declarations = new State.LexicalVariableDeclaration[lexicalDeclarationsCount];
  277. for (var i = 0; i < lexicalDeclarationsCount; i++)
  278. {
  279. var d = _lexicalDeclarations[i];
  280. var boundNames = new List<string>();
  281. d.GetBoundNames(boundNames);
  282. declarations[i] = new State.LexicalVariableDeclaration
  283. {
  284. IsConstantDeclaration = d.IsConstantDeclaration(),
  285. BoundNames = boundNames
  286. };
  287. }
  288. state.LexicalDeclarations = declarations;
  289. }
  290. return state;
  291. }
  292. private static void GetBoundNames(
  293. Node? parameter,
  294. List<Key> target,
  295. bool checkDuplicates,
  296. ref bool _hasRestParameter,
  297. ref bool _hasParameterExpressions,
  298. ref bool _hasDuplicates,
  299. ref bool hasArguments)
  300. {
  301. if (parameter is Identifier identifier)
  302. {
  303. _hasDuplicates |= checkDuplicates && target.Contains(identifier.Name);
  304. target.Add(identifier.Name);
  305. hasArguments |= identifier.Name == "arguments";
  306. return;
  307. }
  308. while (true)
  309. {
  310. if (parameter is RestElement restElement)
  311. {
  312. _hasRestParameter = true;
  313. _hasParameterExpressions = true;
  314. parameter = restElement.Argument;
  315. continue;
  316. }
  317. if (parameter is ArrayPattern arrayPattern)
  318. {
  319. _hasParameterExpressions = true;
  320. ref readonly var arrayPatternElements = ref arrayPattern.Elements;
  321. for (var i = 0; i < arrayPatternElements.Count; i++)
  322. {
  323. var expression = arrayPatternElements[i];
  324. GetBoundNames(
  325. expression,
  326. target,
  327. checkDuplicates,
  328. ref _hasRestParameter,
  329. ref _hasParameterExpressions,
  330. ref _hasDuplicates,
  331. ref hasArguments);
  332. }
  333. }
  334. else if (parameter is ObjectPattern objectPattern)
  335. {
  336. _hasParameterExpressions = true;
  337. ref readonly var objectPatternProperties = ref objectPattern.Properties;
  338. for (var i = 0; i < objectPatternProperties.Count; i++)
  339. {
  340. var property = objectPatternProperties[i];
  341. if (property is Property p)
  342. {
  343. GetBoundNames(
  344. p.Value,
  345. target,
  346. checkDuplicates,
  347. ref _hasRestParameter,
  348. ref _hasParameterExpressions,
  349. ref _hasDuplicates,
  350. ref hasArguments);
  351. }
  352. else
  353. {
  354. _hasRestParameter = true;
  355. _hasParameterExpressions = true;
  356. parameter = ((RestElement) property).Argument;
  357. continue;
  358. }
  359. }
  360. }
  361. else if (parameter is AssignmentPattern assignmentPattern)
  362. {
  363. _hasParameterExpressions = true;
  364. parameter = assignmentPattern.Left;
  365. continue;
  366. }
  367. break;
  368. }
  369. }
  370. private static void ProcessParameters(
  371. IFunction function,
  372. State state,
  373. out bool hasArguments)
  374. {
  375. hasArguments = false;
  376. state.IsSimpleParameterList = true;
  377. var countParameters = true;
  378. ref readonly var functionDeclarationParams = ref function.Params;
  379. var count = functionDeclarationParams.Count;
  380. var parameterNames = new List<Key>(count);
  381. for (var i = 0; i < count; i++)
  382. {
  383. var parameter = functionDeclarationParams[i];
  384. var type = parameter.Type;
  385. if (type == Nodes.Identifier)
  386. {
  387. var id = (Identifier) parameter;
  388. state.HasDuplicates |= parameterNames.Contains(id.Name);
  389. hasArguments = id.Name == "arguments";
  390. parameterNames.Add(id.Name);
  391. }
  392. else if (type != Nodes.Literal)
  393. {
  394. countParameters &= type != Nodes.AssignmentPattern;
  395. state.IsSimpleParameterList = false;
  396. GetBoundNames(
  397. parameter,
  398. parameterNames,
  399. checkDuplicates: true,
  400. ref state.HasRestParameter,
  401. ref state.HasParameterExpressions,
  402. ref state.HasDuplicates,
  403. ref hasArguments);
  404. }
  405. if (countParameters && type is Nodes.Identifier or Nodes.ObjectPattern or Nodes.ArrayPattern)
  406. {
  407. state.Length++;
  408. }
  409. }
  410. state.ParameterNames = parameterNames.ToArray();
  411. }
  412. private static class ArgumentsUsageAstVisitor
  413. {
  414. public static bool HasArgumentsReference(IFunction function)
  415. {
  416. if (HasArgumentsReference(function.Body))
  417. {
  418. return true;
  419. }
  420. ref readonly var parameters = ref function.Params;
  421. for (var i = 0; i < parameters.Count; ++i)
  422. {
  423. if (HasArgumentsReference(parameters[i]))
  424. {
  425. return true;
  426. }
  427. }
  428. return false;
  429. }
  430. private static bool HasArgumentsReference(Node node)
  431. {
  432. foreach (var childNode in node.ChildNodes)
  433. {
  434. var childType = childNode.Type;
  435. if (childType == Nodes.Identifier)
  436. {
  437. if (((Identifier) childNode).Name == "arguments")
  438. {
  439. return true;
  440. }
  441. }
  442. else if (childType != Nodes.FunctionDeclaration && !childNode.ChildNodes.IsEmpty())
  443. {
  444. if (HasArgumentsReference(childNode))
  445. {
  446. return true;
  447. }
  448. }
  449. }
  450. return false;
  451. }
  452. }
  453. }