Engine.Ast.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. using System.Runtime.InteropServices;
  2. using System.Text.RegularExpressions;
  3. using Jint.Native;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Interpreter;
  6. using Jint.Runtime.Interpreter.Expressions;
  7. using Jint.Runtime.Interpreter.Statements;
  8. using Environment = Jint.Runtime.Environments.Environment;
  9. namespace Jint;
  10. public partial class Engine
  11. {
  12. /// <summary>
  13. /// Prepares a script for the engine that includes static analysis data to speed up execution during run-time.
  14. /// </summary>
  15. /// <remarks>
  16. /// Returned instance is reusable and thread-safe. You should prepare scripts only once and then reuse them.
  17. /// </remarks>
  18. public static Prepared<Script> PrepareScript(string code, string? source = null, bool strict = false, ScriptPreparationOptions? options = null)
  19. {
  20. options ??= ScriptPreparationOptions.Default;
  21. var astAnalyzer = new AstAnalyzer(options);
  22. var parserOptions = options.GetParserOptions();
  23. var preparedScript = new Parser(parserOptions with { OnNode = astAnalyzer.NodeVisitor }).ParseScript(code, source, strict);
  24. return new Prepared<Script>(preparedScript, parserOptions);
  25. }
  26. /// <summary>
  27. /// Prepares a module for the engine that includes static analysis data to speed up execution during run-time.
  28. /// </summary>
  29. /// <remarks>
  30. /// Returned instance is reusable and thread-safe. You should prepare modules only once and then reuse them.
  31. /// </remarks>
  32. public static Prepared<Module> PrepareModule(string code, string? source = null, ModulePreparationOptions? options = null)
  33. {
  34. options ??= ModulePreparationOptions.Default;
  35. var astAnalyzer = new AstAnalyzer(options);
  36. var parserOptions = options.GetParserOptions();
  37. var preparedModule = new Parser(parserOptions with { OnNode = astAnalyzer.NodeVisitor }).ParseModule(code, source);
  38. return new Prepared<Module>(preparedModule, parserOptions);
  39. }
  40. private sealed class AstAnalyzer
  41. {
  42. private static readonly bool _canCompileNegativeLookaroundAssertions = typeof(Regex).Assembly.GetName().Version?.Major is not (null or 7 or 8);
  43. private readonly IPreparationOptions<IParsingOptions> _preparationOptions;
  44. private readonly Dictionary<string, Environment.BindingName> _bindingNames = new(StringComparer.Ordinal);
  45. private readonly Dictionary<string, Regex> _regexes = new(StringComparer.Ordinal);
  46. public AstAnalyzer(IPreparationOptions<IParsingOptions> preparationOptions)
  47. {
  48. _preparationOptions = preparationOptions;
  49. }
  50. public void NodeVisitor(Node node, OnNodeContext _)
  51. {
  52. switch (node.Type)
  53. {
  54. case NodeType.Identifier:
  55. var identifier = (Identifier) node;
  56. var name = identifier.Name;
  57. if (!_bindingNames.TryGetValue(name, out var bindingName))
  58. {
  59. _bindingNames[name] = bindingName = new Environment.BindingName(JsString.CachedCreate(name));
  60. }
  61. node.UserData = new JintIdentifierExpression(identifier, bindingName);
  62. break;
  63. case NodeType.Literal:
  64. var literal = (Literal) node;
  65. var constantValue = JintLiteralExpression.ConvertToJsValue(literal);
  66. node.UserData = constantValue is not null ? new JintConstantExpression(literal, constantValue) : null;
  67. break;
  68. case NodeType.MemberExpression:
  69. node.UserData = JintMemberExpression.InitializeDeterminedProperty((MemberExpression) node, cache: true);
  70. break;
  71. case NodeType.ArrowFunctionExpression:
  72. case NodeType.FunctionDeclaration:
  73. case NodeType.FunctionExpression:
  74. var function = (IFunction) node;
  75. node.UserData = JintFunctionDefinition.BuildState(function);
  76. break;
  77. case NodeType.Program:
  78. node.UserData = new CachedHoistingScope((Program) node);
  79. break;
  80. case NodeType.UnaryExpression:
  81. node.UserData = JintUnaryExpression.BuildConstantExpression((NonUpdateUnaryExpression) node);
  82. break;
  83. case NodeType.BinaryExpression:
  84. var binaryExpression = (NonLogicalBinaryExpression) node;
  85. if (_preparationOptions.FoldConstants
  86. && binaryExpression.Operator != Operator.InstanceOf
  87. && binaryExpression.Operator != Operator.In
  88. && binaryExpression is { Left: Literal leftLiteral, Right: Literal rightLiteral })
  89. {
  90. var left = JintLiteralExpression.ConvertToJsValue(leftLiteral);
  91. var right = JintLiteralExpression.ConvertToJsValue(rightLiteral);
  92. if (left is not null && right is not null)
  93. {
  94. // we have fixed result
  95. try
  96. {
  97. var result = JintBinaryExpression.Build(binaryExpression);
  98. var context = new EvaluationContext();
  99. node.UserData = new JintConstantExpression(binaryExpression, (JsValue) result.EvaluateWithoutNodeTracking(context));
  100. }
  101. catch
  102. {
  103. // probably caused an error and error reporting doesn't work without engine
  104. }
  105. }
  106. }
  107. break;
  108. case NodeType.ReturnStatement:
  109. var returnStatement = (ReturnStatement) node;
  110. if (returnStatement.Argument is Literal returnedLiteral)
  111. {
  112. var returnValue = JintLiteralExpression.ConvertToJsValue(returnedLiteral);
  113. if (returnValue is not null)
  114. {
  115. node.UserData = new ConstantStatement(returnStatement, CompletionType.Return, returnValue);
  116. }
  117. }
  118. break;
  119. }
  120. }
  121. }
  122. }
  123. internal sealed class CachedHoistingScope
  124. {
  125. public CachedHoistingScope(Program program)
  126. {
  127. Scope = HoistingScope.GetProgramLevelDeclarations(program);
  128. VarNames = new List<Key>();
  129. GatherVarNames(Scope, VarNames);
  130. LexNames = new List<CachedLexicalName>();
  131. GatherLexNames(Scope, LexNames);
  132. }
  133. internal static void GatherVarNames(HoistingScope scope, List<Key> boundNames)
  134. {
  135. var varDeclarations = scope._variablesDeclarations;
  136. if (varDeclarations != null)
  137. {
  138. for (var i = 0; i < varDeclarations.Count; i++)
  139. {
  140. var d = varDeclarations[i];
  141. d.GetBoundNames(boundNames);
  142. }
  143. }
  144. }
  145. internal static void GatherLexNames(HoistingScope scope, List<CachedLexicalName> boundNames)
  146. {
  147. var lexDeclarations = scope._lexicalDeclarations;
  148. if (lexDeclarations != null)
  149. {
  150. var temp = new List<Key>();
  151. for (var i = 0; i < lexDeclarations.Count; i++)
  152. {
  153. var d = lexDeclarations[i];
  154. temp.Clear();
  155. d.GetBoundNames(temp);
  156. for (var j = 0; j < temp.Count; j++)
  157. {
  158. boundNames.Add(new CachedLexicalName(temp[j], d.IsConstantDeclaration()));
  159. }
  160. }
  161. }
  162. }
  163. [StructLayout(LayoutKind.Auto)]
  164. internal readonly record struct CachedLexicalName(Key Name, bool Constant);
  165. public HoistingScope Scope { get; }
  166. public List<Key> VarNames { get; }
  167. public List<CachedLexicalName> LexNames { get; }
  168. }
  169. internal static class AstPreparationExtensions
  170. {
  171. internal static HoistingScope GetHoistingScope(this Program program)
  172. {
  173. return program.UserData is CachedHoistingScope cached ? cached.Scope : HoistingScope.GetProgramLevelDeclarations(program);
  174. }
  175. internal static List<Key> GetVarNames(this Program program, HoistingScope hoistingScope)
  176. {
  177. List<Key> boundNames;
  178. if (program.UserData is CachedHoistingScope cached)
  179. {
  180. boundNames = cached.VarNames;
  181. }
  182. else
  183. {
  184. boundNames = new List<Key>();
  185. CachedHoistingScope.GatherVarNames(hoistingScope, boundNames);
  186. }
  187. return boundNames;
  188. }
  189. internal static List<CachedHoistingScope.CachedLexicalName> GetLexNames(this Program program, HoistingScope hoistingScope)
  190. {
  191. List<CachedHoistingScope.CachedLexicalName> boundNames;
  192. if (program.UserData is CachedHoistingScope cached)
  193. {
  194. boundNames = cached.LexNames;
  195. }
  196. else
  197. {
  198. boundNames = new List<CachedHoistingScope.CachedLexicalName>();
  199. CachedHoistingScope.GatherLexNames(hoistingScope, boundNames);
  200. }
  201. return boundNames;
  202. }
  203. }