JintFunctionDefinition.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. using System.Runtime.CompilerServices;
  2. using Jint.Native;
  3. using Jint.Native.Function;
  4. using Jint.Native.Generator;
  5. using Jint.Native.Promise;
  6. using Jint.Runtime.Environments;
  7. using Jint.Runtime.Interpreter.Expressions;
  8. namespace Jint.Runtime.Interpreter;
  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 JintExpression? _bodyExpression;
  15. private JintStatementList? _bodyStatementList;
  16. public readonly string? Name;
  17. public readonly IFunction Function;
  18. public JintFunctionDefinition(IFunction function)
  19. {
  20. Function = function;
  21. Name = !string.IsNullOrEmpty(function.Id?.Name) ? function.Id!.Name : null;
  22. }
  23. public bool Strict => Function.IsStrict();
  24. public FunctionThisMode ThisMode => Function.IsStrict() ? FunctionThisMode.Strict : FunctionThisMode.Global;
  25. /// <summary>
  26. /// https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  27. /// </summary>
  28. [MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions) 512)]
  29. internal Completion EvaluateBody(EvaluationContext context, Function functionObject, JsCallArguments argumentsList)
  30. {
  31. Completion result;
  32. JsArguments? argumentsInstance = null;
  33. if (Function.Body is not FunctionBody)
  34. {
  35. // https://tc39.es/ecma262/#sec-runtime-semantics-evaluateconcisebody
  36. _bodyExpression ??= JintExpression.Build((Expression) Function.Body);
  37. if (Function.Async)
  38. {
  39. // local copies to prevent capturing closure created on top of method
  40. var function = functionObject;
  41. var jsValues = argumentsList;
  42. var promiseCapability = PromiseConstructor.NewPromiseCapability(context.Engine, context.Engine.Realm.Intrinsics.Promise);
  43. AsyncFunctionStart(context, promiseCapability, context =>
  44. {
  45. context.Engine.FunctionDeclarationInstantiation(function, jsValues);
  46. context.RunBeforeExecuteStatementChecks(Function.Body);
  47. var jsValue = _bodyExpression.GetValue(context).Clone();
  48. return new Completion(CompletionType.Return, jsValue, _bodyExpression._expression);
  49. });
  50. result = new Completion(CompletionType.Return, promiseCapability.PromiseInstance, Function.Body);
  51. }
  52. else
  53. {
  54. argumentsInstance = context.Engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  55. context.RunBeforeExecuteStatementChecks(Function.Body);
  56. var jsValue = _bodyExpression.GetValue(context).Clone();
  57. result = new Completion(CompletionType.Return, jsValue, Function.Body);
  58. }
  59. }
  60. else if (Function.Generator)
  61. {
  62. result = EvaluateGeneratorBody(context, functionObject, argumentsList);
  63. }
  64. else
  65. {
  66. if (Function.Async)
  67. {
  68. // local copies to prevent capturing closure created on top of method
  69. var function = functionObject;
  70. var arguments = argumentsList;
  71. var promiseCapability = PromiseConstructor.NewPromiseCapability(context.Engine, context.Engine.Realm.Intrinsics.Promise);
  72. _bodyStatementList ??= new JintStatementList(Function);
  73. AsyncFunctionStart(context, promiseCapability, context =>
  74. {
  75. context.Engine.FunctionDeclarationInstantiation(function, arguments);
  76. return _bodyStatementList.Execute(context);
  77. });
  78. result = new Completion(CompletionType.Return, promiseCapability.PromiseInstance, Function.Body);
  79. }
  80. else
  81. {
  82. // https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody
  83. argumentsInstance = context.Engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  84. _bodyStatementList ??= new JintStatementList(Function);
  85. result = _bodyStatementList.Execute(context);
  86. }
  87. }
  88. argumentsInstance?.FunctionWasCalled();
  89. return result;
  90. }
  91. /// <summary>
  92. /// https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
  93. /// </summary>
  94. private static void AsyncFunctionStart(EvaluationContext context, PromiseCapability promiseCapability, Func<EvaluationContext, Completion> asyncFunctionBody)
  95. {
  96. var runningContext = context.Engine.ExecutionContext;
  97. var asyncContext = runningContext;
  98. AsyncBlockStart(context, promiseCapability, asyncFunctionBody, asyncContext);
  99. }
  100. /// <summary>
  101. /// https://tc39.es/ecma262/#sec-asyncblockstart
  102. /// </summary>
  103. private static void AsyncBlockStart(
  104. EvaluationContext context,
  105. PromiseCapability promiseCapability,
  106. Func<EvaluationContext, Completion> asyncBody,
  107. in ExecutionContext asyncContext)
  108. {
  109. var runningContext = context.Engine.ExecutionContext;
  110. // Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution contxt the following steps will be performed:
  111. Completion result;
  112. try
  113. {
  114. result = asyncBody(context);
  115. }
  116. catch (JavaScriptException e)
  117. {
  118. promiseCapability.Reject.Call(JsValue.Undefined, e.Error);
  119. return;
  120. }
  121. if (result.Type == CompletionType.Normal)
  122. {
  123. promiseCapability.Resolve.Call(JsValue.Undefined, JsValue.Undefined);
  124. }
  125. else if (result.Type == CompletionType.Return)
  126. {
  127. promiseCapability.Resolve.Call(JsValue.Undefined, result.Value);
  128. }
  129. else
  130. {
  131. promiseCapability.Reject.Call(JsValue.Undefined, result.Value);
  132. }
  133. /*
  134. 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  135. 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
  136. 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context.
  137. 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.
  138. 8. Return unused.
  139. */
  140. }
  141. /// <summary>
  142. /// https://tc39.es/ecma262/#sec-runtime-semantics-evaluategeneratorbody
  143. /// </summary>
  144. private Completion EvaluateGeneratorBody(
  145. EvaluationContext context,
  146. Function functionObject,
  147. JsCallArguments argumentsList)
  148. {
  149. var engine = context.Engine;
  150. engine.FunctionDeclarationInstantiation(functionObject, argumentsList);
  151. var G = engine.Realm.Intrinsics.Function.OrdinaryCreateFromConstructor(
  152. functionObject,
  153. static intrinsics => intrinsics.GeneratorFunction.PrototypeObject.PrototypeObject,
  154. static (Engine engine, Realm _, object? _) => new GeneratorInstance(engine));
  155. _bodyStatementList ??= new JintStatementList(Function);
  156. _bodyStatementList.Reset();
  157. G.GeneratorStart(_bodyStatementList);
  158. return new Completion(CompletionType.Return, G, Function.Body);
  159. }
  160. internal State Initialize()
  161. {
  162. var node = (Node) Function;
  163. var state = (State) (node.UserData ??= BuildState(Function));
  164. return state;
  165. }
  166. internal sealed class State
  167. {
  168. public bool HasRestParameter;
  169. public int Length;
  170. public Key[] ParameterNames = null!;
  171. public bool HasDuplicates;
  172. public bool IsSimpleParameterList;
  173. public bool HasParameterExpressions;
  174. public bool ArgumentsObjectNeeded;
  175. public bool RequiresInputArgumentsOwnership;
  176. public List<Key>? VarNames;
  177. public LinkedList<FunctionDeclaration>? FunctionsToInitialize;
  178. public readonly HashSet<Key> FunctionNames = new();
  179. public DeclarationCache? LexicalDeclarations;
  180. public HashSet<Key>? ParameterBindings;
  181. public List<VariableValuePair>? VarsToInitialize;
  182. public bool NeedsEvalContext;
  183. internal readonly record struct VariableValuePair(Key Name, JsValue? InitialValue);
  184. }
  185. internal static State BuildState(IFunction function)
  186. {
  187. var state = new State();
  188. ProcessParameters(function, state, out var hasArguments);
  189. var strict = function.IsStrict();
  190. var hoistingScope = HoistingScope.GetFunctionLevelDeclarations(strict, function);
  191. var functionDeclarations = hoistingScope._functionDeclarations;
  192. var lexicalNames = hoistingScope._lexicalNames;
  193. state.VarNames = hoistingScope._varNames;
  194. LinkedList<FunctionDeclaration>? functionsToInitialize = null;
  195. if (functionDeclarations != null)
  196. {
  197. functionsToInitialize = new LinkedList<FunctionDeclaration>();
  198. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  199. {
  200. var d = functionDeclarations[i];
  201. var fn = d.Id!.Name;
  202. if (state.FunctionNames.Add(fn))
  203. {
  204. functionsToInitialize.AddFirst(d);
  205. }
  206. }
  207. }
  208. state.FunctionsToInitialize = functionsToInitialize;
  209. state.ArgumentsObjectNeeded = true;
  210. var thisMode = strict ? FunctionThisMode.Strict : FunctionThisMode.Global;
  211. if (function.Type == NodeType.ArrowFunctionExpression)
  212. {
  213. thisMode = FunctionThisMode.Lexical;
  214. }
  215. if (thisMode == FunctionThisMode.Lexical || hasArguments)
  216. {
  217. state.ArgumentsObjectNeeded = false;
  218. }
  219. else if (!state.HasParameterExpressions)
  220. {
  221. if (state.FunctionNames.Contains(KnownKeys.Arguments) || lexicalNames?.Contains(KnownKeys.Arguments.Name) == true)
  222. {
  223. state.ArgumentsObjectNeeded = false;
  224. }
  225. }
  226. if (state.ArgumentsObjectNeeded)
  227. {
  228. // just one extra check...
  229. state.ArgumentsObjectNeeded = ArgumentsUsageAstVisitor.HasArgumentsReference(function);
  230. }
  231. state.NeedsEvalContext = !strict;
  232. if (state.NeedsEvalContext)
  233. {
  234. // yet another extra check
  235. state.NeedsEvalContext = EvalContextAstVisitor.HasEvalOrDebugger(function);
  236. }
  237. var parameterBindings = new HashSet<Key>(state.ParameterNames);
  238. if (state.ArgumentsObjectNeeded)
  239. {
  240. parameterBindings.Add(KnownKeys.Arguments);
  241. }
  242. if (function.Type == NodeType.ArrowFunctionExpression)
  243. {
  244. state.RequiresInputArgumentsOwnership = state.ArgumentsObjectNeeded ||
  245. (function.Async && ArgumentsUsageAstVisitor.HasArgumentsReference(function));
  246. }
  247. else
  248. {
  249. state.RequiresInputArgumentsOwnership = state.ArgumentsObjectNeeded &&
  250. (function.Async || function.Generator);
  251. }
  252. state.ParameterBindings = parameterBindings;
  253. var varsToInitialize = new List<State.VariableValuePair>();
  254. if (!state.HasParameterExpressions)
  255. {
  256. var instantiatedVarNames = state.VarNames != null
  257. ? new HashSet<Key>(state.ParameterBindings)
  258. : new HashSet<Key>();
  259. for (var i = 0; i < state.VarNames?.Count; i++)
  260. {
  261. var n = state.VarNames[i];
  262. if (instantiatedVarNames.Add(n))
  263. {
  264. varsToInitialize.Add(new State.VariableValuePair(Name: n, InitialValue: null));
  265. }
  266. }
  267. }
  268. else
  269. {
  270. var instantiatedVarNames = state.VarNames != null
  271. ? new HashSet<Key>(state.ParameterBindings)
  272. : null;
  273. for (var i = 0; i < state.VarNames?.Count; i++)
  274. {
  275. var n = state.VarNames[i];
  276. if (instantiatedVarNames!.Add(n))
  277. {
  278. JsValue? initialValue = null;
  279. if (!state.ParameterBindings.Contains(n) || state.FunctionNames.Contains(n))
  280. {
  281. initialValue = JsValue.Undefined;
  282. }
  283. varsToInitialize.Add(new State.VariableValuePair(Name: n, InitialValue: initialValue));
  284. }
  285. }
  286. }
  287. state.VarsToInitialize = varsToInitialize;
  288. if (hoistingScope._lexicalDeclarations != null)
  289. {
  290. state.LexicalDeclarations = DeclarationCacheBuilder.Build(hoistingScope._lexicalDeclarations);
  291. }
  292. return state;
  293. }
  294. private static void GetBoundNames(
  295. Node parameter,
  296. List<Key> target,
  297. bool checkDuplicates,
  298. ref bool hasRestParameter,
  299. ref bool hasParameterExpressions,
  300. ref bool hasDuplicates,
  301. ref bool hasArguments)
  302. {
  303. Start:
  304. if (parameter.Type == NodeType.Identifier)
  305. {
  306. var key = (Key) ((Identifier) parameter).Name;
  307. target.Add(key);
  308. hasDuplicates |= checkDuplicates && target.Contains(key);
  309. hasArguments |= key == KnownKeys.Arguments;
  310. return;
  311. }
  312. while (true)
  313. {
  314. if (parameter.Type == NodeType.RestElement)
  315. {
  316. hasRestParameter = true;
  317. parameter = ((RestElement) parameter).Argument;
  318. continue;
  319. }
  320. if (parameter.Type == NodeType.ArrayPattern)
  321. {
  322. foreach (var element in ((ArrayPattern) parameter).Elements.AsSpan())
  323. {
  324. if (element is null)
  325. {
  326. continue;
  327. }
  328. if (element.Type == NodeType.RestElement)
  329. {
  330. hasRestParameter = true;
  331. parameter = ((RestElement) element).Argument;
  332. goto Start;
  333. }
  334. GetBoundNames(
  335. element,
  336. target,
  337. checkDuplicates,
  338. ref hasRestParameter,
  339. ref hasParameterExpressions,
  340. ref hasDuplicates,
  341. ref hasArguments);
  342. }
  343. }
  344. else if (parameter.Type == NodeType.ObjectPattern)
  345. {
  346. foreach (var property in ((ObjectPattern) parameter).Properties.AsSpan())
  347. {
  348. if (property.Type == NodeType.RestElement)
  349. {
  350. hasRestParameter = true;
  351. parameter = ((RestElement) property).Argument;
  352. goto Start;
  353. }
  354. GetBoundNames(
  355. ((AssignmentProperty) property).Value,
  356. target,
  357. checkDuplicates,
  358. ref hasRestParameter,
  359. ref hasParameterExpressions,
  360. ref hasDuplicates,
  361. ref hasArguments);
  362. }
  363. }
  364. else if (parameter.Type == NodeType.AssignmentPattern)
  365. {
  366. var assignmentPattern = (AssignmentPattern) parameter;
  367. hasParameterExpressions |= ExpressionAstVisitor.HasExpression(assignmentPattern.ChildNodes);
  368. parameter = assignmentPattern.Left;
  369. continue;
  370. }
  371. break;
  372. }
  373. }
  374. private static void ProcessParameters(
  375. IFunction function,
  376. State state,
  377. out bool hasArguments)
  378. {
  379. hasArguments = false;
  380. state.IsSimpleParameterList = true;
  381. var countParameters = true;
  382. ref readonly var functionDeclarationParams = ref function.Params;
  383. var count = functionDeclarationParams.Count;
  384. var parameterNames = new List<Key>(count);
  385. foreach (var parameter in function.Params.AsSpan())
  386. {
  387. var type = parameter.Type;
  388. if (type == NodeType.Identifier)
  389. {
  390. var key = (Key) ((Identifier) parameter).Name;
  391. state.HasDuplicates |= parameterNames.Contains(key);
  392. hasArguments |= key == KnownKeys.Arguments;
  393. parameterNames.Add(key);
  394. }
  395. else if (type != NodeType.Literal)
  396. {
  397. countParameters &= type != NodeType.AssignmentPattern;
  398. state.IsSimpleParameterList = false;
  399. GetBoundNames(
  400. parameter,
  401. parameterNames,
  402. checkDuplicates: true,
  403. ref state.HasRestParameter,
  404. ref state.HasParameterExpressions,
  405. ref state.HasDuplicates,
  406. ref hasArguments);
  407. }
  408. if (countParameters && type is NodeType.Identifier or NodeType.ObjectPattern or NodeType.ArrayPattern)
  409. {
  410. state.Length++;
  411. }
  412. }
  413. state.ParameterNames = parameterNames.ToArray();
  414. }
  415. private static class ArgumentsUsageAstVisitor
  416. {
  417. public static bool HasArgumentsReference(IFunction function)
  418. {
  419. if (HasArgumentsReference(function.Body))
  420. {
  421. return true;
  422. }
  423. foreach (var parameter in function.Params.AsSpan())
  424. {
  425. if (HasArgumentsReference(parameter))
  426. {
  427. return true;
  428. }
  429. }
  430. return false;
  431. }
  432. private static bool HasArgumentsReference(Node node)
  433. {
  434. foreach (var childNode in node.ChildNodes)
  435. {
  436. var childType = childNode.Type;
  437. if (childType == NodeType.Identifier)
  438. {
  439. if (string.Equals(((Identifier) childNode).Name, "arguments", StringComparison.Ordinal))
  440. {
  441. return true;
  442. }
  443. }
  444. else if (childType != NodeType.FunctionDeclaration && !childNode.ChildNodes.IsEmpty())
  445. {
  446. if (HasArgumentsReference(childNode))
  447. {
  448. return true;
  449. }
  450. }
  451. }
  452. return false;
  453. }
  454. }
  455. private static class EvalContextAstVisitor
  456. {
  457. public static bool HasEvalOrDebugger(IFunction function)
  458. {
  459. if (HasEvalOrDebugger(function.Body))
  460. {
  461. return true;
  462. }
  463. return false;
  464. }
  465. private static bool HasEvalOrDebugger(Node node)
  466. {
  467. foreach (var childNode in node.ChildNodes)
  468. {
  469. var childType = childNode.Type;
  470. if (childType == NodeType.DebuggerStatement)
  471. {
  472. return true;
  473. }
  474. if (childType == NodeType.CallExpression)
  475. {
  476. if (((CallExpression) childNode).Callee is Identifier identifier && identifier.Name.Equals("eval", StringComparison.Ordinal))
  477. {
  478. return true;
  479. }
  480. }
  481. else if (childType != NodeType.FunctionDeclaration && !childNode.ChildNodes.IsEmpty())
  482. {
  483. if (HasEvalOrDebugger(childNode))
  484. {
  485. return true;
  486. }
  487. }
  488. }
  489. return false;
  490. }
  491. }
  492. private static class ExpressionAstVisitor
  493. {
  494. internal static bool HasExpression(ChildNodes nodes)
  495. {
  496. foreach (var childNode in nodes)
  497. {
  498. switch (childNode.Type)
  499. {
  500. case NodeType.ArrowFunctionExpression:
  501. case NodeType.FunctionExpression:
  502. case NodeType.CallExpression:
  503. case NodeType.AssignmentExpression:
  504. return true;
  505. case NodeType.Identifier:
  506. case NodeType.Literal:
  507. continue;
  508. default:
  509. if (!childNode.ChildNodes.IsEmpty())
  510. {
  511. if (HasExpression(childNode.ChildNodes))
  512. {
  513. return true;
  514. }
  515. }
  516. break;
  517. }
  518. }
  519. return false;
  520. }
  521. }
  522. }