AstExtensions.cs 20 KB

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