EsprimaExtensions.cs 20 KB

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