-
-
Notifications
You must be signed in to change notification settings - Fork 547
/
FunctionEnvironmentRecord.cs
428 lines (381 loc) · 15.4 KB
/
FunctionEnvironmentRecord.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Esprima.Ast;
using Jint.Native;
using Jint.Native.Array;
using Jint.Native.Function;
using Jint.Native.Iterator;
using Jint.Native.Object;
using Jint.Runtime.Interpreter.Expressions;
namespace Jint.Runtime.Environments
{
/// <summary>
/// https://tc39.es/ecma262/#sec-function-environment-records
/// </summary>
internal sealed class FunctionEnvironmentRecord : DeclarativeEnvironmentRecord
{
private enum ThisBindingStatus
{
Lexical,
Initialized,
Uninitialized
}
private JsValue _thisValue;
private ThisBindingStatus _thisBindingStatus;
internal readonly FunctionInstance _functionObject;
public FunctionEnvironmentRecord(
Engine engine,
FunctionInstance functionObject,
JsValue newTarget) : base(engine)
{
_functionObject = functionObject;
NewTarget = newTarget;
if (functionObject._functionDefinition.Function is ArrowFunctionExpression)
{
_thisBindingStatus = ThisBindingStatus.Lexical;
}
else
{
_thisBindingStatus = ThisBindingStatus.Uninitialized;
}
}
public override bool HasThisBinding() => _thisBindingStatus != ThisBindingStatus.Lexical;
public override bool HasSuperBinding() =>
_thisBindingStatus != ThisBindingStatus.Lexical && !_functionObject._homeObject.IsUndefined();
public override JsValue WithBaseObject()
{
return _thisBindingStatus == ThisBindingStatus.Uninitialized
? ExceptionHelper.ThrowReferenceError<JsValue>(_engine)
: _thisValue;
}
public JsValue BindThisValue(JsValue value)
{
if (_thisBindingStatus == ThisBindingStatus.Initialized)
{
ExceptionHelper.ThrowReferenceError<JsValue>(_engine);
}
_thisValue = value;
_thisBindingStatus = ThisBindingStatus.Initialized;
return value;
}
public override JsValue GetThisBinding()
{
return _thisBindingStatus == ThisBindingStatus.Uninitialized
? ExceptionHelper.ThrowReferenceError<JsValue>(_engine)
: _thisValue;
}
public JsValue GetSuperBase()
{
var home = _functionObject._homeObject;
return home.IsUndefined()
? Undefined
: ((ObjectInstance) home).GetPrototypeOf();
}
// optimization to have logic near record internal structures.
internal void InitializeParameters(
Key[] parameterNames,
bool hasDuplicates,
JsValue[] arguments)
{
var value = hasDuplicates ? Undefined : null;
var directSet = !hasDuplicates && _dictionary.Count == 0;
for (var i = 0; (uint) i < (uint) parameterNames.Length; i++)
{
var paramName = parameterNames[i];
if (directSet || !_dictionary.ContainsKey(paramName))
{
var parameterValue = value;
if (arguments != null)
{
parameterValue = (uint) i < (uint) arguments.Length ? arguments[i] : Undefined;
}
_dictionary[paramName] = new Binding(parameterValue, canBeDeleted: false, mutable: true, strict: false);
}
}
}
internal void AddFunctionParameters(IFunction functionDeclaration, JsValue[] arguments)
{
bool empty = _dictionary.Count == 0;
ref readonly var parameters = ref functionDeclaration.Params;
var count = parameters.Count;
for (var i = 0; i < count; i++)
{
SetFunctionParameter(parameters[i], arguments, i, empty);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetFunctionParameter(
Node parameter,
JsValue[] arguments,
int index,
bool initiallyEmpty)
{
if (parameter is Identifier identifier)
{
var argument = (uint) index < (uint) arguments.Length ? arguments[index] : Undefined;
SetItemSafely(identifier.Name, argument, initiallyEmpty);
}
else
{
SetFunctionParameterUnlikely(parameter, arguments, index, initiallyEmpty);
}
}
private void SetFunctionParameterUnlikely(
Node parameter,
JsValue[] arguments,
int index,
bool initiallyEmpty)
{
var argument = arguments.Length > index ? arguments[index] : Undefined;
if (parameter is RestElement restElement)
{
HandleRestElementArray(restElement, arguments, index, initiallyEmpty);
}
else if (parameter is ArrayPattern arrayPattern)
{
HandleArrayPattern(initiallyEmpty, argument, arrayPattern);
}
else if (parameter is ObjectPattern objectPattern)
{
HandleObjectPattern(initiallyEmpty, argument, objectPattern);
}
else if (parameter is AssignmentPattern assignmentPattern)
{
HandleAssignmentPatternOrExpression(assignmentPattern.Left, assignmentPattern.Right, argument, initiallyEmpty);
}
else if (parameter is AssignmentExpression assignmentExpression)
{
HandleAssignmentPatternOrExpression(assignmentExpression.Left, assignmentExpression.Right, argument, initiallyEmpty);
}
}
private void HandleObjectPattern(bool initiallyEmpty, JsValue argument, ObjectPattern objectPattern)
{
if (argument.IsNullOrUndefined())
{
ExceptionHelper.ThrowTypeError(_engine, "Destructed parameter is null or undefined");
}
if (!argument.IsObject())
{
return;
}
var argumentObject = argument.AsObject();
var processedProperties = objectPattern.Properties.Count > 0 &&
objectPattern.Properties[objectPattern.Properties.Count - 1] is RestElement
? new HashSet<JsValue>()
: null;
var jsValues = _engine._jsValueArrayPool.RentArray(1);
foreach (var property in objectPattern.Properties)
{
var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
var paramVarEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
_engine.EnterExecutionContext(paramVarEnv, paramVarEnv);
try
{
if (property is Property p)
{
JsString propertyName;
if (p.Key is Identifier propertyIdentifier)
{
propertyName = JsString.Create(propertyIdentifier.Name);
}
else if (p.Key is Literal propertyLiteral)
{
propertyName = JsString.Create(propertyLiteral.Raw);
}
else if (p.Key is CallExpression callExpression)
{
var jintCallExpression = new JintCallExpression(_engine, callExpression);
var jsValue = jintCallExpression.GetValue();
propertyName = TypeConverter.ToJsString(jsValue);
}
else
{
propertyName = ExceptionHelper.ThrowArgumentOutOfRangeException<JsString>("property", "unknown object pattern property type");
}
processedProperties?.Add(propertyName.ToString());
jsValues[0] = argumentObject.Get(propertyName);
SetFunctionParameter(p.Value, jsValues, 0, initiallyEmpty);
}
else
{
if (((RestElement) property).Argument is Identifier restIdentifier)
{
var rest = _engine.Object.Construct(argumentObject.Properties.Count - processedProperties.Count);
argumentObject.CopyDataProperties(rest, processedProperties);
SetItemSafely(restIdentifier.Name, rest, initiallyEmpty);
}
else
{
ExceptionHelper.ThrowSyntaxError(_engine, "Object rest parameter can only be objects");
}
}
}
finally
{
_engine.LeaveExecutionContext();
}
}
_engine._jsValueArrayPool.ReturnArray(jsValues);
}
private void HandleArrayPattern(bool initiallyEmpty, JsValue argument, ArrayPattern arrayPattern)
{
if (argument.IsNull())
{
ExceptionHelper.ThrowTypeError(_engine, "Destructed parameter is null");
}
ArrayInstance array = null;
var arrayContents = System.Array.Empty<JsValue>();
if (argument.IsArray())
{
array = argument.AsArray();
}
else if (argument.IsObject() && argument.TryGetIterator(_engine, out var iterator))
{
array = _engine.Array.ConstructFast(0);
var protocol = new ArrayPatternProtocol(_engine, array, iterator, arrayPattern.Elements.Count);
protocol.Execute();
}
if (!ReferenceEquals(array, null))
{
arrayContents = new JsValue[array.GetLength()];
for (uint i = 0; i < (uint) arrayContents.Length; i++)
{
arrayContents[i] = array.Get(i);
}
}
for (uint arrayIndex = 0; arrayIndex < arrayPattern.Elements.Count; arrayIndex++)
{
SetFunctionParameter(arrayPattern.Elements[(int) arrayIndex], arrayContents, (int) arrayIndex, initiallyEmpty);
}
}
private void HandleRestElementArray(
RestElement restElement,
JsValue[] arguments,
int index,
bool initiallyEmpty)
{
// index + 1 == parameters.count because rest is last
int restCount = arguments.Length - (index + 1) + 1;
uint count = restCount > 0 ? (uint) restCount : 0;
var rest = _engine.Array.ConstructFast(count);
uint targetIndex = 0;
for (var argIndex = index; argIndex < arguments.Length; ++argIndex)
{
rest.SetIndexValue(targetIndex++, arguments[argIndex], updateLength: false);
}
if (restElement.Argument is Identifier restIdentifier)
{
SetItemSafely(restIdentifier.Name, rest, initiallyEmpty);
}
else if (restElement.Argument is BindingPattern bindingPattern)
{
SetFunctionParameter(bindingPattern, new JsValue[]
{
rest
}, index, initiallyEmpty);
}
else
{
ExceptionHelper.ThrowSyntaxError(_engine, "Rest parameters can only be identifiers or arrays");
}
}
private void HandleAssignmentPatternOrExpression(
Node left,
Node right,
JsValue argument,
bool initiallyEmpty)
{
var idLeft = left as Identifier;
if (idLeft != null
&& right is Identifier idRight
&& idLeft.Name == idRight.Name)
{
ExceptionHelper.ThrowReferenceError(_engine, idRight.Name);
}
if (argument.IsUndefined())
{
var expression = right.As<Expression>();
var jintExpression = JintExpression.Build(_engine, expression);
var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
var paramVarEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
_engine.EnterExecutionContext(paramVarEnv, paramVarEnv);
try
{
argument = jintExpression.GetValue();
}
finally
{
_engine.LeaveExecutionContext();
}
if (idLeft != null && right.IsFunctionWithName())
{
((FunctionInstance) argument).SetFunctionName(idLeft.Name);
}
}
SetFunctionParameter(left, new[]
{
argument
}, 0, initiallyEmpty);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetItemSafely(Key name, JsValue argument, bool initiallyEmpty)
{
if (initiallyEmpty)
{
_dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
}
else
{
SetItemCheckExisting(name, argument);
}
}
private void SetItemCheckExisting(Key name, JsValue argument)
{
if (!_dictionary.TryGetValue(name, out var existing))
{
_dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
}
else
{
if (existing.Mutable)
{
_dictionary[name] = existing.ChangeValue(argument);
}
else
{
ExceptionHelper.ThrowTypeError(_engine, "Can't update the value of an immutable binding.");
}
}
}
private sealed class ArrayPatternProtocol : IteratorProtocol
{
private readonly ArrayInstance _instance;
private readonly int _max;
private long _index = -1;
public ArrayPatternProtocol(
Engine engine,
ArrayInstance instance,
IIterator iterator,
int max) : base(engine, iterator, 0)
{
_instance = instance;
_max = max;
}
protected override void ProcessItem(JsValue[] args, JsValue currentValue)
{
_index++;
var jsValue = ExtractValueFromIteratorInstance(currentValue);
_instance.SetIndexValue((uint) _index, jsValue, updateLength: false);
}
protected override bool ShouldContinue => _index < _max;
protected override void IterationEnd()
{
if (_index >= 0)
{
_instance.SetLength((uint) _index);
IteratorClose(CompletionType.Normal);
}
}
}
}
}