JintFunctionDefinition.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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 List<Key>? VarNames;
  176. public LinkedList<FunctionDeclaration>? FunctionsToInitialize;
  177. public readonly HashSet<Key> FunctionNames = new();
  178. public DeclarationCache? LexicalDeclarations;
  179. public HashSet<Key>? ParameterBindings;
  180. public List<VariableValuePair>? VarsToInitialize;
  181. public bool NeedsEvalContext;
  182. internal readonly record struct VariableValuePair(Key Name, JsValue? InitialValue);
  183. }
  184. internal static State BuildState(IFunction function)
  185. {
  186. var state = new State();
  187. ProcessParameters(function, state, out var hasArguments);
  188. var strict = function.IsStrict();
  189. var hoistingScope = HoistingScope.GetFunctionLevelDeclarations(strict, function);
  190. var functionDeclarations = hoistingScope._functionDeclarations;
  191. var lexicalNames = hoistingScope._lexicalNames;
  192. state.VarNames = hoistingScope._varNames;
  193. LinkedList<FunctionDeclaration>? functionsToInitialize = null;
  194. if (functionDeclarations != null)
  195. {
  196. functionsToInitialize = new LinkedList<FunctionDeclaration>();
  197. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  198. {
  199. var d = functionDeclarations[i];
  200. var fn = d.Id!.Name;
  201. if (state.FunctionNames.Add(fn))
  202. {
  203. functionsToInitialize.AddFirst(d);
  204. }
  205. }
  206. }
  207. state.FunctionsToInitialize = functionsToInitialize;
  208. state.ArgumentsObjectNeeded = true;
  209. var thisMode = strict ? FunctionThisMode.Strict : FunctionThisMode.Global;
  210. if (function.Type == NodeType.ArrowFunctionExpression)
  211. {
  212. thisMode = FunctionThisMode.Lexical;
  213. }
  214. if (thisMode == FunctionThisMode.Lexical || hasArguments)
  215. {
  216. state.ArgumentsObjectNeeded = false;
  217. }
  218. else if (!state.HasParameterExpressions)
  219. {
  220. if (state.FunctionNames.Contains(KnownKeys.Arguments) || lexicalNames?.Contains(KnownKeys.Arguments.Name) == true)
  221. {
  222. state.ArgumentsObjectNeeded = false;
  223. }
  224. }
  225. if (state.ArgumentsObjectNeeded)
  226. {
  227. // just one extra check...
  228. state.ArgumentsObjectNeeded = ArgumentsUsageAstVisitor.HasArgumentsReference(function);
  229. }
  230. state.NeedsEvalContext = !strict;
  231. if (state.NeedsEvalContext)
  232. {
  233. // yet another extra check
  234. state.NeedsEvalContext = EvalContextAstVisitor.HasEvalOrDebugger(function);
  235. }
  236. var parameterBindings = new HashSet<Key>(state.ParameterNames);
  237. if (state.ArgumentsObjectNeeded)
  238. {
  239. parameterBindings.Add(KnownKeys.Arguments);
  240. }
  241. state.ParameterBindings = parameterBindings;
  242. var varsToInitialize = new List<State.VariableValuePair>();
  243. if (!state.HasParameterExpressions)
  244. {
  245. var instantiatedVarNames = state.VarNames != null
  246. ? new HashSet<Key>(state.ParameterBindings)
  247. : new HashSet<Key>();
  248. for (var i = 0; i < state.VarNames?.Count; i++)
  249. {
  250. var n = state.VarNames[i];
  251. if (instantiatedVarNames.Add(n))
  252. {
  253. varsToInitialize.Add(new State.VariableValuePair(Name: n, InitialValue: null));
  254. }
  255. }
  256. }
  257. else
  258. {
  259. var instantiatedVarNames = state.VarNames != null
  260. ? new HashSet<Key>(state.ParameterBindings)
  261. : null;
  262. for (var i = 0; i < state.VarNames?.Count; i++)
  263. {
  264. var n = state.VarNames[i];
  265. if (instantiatedVarNames!.Add(n))
  266. {
  267. JsValue? initialValue = null;
  268. if (!state.ParameterBindings.Contains(n) || state.FunctionNames.Contains(n))
  269. {
  270. initialValue = JsValue.Undefined;
  271. }
  272. varsToInitialize.Add(new State.VariableValuePair(Name: n, InitialValue: initialValue));
  273. }
  274. }
  275. }
  276. state.VarsToInitialize = varsToInitialize;
  277. if (hoistingScope._lexicalDeclarations != null)
  278. {
  279. state.LexicalDeclarations = DeclarationCacheBuilder.Build(hoistingScope._lexicalDeclarations);
  280. }
  281. return state;
  282. }
  283. private static void GetBoundNames(
  284. Node parameter,
  285. List<Key> target,
  286. bool checkDuplicates,
  287. ref bool hasRestParameter,
  288. ref bool hasParameterExpressions,
  289. ref bool hasDuplicates,
  290. ref bool hasArguments)
  291. {
  292. Start:
  293. if (parameter.Type == NodeType.Identifier)
  294. {
  295. var key = (Key) ((Identifier) parameter).Name;
  296. target.Add(key);
  297. hasDuplicates |= checkDuplicates && target.Contains(key);
  298. hasArguments |= key == KnownKeys.Arguments;
  299. return;
  300. }
  301. while (true)
  302. {
  303. if (parameter.Type == NodeType.RestElement)
  304. {
  305. hasRestParameter = true;
  306. parameter = ((RestElement) parameter).Argument;
  307. continue;
  308. }
  309. if (parameter.Type == NodeType.ArrayPattern)
  310. {
  311. foreach (var element in ((ArrayPattern) parameter).Elements.AsSpan())
  312. {
  313. if (element is null)
  314. {
  315. continue;
  316. }
  317. if (element.Type == NodeType.RestElement)
  318. {
  319. hasRestParameter = true;
  320. parameter = ((RestElement) element).Argument;
  321. goto Start;
  322. }
  323. GetBoundNames(
  324. element,
  325. target,
  326. checkDuplicates,
  327. ref hasRestParameter,
  328. ref hasParameterExpressions,
  329. ref hasDuplicates,
  330. ref hasArguments);
  331. }
  332. }
  333. else if (parameter.Type == NodeType.ObjectPattern)
  334. {
  335. foreach (var property in ((ObjectPattern) parameter).Properties.AsSpan())
  336. {
  337. if (property.Type == NodeType.RestElement)
  338. {
  339. hasRestParameter = true;
  340. parameter = ((RestElement) property).Argument;
  341. goto Start;
  342. }
  343. GetBoundNames(
  344. ((AssignmentProperty) property).Value,
  345. target,
  346. checkDuplicates,
  347. ref hasRestParameter,
  348. ref hasParameterExpressions,
  349. ref hasDuplicates,
  350. ref hasArguments);
  351. }
  352. }
  353. else if (parameter.Type == NodeType.AssignmentPattern)
  354. {
  355. var assignmentPattern = (AssignmentPattern) parameter;
  356. hasParameterExpressions |= ExpressionAstVisitor.HasExpression(assignmentPattern.ChildNodes);
  357. parameter = assignmentPattern.Left;
  358. continue;
  359. }
  360. break;
  361. }
  362. }
  363. private static void ProcessParameters(
  364. IFunction function,
  365. State state,
  366. out bool hasArguments)
  367. {
  368. hasArguments = false;
  369. state.IsSimpleParameterList = true;
  370. var countParameters = true;
  371. ref readonly var functionDeclarationParams = ref function.Params;
  372. var count = functionDeclarationParams.Count;
  373. var parameterNames = new List<Key>(count);
  374. foreach (var parameter in function.Params.AsSpan())
  375. {
  376. var type = parameter.Type;
  377. if (type == NodeType.Identifier)
  378. {
  379. var key = (Key) ((Identifier) parameter).Name;
  380. state.HasDuplicates |= parameterNames.Contains(key);
  381. hasArguments |= key == KnownKeys.Arguments;
  382. parameterNames.Add(key);
  383. }
  384. else if (type != NodeType.Literal)
  385. {
  386. countParameters &= type != NodeType.AssignmentPattern;
  387. state.IsSimpleParameterList = false;
  388. GetBoundNames(
  389. parameter,
  390. parameterNames,
  391. checkDuplicates: true,
  392. ref state.HasRestParameter,
  393. ref state.HasParameterExpressions,
  394. ref state.HasDuplicates,
  395. ref hasArguments);
  396. }
  397. if (countParameters && type is NodeType.Identifier or NodeType.ObjectPattern or NodeType.ArrayPattern)
  398. {
  399. state.Length++;
  400. }
  401. }
  402. state.ParameterNames = parameterNames.ToArray();
  403. }
  404. private static class ArgumentsUsageAstVisitor
  405. {
  406. public static bool HasArgumentsReference(IFunction function)
  407. {
  408. if (HasArgumentsReference(function.Body))
  409. {
  410. return true;
  411. }
  412. foreach (var parameter in function.Params.AsSpan())
  413. {
  414. if (HasArgumentsReference(parameter))
  415. {
  416. return true;
  417. }
  418. }
  419. return false;
  420. }
  421. private static bool HasArgumentsReference(Node node)
  422. {
  423. foreach (var childNode in node.ChildNodes)
  424. {
  425. var childType = childNode.Type;
  426. if (childType == NodeType.Identifier)
  427. {
  428. if (string.Equals(((Identifier) childNode).Name, "arguments", StringComparison.Ordinal))
  429. {
  430. return true;
  431. }
  432. }
  433. else if (childType != NodeType.FunctionDeclaration && !childNode.ChildNodes.IsEmpty())
  434. {
  435. if (HasArgumentsReference(childNode))
  436. {
  437. return true;
  438. }
  439. }
  440. }
  441. return false;
  442. }
  443. }
  444. private static class EvalContextAstVisitor
  445. {
  446. public static bool HasEvalOrDebugger(IFunction function)
  447. {
  448. if (HasEvalOrDebugger(function.Body))
  449. {
  450. return true;
  451. }
  452. return false;
  453. }
  454. private static bool HasEvalOrDebugger(Node node)
  455. {
  456. foreach (var childNode in node.ChildNodes)
  457. {
  458. var childType = childNode.Type;
  459. if (childType == NodeType.DebuggerStatement)
  460. {
  461. return true;
  462. }
  463. if (childType == NodeType.CallExpression)
  464. {
  465. if (((CallExpression) childNode).Callee is Identifier identifier && identifier.Name.Equals("eval", StringComparison.Ordinal))
  466. {
  467. return true;
  468. }
  469. }
  470. else if (childType != NodeType.FunctionDeclaration && !childNode.ChildNodes.IsEmpty())
  471. {
  472. if (HasEvalOrDebugger(childNode))
  473. {
  474. return true;
  475. }
  476. }
  477. }
  478. return false;
  479. }
  480. }
  481. private static class ExpressionAstVisitor
  482. {
  483. internal static bool HasExpression(ChildNodes nodes)
  484. {
  485. foreach (var childNode in nodes)
  486. {
  487. switch (childNode.Type)
  488. {
  489. case NodeType.ArrowFunctionExpression:
  490. case NodeType.FunctionExpression:
  491. case NodeType.CallExpression:
  492. case NodeType.AssignmentExpression:
  493. return true;
  494. case NodeType.Identifier:
  495. case NodeType.Literal:
  496. continue;
  497. default:
  498. if (!childNode.ChildNodes.IsEmpty())
  499. {
  500. if (HasExpression(childNode.ChildNodes))
  501. {
  502. return true;
  503. }
  504. }
  505. break;
  506. }
  507. }
  508. return false;
  509. }
  510. }
  511. }