2
0

Engine.Ast.cs 8.5 KB

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