AstExtensions.cs 19 KB

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