EsprimaExtensions.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using System.Runtime.CompilerServices;
  2. using Esprima;
  3. using Esprima.Ast;
  4. using Jint.Native;
  5. using Jint.Native.Function;
  6. using Jint.Native.Object;
  7. using Jint.Runtime;
  8. using Jint.Runtime.Environments;
  9. using Jint.Runtime.Interpreter;
  10. using Jint.Runtime.Interpreter.Expressions;
  11. using Jint.Runtime.Modules;
  12. namespace Jint
  13. {
  14. public static class EsprimaExtensions
  15. {
  16. public static JsValue GetKey<T>(this T property, Engine engine) where T : IProperty => GetKey(property.Key, engine, property.Computed);
  17. public static JsValue GetKey(this Expression expression, Engine engine, bool resolveComputed = false)
  18. {
  19. var key = TryGetKey(expression, engine, resolveComputed);
  20. if (key is not null)
  21. {
  22. return TypeConverter.ToPropertyKey(key);
  23. }
  24. ExceptionHelper.ThrowArgumentException("Unable to extract correct key, node type: " + expression.Type);
  25. return JsValue.Undefined;
  26. }
  27. internal static JsValue TryGetKey<T>(this T property, Engine engine) where T : IProperty
  28. {
  29. return TryGetKey(property.Key, engine, property.Computed);
  30. }
  31. internal static JsValue TryGetKey<T>(this T expression, Engine engine, bool resolveComputed) where T : Expression
  32. {
  33. JsValue key;
  34. if (expression is Literal literal)
  35. {
  36. key = literal.TokenType == TokenType.NullLiteral ? JsValue.Null : LiteralKeyToString(literal);
  37. }
  38. else if (!resolveComputed && expression is Identifier identifier)
  39. {
  40. key = identifier.Name;
  41. }
  42. else if (resolveComputed)
  43. {
  44. return TryGetComputedPropertyKey(expression, engine);
  45. }
  46. else
  47. {
  48. key = JsValue.Undefined;
  49. }
  50. return key;
  51. }
  52. private static JsValue TryGetComputedPropertyKey<T>(T expression, Engine engine)
  53. where T : Expression
  54. {
  55. if (expression.Type is Nodes.Identifier
  56. or Nodes.CallExpression
  57. or Nodes.BinaryExpression
  58. or Nodes.UpdateExpression
  59. or Nodes.AssignmentExpression
  60. or Nodes.UnaryExpression
  61. or Nodes.MemberExpression
  62. or Nodes.LogicalExpression
  63. or Nodes.ConditionalExpression
  64. or Nodes.ArrowFunctionExpression
  65. or Nodes.FunctionExpression
  66. or Nodes.YieldExpression
  67. or Nodes.TemplateLiteral)
  68. {
  69. var context = engine._activeEvaluationContext;
  70. return JintExpression.Build(expression).GetValue(context!);
  71. }
  72. return JsValue.Undefined;
  73. }
  74. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  75. internal static bool IsFunctionDefinition<T>(this T node) where T : Node
  76. {
  77. var type = node.Type;
  78. return type
  79. is Nodes.FunctionExpression
  80. or Nodes.ArrowFunctionExpression
  81. or Nodes.ArrowParameterPlaceHolder
  82. or Nodes.ClassExpression;
  83. }
  84. /// <summary>
  85. /// https://tc39.es/ecma262/#sec-static-semantics-isconstantdeclaration
  86. /// </summary>
  87. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  88. internal static bool IsConstantDeclaration(this Declaration d)
  89. {
  90. return d is VariableDeclaration { Kind: VariableDeclarationKind.Const };
  91. }
  92. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  93. internal static bool HasName<T>(this T node) where T : Node
  94. {
  95. if (!node.IsFunctionDefinition())
  96. {
  97. return false;
  98. }
  99. if ((node as IFunction)?.Id is not null)
  100. {
  101. return true;
  102. }
  103. if ((node as ClassExpression)?.Id is not null)
  104. {
  105. return true;
  106. }
  107. return false;
  108. }
  109. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  110. internal static bool IsAnonymousFunctionDefinition<T>(this T node) where T : Node
  111. {
  112. if (!node.IsFunctionDefinition())
  113. {
  114. return false;
  115. }
  116. if (node.HasName())
  117. {
  118. return false;
  119. }
  120. return true;
  121. }
  122. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  123. internal static bool IsOptional<T>(this T node) where T : Expression
  124. {
  125. switch (node)
  126. {
  127. case MemberExpression { Optional: true }:
  128. case CallExpression { Optional: true }:
  129. return true;
  130. default:
  131. return false;
  132. }
  133. }
  134. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  135. internal static string LiteralKeyToString(Literal literal)
  136. {
  137. // prevent conversion to scientific notation
  138. if (literal.Value is double d)
  139. {
  140. return TypeConverter.ToString(d);
  141. }
  142. return literal.Value as string ?? Convert.ToString(literal.Value, provider: null) ?? "";
  143. }
  144. internal static void GetBoundNames(this VariableDeclaration variableDeclaration, List<string> target)
  145. {
  146. ref readonly var declarations = ref variableDeclaration.Declarations;
  147. for (var i = 0; i < declarations.Count; i++)
  148. {
  149. var declaration = declarations[i];
  150. GetBoundNames(declaration.Id, target);
  151. }
  152. }
  153. internal static void GetBoundNames(this Node? parameter, List<string> target)
  154. {
  155. if (parameter is null || parameter.Type == Nodes.Literal)
  156. {
  157. return;
  158. }
  159. // try to get away without a loop
  160. if (parameter is Identifier id)
  161. {
  162. target.Add(id.Name);
  163. return;
  164. }
  165. if (parameter is VariableDeclaration variableDeclaration)
  166. {
  167. variableDeclaration.GetBoundNames(target);
  168. return;
  169. }
  170. while (true)
  171. {
  172. if (parameter is Identifier identifier)
  173. {
  174. target.Add(identifier.Name);
  175. return;
  176. }
  177. if (parameter is RestElement restElement)
  178. {
  179. parameter = restElement.Argument;
  180. continue;
  181. }
  182. if (parameter is ArrayPattern arrayPattern)
  183. {
  184. ref readonly var arrayPatternElements = ref arrayPattern.Elements;
  185. for (var i = 0; i < arrayPatternElements.Count; i++)
  186. {
  187. var expression = arrayPatternElements[i];
  188. GetBoundNames(expression, target);
  189. }
  190. }
  191. else if (parameter is ObjectPattern objectPattern)
  192. {
  193. ref readonly var objectPatternProperties = ref objectPattern.Properties;
  194. for (var i = 0; i < objectPatternProperties.Count; i++)
  195. {
  196. var property = objectPatternProperties[i];
  197. if (property is Property p)
  198. {
  199. GetBoundNames(p.Value, target);
  200. }
  201. else
  202. {
  203. GetBoundNames((RestElement) property, target);
  204. }
  205. }
  206. }
  207. else if (parameter is AssignmentPattern assignmentPattern)
  208. {
  209. parameter = assignmentPattern.Left;
  210. continue;
  211. }
  212. else if (parameter is ClassDeclaration classDeclaration)
  213. {
  214. var name = classDeclaration.Id?.Name;
  215. if (name != null)
  216. {
  217. target.Add(name);
  218. }
  219. }
  220. break;
  221. }
  222. }
  223. internal static void BindingInitialization(
  224. this Node? expression,
  225. EvaluationContext context,
  226. JsValue value,
  227. EnvironmentRecord env)
  228. {
  229. if (expression is Identifier identifier)
  230. {
  231. var catchEnvRecord = (DeclarativeEnvironmentRecord) env;
  232. catchEnvRecord.CreateMutableBindingAndInitialize(identifier.Name, canBeDeleted: false, value);
  233. }
  234. else if (expression is BindingPattern bindingPattern)
  235. {
  236. BindingPatternAssignmentExpression.ProcessPatterns(
  237. context,
  238. bindingPattern,
  239. value,
  240. env);
  241. }
  242. }
  243. /// <summary>
  244. /// https://tc39.es/ecma262/#sec-runtime-semantics-definemethod
  245. /// </summary>
  246. internal static Record DefineMethod<T>(this T m, ObjectInstance obj, ObjectInstance? functionPrototype = null) where T : IProperty
  247. {
  248. var engine = obj.Engine;
  249. var propKey = TypeConverter.ToPropertyKey(m.GetKey(engine));
  250. var intrinsics = engine.Realm.Intrinsics;
  251. var runningExecutionContext = engine.ExecutionContext;
  252. var scope = runningExecutionContext.LexicalEnvironment;
  253. var privateScope= runningExecutionContext.PrivateEnvironment;
  254. var prototype = functionPrototype ?? intrinsics.Function.PrototypeObject;
  255. var function = m.Value as IFunction;
  256. if (function is null)
  257. {
  258. ExceptionHelper.ThrowSyntaxError(engine.Realm);
  259. }
  260. var definition = new JintFunctionDefinition(function);
  261. var closure = intrinsics.Function.OrdinaryFunctionCreate(prototype, definition, definition.ThisMode, scope, privateScope);
  262. closure.MakeMethod(obj);
  263. return new Record(propKey, closure);
  264. }
  265. internal static void GetImportEntries(this ImportDeclaration import, List<ImportEntry> importEntries, HashSet<string> requestedModules)
  266. {
  267. var source = import.Source.StringValue!;
  268. var specifiers = import.Specifiers;
  269. requestedModules.Add(source);
  270. foreach (var specifier in specifiers)
  271. {
  272. switch (specifier)
  273. {
  274. case ImportNamespaceSpecifier namespaceSpecifier:
  275. importEntries.Add(new ImportEntry(source, "*", namespaceSpecifier.Local.GetModuleKey()));
  276. break;
  277. case ImportSpecifier importSpecifier:
  278. importEntries.Add(new ImportEntry(source, importSpecifier.Imported.GetModuleKey(), importSpecifier.Local.GetModuleKey()));
  279. break;
  280. case ImportDefaultSpecifier defaultSpecifier:
  281. importEntries.Add(new ImportEntry(source, "default", defaultSpecifier.Local.GetModuleKey()));
  282. break;
  283. }
  284. }
  285. }
  286. internal static void GetExportEntries(this ExportDeclaration export, List<ExportEntry> exportEntries, HashSet<string> requestedModules)
  287. {
  288. switch (export)
  289. {
  290. case ExportDefaultDeclaration defaultDeclaration:
  291. GetExportEntries(true, defaultDeclaration.Declaration, exportEntries);
  292. break;
  293. case ExportAllDeclaration allDeclaration:
  294. //Note: there is a pending PR for Esprima to support exporting an imported modules content as a namespace i.e. 'export * as ns from "mod"'
  295. requestedModules.Add(allDeclaration.Source.StringValue!);
  296. exportEntries.Add(new(allDeclaration.Exported?.GetModuleKey(), allDeclaration.Source.StringValue, "*", null));
  297. break;
  298. case ExportNamedDeclaration namedDeclaration:
  299. ref readonly var specifiers = ref namedDeclaration.Specifiers;
  300. if (specifiers.Count == 0)
  301. {
  302. GetExportEntries(false, namedDeclaration.Declaration!, exportEntries, namedDeclaration.Source?.StringValue);
  303. }
  304. else
  305. {
  306. for (var i = 0; i < specifiers.Count; i++)
  307. {
  308. var specifier = specifiers[i];
  309. if (namedDeclaration.Source != null)
  310. {
  311. exportEntries.Add(new(specifier.Exported.GetModuleKey(), namedDeclaration.Source.StringValue, specifier.Local.GetModuleKey(), null));
  312. }
  313. else
  314. {
  315. exportEntries.Add(new(specifier.Exported.GetModuleKey(), null, null, specifier.Local.GetModuleKey()));
  316. }
  317. }
  318. }
  319. if (namedDeclaration.Source is not null)
  320. {
  321. requestedModules.Add(namedDeclaration.Source.StringValue!);
  322. }
  323. break;
  324. }
  325. }
  326. private static void GetExportEntries(bool defaultExport, StatementListItem declaration, List<ExportEntry> exportEntries, string? moduleRequest = null)
  327. {
  328. var names = GetExportNames(declaration);
  329. if (names.Count == 0)
  330. {
  331. if (defaultExport)
  332. {
  333. exportEntries.Add(new("default", null, null, "*default*"));
  334. }
  335. }
  336. else
  337. {
  338. for (var i = 0; i < names.Count; i++)
  339. {
  340. var name = names[i];
  341. var exportName = defaultExport ? "default" : name;
  342. exportEntries.Add(new(exportName, moduleRequest, null, name));
  343. }
  344. }
  345. }
  346. private static List<string> GetExportNames(StatementListItem declaration)
  347. {
  348. var result = new List<string>();
  349. switch (declaration)
  350. {
  351. case FunctionDeclaration functionDeclaration:
  352. var funcName = functionDeclaration.Id?.Name;
  353. if (funcName is not null)
  354. {
  355. result.Add(funcName);
  356. }
  357. break;
  358. case ClassDeclaration classDeclaration:
  359. var className = classDeclaration.Id?.Name;
  360. if (className is not null)
  361. {
  362. result.Add(className);
  363. }
  364. break;
  365. case VariableDeclaration variableDeclaration:
  366. ref readonly var declarators = ref variableDeclaration.Declarations;
  367. for (var i = 0; i < declarators.Count; i++)
  368. {
  369. var declarator = declarators[i];
  370. var varName = declarator.Id.As<Identifier>()?.Name;
  371. if (varName is not null)
  372. {
  373. result.Add(varName);
  374. }
  375. }
  376. break;
  377. }
  378. return result;
  379. }
  380. private static string? GetModuleKey(this Expression expression)
  381. {
  382. return (expression as Identifier)?.Name ?? (expression as Literal)?.StringValue;
  383. }
  384. internal readonly record struct Record(JsValue Key, ScriptFunctionInstance Closure);
  385. /// <summary>
  386. /// Creates a dummy node that can be used when only location available and node is required.
  387. /// </summary>
  388. internal static SyntaxElement CreateLocationNode(in Location location)
  389. {
  390. return new MinimalSyntaxElement(location);
  391. }
  392. }
  393. internal sealed class MinimalSyntaxElement : SyntaxElement
  394. {
  395. public MinimalSyntaxElement(in Location location)
  396. {
  397. Location = location;
  398. }
  399. }
  400. }