Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 56 additions & 1 deletion Jint/Engine.Ast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,30 @@ public static Prepared<Script> PrepareScript(string code, string? source = null,
}
}

/// <summary>
/// Prepares a script for the engine that includes static analysis data to speed up execution during run-time.
/// </summary>
/// <remarks>
/// Returned instance is reusable and thread-safe. You should prepare scripts only once and then reuse them.
/// </remarks>
public static Prepared<Script> PrepareScript(Script script, ScriptPreparationOptions? options = null)
{
options ??= ScriptPreparationOptions.Default;

var astAnalyzer = new AstAnalyzer(options);
var parserOptions = options.GetParserOptions();

try
{
astAnalyzer.Visit(script);
return new Prepared<Script>(script, parserOptions);
}
catch (Exception e)
{
throw new ScriptPreparationException("Could not prepare script: " + e.Message, e);
}
}

/// <summary>
/// Prepares a module for the engine that includes static analysis data to speed up execution during run-time.
/// </summary>
Expand All @@ -59,7 +83,31 @@ public static Prepared<Module> PrepareModule(string code, string? source = null,
}
}

private sealed class AstAnalyzer
/// <summary>
/// Prepares a module for the engine that includes static analysis data to speed up execution during run-time.
/// </summary>
/// <remarks>
/// Returned instance is reusable and thread-safe. You should prepare modules only once and then reuse them.
/// </remarks>
public static Prepared<Module> PrepareModule(Module module, ModulePreparationOptions? options = null)
{
options ??= ModulePreparationOptions.Default;

var astAnalyzer = new AstAnalyzer(options);
var parserOptions = options.GetParserOptions();

try
{
astAnalyzer.Visit(module);
return new Prepared<Module>(module, parserOptions);
}
catch (Exception e)
{
throw new ScriptPreparationException("Could not prepare script: " + e.Message, e);
}
}

private sealed class AstAnalyzer : AstVisitor
{
private readonly IPreparationOptions<IParsingOptions> _preparationOptions;
private readonly Dictionary<string, Environment.BindingName> _bindingNames = new(StringComparer.Ordinal);
Expand All @@ -70,6 +118,11 @@ public AstAnalyzer(IPreparationOptions<IParsingOptions> preparationOptions)
}

public void NodeVisitor(Node node, OnNodeContext _)
{
Visit(node);
}

public override object? Visit(Node node)
{
switch (node.Type)
{
Expand Down Expand Up @@ -154,6 +207,8 @@ public void NodeVisitor(Node node, OnNodeContext _)
node.UserData = JintBlockStatement.BuildState((BlockStatement) node);
break;
}

return base.Visit(node);
}
}
}
Expand Down
Loading