EsprimaExtensions.cs 19 KB

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