JintFunctionDefinition.cs 19 KB

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