JintCallStack.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Text;
  5. using Esprima;
  6. using Esprima.Ast;
  7. using Jint.Collections;
  8. using Jint.Native.Function;
  9. using Jint.Runtime.Environments;
  10. using Jint.Runtime.Interpreter.Expressions;
  11. using Environment = Jint.Runtime.Environments.Environment;
  12. namespace Jint.Runtime.CallStack
  13. {
  14. // smaller version with only required info
  15. internal readonly record struct CallStackExecutionContext
  16. {
  17. public CallStackExecutionContext(in ExecutionContext context)
  18. {
  19. LexicalEnvironment = context.LexicalEnvironment;
  20. }
  21. internal readonly Environment LexicalEnvironment;
  22. internal Environment GetThisEnvironment()
  23. {
  24. var lex = LexicalEnvironment;
  25. while (true)
  26. {
  27. if (lex is not null)
  28. {
  29. if (lex.HasThisBinding())
  30. {
  31. return lex;
  32. }
  33. lex = lex._outerEnv;
  34. }
  35. }
  36. }
  37. }
  38. internal sealed class JintCallStack
  39. {
  40. private readonly RefStack<CallStackElement> _stack = new();
  41. private readonly Dictionary<CallStackElement, int>? _statistics;
  42. // Internal for use by DebugHandler
  43. internal RefStack<CallStackElement> Stack => _stack;
  44. public JintCallStack(bool trackRecursionDepth)
  45. {
  46. if (trackRecursionDepth)
  47. {
  48. _statistics = new Dictionary<CallStackElement, int>(CallStackElementComparer.Instance);
  49. }
  50. }
  51. public int Push(FunctionInstance functionInstance, JintExpression? expression, in ExecutionContext executionContext)
  52. {
  53. var item = new CallStackElement(functionInstance, expression, new CallStackExecutionContext(executionContext));
  54. _stack.Push(item);
  55. if (_statistics is not null)
  56. {
  57. #pragma warning disable CA1854
  58. #pragma warning disable CA1864
  59. if (_statistics.ContainsKey(item))
  60. #pragma warning restore CA1854
  61. #pragma warning restore CA1864
  62. {
  63. return ++_statistics[item];
  64. }
  65. else
  66. {
  67. _statistics.Add(item, 0);
  68. return 0;
  69. }
  70. }
  71. return -1;
  72. }
  73. public CallStackElement Pop()
  74. {
  75. ref readonly var item = ref _stack.Pop();
  76. if (_statistics is not null)
  77. {
  78. if (_statistics[item] == 0)
  79. {
  80. _statistics.Remove(item);
  81. }
  82. else
  83. {
  84. _statistics[item]--;
  85. }
  86. }
  87. return item;
  88. }
  89. public bool TryPeek([NotNullWhen(true)] out CallStackElement item)
  90. {
  91. return _stack.TryPeek(out item);
  92. }
  93. public int Count => _stack._size;
  94. public void Clear()
  95. {
  96. _stack.Clear();
  97. _statistics?.Clear();
  98. }
  99. public override string ToString()
  100. {
  101. return string.Join("->", _stack.Select(static cse => cse.ToString()).Reverse());
  102. }
  103. internal string BuildCallStackString(Location location, int excludeTop = 0)
  104. {
  105. static void AppendLocation(
  106. ref ValueStringBuilder sb,
  107. string shortDescription,
  108. in Location loc,
  109. in CallStackElement? element)
  110. {
  111. sb.Append(" at");
  112. if (!string.IsNullOrWhiteSpace(shortDescription))
  113. {
  114. sb.Append(' ');
  115. sb.Append(shortDescription);
  116. }
  117. if (element?.Arguments is not null)
  118. {
  119. // it's a function
  120. sb.Append(" (");
  121. for (var index = 0; index < element.Value.Arguments.Value.Count; index++)
  122. {
  123. if (index != 0)
  124. {
  125. sb.Append(", ");
  126. }
  127. var arg = element.Value.Arguments.Value[index];
  128. sb.Append(GetPropertyKey(arg));
  129. }
  130. sb.Append(')');
  131. }
  132. sb.Append(' ');
  133. sb.Append(loc.Source);
  134. sb.Append(':');
  135. sb.Append(loc.End.Line.ToString(CultureInfo.InvariantCulture));
  136. sb.Append(':');
  137. sb.Append((loc.Start.Column + 1).ToString(CultureInfo.InvariantCulture)); // report column number instead of index
  138. sb.Append(System.Environment.NewLine);
  139. }
  140. var builder = new ValueStringBuilder();
  141. // stack is one frame behind function-wise when we start to process it from expression level
  142. var index = _stack._size - 1 - excludeTop;
  143. var element = index >= 0 ? _stack[index] : (CallStackElement?) null;
  144. var shortDescription = element?.ToString() ?? "";
  145. AppendLocation(ref builder, shortDescription, location, element);
  146. location = element?.Location ?? default;
  147. index--;
  148. while (index >= -1)
  149. {
  150. element = index >= 0 ? _stack[index] : null;
  151. shortDescription = element?.ToString() ?? "";
  152. AppendLocation(ref builder, shortDescription, location, element);
  153. location = element?.Location ?? default;
  154. index--;
  155. }
  156. var result = builder.AsSpan().TrimEnd().ToString();
  157. builder.Dispose();
  158. return result;
  159. }
  160. /// <summary>
  161. /// A version of <see cref="EsprimaExtensions.GetKey"/> that cannot get into loop as we are already building a stack.
  162. /// </summary>
  163. private static string GetPropertyKey(Node expression)
  164. {
  165. if (expression is Literal literal)
  166. {
  167. return EsprimaExtensions.LiteralKeyToString(literal);
  168. }
  169. if (expression is Identifier identifier)
  170. {
  171. return identifier.Name ?? "";
  172. }
  173. if (expression is StaticMemberExpression staticMemberExpression)
  174. {
  175. return GetPropertyKey(staticMemberExpression.Object) + "." +
  176. GetPropertyKey(staticMemberExpression.Property);
  177. }
  178. return "?";
  179. }
  180. }
  181. }