JintFunctionDefinition.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Esprima;
  2. using Esprima.Ast;
  3. using Jint.Runtime.Interpreter.Statements;
  4. namespace Jint.Runtime.Interpreter
  5. {
  6. internal sealed class JintFunctionDefinition
  7. {
  8. internal readonly IFunction _function;
  9. internal readonly string _name;
  10. internal readonly bool _strict;
  11. internal readonly string[] _parameterNames;
  12. internal readonly JintStatement _body;
  13. internal bool _hasRestParameter;
  14. public readonly HoistingScope _hoistingScope;
  15. public JintFunctionDefinition(Engine engine, IFunction function)
  16. {
  17. _function = function;
  18. _hoistingScope = function.HoistingScope;
  19. _name = !string.IsNullOrEmpty(function.Id?.Name) ? function.Id.Name : null;
  20. _strict = function.Strict;
  21. _parameterNames = GetParameterNames(function);
  22. _body = JintStatement.Build(engine, function.Body);
  23. }
  24. private string[] GetParameterNames(IFunction functionDeclaration)
  25. {
  26. var list = functionDeclaration.Params;
  27. var count = list.Count;
  28. if (count == 0)
  29. {
  30. return System.ArrayExt.Empty<string>();
  31. }
  32. var names = new string[count];
  33. for (var i = 0; i < count; ++i)
  34. {
  35. var node = list[i];
  36. if (node is Identifier identifier)
  37. {
  38. names[i] = identifier.Name;
  39. }
  40. else if (node is AssignmentPattern ap)
  41. {
  42. names[i] = ((Identifier) ap.Left).Name;
  43. }
  44. else if (node is RestElement re)
  45. {
  46. if (re.Argument is Identifier id)
  47. {
  48. names[i] = id.Name;
  49. }
  50. else
  51. {
  52. names[i] = "";
  53. }
  54. _hasRestParameter = true;
  55. }
  56. }
  57. return names;
  58. }
  59. }
  60. }