FunctionConstructor.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. using Esprima;
  2. using Esprima.Ast;
  3. using Jint.Native.Object;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Descriptors;
  6. using Jint.Runtime.Environments;
  7. using Jint.Runtime.Interpreter;
  8. namespace Jint.Native.Function
  9. {
  10. /// <summary>
  11. /// https://tc39.es/ecma262/#sec-function-constructor
  12. /// </summary>
  13. public sealed class FunctionConstructor : FunctionInstance, IConstructor
  14. {
  15. private static readonly JsString _functionName = new JsString("Function");
  16. private static readonly JsString _functionNameAnonymous = new JsString("anonymous");
  17. private readonly JavaScriptParser _parser = new(new ParserOptions { Tolerant = false });
  18. internal FunctionConstructor(
  19. Engine engine,
  20. Realm realm,
  21. ObjectPrototype objectPrototype)
  22. : base(engine, realm, _functionName)
  23. {
  24. PrototypeObject = new FunctionPrototype(engine, realm, objectPrototype);
  25. _prototype = PrototypeObject;
  26. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  27. _length = new PropertyDescriptor(JsNumber.PositiveOne, PropertyFlag.Configurable);
  28. }
  29. public FunctionPrototype PrototypeObject { get; }
  30. protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments)
  31. {
  32. return Construct(arguments, thisObject);
  33. }
  34. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) => Construct(arguments, newTarget);
  35. private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  36. {
  37. var function = CreateDynamicFunction(
  38. this,
  39. newTarget,
  40. FunctionKind.Normal,
  41. arguments);
  42. return function;
  43. }
  44. /// <summary>
  45. /// https://tc39.es/ecma262/#sec-createdynamicfunction
  46. /// </summary>
  47. internal FunctionInstance CreateDynamicFunction(
  48. ObjectInstance constructor,
  49. JsValue newTarget,
  50. FunctionKind kind,
  51. JsValue[] args)
  52. {
  53. // TODO var callerContext = _engine.GetExecutionContext(1);
  54. var callerContext = _engine.ExecutionContext;
  55. var callerRealm = callerContext.Realm;
  56. var calleeRealm = _engine.ExecutionContext.Realm;
  57. _engine._host.EnsureCanCompileStrings(callerRealm, calleeRealm);
  58. if (newTarget.IsUndefined())
  59. {
  60. newTarget = constructor;
  61. }
  62. Func<Intrinsics, ObjectInstance>? fallbackProto = null;
  63. switch (kind)
  64. {
  65. case FunctionKind.Normal:
  66. fallbackProto = static intrinsics => intrinsics.Function.PrototypeObject;
  67. break;
  68. case FunctionKind.Generator:
  69. case FunctionKind.AsyncGenerator:
  70. case FunctionKind.Async:
  71. default:
  72. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(kind), kind.ToString());
  73. break;
  74. }
  75. var argCount = args.Length;
  76. var p = "";
  77. var body = "";
  78. if (argCount == 1)
  79. {
  80. body = TypeConverter.ToString(args[0]);
  81. }
  82. else if (argCount > 1)
  83. {
  84. var firstArg = args[0];
  85. p = TypeConverter.ToString(firstArg);
  86. for (var k = 1; k < argCount - 1; k++)
  87. {
  88. var nextArg = args[k];
  89. p += "," + TypeConverter.ToString(nextArg);
  90. }
  91. body = TypeConverter.ToString(args[argCount - 1]);
  92. }
  93. IFunction? function = null;
  94. try
  95. {
  96. string? functionExpression = null;
  97. if (argCount == 0)
  98. {
  99. switch (kind)
  100. {
  101. case FunctionKind.Normal:
  102. functionExpression = "function f(){}";
  103. break;
  104. case FunctionKind.Generator:
  105. functionExpression = "function* f(){}";
  106. break;
  107. case FunctionKind.Async:
  108. ExceptionHelper.ThrowNotImplementedException("Async functions not implemented");
  109. break;
  110. case FunctionKind.AsyncGenerator:
  111. ExceptionHelper.ThrowNotImplementedException("Async generators not implemented");
  112. break;
  113. default:
  114. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(kind), kind.ToString());
  115. break;
  116. }
  117. }
  118. else
  119. {
  120. switch (kind)
  121. {
  122. case FunctionKind.Normal:
  123. functionExpression = "function f(";
  124. break;
  125. case FunctionKind.Generator:
  126. functionExpression = "function* f(";
  127. break;
  128. case FunctionKind.Async:
  129. ExceptionHelper.ThrowNotImplementedException("Async functions not implemented");
  130. break;
  131. case FunctionKind.AsyncGenerator:
  132. ExceptionHelper.ThrowNotImplementedException("Async generators not implemented");
  133. break;
  134. default:
  135. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(kind), kind.ToString());
  136. break;
  137. }
  138. if (p.IndexOf('/') != -1)
  139. {
  140. // ensure comments don't screw up things
  141. functionExpression += "\n" + p + "\n";
  142. }
  143. else
  144. {
  145. functionExpression += p;
  146. }
  147. functionExpression += ")";
  148. if (body.IndexOf('/') != -1)
  149. {
  150. // ensure comments don't screw up things
  151. functionExpression += "{\n" + body + "\n}";
  152. }
  153. else
  154. {
  155. functionExpression += "{" + body + "}";
  156. }
  157. }
  158. function = (IFunction) _parser.ParseScript(functionExpression).Body[0];
  159. }
  160. catch (ParserException ex)
  161. {
  162. ExceptionHelper.ThrowSyntaxError(_engine.ExecutionContext.Realm, ex.Message);
  163. }
  164. var proto = GetPrototypeFromConstructor(newTarget, fallbackProto);
  165. var realmF = _realm;
  166. var scope = realmF.GlobalEnv;
  167. PrivateEnvironmentRecord? privateScope = null;
  168. var definition = new JintFunctionDefinition(function);
  169. FunctionInstance F = OrdinaryFunctionCreate(proto, definition, function.Strict ? FunctionThisMode.Strict : FunctionThisMode.Global, scope, privateScope);
  170. F.SetFunctionName(_functionNameAnonymous, force: true);
  171. if (kind == FunctionKind.Generator)
  172. {
  173. ExceptionHelper.ThrowNotImplementedException("generators not implemented");
  174. }
  175. else if (kind == FunctionKind.AsyncGenerator)
  176. {
  177. // TODO
  178. // Let prototype be ! OrdinaryObjectCreate(%AsyncGeneratorFunction.prototype.prototype%).
  179. // Perform DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  180. ExceptionHelper.ThrowNotImplementedException("async generators not implemented");
  181. }
  182. else if (kind == FunctionKind.Normal)
  183. {
  184. F.MakeConstructor();
  185. }
  186. return F;
  187. }
  188. /// <summary>
  189. /// https://tc39.es/ecma262/#sec-ordinaryfunctioncreate
  190. /// </summary>
  191. internal ScriptFunctionInstance OrdinaryFunctionCreate(
  192. ObjectInstance functionPrototype,
  193. JintFunctionDefinition function,
  194. FunctionThisMode thisMode,
  195. EnvironmentRecord scope,
  196. PrivateEnvironmentRecord? privateScope)
  197. {
  198. return new ScriptFunctionInstance(
  199. _engine,
  200. function,
  201. scope,
  202. thisMode,
  203. functionPrototype)
  204. {
  205. _privateEnvironment = privateScope,
  206. _realm = _realm
  207. };
  208. }
  209. /// <summary>
  210. /// https://tc39.es/ecma262/#sec-runtime-semantics-instantiatefunctionobject
  211. /// </summary>
  212. internal FunctionInstance InstantiateFunctionObject(
  213. JintFunctionDefinition functionDeclaration,
  214. EnvironmentRecord scope,
  215. PrivateEnvironmentRecord? privateScope)
  216. {
  217. return !functionDeclaration.Function.Generator
  218. ? InstantiateOrdinaryFunctionObject(functionDeclaration, scope, privateScope)
  219. : InstantiateGeneratorFunctionObject(functionDeclaration, scope, privateScope);
  220. }
  221. /// <summary>
  222. /// https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionobject
  223. /// </summary>
  224. private FunctionInstance InstantiateOrdinaryFunctionObject(
  225. JintFunctionDefinition functionDeclaration,
  226. EnvironmentRecord scope,
  227. PrivateEnvironmentRecord? privateScope)
  228. {
  229. var F = OrdinaryFunctionCreate(
  230. _realm.Intrinsics.Function.PrototypeObject,
  231. functionDeclaration,
  232. functionDeclaration.ThisMode,
  233. scope,
  234. privateScope);
  235. var name = functionDeclaration.Name ?? "default";
  236. F.SetFunctionName(name);
  237. F.MakeConstructor();
  238. return F;
  239. }
  240. /// <summary>
  241. /// https://tc39.es/ecma262/#sec-runtime-semantics-instantiategeneratorfunctionobject
  242. /// </summary>
  243. private FunctionInstance InstantiateGeneratorFunctionObject(
  244. JintFunctionDefinition functionDeclaration,
  245. EnvironmentRecord scope,
  246. PrivateEnvironmentRecord? privateScope)
  247. {
  248. // TODO generators
  249. return InstantiateOrdinaryFunctionObject(functionDeclaration, scope, privateScope);
  250. }
  251. }
  252. }