JintObjectExpression.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using Jint.Collections;
  2. using Jint.Native;
  3. using Jint.Native.Function;
  4. using Jint.Native.Object;
  5. using Jint.Runtime.Descriptors;
  6. namespace Jint.Runtime.Interpreter.Expressions;
  7. /// <summary>
  8. /// https://tc39.es/ecma262/#sec-object-initializer
  9. /// </summary>
  10. internal sealed class JintObjectExpression : JintExpression
  11. {
  12. private JintExpression[] _valueExpressions = Array.Empty<JintExpression>();
  13. private ObjectProperty?[] _properties = Array.Empty<ObjectProperty>();
  14. // check if we can do a shortcut when all are object properties
  15. // and don't require duplicate checking
  16. private bool _canBuildFast;
  17. private bool _initialized;
  18. private sealed class ObjectProperty
  19. {
  20. internal readonly string? _key;
  21. private JsString? _keyJsString;
  22. internal readonly Property _value;
  23. private JintFunctionDefinition? _functionDefinition;
  24. public ObjectProperty(string? key, Property property)
  25. {
  26. _key = key;
  27. _value = property;
  28. }
  29. public JsString? KeyJsString => _keyJsString ??= _key != null ? JsString.Create(_key) : null;
  30. public JintFunctionDefinition GetFunctionDefinition(Engine engine)
  31. {
  32. if (_functionDefinition is not null)
  33. {
  34. return _functionDefinition;
  35. }
  36. var function = _value.Value as IFunction;
  37. if (function is null)
  38. {
  39. ExceptionHelper.ThrowSyntaxError(engine.Realm);
  40. }
  41. _functionDefinition = new JintFunctionDefinition(function);
  42. return _functionDefinition;
  43. }
  44. }
  45. private JintObjectExpression(ObjectExpression expression) : base(expression)
  46. {
  47. }
  48. public static JintExpression Build(ObjectExpression expression)
  49. {
  50. return expression.Properties.Count == 0
  51. ? JintEmptyObjectExpression.Instance
  52. : new JintObjectExpression(expression);
  53. }
  54. private void Initialize()
  55. {
  56. _canBuildFast = true;
  57. var expression = (ObjectExpression) _expression;
  58. ref readonly var properties = ref expression.Properties;
  59. _valueExpressions = new JintExpression[properties.Count];
  60. _properties = new ObjectProperty[properties.Count];
  61. for (var i = 0; i < _properties.Length; i++)
  62. {
  63. string? propName = null;
  64. var property = properties[i];
  65. if (property is Acornima.Ast.ObjectProperty p)
  66. {
  67. if (p.Key is Literal literal)
  68. {
  69. propName = AstExtensions.LiteralKeyToString(literal);
  70. }
  71. if (!p.Computed && p.Key is Identifier identifier)
  72. {
  73. propName = identifier.Name;
  74. _canBuildFast &= !string.Equals(propName, "__proto__", StringComparison.Ordinal);
  75. }
  76. _properties[i] = new ObjectProperty(propName, p);
  77. if (p.Kind is PropertyKind.Init)
  78. {
  79. var propertyValue = p.Value;
  80. _valueExpressions[i] = Build((Expression) propertyValue);
  81. _canBuildFast &= !propertyValue.IsFunctionDefinition();
  82. }
  83. else
  84. {
  85. _canBuildFast = false;
  86. }
  87. }
  88. else if (property is SpreadElement spreadElement)
  89. {
  90. _canBuildFast = false;
  91. _properties[i] = null;
  92. _valueExpressions[i] = Build(spreadElement.Argument);
  93. }
  94. else
  95. {
  96. ExceptionHelper.ThrowArgumentOutOfRangeException("property", "cannot handle property " + property);
  97. }
  98. _canBuildFast &= propName != null;
  99. }
  100. }
  101. protected override object EvaluateInternal(EvaluationContext context)
  102. {
  103. if (!_initialized)
  104. {
  105. Initialize();
  106. _initialized = true;
  107. }
  108. return _canBuildFast
  109. ? BuildObjectFast(context)
  110. : BuildObjectNormal(context);
  111. }
  112. /// <summary>
  113. /// Version that can safely build plain object with only normal init/data fields fast.
  114. /// </summary>
  115. private JsObject BuildObjectFast(EvaluationContext context)
  116. {
  117. var obj = new JsObject(context.Engine);
  118. var properties = new PropertyDictionary(_properties.Length, checkExistingKeys: true);
  119. for (var i = 0; i < _properties.Length; i++)
  120. {
  121. var objectProperty = _properties[i];
  122. var valueExpression = _valueExpressions[i];
  123. var propValue = valueExpression.GetValue(context).Clone();
  124. properties[objectProperty!._key!] = new PropertyDescriptor(propValue, PropertyFlag.ConfigurableEnumerableWritable);
  125. }
  126. obj.SetProperties(properties);
  127. return obj;
  128. }
  129. /// <summary>
  130. /// https://tc39.es/ecma262/#sec-object-initializer-runtime-semantics-propertydefinitionevaluation
  131. /// </summary>
  132. private object BuildObjectNormal(EvaluationContext context)
  133. {
  134. var engine = context.Engine;
  135. var obj = engine.Realm.Intrinsics.Object.Construct(_properties.Length);
  136. for (var i = 0; i < _properties.Length; i++)
  137. {
  138. var objectProperty = _properties[i];
  139. if (objectProperty is null)
  140. {
  141. // spread
  142. if (_valueExpressions[i].GetValue(context) is ObjectInstance source)
  143. {
  144. source.CopyDataProperties(obj, null);
  145. }
  146. continue;
  147. }
  148. var property = objectProperty._value;
  149. if (property.Method)
  150. {
  151. ClassDefinition.MethodDefinitionEvaluation(engine, obj, property, enumerable: true);
  152. continue;
  153. }
  154. JsValue? propName = objectProperty.KeyJsString;
  155. if (propName is null)
  156. {
  157. var value = property.TryGetKey(engine);
  158. if (context.IsAbrupt())
  159. {
  160. return value;
  161. }
  162. propName = TypeConverter.ToPropertyKey(value);
  163. }
  164. if (property.Kind == PropertyKind.Init)
  165. {
  166. var expr = _valueExpressions[i];
  167. var completion = expr.GetValue(context);
  168. if (context.IsAbrupt())
  169. {
  170. return completion;
  171. }
  172. var propValue = completion.Clone();
  173. if (string.Equals(objectProperty._key, "__proto__", StringComparison.Ordinal) && !objectProperty._value.Computed && !objectProperty._value.Shorthand)
  174. {
  175. if (propValue.IsObject() || propValue.IsNull())
  176. {
  177. obj.SetPrototypeOf(propValue);
  178. }
  179. continue;
  180. }
  181. if (expr._expression.IsAnonymousFunctionDefinition())
  182. {
  183. var closure = (Function) propValue;
  184. closure.SetFunctionName(propName);
  185. }
  186. obj.CreateDataPropertyOrThrow(propName, propValue);
  187. }
  188. else if (property.Kind is PropertyKind.Get or PropertyKind.Set)
  189. {
  190. var function = objectProperty.GetFunctionDefinition(engine);
  191. var closure = engine.Realm.Intrinsics.Function.OrdinaryFunctionCreate(
  192. engine.Realm.Intrinsics.Function.PrototypeObject,
  193. function,
  194. function.ThisMode,
  195. engine.ExecutionContext.LexicalEnvironment,
  196. engine.ExecutionContext.PrivateEnvironment);
  197. closure.SetFunctionName(propName, property.Kind == PropertyKind.Get ? "get" : "set");
  198. closure.MakeMethod(obj);
  199. var propDesc = new GetSetPropertyDescriptor(
  200. get: property.Kind == PropertyKind.Get ? closure : null,
  201. set: property.Kind == PropertyKind.Set ? closure : null,
  202. PropertyFlag.Enumerable | PropertyFlag.Configurable);
  203. obj.DefinePropertyOrThrow(propName, propDesc);
  204. }
  205. }
  206. return obj;
  207. }
  208. internal sealed class JintEmptyObjectExpression : JintExpression
  209. {
  210. public static JintEmptyObjectExpression Instance = new(new ObjectExpression(NodeList.From(Array.Empty<Node>())));
  211. private JintEmptyObjectExpression(Expression expression) : base(expression)
  212. {
  213. }
  214. protected override object EvaluateInternal(EvaluationContext context)
  215. {
  216. return new JsObject(context.Engine);
  217. }
  218. public override JsValue GetValue(EvaluationContext context)
  219. {
  220. return new JsObject(context.Engine);
  221. }
  222. }
  223. }