public static Delegate ToDelegate(this Type type, FunctionInstance function, EngineInstance engine)
        {
            if (type == typeof(DomEventHandler))
            {
                return(function.ToListener(engine));
            }

            var method = typeof(DomDelegates).GetMethod("ToCallback").MakeGenericMethod(type);

            return(method.Invoke(null, new Object[] { function, engine }) as Delegate);
        }
Beispiel #2
0
        public ArgumentsInstance Rent(
            FunctionInstance func,
            Key[] formals,
            JsValue[] argumentsList,
            DeclarativeEnvironmentRecord env,
            bool hasRestParameter)
        {
            var obj = _pool.Allocate();

            obj.Prepare(func, formals, argumentsList, env, hasRestParameter);
            return(obj);
        }
        public void Analyze(Engine engine)
        {
            HasDynamicReturns = false;

            if (!(MapFunc is ScriptFunctionInstance sfi))
            {
                return;
            }

            var theFuncAst = sfi.GetFunctionAst();

            var res = CheckIfSimpleMapExpression(engine, theFuncAst);

            if (res != null)
            {
                MapFunc    = res.Value.Function;
                theFuncAst = res.Value.FunctionAst;
            }

            foreach (var returnStatement in JavaScriptIndexUtils.GetReturnStatements(theFuncAst.Body))
            {
                if (returnStatement.Argument == null) // return;
                {
                    continue;
                }

                if (!(returnStatement.Argument is ObjectExpression oe))
                {
                    HasDynamicReturns = true;
                    continue;
                }
                //If we got here we must validate that all return statements have the same structure.
                //Having zero fields means its the first return statements we encounter that has a structure.
                if (Fields.Count == 0)
                {
                    foreach (var prop in oe.Properties)
                    {
                        var fieldName = prop.Key.GetKey();
                        if (fieldName == "_")
                        {
                            HasDynamicReturns = true;
                        }

                        Fields.Add(fieldName);
                    }
                }
                else if (CompareFields(oe) == false)
                {
                    throw new InvalidOperationException($"Index {IndexName} contains different return structure from different code paths," +
                                                        $" expected properties: {string.Join(", ", Fields)} but also got:{string.Join(", ", oe.Properties.Select(x => x.Key.GetKey()))}");
                }
            }
        }
Beispiel #4
0
        public ArgumentsInstance Rent(
            FunctionInstance func,
            string[] names,
            JsValue[] args,
            EnvironmentRecord env,
            bool strict)
        {
            var obj = _pool.Allocate();

            obj.Prepare(func, names, args, env, strict);
            return(obj);
        }
Beispiel #5
0
        // DO NOT USE
        public Shader(string name, FunctionInstance InitFunc, FunctionInstance FallbackFunc, FunctionInstance DrawFunc)
        {
            throw new NotImplementedException();

            /*
             * Name = name;
             * Init = InitFunc;
             * Fallback = FallbackFunc;
             * Draw = DrawFunc;
             *
             * IsSimple = false;
             */
        }
Beispiel #6
0
 private ExecutionContext(ScriptEngine engine, RuntimeScope parentScope,
                          BindingStatus thisBindingStatus, object thisValue,
                          UserDefinedFunction executingFunction, FunctionInstance newTarget,
                          ObjectInstance functionContainer)
 {
     this.Engine            = engine ?? throw new ArgumentNullException(nameof(engine));
     this.ParentScope       = parentScope;
     this.ThisBindingStatus = thisBindingStatus;
     this.thisValue         = thisValue;
     this.ExecutingFunction = executingFunction;
     this.NewTarget         = newTarget;
     this.FunctionContainer = functionContainer;
 }
Beispiel #7
0
        public static DomEventHandler ToListener(this FunctionInstance function, EngineInstance engine) => (obj, ev) =>
        {
            var objAsJs = obj.ToJsValue(engine);
            var evAsJs  = ev.ToJsValue(engine);

            try
            {
                function.Call(objAsJs, new[] { evAsJs });
            }
            catch (JavaScriptException jsException)
            {
                var window = (IWindow)engine.Window.Value;
                window.Fire <ErrorEvent>(e => e.Init(null, jsException.LineNumber, jsException.Column, jsException));
            }
        };
        protected override void Prepare()
        {
            _engine = new ScriptEngine
            {
                ForceStrictMode = true,
            };

            _engine.SetGlobalFunction("log", new Action <object>(Console.WriteLine));
            _engine.Global["window"] = _engine.Global;
            _engine.Execute("var exports = {};");

            _engine.Execute(Compiler);

            _compiler = _engine.Global["transform"] as FunctionInstance ?? throw new InvalidOperationException("Missing compiler");
        }
Beispiel #9
0
 public void ExecuteFunction(FunctionInstance instance, object[] arguments)
 {
     lock (update_lock)
     {
         if (System.Threading.Thread.CurrentThread == execution_thread)
         {
             instance.Execute(true, arguments);
         }
         else
         {
             deferred_call_queue.Add(delegate() {
                 instance.Execute(true, arguments);
             });
         }
     }
 }
Beispiel #10
0
        private async void SetTimeout(ManticoreEngine engine, FunctionInstance callback, int timeout)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(timeout));

            engine.Js(() =>
            {
                try
                {
                    callback.Call(JsValue.Null, new JsValue[] { });
                }
                catch (Exception x)
                {
                    Debug.WriteLine(x);
                }
            });
        }
 public FunctionEnvironmentRecord(
     Engine engine,
     FunctionInstance functionObject,
     JsValue newTarget) : base(engine)
 {
     _functionObject = functionObject;
     _newTarget      = newTarget;
     if (functionObject is ArrowFunctionInstance)
     {
         _thisBindingStatus = ThisBindingStatus.Lexical;
     }
     else
     {
         _thisBindingStatus = ThisBindingStatus.Uninitialized;
     }
 }
Beispiel #12
0
        internal void Prepare(
            FunctionInstance func,
            Key[] names,
            JsValue[] args,
            DeclarativeEnvironmentRecord env,
            bool hasRestParameter)
        {
            _func             = func;
            _names            = names;
            _args             = args;
            _env              = env;
            _hasRestParameter = hasRestParameter;
            _canReturnToPool  = true;

            ClearProperties();
        }
        public object CallAsUser(string applicationId, FunctionInstance function, object thisObj, params object[] arguments)
        {
            if (thisObj == null || thisObj == Null.Value || thisObj == Undefined.Value)
            {
                thisObj = this.Engine.Global;
            }

            object result = null;

            ImpersonationHelper.InvokeAsUser(applicationId, new Action(() =>
            {
                result = function.Call(thisObj, arguments);
            }));

            return(result);
        }
Beispiel #14
0
        protected virtual void ResetScriptEngine(ScriptSource source, IJinxBotClient client)
        {
            _jsEngine = new ScriptEngine();
            _host     = new JsHost(_jsEngine, client);
            _jsEngine.Execute(source);

            __accountCreated        = GetFunc("accountCreated");
            __accountCreationFailed = GetFunc("accountCreationFailed");
            __adChanged             = GetFunc("adChanged");
            __channelDidNotExist    = GetFunc("channelDidNotExist");
            __channelListReceived   = GetFunc("channelListReceived");
            __channelWasFull        = GetFunc("channelWasFull");
            __channelWasRestricted  = GetFunc("channelWasRestricted");
            __clientCheckFailed     = GetFunc("clientCheckFailed");
            __clientCheckPassed     = GetFunc("clientCheckPassed");
            __commandSent           = GetFunc("commandSent");
            __connected             = GetFunc("connected");
            __disconnected          = GetFunc("disconnected");
            __enteredChat           = GetFunc("enteredChat");
            __error                   = GetFunc("error");
            __friendAdded             = GetFunc("friendAdded");
            __friendListReceived      = GetFunc("friendListReceived");
            __friendMoved             = GetFunc("friendMoved");
            __friendRemoved           = GetFunc("friendRemoved");
            __friendUpdated           = GetFunc("friendUpdated");
            __information             = GetFunc("information");
            __informationReceived     = GetFunc("informationReceived");
            __joinedChannel           = GetFunc("joinedChannel");
            __loginFailed             = GetFunc("loginFailed");
            __loginSucceeded          = GetFunc("loginSucceeded");
            __messageSent             = GetFunc("messageSent");
            __profileLookupFailed     = GetFunc("profileLookupFailed");
            __serverBroadcast         = GetFunc("serverBroadcast");
            __serverErrorReceived     = GetFunc("serverErrorReceived");
            __serverNews              = GetFunc("serverNews");
            __userEmoted              = GetFunc("userEmoted");
            __userFlagsChanged        = GetFunc("userFlagsChanged");
            __userJoined              = GetFunc("userJoined");
            __userLeft                = GetFunc("userLeft");
            __userProfileReceived     = GetFunc("userProfileReceived");
            __userShown               = GetFunc("userShown");
            __userSpoke               = GetFunc("userSpoke");
            __warcraftProfileReceived = GetFunc("warcraftProfileReceived");
            __whisperReceived         = GetFunc("whisperReceived");
            __whisperSent             = GetFunc("whisperSent");
        }
Beispiel #15
0
        public override void SetEventListener(string eventName, FunctionInstance callback)
        {
            switch (eventName)
            {
            case "onClick":
                Button.onClick.RemoveAllListeners();
                if (callback != null)
                {
                    Button.onClick.AddListener(new UnityAction(() => callback.Invoke()));
                }
                return;

            default:
                base.SetEventListener(eventName, callback);
                return;
            }
        }
Beispiel #16
0
        internal void Prepare(
            FunctionInstance func,
            string[] names,
            JsValue[] args,
            EnvironmentRecord env,
            bool strict)
        {
            _func   = func;
            _names  = names;
            _args   = args;
            _env    = env;
            _strict = strict;

            _properties?.Clear();
            _intrinsicProperties?.Clear();

            _initialized = false;
        }
        public void Works()
        {
            var descriptor         = new FunctionDescriptor();
            var instance           = new FunctionInstance(Guid.NewGuid(), null, ExecutionReason.AutomaticTrigger, null, null, descriptor);
            var writer             = new TestTraceWriter(TraceLevel.Info);
            var functionTraceLevel = TraceLevel.Info;
            var hostInstanceId     = Guid.NewGuid();

            var instanceWriter = new FunctionInstanceTraceWriter(instance, hostInstanceId, writer, functionTraceLevel);

            instanceWriter.Info("Test Info");

            var traceEvent = writer.Traces.Single();

            Assert.Equal(3, traceEvent.Properties.Count);
            Assert.Equal(instance.Id, traceEvent.Properties["MS_FunctionInvocationId"]);
            Assert.Equal(hostInstanceId, traceEvent.Properties["MS_HostInstanceId"]);
            Assert.Equal(descriptor, traceEvent.Properties["MS_FunctionDescriptor"]);
        }
Beispiel #18
0
        public DeferredInstance Construct(FunctionInstance function, params object[] parameters)
        {
            var state = new DeferredState
            {
                This       = this.Engine.Evaluate("this;"),
                Parameters = parameters,
            };

            var task = new Task <object>(s => {
                var localState = s as DeferredState;
                return(localState == null
                                            ? null
                                            : function.Call(localState.This, localState.Parameters));
            }, state);

            task.Start();

            return(new DeferredInstance(this.InstancePrototype, task));
        }
Beispiel #19
0
 public Types.ICalculonType Parse(string input)
 {
     if (Literal.IsMatch(input))
     {
         Literal l = new Literal(input);
         return(l);
     }
     else if (Real.IsMatch(input))
     {
         Real r = new Real(input);
         return(r);
     }
     else if (Rational.IsMatch(input))
     {
         Rational rat = new Rational(input);
         return(rat);
     }
     else if (Integer.IsMatch(input))
     {
         Integer i = new Integer(input);
         return(i);
     }
     else if (RealConstant.IsMatch(input))
     {
         RealConstant rc = new RealConstant(input);
         return(rc);
     }
     else if (HelpType.IsMatch(input))
     {
         HelpType ht = new HelpType();
         return(ht);
     }
     else
     {
         FunctionInstance fi = FunctionFactory.Instance[input];
         if (fi.IsError)
         {
             return(new ErrorType(String.Format(GetString("NotNumNotString"), input)));
         }
         return(fi);
     }
 }
Beispiel #20
0
        void Xhr(ObjectInstance href, ObjectInstance type, FunctionInstance callback, FunctionInstance errorCallback)
        {
            var filename        = href.ToString();
            var referencingFile = currentFiles.Peek();

            try
            {
                var file    = referencingFile.Directory.GetFile(filename);
                var content = file.OpenRead().ReadToEnd();
                callback.Call(Null.Value, content, DateTime.MinValue);
            }
            catch (FileNotFoundException ex)
            {
                throw FileNotFoundExceptionWithSourceFilename(referencingFile, ex);
            }
            catch (DirectoryNotFoundException ex)
            {
                throw DirectoryNotFoundExceptionWithSourceFilename(referencingFile, ex);
            }
        }
Beispiel #21
0
        public static T ToCallback <T>(this FunctionInstance function, EngineInstance engine)
        {
            var methodInfo = typeof(T).GetRuntimeMethods().First(m => m.Name == "Invoke");
            var convert    = typeof(EngineExtensions).GetRuntimeMethod("ToJsValue", ToJsValueSignature);
            var mps        = methodInfo.GetParameters();
            var parameters = new ParameterExpression[mps.Length];

            for (var i = 0; i < mps.Length; i++)
            {
                parameters[i] = Expression.Parameter(mps[i].ParameterType, mps[i].Name);
            }

            var objExpr    = Expression.Constant(function);
            var engineExpr = Expression.Constant(engine);
            var call       = Expression.Call(objExpr, "Call", new Type[0], new Expression[]
            {
                Expression.Call(convert, parameters[0], engineExpr),
                Expression.NewArrayInit(typeof(JsValue), parameters.Skip(1).Select(m => Expression.Call(convert, m, engineExpr)).ToArray())
            });

            return(Expression.Lambda <T>(call, parameters).Compile());
        }
Beispiel #22
0
 private void SetTimeout(ManticoreEngine engine, FunctionInstance callback, int timeout)
 {
     System.Timers.Timer timer = new System.Timers.Timer();
     // TODO not sure there may be a better way to emulate NextTick
     timer.Interval  = Math.Max(1, timeout);
     timer.AutoReset = false;
     timer.Elapsed  += (obj, args) =>
     {
         engine.Js(() =>
         {
             try
             {
                 callback.Call(JsValue.Null, new JsValue[] { });
             }
             catch (Exception x)
             {
                 // TODO perhaps throw this error INTO JS?
                 Log("error", x.ToString(), JsValue.Null);
             }
         });
     };
     timer.Start();
 }
        private void CallFunction(Context context, FunctionInstance functionInstance)
        {
            var arguments = new List <MelonObject>();

            while (context.Arguments.Count > 0)
            {
                arguments.Add(context.Arguments.Pop());
            }

            MelonObject self = null;

            if (context._stack.Count > 0)
            {
                self = context.Pop();
            }

            var returnVal = functionInstance.Run(self, arguments.ToArray());

            if (returnVal != null)
            {
                context.Push(returnVal);
            }
        }
Beispiel #24
0
        public JsHost(ScriptEngine engine, IJinxBotClient client)
        {
            Debug.Assert(engine != null);
            Debug.Assert(client != null);

            _engine   = engine;
            _client   = client;
            _jsClient = new JsJinxBotClientObjectInstance(client, this, engine);

            _engine.SetGlobalValue("Colors", new Colors(engine));
            _engine.SetGlobalValue("CssClasses", new CssClasses(engine));
            _engine.SetGlobalFunction("send", (Action <string>)send);
            _engine.SetGlobalFunction("addChat", (Action <ArrayInstance>)addChat);
            _engine.SetGlobalFunction("format", (Func <string, ArrayInstance, string>)format);
            _engine.SetGlobalFunction("setTimeout", (Func <double, ObjectInstance, int>)setTimeout);
            _engine.SetGlobalFunction("clearTimeout", (Action <int>)clearTimeout);
            _engine.SetGlobalFunction("setInterval", (Func <double, ObjectInstance, int>)setInterval);
            _engine.SetGlobalFunction("clearInterval", (Action <int>)clearInterval);

            FunctionInstance instance = engine.Evaluate(DUMP_FUNC) as FunctionInstance;

            engine.SetGlobalValue("dump", instance);
            engine.SetGlobalValue("client", _jsClient);
        }
Beispiel #25
0
        public int setTimeout(double msTimeout, ObjectInstance callback)
        {
            if (callback == null)
            {
                return(-1);
            }

            StringInstance   strInst  = callback as StringInstance;
            FunctionInstance funcInst = callback as FunctionInstance;

            if (funcInst == null && strInst == null)
            {
                return(-1);
            }

            int   id    = Interlocked.Increment(ref _timeoutId);
            Timer timer = new Timer(msTimeout);

            timer.AutoReset = false;
            _timers.Add(id, timer);
            timer.Elapsed += (sender, e) =>
            {
                if (funcInst != null)
                {
                    funcInst.Call(null);
                }
                else
                {
                    _engine.Evaluate(strInst.ToString());
                }

                timer.Dispose();
            };
            timer.Start();
            return(id);
        }
Beispiel #26
0
        //  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 (int i = 0, len = functionInstance.FormalParameters.Length; i < len; 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 (int i = 0, len = functionDeclarations.Count; i < len; 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 (int i = 0, ilen = variableDeclarations.Count; i < ilen; i++)
            {
                var varDeclations = variableDeclarations[i];
                for (int j = 0, jlen = varDeclations.Declarations.Count; j < jlen; j++)
                {
                    var d  = varDeclations.Declarations[j];
                    var dn = d.Id.Name;
                    var varAlreadyDeclared = env.HasBinding(dn);
                    if (!varAlreadyDeclared)
                    {
                        env.CreateMutableBinding(dn, configurableBindings);
                        env.SetMutableBinding(dn, Undefined.Instance, strict);
                    }
                }
            }
        }
Beispiel #27
0
        public void Analyze(Engine engine)
        {
            HasDynamicReturns = false;
            HasBoostedFields  = false;

            IFunction theFuncAst;

            switch (MapFunc)
            {
            case ArrowFunctionInstance afi:
                theFuncAst = afi.FunctionDeclaration;
                break;

            case ScriptFunctionInstance sfi:
                theFuncAst = sfi.FunctionDeclaration;
                break;

            default:
                return;
            }

            var res = CheckIfSimpleMapExpression(engine, theFuncAst);

            if (res != null)
            {
                MapFunc    = res.Value.Function;
                theFuncAst = res.Value.FunctionAst;
            }

            foreach (var returnStatement in JavaScriptIndexUtils.GetReturnStatements(theFuncAst))
            {
                if (returnStatement.Argument == null) // return;
                {
                    continue;
                }

                switch (returnStatement.Argument)
                {
                case ObjectExpression oe:

                    //If we got here we must validate that all return statements have the same structure.
                    //Having zero fields means its the first return statements we encounter that has a structure.
                    if (Fields.Count == 0)
                    {
                        foreach (var prop in oe.Properties)
                        {
                            if (prop is Property property)
                            {
                                var fieldName         = property.GetKey(engine);
                                var fieldNameAsString = fieldName.AsString();
                                if (fieldName == "_")
                                {
                                    HasDynamicReturns = true;
                                }

                                Fields.Add(fieldNameAsString);

                                var fieldValue = property.Value;
                                if (IsBoostExpression(fieldValue))
                                {
                                    HasBoostedFields = true;
                                }
                            }
                        }
                    }
                    else if (CompareFields(oe) == false)
                    {
                        throw new InvalidOperationException($"Index {IndexName} contains different return structure from different code paths," +
                                                            $" expected properties: {string.Join(", ", Fields)} but also got:{string.Join(", ", oe.Properties.Select(x => x.GetKey(engine)))}");
                    }

                    break;

                case CallExpression ce:

                    if (IsBoostExpression(ce))
                    {
                        HasBoostedFields = true;
                    }
                    else
                    {
                        HasDynamicReturns = true;
                    }

                    break;

                default:
                    HasDynamicReturns = true;
                    break;
                }
            }
Beispiel #28
0
        public bool Download(FunctionInstance callback)
        {
            if (callback == null)
            {
                return(false);
            }

            try {
                var request = (HttpWebRequest)HttpWebRequest.Create(uri);

                request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Reload);
                request.Method      = method.ToUpper();

                foreach (object obj in Headers.Items)
                {
                    string str = obj.ToString();

                    if (str.StartsWith("host"))
                    {
                        request.Host = str.Substring(str.IndexOf(':') + 1).Trim();
                    }

                    else if (str.StartsWith("content-type"))
                    {
                        request.ContentType = str.Substring(str.IndexOf(':') + 1).Trim();
                    }

                    else if (str.StartsWith("content-length"))
                    {
                        if (Int32.TryParse(str.Substring(str.IndexOf(':') + 1), out int length))
                        {
                            request.ContentLength = length;
                        }
                    }
                    else if (str.StartsWith("connection"))
                    {
                        request.Connection = str.Substring(str.IndexOf(':') + 1).Trim();
                    }

                    else if (str.StartsWith("date"))
                    {
                        DateTime date = DateTime.MinValue;

                        if (DateTime.TryParse(str.Substring(str.IndexOf(':') + 1), out date))
                        {
                            request.Date = date;
                        }
                    }
                    else if (str.StartsWith("expect"))
                    {
                        request.Expect = str.Substring(str.IndexOf(':') + 1).Trim();
                    }

                    else if (str.StartsWith("accept"))
                    {
                        request.Accept = str.Substring(str.IndexOf(':') + 1).Trim();
                    }

                    else if (str.StartsWith("user-agent"))
                    {
                        request.UserAgent = str.Substring(str.IndexOf(':') + 1).Trim();
                    }

                    else if (str.StartsWith("referer"))
                    {
                        request.Referer = str.Substring(str.IndexOf(':') + 1).Trim();
                    }

                    else if (str.StartsWith("TE"))
                    {
                        request.TransferEncoding = str.Substring(str.IndexOf(':') + 1).Trim();
                    }

                    else if (str.StartsWith("if-modified-since"))
                    {
                        DateTime date = DateTime.MinValue;

                        if (DateTime.TryParse(str.Substring(str.IndexOf(':') + 1), out date))
                        {
                            request.IfModifiedSince = date;
                        }
                    }
                    else
                    {
                        request.Headers.Add(str);
                    }
                }

                if (request.Method == "POST")
                {
                    if (!String.IsNullOrEmpty(PostContent))
                    {
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(PostContent);
                        request.ContentLength = buffer.Length;

                        var stream = request.GetRequestStream();
                        stream.Write(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        request.ContentLength = 0;
                    }
                }


                request.BeginGetResponse((IAsyncResult ar) => {
                    try {
                        var response = request.EndGetResponse(ar);
                        var stream   = response.GetResponseStream();

                        var reader  = new StreamReader(stream, System.Text.Encoding.UTF8);
                        string page = reader.ReadToEnd();

                        callback.Call(this, page);
                    }
                    catch (JavaScriptException jex) {
                        JurassicPlugin.Self.OnError(jex);
                    }
                    catch (Exception ex) {
                        JurassicPlugin.Self.OnError(new JavaScriptException(Engine, ErrorType.Error, ex.Message, ex));
                    }
                }, null);

                return(true);
            }
            catch (Exception e) {
                JurassicPlugin.Self.OnError(new JavaScriptException(Engine, ErrorType.Error, e.Message, e));
            }

            return(false);
        }
        public static ArgumentsInstance CreateArgumentsObject(Engine engine, FunctionInstance func, string[] names, JsValue[] args, EnvironmentRecord env, bool strict)
        {
            var obj = new ArgumentsInstance(engine, self =>
            {
                var len = args.Length;
                self.FastAddProperty("length", len, true, false, true);
                var map         = engine.Object.Construct(Arguments.Empty);
                var mappedNamed = new List <string>();
                var indx        = 0;
                while (indx <= len - 1)
                {
                    var indxStr = TypeConverter.ToString(indx);
                    var val     = args[indx];
                    self.FastAddProperty(indxStr, val, true, true, true);
                    if (indx < names.Length)
                    {
                        var name = names[indx];
                        if (!strict && !mappedNamed.Contains(name))
                        {
                            mappedNamed.Add(name);
                            Func <JsValue, JsValue> g = n => env.GetBindingValue(name, false);
                            var p = new Action <JsValue, JsValue>((n, o) => env.SetMutableBinding(name, o, true));

                            map.DefineOwnProperty(indxStr, new ClrAccessDescriptor(engine, g, p)
                            {
                                Configurable = true
                            }, false);
                        }
                    }
                    indx++;
                }

                // step 12
                if (mappedNamed.Count > 0)
                {
                    self.ParameterMap = map;
                }

                // step 13
                if (!strict)
                {
                    self.FastAddProperty("callee", func, true, false, true);
                }
                // step 14
                else
                {
                    var thrower = engine.Function.ThrowTypeError;
                    self.DefineOwnProperty("caller", new PropertyDescriptor(get: thrower, set: thrower, enumerable: false, configurable: false), false);
                    self.DefineOwnProperty("callee", new PropertyDescriptor(get: thrower, set: thrower, enumerable: false, configurable: false), false);
                }
            });

            // These properties are pre-initialized as their don't trigger
            // the EnsureInitialized() event and are cheap
            obj.Prototype  = engine.Object.PrototypeObject;
            obj.Extensible = true;
            obj.Strict     = strict;


            return(obj);
        }
 /// <summary>
 /// Initializes a getter/setter property.
 /// </summary>
 /// <param name="key"> The property key (either a string or a Symbol). </param>
 /// <param name="getter"> The function to call to retrieve the property value. </param>
 /// <param name="setter"> The function to call to set the property value. </param>
 /// <param name="attributes"> Indicates whether the property is readable, writable and/or enumerable. </param>
 public PropertyNameAndValue(object key, FunctionInstance getter, FunctionInstance setter, PropertyAttributes attributes)
 {
     this.key        = key;
     this.descriptor = new PropertyDescriptor(getter, setter, attributes);
 }
 /// <summary>
 /// Initializes a getter/setter property.
 /// </summary>
 /// <param name="key"> The property key (either a string or a Symbol). </param>
 /// <param name="getter"> The function to call to retrieve the property value. </param>
 /// <param name="setter"> The function to call to set the property value. </param>
 /// <param name="attributes"> Indicates whether the property is readable, writable and/or enumerable. </param>
 public PropertyNameAndValue(object key, FunctionInstance getter, FunctionInstance setter, PropertyAttributes attributes)
 {
     this.key = key;
     this.descriptor = new PropertyDescriptor(getter, setter, attributes);
 }