forked from sebastienros/jint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Engine.cs
885 lines (731 loc) · 32.9 KB
/
Engine.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
using System;
using System.Collections.Generic;
using Esprima;
using Esprima.Ast;
using Jint.Native;
using Jint.Native.Argument;
using Jint.Native.Array;
using Jint.Native.Boolean;
using Jint.Native.Date;
using Jint.Native.Error;
using Jint.Native.Function;
using Jint.Native.Global;
using Jint.Native.Json;
using Jint.Native.Math;
using Jint.Native.Number;
using Jint.Native.Object;
using Jint.Native.RegExp;
using Jint.Native.String;
using Jint.Native.Symbol;
using Jint.Runtime;
using Jint.Runtime.CallStack;
using Jint.Runtime.Debugger;
using Jint.Runtime.Descriptors;
using Jint.Runtime.Environments;
using Jint.Runtime.Interop;
using Jint.Runtime.References;
namespace Jint
{
public class Engine
{
private readonly ExpressionInterpreter _expressions;
private readonly StatementInterpreter _statements;
private readonly Stack<ExecutionContext> _executionContexts;
private JsValue _completionValue = JsValue.Undefined;
private int _statementsCount;
private long _timeoutTicks;
private INode _lastSyntaxNode = null;
public ITypeConverter ClrTypeConverter;
// cache of types used when resolving CLR type names
internal Dictionary<string, Type> TypeCache = new Dictionary<string, Type>();
internal static Dictionary<Type, Func<Engine, object, JsValue>> TypeMappers = new Dictionary<Type, Func<Engine, object, JsValue>>()
{
{ typeof(bool), (Engine engine, object v) => (bool) v ? JsValue.True : JsValue.False },
{ typeof(byte), (Engine engine, object v) => JsValue.FromInt((byte)v) },
{ typeof(char), (Engine engine, object v) => JsValue.FromChar((char)v) },
{ typeof(DateTime), (Engine engine, object v) => engine.Date.Construct((DateTime)v) },
{ typeof(DateTimeOffset), (Engine engine, object v) => engine.Date.Construct((DateTimeOffset)v) },
{ typeof(decimal), (Engine engine, object v) => (JsValue) (double)(decimal)v },
{ typeof(double), (Engine engine, object v) => (JsValue)(double)v },
{ typeof(Int16), (Engine engine, object v) => JsValue.FromInt((Int16)v) },
{ typeof(Int32), (Engine engine, object v) => JsValue.FromInt((Int32)v) },
{ typeof(Int64), (Engine engine, object v) => (JsValue)(Int64)v },
{ typeof(SByte), (Engine engine, object v) => JsValue.FromInt((SByte)v) },
{ typeof(Single), (Engine engine, object v) => (JsValue)(Single)v },
{ typeof(string), (Engine engine, object v) => (JsValue) (string)v },
{ typeof(UInt16), (Engine engine, object v) => JsValue.FromInt((UInt16)v) },
{ typeof(UInt32), (Engine engine, object v) => JsValue.FromInt((UInt32)v) },
{ typeof(UInt64), (Engine engine, object v) => JsValue.FromInt((UInt64)v) },
{ typeof(JsValue), (Engine engine, object v) => (JsValue)v },
{ typeof(System.Text.RegularExpressions.Regex), (Engine engine, object v) => engine.RegExp.Construct((System.Text.RegularExpressions.Regex)v, "") }
};
internal JintCallStack CallStack = new JintCallStack();
public Engine() : this(null)
{
}
public Engine(Action<Options> options)
{
_executionContexts = new Stack<ExecutionContext>();
Global = GlobalObject.CreateGlobalObject(this);
Object = ObjectConstructor.CreateObjectConstructor(this);
Function = FunctionConstructor.CreateFunctionConstructor(this);
Symbol = SymbolConstructor.CreateSymbolConstructor(this);
Array = ArrayConstructor.CreateArrayConstructor(this);
String = StringConstructor.CreateStringConstructor(this);
RegExp = RegExpConstructor.CreateRegExpConstructor(this);
Number = NumberConstructor.CreateNumberConstructor(this);
Boolean = BooleanConstructor.CreateBooleanConstructor(this);
Date = DateConstructor.CreateDateConstructor(this);
Math = MathInstance.CreateMathObject(this);
Json = JsonInstance.CreateJsonObject(this);
Error = ErrorConstructor.CreateErrorConstructor(this, "Error");
EvalError = ErrorConstructor.CreateErrorConstructor(this, "EvalError");
RangeError = ErrorConstructor.CreateErrorConstructor(this, "RangeError");
ReferenceError = ErrorConstructor.CreateErrorConstructor(this, "ReferenceError");
SyntaxError = ErrorConstructor.CreateErrorConstructor(this, "SyntaxError");
TypeError = ErrorConstructor.CreateErrorConstructor(this, "TypeError");
UriError = ErrorConstructor.CreateErrorConstructor(this, "URIError");
GlobalSymbolRegistry = new GlobalSymbolRegistry();
// Because the properties might need some of the built-in object
// their configuration is delayed to a later step
Global.Configure();
Object.Configure();
Object.PrototypeObject.Configure();
Symbol.Configure();
Symbol.PrototypeObject.Configure();
Function.Configure();
Function.PrototypeObject.Configure();
Array.Configure();
Array.PrototypeObject.Configure();
String.Configure();
String.PrototypeObject.Configure();
RegExp.Configure();
RegExp.PrototypeObject.Configure();
Number.Configure();
Number.PrototypeObject.Configure();
Boolean.Configure();
Boolean.PrototypeObject.Configure();
Date.Configure();
Date.PrototypeObject.Configure();
Math.Configure();
Json.Configure();
Error.Configure();
Error.PrototypeObject.Configure();
// create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3
GlobalEnvironment = LexicalEnvironment.NewObjectEnvironment(this, Global, null, false);
// create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1
EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global);
Options = new Options();
if (options != null)
{
options(Options);
}
Eval = new EvalFunctionInstance(this, new string[0], LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode);
Global.FastAddProperty("eval", Eval, true, false, true);
_statements = new StatementInterpreter(this);
_expressions = new ExpressionInterpreter(this);
if (Options._IsClrAllowed)
{
Global.FastAddProperty("System", new NamespaceReference(this, "System"), false, false, false);
Global.FastAddProperty("importNamespace", new ClrFunctionInstance(this, (thisObj, arguments) =>
{
return new NamespaceReference(this, TypeConverter.ToString(arguments.At(0)));
}), false, false, false);
}
ClrTypeConverter = new DefaultTypeConverter(this);
BreakPoints = new List<BreakPoint>();
DebugHandler = new DebugHandler(this);
}
public LexicalEnvironment GlobalEnvironment;
public GlobalObject Global { get; private set; }
public ObjectConstructor Object { get; private set; }
public FunctionConstructor Function { get; private set; }
public ArrayConstructor Array { get; private set; }
public StringConstructor String { get; private set; }
public RegExpConstructor RegExp { get; private set; }
public BooleanConstructor Boolean { get; private set; }
public NumberConstructor Number { get; private set; }
public DateConstructor Date { get; private set; }
public MathInstance Math { get; private set; }
public JsonInstance Json { get; private set; }
public SymbolConstructor Symbol { get; private set; }
public EvalFunctionInstance Eval { get; private set; }
public ErrorConstructor Error { get; private set; }
public ErrorConstructor EvalError { get; private set; }
public ErrorConstructor SyntaxError { get; private set; }
public ErrorConstructor TypeError { get; private set; }
public ErrorConstructor RangeError { get; private set; }
public ErrorConstructor ReferenceError { get; private set; }
public ErrorConstructor UriError { get; private set; }
public ExecutionContext ExecutionContext { get { return _executionContexts.Peek(); } }
public GlobalSymbolRegistry GlobalSymbolRegistry { get; }
internal Options Options { get; private set; }
#region Debugger
public delegate StepMode DebugStepDelegate(object sender, DebugInformation e);
public delegate StepMode BreakDelegate(object sender, DebugInformation e);
public event DebugStepDelegate Step;
public event BreakDelegate Break;
internal DebugHandler DebugHandler { get; private set; }
public List<BreakPoint> BreakPoints { get; private set; }
internal StepMode? InvokeStepEvent(DebugInformation info)
{
if (Step != null)
{
return Step(this, info);
}
return null;
}
internal StepMode? InvokeBreakEvent(DebugInformation info)
{
if (Break != null)
{
return Break(this, info);
}
return null;
}
#endregion
public ExecutionContext EnterExecutionContext(LexicalEnvironment lexicalEnvironment, LexicalEnvironment variableEnvironment, JsValue thisBinding)
{
var executionContext = new ExecutionContext
{
LexicalEnvironment = lexicalEnvironment,
VariableEnvironment = variableEnvironment,
ThisBinding = thisBinding
};
_executionContexts.Push(executionContext);
return executionContext;
}
public Engine SetValue(string name, Delegate value)
{
Global.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true);
return this;
}
public Engine SetValue(string name, string value)
{
return SetValue(name, new JsValue(value));
}
public Engine SetValue(string name, double value)
{
return SetValue(name, new JsValue(value));
}
public Engine SetValue(string name, int value)
{
return SetValue(name, JsValue.FromInt(value));
}
public Engine SetValue(string name, bool value)
{
return SetValue(name, value ? JsValue.True : JsValue.False);
}
public Engine SetValue(string name, JsValue value)
{
Global.Put(name, value, false);
return this;
}
public Engine SetValue(string name, Object obj)
{
return SetValue(name, JsValue.FromObject(this, obj));
}
public void LeaveExecutionContext()
{
_executionContexts.Pop();
}
/// <summary>
/// Initializes the statements count
/// </summary>
public void ResetStatementsCount()
{
_statementsCount = 0;
}
public void ResetTimeoutTicks()
{
var timeoutIntervalTicks = Options._TimeoutInterval.Ticks;
_timeoutTicks = timeoutIntervalTicks > 0 ? DateTime.UtcNow.Ticks + timeoutIntervalTicks : 0;
}
/// <summary>
/// Initializes list of references of called functions
/// </summary>
public void ResetCallStack()
{
CallStack.Clear();
}
public Engine Execute(string source)
{
return Execute(source, new ParserOptions
{
AdaptRegexp = true,
Tolerant = false,
Loc = true
});
}
public Engine Execute(string source, ParserOptions parserOptions)
{
var parser = new JavaScriptParser(source, parserOptions);
return Execute(parser.ParseProgram());
}
public Engine Execute(Program program)
{
ResetStatementsCount();
ResetTimeoutTicks();
ResetLastStatement();
ResetCallStack();
using (new StrictModeScope(Options._IsStrict || program.Strict))
{
DeclarationBindingInstantiation(DeclarationBindingType.GlobalCode, program.HoistingScope.FunctionDeclarations, program.HoistingScope.VariableDeclarations, null, null);
var result = _statements.ExecuteProgram(program);
if (result.Type == Completion.Throw)
{
throw new JavaScriptException(result.GetValueOrDefault())
.SetCallstack(this, result.Location);
}
_completionValue = result.GetValueOrDefault();
}
return this;
}
private void ResetLastStatement()
{
_lastSyntaxNode = null;
}
/// <summary>
/// Gets the last evaluated statement completion value
/// </summary>
public JsValue GetCompletionValue()
{
return _completionValue;
}
public Completion ExecuteStatement(Statement statement)
{
var maxStatements = Options._MaxStatements;
if (maxStatements > 0 && _statementsCount++ > maxStatements)
{
throw new StatementsCountOverflowException();
}
if (_timeoutTicks > 0 && _timeoutTicks < DateTime.UtcNow.Ticks)
{
throw new TimeoutException();
}
_lastSyntaxNode = statement;
if (Options._IsDebugMode)
{
DebugHandler.OnStep(statement);
}
switch (statement.Type)
{
case Nodes.BlockStatement:
return _statements.ExecuteBlockStatement(statement.As<BlockStatement>());
case Nodes.BreakStatement:
return _statements.ExecuteBreakStatement(statement.As<BreakStatement>());
case Nodes.ContinueStatement:
return _statements.ExecuteContinueStatement(statement.As<ContinueStatement>());
case Nodes.DoWhileStatement:
return _statements.ExecuteDoWhileStatement(statement.As<DoWhileStatement>());
case Nodes.DebuggerStatement:
return _statements.ExecuteDebuggerStatement(statement.As<DebuggerStatement>());
case Nodes.EmptyStatement:
return _statements.ExecuteEmptyStatement(statement.As<EmptyStatement>());
case Nodes.ExpressionStatement:
return _statements.ExecuteExpressionStatement(statement.As<ExpressionStatement>());
case Nodes.ForStatement:
return _statements.ExecuteForStatement(statement.As<ForStatement>());
case Nodes.ForInStatement:
return _statements.ExecuteForInStatement(statement.As<ForInStatement>());
case Nodes.FunctionDeclaration:
return Completion.Empty;
case Nodes.IfStatement:
return _statements.ExecuteIfStatement(statement.As<IfStatement>());
case Nodes.LabeledStatement:
return _statements.ExecuteLabeledStatement(statement.As<LabeledStatement>());
case Nodes.ReturnStatement:
return _statements.ExecuteReturnStatement(statement.As<ReturnStatement>());
case Nodes.SwitchStatement:
return _statements.ExecuteSwitchStatement(statement.As<SwitchStatement>());
case Nodes.ThrowStatement:
return _statements.ExecuteThrowStatement(statement.As<ThrowStatement>());
case Nodes.TryStatement:
return _statements.ExecuteTryStatement(statement.As<TryStatement>());
case Nodes.VariableDeclaration:
return _statements.ExecuteVariableDeclaration(statement.As<VariableDeclaration>());
case Nodes.WhileStatement:
return _statements.ExecuteWhileStatement(statement.As<WhileStatement>());
case Nodes.WithStatement:
return _statements.ExecuteWithStatement(statement.As<WithStatement>());
case Nodes.Program:
return _statements.ExecuteProgram(statement.As<Program>());
default:
throw new ArgumentOutOfRangeException();
}
}
public object EvaluateExpression(Expression expression)
{
_lastSyntaxNode = expression;
switch (expression.Type)
{
case Nodes.AssignmentExpression:
return _expressions.EvaluateAssignmentExpression(expression.As<AssignmentExpression>());
case Nodes.ArrayExpression:
return _expressions.EvaluateArrayExpression(expression.As<ArrayExpression>());
case Nodes.BinaryExpression:
return _expressions.EvaluateBinaryExpression(expression.As<BinaryExpression>());
case Nodes.CallExpression:
return _expressions.EvaluateCallExpression(expression.As<CallExpression>());
case Nodes.ConditionalExpression:
return _expressions.EvaluateConditionalExpression(expression.As<ConditionalExpression>());
case Nodes.FunctionExpression:
return _expressions.EvaluateFunctionExpression(expression.As<IFunction>());
case Nodes.Identifier:
return _expressions.EvaluateIdentifier(expression.As<Identifier>());
case Nodes.Literal:
return _expressions.EvaluateLiteral(expression.As<Literal>());
case Nodes.LogicalExpression:
return _expressions.EvaluateLogicalExpression(expression.As<BinaryExpression>());
case Nodes.MemberExpression:
return _expressions.EvaluateMemberExpression(expression.As<MemberExpression>());
case Nodes.NewExpression:
return _expressions.EvaluateNewExpression(expression.As<NewExpression>());
case Nodes.ObjectExpression:
return _expressions.EvaluateObjectExpression(expression.As<ObjectExpression>());
case Nodes.SequenceExpression:
return _expressions.EvaluateSequenceExpression(expression.As<SequenceExpression>());
case Nodes.ThisExpression:
return _expressions.EvaluateThisExpression(expression.As<ThisExpression>());
case Nodes.UpdateExpression:
return _expressions.EvaluateUpdateExpression(expression.As<UpdateExpression>());
case Nodes.UnaryExpression:
return _expressions.EvaluateUnaryExpression(expression.As<UnaryExpression>());
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public JsValue GetValue(object value)
{
var reference = value as Reference;
if (reference == null)
{
var completion = value as Completion;
if (completion != null)
{
return GetValue(completion.Value);
}
return (JsValue)value;
}
if (reference.IsUnresolvableReference())
{
if (Options._ReferenceResolver != null &&
Options._ReferenceResolver.TryUnresolvableReference(this, reference, out JsValue val))
{
return val;
}
throw new JavaScriptException(ReferenceError, reference.GetReferencedName() + " is not defined");
}
var baseValue = reference.GetBase();
if (reference.IsPropertyReference())
{
if (Options._ReferenceResolver != null &&
Options._ReferenceResolver.TryPropertyReference(this, reference, ref baseValue))
{
return baseValue;
}
if (reference.HasPrimitiveBase() == false)
{
var o = TypeConverter.ToObject(this, baseValue);
return o.Get(reference.GetReferencedName());
}
else
{
var o = TypeConverter.ToObject(this, baseValue);
var desc = o.GetProperty(reference.GetReferencedName());
if (desc == PropertyDescriptor.Undefined)
{
return JsValue.Undefined;
}
if (desc.IsDataDescriptor())
{
return desc.Value;
}
var getter = desc.Get;
if (getter == Undefined.Instance)
{
return Undefined.Instance;
}
var callable = (ICallable)getter.AsObject();
return callable.Call(baseValue, Arguments.Empty);
}
}
else
{
var record = baseValue.As<EnvironmentRecord>();
if (record == null)
{
throw new ArgumentException();
}
return record.GetBindingValue(reference.GetReferencedName(), reference.IsStrict());
}
}
/// <summary>
/// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.2
/// </summary>
/// <param name="reference"></param>
/// <param name="value"></param>
public void PutValue(Reference reference, JsValue value)
{
if (reference.IsUnresolvableReference())
{
if (reference.IsStrict())
{
throw new JavaScriptException(ReferenceError);
}
Global.Put(reference.GetReferencedName(), value, false);
}
else if (reference.IsPropertyReference())
{
var baseValue = reference.GetBase();
if (!reference.HasPrimitiveBase())
{
baseValue.AsObject().Put(reference.GetReferencedName(), value, reference.IsStrict());
}
else
{
PutPrimitiveBase(baseValue, reference.GetReferencedName(), value, reference.IsStrict());
}
}
else
{
var baseValue = reference.GetBase();
var record = baseValue.As<EnvironmentRecord>();
if (record == null)
{
throw new ArgumentNullException();
}
record.SetMutableBinding(reference.GetReferencedName(), value, reference.IsStrict());
}
}
/// <summary>
/// Used by PutValue when the reference has a primitive base value
/// </summary>
/// <param name="b"></param>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="throwOnError"></param>
public void PutPrimitiveBase(JsValue b, string name, JsValue value, bool throwOnError)
{
var o = TypeConverter.ToObject(this, b);
if (!o.CanPut(name))
{
if (throwOnError)
{
throw new JavaScriptException(TypeError);
}
return;
}
var ownDesc = o.GetOwnProperty(name);
if (ownDesc.IsDataDescriptor())
{
if (throwOnError)
{
throw new JavaScriptException(TypeError);
}
return;
}
var desc = o.GetProperty(name);
if (desc.IsAccessorDescriptor())
{
var setter = (ICallable)desc.Set.AsObject();
setter.Call(b, new[] { value });
}
else
{
if (throwOnError)
{
throw new JavaScriptException(TypeError);
}
}
}
/// <summary>
/// Invoke the current value as function.
/// </summary>
/// <param name="propertyName">The arguments of the function call.</param>
/// <returns>The value returned by the function call.</returns>
public JsValue Invoke(string propertyName, params object[] arguments)
{
return Invoke(propertyName, null, arguments);
}
/// <summary>
/// Invoke the current value as function.
/// </summary>
/// <param name="propertyName">The name of the function to call.</param>
/// <param name="thisObj">The this value inside the function call.</param>
/// <param name="arguments">The arguments of the function call.</param>
/// <returns>The value returned by the function call.</returns>
public JsValue Invoke(string propertyName, object thisObj, object[] arguments)
{
var value = GetValue(propertyName);
return Invoke(value, thisObj, arguments);
}
/// <summary>
/// Invoke the current value as function.
/// </summary>
/// <param name="value">The function to call.</param>
/// <param name="arguments">The arguments of the function call.</param>
/// <returns>The value returned by the function call.</returns>
public JsValue Invoke(JsValue value, params object[] arguments)
{
return Invoke(value, null, arguments);
}
/// <summary>
/// Invoke the current value as function.
/// </summary>
/// <param name="value">The function to call.</param>
/// <param name="thisObj">The this value inside the function call.</param>
/// <param name="arguments">The arguments of the function call.</param>
/// <returns>The value returned by the function call.</returns>
public JsValue Invoke(JsValue value, object thisObj, object[] arguments)
{
var callable = value.TryCast<ICallable>();
if (callable == null)
{
throw new ArgumentException("Can only invoke functions");
}
var items = new JsValue[arguments.Length];
for (int i = 0; i < arguments.Length; ++i)
{
items[i] = JsValue.FromObject(this, arguments[i]);
}
return callable.Call(JsValue.FromObject(this, thisObj), items);
}
/// <summary>
/// Gets a named value from the Global scope.
/// </summary>
/// <param name="propertyName">The name of the property to return.</param>
public JsValue GetValue(string propertyName)
{
return GetValue(Global, propertyName);
}
/// <summary>
/// Gets the last evaluated <see cref="INode"/>.
/// </summary>
public INode GetLastSyntaxNode()
{
return _lastSyntaxNode;
}
/// <summary>
/// Gets a named value from the specified scope.
/// </summary>
/// <param name="scope">The scope to get the property from.</param>
/// <param name="propertyName">The name of the property to return.</param>
public JsValue GetValue(JsValue scope, string propertyName)
{
if (System.String.IsNullOrEmpty(propertyName))
{
throw new ArgumentException("propertyName");
}
var reference = new Reference(scope, propertyName, Options._IsStrict);
return GetValue(reference);
}
// http://www.ecma-international.org/ecma-262/5.1/#sec-10.5
public void DeclarationBindingInstantiation(
DeclarationBindingType declarationBindingType,
IList<FunctionDeclaration> functionDeclarations,
IList<VariableDeclaration> variableDeclarations,
FunctionInstance functionInstance,
JsValue[] arguments)
{
var env = ExecutionContext.VariableEnvironment.Record;
bool configurableBindings = declarationBindingType == DeclarationBindingType.EvalCode;
var strict = StrictModeScope.IsStrictModeCode;
if (declarationBindingType == DeclarationBindingType.FunctionCode)
{
var argCount = arguments.Length;
var n = 0;
for (var i = 0; i < functionInstance.FormalParameters.Length; i++)
{
var argName = functionInstance.FormalParameters[i];
n++;
var v = n > argCount ? Undefined.Instance : arguments[n - 1];
var argAlreadyDeclared = env.HasBinding(argName);
if (!argAlreadyDeclared)
{
env.CreateMutableBinding(argName);
}
env.SetMutableBinding(argName, v, strict);
}
}
for (var i = 0; i < functionDeclarations.Count; i++)
{
var f = functionDeclarations[i];
var fn = f.Id.Name;
var fo = Function.CreateFunctionObject(f);
var funcAlreadyDeclared = env.HasBinding(fn);
if (!funcAlreadyDeclared)
{
env.CreateMutableBinding(fn, configurableBindings);
}
else
{
if (env == GlobalEnvironment.Record)
{
var go = Global;
var existingProp = go.GetProperty(fn);
if (existingProp.Configurable.Value)
{
go.DefineOwnProperty(fn,
new PropertyDescriptor(
value: Undefined.Instance,
writable: true,
enumerable: true,
configurable: configurableBindings
), true);
}
else
{
if (existingProp.IsAccessorDescriptor() || (!existingProp.Enumerable.Value))
{
throw new JavaScriptException(TypeError);
}
}
}
}
env.SetMutableBinding(fn, fo, strict);
}
var argumentsAlreadyDeclared = env.HasBinding("arguments");
if (declarationBindingType == DeclarationBindingType.FunctionCode && !argumentsAlreadyDeclared)
{
var argsObj = ArgumentsInstance.CreateArgumentsObject(this, functionInstance, functionInstance.FormalParameters, arguments, env, strict);
if (strict)
{
var declEnv = env as DeclarativeEnvironmentRecord;
if (declEnv == null)
{
throw new ArgumentException();
}
declEnv.CreateImmutableBinding("arguments");
declEnv.InitializeImmutableBinding("arguments", argsObj);
}
else
{
env.CreateMutableBinding("arguments");
env.SetMutableBinding("arguments", argsObj, false);
}
}
// process all variable declarations in the current parser scope
for (var i = 0; i < variableDeclarations.Count; i++)
{
var variableDeclaration = variableDeclarations[i];
var declarations = (List<VariableDeclarator>) variableDeclaration.Declarations;
foreach (var d in declarations)
{
var dn = d.Id.As<Identifier>().Name;
var varAlreadyDeclared = env.HasBinding(dn);
if (!varAlreadyDeclared)
{
env.CreateMutableBinding(dn, configurableBindings);
env.SetMutableBinding(dn, Undefined.Instance, strict);
}
}
}
}
}
}