Engine.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Jint.Native;
  5. using Jint.Native.Argument;
  6. using Jint.Native.Array;
  7. using Jint.Native.Boolean;
  8. using Jint.Native.Date;
  9. using Jint.Native.Error;
  10. using Jint.Native.Function;
  11. using Jint.Native.Global;
  12. using Jint.Native.Json;
  13. using Jint.Native.Math;
  14. using Jint.Native.Number;
  15. using Jint.Native.Object;
  16. using Jint.Native.RegExp;
  17. using Jint.Native.String;
  18. using Jint.Parser;
  19. using Jint.Parser.Ast;
  20. using Jint.Runtime;
  21. using Jint.Runtime.Descriptors;
  22. using Jint.Runtime.Environments;
  23. using Jint.Runtime.Interop;
  24. using Jint.Runtime.References;
  25. namespace Jint
  26. {
  27. public class Engine
  28. {
  29. private readonly ExpressionInterpreter _expressions;
  30. private readonly StatementInterpreter _statements;
  31. private readonly Stack<ExecutionContext> _executionContexts;
  32. private JsValue _completionValue = JsValue.Undefined;
  33. private int _statementsCount;
  34. private long _timeoutTicks;
  35. private SyntaxNode _lastSyntaxNode = null;
  36. // cache of types used when resolving CLR type names
  37. internal Dictionary<string, Type> TypeCache = new Dictionary<string, Type>();
  38. public Engine() : this(null)
  39. {
  40. }
  41. public Engine(Action<Options> options)
  42. {
  43. _executionContexts = new Stack<ExecutionContext>();
  44. Global = GlobalObject.CreateGlobalObject(this);
  45. Object = ObjectConstructor.CreateObjectConstructor(this);
  46. Function = FunctionConstructor.CreateFunctionConstructor(this);
  47. Array = ArrayConstructor.CreateArrayConstructor(this);
  48. String = StringConstructor.CreateStringConstructor(this);
  49. RegExp = RegExpConstructor.CreateRegExpConstructor(this);
  50. Number = NumberConstructor.CreateNumberConstructor(this);
  51. Boolean = BooleanConstructor.CreateBooleanConstructor(this);
  52. Date = DateConstructor.CreateDateConstructor(this);
  53. Math = MathInstance.CreateMathObject(this);
  54. Json = JsonInstance.CreateJsonObject(this);
  55. Error = ErrorConstructor.CreateErrorConstructor(this, "Error");
  56. EvalError = ErrorConstructor.CreateErrorConstructor(this, "EvalError");
  57. RangeError = ErrorConstructor.CreateErrorConstructor(this, "RangeError");
  58. ReferenceError = ErrorConstructor.CreateErrorConstructor(this, "ReferenceError");
  59. SyntaxError = ErrorConstructor.CreateErrorConstructor(this, "SyntaxError");
  60. TypeError = ErrorConstructor.CreateErrorConstructor(this, "TypeError");
  61. UriError = ErrorConstructor.CreateErrorConstructor(this, "URIError");
  62. // Because the properties might need some of the built-in object
  63. // their configuration is delayed to a later step
  64. Global.Configure();
  65. Object.Configure();
  66. Object.PrototypeObject.Configure();
  67. Function.Configure();
  68. Function.PrototypeObject.Configure();
  69. Array.Configure();
  70. Array.PrototypeObject.Configure();
  71. String.Configure();
  72. String.PrototypeObject.Configure();
  73. RegExp.Configure();
  74. RegExp.PrototypeObject.Configure();
  75. Number.Configure();
  76. Number.PrototypeObject.Configure();
  77. Boolean.Configure();
  78. Boolean.PrototypeObject.Configure();
  79. Date.Configure();
  80. Date.PrototypeObject.Configure();
  81. Math.Configure();
  82. Json.Configure();
  83. Error.Configure();
  84. Error.PrototypeObject.Configure();
  85. // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3
  86. GlobalEnvironment = LexicalEnvironment.NewObjectEnvironment(this, Global, null, false);
  87. // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1
  88. EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global);
  89. Options = new Options();
  90. if (options != null)
  91. {
  92. options(Options);
  93. }
  94. Eval = new EvalFunctionInstance(this, new string[0], LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode);
  95. Global.FastAddProperty("eval", Eval, true, false, true);
  96. _statements = new StatementInterpreter(this);
  97. _expressions = new ExpressionInterpreter(this);
  98. if (Options.IsClrAllowed())
  99. {
  100. Global.FastAddProperty("System", new NamespaceReference(this, "System"), false, false, false);
  101. Global.FastAddProperty("importNamespace", new ClrFunctionInstance(this, (thisObj, arguments) =>
  102. {
  103. return new NamespaceReference(this, TypeConverter.ToString(arguments.At(0)));
  104. }), false, false, false);
  105. }
  106. }
  107. public LexicalEnvironment GlobalEnvironment;
  108. public GlobalObject Global { get; private set; }
  109. public ObjectConstructor Object { get; private set; }
  110. public FunctionConstructor Function { get; private set; }
  111. public ArrayConstructor Array { get; private set; }
  112. public StringConstructor String { get; private set; }
  113. public RegExpConstructor RegExp { get; private set; }
  114. public BooleanConstructor Boolean { get; private set; }
  115. public NumberConstructor Number { get; private set; }
  116. public DateConstructor Date { get; private set; }
  117. public MathInstance Math { get; private set; }
  118. public JsonInstance Json { get; private set; }
  119. public EvalFunctionInstance Eval { get; private set; }
  120. public ErrorConstructor Error { get; private set; }
  121. public ErrorConstructor EvalError { get; private set; }
  122. public ErrorConstructor SyntaxError { get; private set; }
  123. public ErrorConstructor TypeError { get; private set; }
  124. public ErrorConstructor RangeError { get; private set; }
  125. public ErrorConstructor ReferenceError { get; private set; }
  126. public ErrorConstructor UriError { get; private set; }
  127. public ExecutionContext ExecutionContext { get { return _executionContexts.Peek(); } }
  128. internal Options Options { get; private set; }
  129. public ExecutionContext EnterExecutionContext(LexicalEnvironment lexicalEnvironment, LexicalEnvironment variableEnvironment, JsValue thisBinding)
  130. {
  131. var executionContext = new ExecutionContext
  132. {
  133. LexicalEnvironment = lexicalEnvironment,
  134. VariableEnvironment = variableEnvironment,
  135. ThisBinding = thisBinding
  136. };
  137. _executionContexts.Push(executionContext);
  138. return executionContext;
  139. }
  140. public Engine SetValue(string name, Delegate value)
  141. {
  142. Global.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true);
  143. return this;
  144. }
  145. public Engine SetValue(string name, string value)
  146. {
  147. return SetValue(name, new JsValue(value));
  148. }
  149. public Engine SetValue(string name, double value)
  150. {
  151. return SetValue(name, new JsValue(value));
  152. }
  153. public Engine SetValue(string name, bool value)
  154. {
  155. return SetValue(name, new JsValue(value));
  156. }
  157. public Engine SetValue(string name, JsValue value)
  158. {
  159. Global.Put(name, value, false);
  160. return this;
  161. }
  162. public Engine SetValue(string name, Object obj)
  163. {
  164. return SetValue(name, JsValue.FromObject(this, obj));
  165. }
  166. public void LeaveExecutionContext()
  167. {
  168. _executionContexts.Pop();
  169. }
  170. /// <summary>
  171. /// Initializes the statements count
  172. /// </summary>
  173. public void ResetStatementsCount()
  174. {
  175. _statementsCount = 0;
  176. }
  177. public void ResetTimeoutTicks()
  178. {
  179. var timeoutIntervalTicks = Options.GetTimeoutInterval().Ticks;
  180. _timeoutTicks = timeoutIntervalTicks > 0 ? DateTime.UtcNow.Ticks + timeoutIntervalTicks : 0;
  181. }
  182. public Engine Execute(string source)
  183. {
  184. var parser = new JavaScriptParser();
  185. return Execute(parser.Parse(source));
  186. }
  187. public Engine Execute(string source, ParserOptions parserOptions)
  188. {
  189. var parser = new JavaScriptParser();
  190. return Execute(parser.Parse(source, parserOptions));
  191. }
  192. public Engine Execute(Program program)
  193. {
  194. ResetStatementsCount();
  195. ResetTimeoutTicks();
  196. ResetLastStatement();
  197. using (new StrictModeScope(Options.IsStrict() || program.Strict))
  198. {
  199. DeclarationBindingInstantiation(DeclarationBindingType.GlobalCode, program.FunctionDeclarations, program.VariableDeclarations, null, null);
  200. var result = _statements.ExecuteProgram(program);
  201. if (result.Type == Completion.Throw)
  202. {
  203. throw new JavaScriptException(result.GetValueOrDefault());
  204. }
  205. _completionValue = result.GetValueOrDefault();
  206. }
  207. return this;
  208. }
  209. private void ResetLastStatement()
  210. {
  211. _lastSyntaxNode = null;
  212. }
  213. /// <summary>
  214. /// Gets the last evaluated statement completion value
  215. /// </summary>
  216. public JsValue GetCompletionValue()
  217. {
  218. return _completionValue;
  219. }
  220. public Completion ExecuteStatement(Statement statement)
  221. {
  222. var maxStatements = Options.GetMaxStatements();
  223. if (maxStatements > 0 && _statementsCount++ > maxStatements)
  224. {
  225. throw new StatementsCountOverflowException();
  226. }
  227. if (_timeoutTicks > 0 && _timeoutTicks < DateTime.UtcNow.Ticks)
  228. {
  229. throw new TimeoutException();
  230. }
  231. _lastSyntaxNode = statement;
  232. switch (statement.Type)
  233. {
  234. case SyntaxNodes.BlockStatement:
  235. return _statements.ExecuteBlockStatement(statement.As<BlockStatement>());
  236. case SyntaxNodes.BreakStatement:
  237. return _statements.ExecuteBreakStatement(statement.As<BreakStatement>());
  238. case SyntaxNodes.ContinueStatement:
  239. return _statements.ExecuteContinueStatement(statement.As<ContinueStatement>());
  240. case SyntaxNodes.DoWhileStatement:
  241. return _statements.ExecuteDoWhileStatement(statement.As<DoWhileStatement>());
  242. case SyntaxNodes.DebuggerStatement:
  243. return _statements.ExecuteDebuggerStatement(statement.As<DebuggerStatement>());
  244. case SyntaxNodes.EmptyStatement:
  245. return _statements.ExecuteEmptyStatement(statement.As<EmptyStatement>());
  246. case SyntaxNodes.ExpressionStatement:
  247. return _statements.ExecuteExpressionStatement(statement.As<ExpressionStatement>());
  248. case SyntaxNodes.ForStatement:
  249. return _statements.ExecuteForStatement(statement.As<ForStatement>());
  250. case SyntaxNodes.ForInStatement:
  251. return _statements.ExecuteForInStatement(statement.As<ForInStatement>());
  252. case SyntaxNodes.FunctionDeclaration:
  253. return new Completion(Completion.Normal, null, null);
  254. case SyntaxNodes.IfStatement:
  255. return _statements.ExecuteIfStatement(statement.As<IfStatement>());
  256. case SyntaxNodes.LabeledStatement:
  257. return _statements.ExecuteLabelledStatement(statement.As<LabelledStatement>());
  258. case SyntaxNodes.ReturnStatement:
  259. return _statements.ExecuteReturnStatement(statement.As<ReturnStatement>());
  260. case SyntaxNodes.SwitchStatement:
  261. return _statements.ExecuteSwitchStatement(statement.As<SwitchStatement>());
  262. case SyntaxNodes.ThrowStatement:
  263. return _statements.ExecuteThrowStatement(statement.As<ThrowStatement>());
  264. case SyntaxNodes.TryStatement:
  265. return _statements.ExecuteTryStatement(statement.As<TryStatement>());
  266. case SyntaxNodes.VariableDeclaration:
  267. return _statements.ExecuteVariableDeclaration(statement.As<VariableDeclaration>());
  268. case SyntaxNodes.WhileStatement:
  269. return _statements.ExecuteWhileStatement(statement.As<WhileStatement>());
  270. case SyntaxNodes.WithStatement:
  271. return _statements.ExecuteWithStatement(statement.As<WithStatement>());
  272. case SyntaxNodes.Program:
  273. return _statements.ExecuteProgram(statement.As<Program>());
  274. default:
  275. throw new ArgumentOutOfRangeException();
  276. }
  277. }
  278. public object EvaluateExpression(Expression expression)
  279. {
  280. _lastSyntaxNode = expression;
  281. switch (expression.Type)
  282. {
  283. case SyntaxNodes.AssignmentExpression:
  284. return _expressions.EvaluateAssignmentExpression(expression.As<AssignmentExpression>());
  285. case SyntaxNodes.ArrayExpression:
  286. return _expressions.EvaluateArrayExpression(expression.As<ArrayExpression>());
  287. case SyntaxNodes.BinaryExpression:
  288. return _expressions.EvaluateBinaryExpression(expression.As<BinaryExpression>());
  289. case SyntaxNodes.CallExpression:
  290. return _expressions.EvaluateCallExpression(expression.As<CallExpression>());
  291. case SyntaxNodes.ConditionalExpression:
  292. return _expressions.EvaluateConditionalExpression(expression.As<ConditionalExpression>());
  293. case SyntaxNodes.FunctionExpression:
  294. return _expressions.EvaluateFunctionExpression(expression.As<FunctionExpression>());
  295. case SyntaxNodes.Identifier:
  296. return _expressions.EvaluateIdentifier(expression.As<Identifier>());
  297. case SyntaxNodes.Literal:
  298. return _expressions.EvaluateLiteral(expression.As<Literal>());
  299. case SyntaxNodes.RegularExpressionLiteral:
  300. return _expressions.EvaluateLiteral(expression.As<Literal>());
  301. case SyntaxNodes.LogicalExpression:
  302. return _expressions.EvaluateLogicalExpression(expression.As<LogicalExpression>());
  303. case SyntaxNodes.MemberExpression:
  304. return _expressions.EvaluateMemberExpression(expression.As<MemberExpression>());
  305. case SyntaxNodes.NewExpression:
  306. return _expressions.EvaluateNewExpression(expression.As<NewExpression>());
  307. case SyntaxNodes.ObjectExpression:
  308. return _expressions.EvaluateObjectExpression(expression.As<ObjectExpression>());
  309. case SyntaxNodes.SequenceExpression:
  310. return _expressions.EvaluateSequenceExpression(expression.As<SequenceExpression>());
  311. case SyntaxNodes.ThisExpression:
  312. return _expressions.EvaluateThisExpression(expression.As<ThisExpression>());
  313. case SyntaxNodes.UpdateExpression:
  314. return _expressions.EvaluateUpdateExpression(expression.As<UpdateExpression>());
  315. case SyntaxNodes.UnaryExpression:
  316. return _expressions.EvaluateUnaryExpression(expression.As<UnaryExpression>());
  317. default:
  318. throw new ArgumentOutOfRangeException();
  319. }
  320. }
  321. /// <summary>
  322. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
  323. /// </summary>
  324. /// <param name="value"></param>
  325. /// <returns></returns>
  326. public JsValue GetValue(object value)
  327. {
  328. var reference = value as Reference;
  329. if (reference == null)
  330. {
  331. var completion = value as Completion;
  332. if (completion != null)
  333. {
  334. return GetValue(completion.Value);
  335. }
  336. return (JsValue)value;
  337. }
  338. if (reference.IsUnresolvableReference())
  339. {
  340. throw new JavaScriptException(ReferenceError, reference.GetReferencedName() + " is not defined");
  341. }
  342. var baseValue = reference.GetBase();
  343. if (reference.IsPropertyReference())
  344. {
  345. if (reference.HasPrimitiveBase() == false)
  346. {
  347. var o = TypeConverter.ToObject(this, baseValue);
  348. return o.Get(reference.GetReferencedName());
  349. }
  350. else
  351. {
  352. var o = TypeConverter.ToObject(this, baseValue);
  353. var desc = o.GetProperty(reference.GetReferencedName());
  354. if (desc == PropertyDescriptor.Undefined)
  355. {
  356. return JsValue.Undefined;
  357. }
  358. if (desc.IsDataDescriptor())
  359. {
  360. return desc.Value.Value;
  361. }
  362. var getter = desc.Get.Value;
  363. if (getter == Undefined.Instance)
  364. {
  365. return Undefined.Instance;
  366. }
  367. var callable = (ICallable)getter.AsObject();
  368. return callable.Call(baseValue, Arguments.Empty);
  369. }
  370. }
  371. else
  372. {
  373. var record = baseValue.As<EnvironmentRecord>();
  374. if (record == null)
  375. {
  376. throw new ArgumentException();
  377. }
  378. return record.GetBindingValue(reference.GetReferencedName(), reference.IsStrict());
  379. }
  380. }
  381. /// <summary>
  382. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.2
  383. /// </summary>
  384. /// <param name="reference"></param>
  385. /// <param name="value"></param>
  386. public void PutValue(Reference reference, JsValue value)
  387. {
  388. if (reference.IsUnresolvableReference())
  389. {
  390. if (reference.IsStrict())
  391. {
  392. throw new JavaScriptException(ReferenceError);
  393. }
  394. Global.Put(reference.GetReferencedName(), value, false);
  395. }
  396. else if (reference.IsPropertyReference())
  397. {
  398. var baseValue = reference.GetBase();
  399. if (!reference.HasPrimitiveBase())
  400. {
  401. baseValue.AsObject().Put(reference.GetReferencedName(), value, reference.IsStrict());
  402. }
  403. else
  404. {
  405. PutPrimitiveBase(baseValue, reference.GetReferencedName(), value, reference.IsStrict());
  406. }
  407. }
  408. else
  409. {
  410. var baseValue = reference.GetBase();
  411. var record = baseValue.As<EnvironmentRecord>();
  412. if (record == null)
  413. {
  414. throw new ArgumentNullException();
  415. }
  416. record.SetMutableBinding(reference.GetReferencedName(), value, reference.IsStrict());
  417. }
  418. }
  419. /// <summary>
  420. /// Used by PutValue when the reference has a primitive base value
  421. /// </summary>
  422. /// <param name="b"></param>
  423. /// <param name="name"></param>
  424. /// <param name="value"></param>
  425. /// <param name="throwOnError"></param>
  426. public void PutPrimitiveBase(JsValue b, string name, JsValue value, bool throwOnError)
  427. {
  428. var o = TypeConverter.ToObject(this, b);
  429. if (!o.CanPut(name))
  430. {
  431. if (throwOnError)
  432. {
  433. throw new JavaScriptException(TypeError);
  434. }
  435. return;
  436. }
  437. var ownDesc = o.GetOwnProperty(name);
  438. if (ownDesc.IsDataDescriptor())
  439. {
  440. if (throwOnError)
  441. {
  442. throw new JavaScriptException(TypeError);
  443. }
  444. return;
  445. }
  446. var desc = o.GetProperty(name);
  447. if (desc.IsAccessorDescriptor())
  448. {
  449. var setter = (ICallable)desc.Set.Value.AsObject();
  450. setter.Call(b, new[] { value });
  451. }
  452. else
  453. {
  454. if (throwOnError)
  455. {
  456. throw new JavaScriptException(TypeError);
  457. }
  458. }
  459. }
  460. /// <summary>
  461. /// Invoke the current value as function.
  462. /// </summary>
  463. /// <param name="propertyName">The arguments of the function call.</param>
  464. /// <returns>The value returned by the function call.</returns>
  465. public JsValue Invoke(string propertyName, params object[] arguments)
  466. {
  467. return Invoke(propertyName, null, arguments);
  468. }
  469. /// <summary>
  470. /// Invoke the current value as function.
  471. /// </summary>
  472. /// <param name="propertyName">The name of the function to call.</param>
  473. /// <param name="thisObj">The this value inside the function call.</param>
  474. /// <param name="arguments">The arguments of the function call.</param>
  475. /// <returns>The value returned by the function call.</returns>
  476. public JsValue Invoke(string propertyName, object thisObj, object[] arguments)
  477. {
  478. var value = GetValue(propertyName);
  479. var callable = value.TryCast<ICallable>();
  480. if (callable == null)
  481. {
  482. throw new ArgumentException("Can only invoke functions");
  483. }
  484. return callable.Call(JsValue.FromObject(this, thisObj), arguments.Select(x => JsValue.FromObject(this, x)).ToArray());
  485. }
  486. /// <summary>
  487. /// Gets a named value from the Global scope.
  488. /// </summary>
  489. /// <param name="propertyName">The name of the property to return.</param>
  490. public JsValue GetValue(string propertyName)
  491. {
  492. return GetValue(Global, propertyName);
  493. }
  494. /// <summary>
  495. /// Gets the last evaluated <see cref="SyntaxNode"/>.
  496. /// </summary>
  497. public SyntaxNode GetLastSyntaxNode()
  498. {
  499. return _lastSyntaxNode;
  500. }
  501. /// <summary>
  502. /// Gets a named value from the specified scope.
  503. /// </summary>
  504. /// <param name="scope">The scope to get the property from.</param>
  505. /// <param name="propertyName">The name of the property to return.</param>
  506. public JsValue GetValue(JsValue scope, string propertyName)
  507. {
  508. if (System.String.IsNullOrEmpty(propertyName))
  509. {
  510. throw new ArgumentException("propertyName");
  511. }
  512. var reference = new Reference(scope, propertyName, Options.IsStrict());
  513. return GetValue(reference);
  514. }
  515. // http://www.ecma-international.org/ecma-262/5.1/#sec-10.5
  516. public void DeclarationBindingInstantiation(DeclarationBindingType declarationBindingType, IList<FunctionDeclaration> functionDeclarations, IList<VariableDeclaration> variableDeclarations, FunctionInstance functionInstance, JsValue[] arguments)
  517. {
  518. var env = ExecutionContext.VariableEnvironment.Record;
  519. bool configurableBindings = declarationBindingType == DeclarationBindingType.EvalCode;
  520. var strict = StrictModeScope.IsStrictModeCode;
  521. if (declarationBindingType == DeclarationBindingType.FunctionCode)
  522. {
  523. var argCount = arguments.Length;
  524. var n = 0;
  525. foreach (var argName in functionInstance.FormalParameters)
  526. {
  527. n++;
  528. var v = n > argCount ? Undefined.Instance : arguments[n - 1];
  529. var argAlreadyDeclared = env.HasBinding(argName);
  530. if (!argAlreadyDeclared)
  531. {
  532. env.CreateMutableBinding(argName);
  533. }
  534. env.SetMutableBinding(argName, v, strict);
  535. }
  536. }
  537. foreach (var f in functionDeclarations)
  538. {
  539. var fn = f.Id.Name;
  540. var fo = Function.CreateFunctionObject(f);
  541. var funcAlreadyDeclared = env.HasBinding(fn);
  542. if (!funcAlreadyDeclared)
  543. {
  544. env.CreateMutableBinding(fn, configurableBindings);
  545. }
  546. else
  547. {
  548. if (env == GlobalEnvironment.Record)
  549. {
  550. var go = Global;
  551. var existingProp = go.GetProperty(fn);
  552. if (existingProp.Configurable.Value.AsBoolean())
  553. {
  554. go.DefineOwnProperty(fn,
  555. new PropertyDescriptor(
  556. value: Undefined.Instance,
  557. writable: true,
  558. enumerable: true,
  559. configurable: configurableBindings
  560. ), true);
  561. }
  562. else
  563. {
  564. if (existingProp.IsAccessorDescriptor() || (!existingProp.Enumerable.Value.AsBoolean()))
  565. {
  566. throw new JavaScriptException(TypeError);
  567. }
  568. }
  569. }
  570. }
  571. env.SetMutableBinding(fn, fo, strict);
  572. }
  573. var argumentsAlreadyDeclared = env.HasBinding("arguments");
  574. if (declarationBindingType == DeclarationBindingType.FunctionCode && !argumentsAlreadyDeclared)
  575. {
  576. var argsObj = ArgumentsInstance.CreateArgumentsObject(this, functionInstance, functionInstance.FormalParameters, arguments, env, strict);
  577. if (strict)
  578. {
  579. var declEnv = env as DeclarativeEnvironmentRecord;
  580. if (declEnv == null)
  581. {
  582. throw new ArgumentException();
  583. }
  584. declEnv.CreateImmutableBinding("arguments");
  585. declEnv.InitializeImmutableBinding("arguments", argsObj);
  586. }
  587. else
  588. {
  589. env.CreateMutableBinding("arguments");
  590. env.SetMutableBinding("arguments", argsObj, false);
  591. }
  592. }
  593. // process all variable declarations in the current parser scope
  594. foreach (var d in variableDeclarations.SelectMany(x => x.Declarations))
  595. {
  596. var dn = d.Id.Name;
  597. var varAlreadyDeclared = env.HasBinding(dn);
  598. if (!varAlreadyDeclared)
  599. {
  600. env.CreateMutableBinding(dn, configurableBindings);
  601. env.SetMutableBinding(dn, Undefined.Instance, strict);
  602. }
  603. }
  604. }
  605. }
  606. }