public static ArrayInstance From(ScriptEngine engine, ObjectInstance iterable, FunctionInstance mapFunction, object thisArg) { var result = new List <object>(); var iterator = TypeUtilities.GetIterator(engine, iterable); if (iterator != null) { // Initialize the array from an iterator. int index = 0; foreach (var item in TypeUtilities.Iterate(engine, iterator)) { object mappedValue = mapFunction?.Call(thisArg ?? Undefined.Value, item, index) ?? item; result.Add(mappedValue); index++; } } else { // Initialize the array from an array-like object. uint length = ArrayInstance.GetLength(iterable); for (int i = 0; i < length; i++) { object mappedValue = mapFunction?.Call(thisArg ?? Undefined.Value, iterable[i], i) ?? iterable[i]; result.Add(mappedValue); } } return(engine.Array.New(result.ToArray())); }
public void ForEach(FunctionInstance callback, object thisArg) { var node = this.list.First; // This event handler is for when the user-supplied callback deletes the current // linked list node while we're iterating over it. Action <LinkedListNode <object> > beforeDeleteHandler = (deletedNode) => { if (deletedNode == node) { node = node.Previous; } }; BeforeDelete += beforeDeleteHandler; try { while (node != null) { // Call the user-supplied callback. callback.Call(thisArg, node.Value, node.Value, this); // Go to the next node in the linked list. node = node == null ? this.list.First : node.Next; } } finally { BeforeDelete -= beforeDeleteHandler; } }
/// <summary> /// Creates a new Promise instance. /// </summary> /// <param name="prototype"></param> /// <param name="executor"></param> internal PromiseInstance(ObjectInstance prototype, FunctionInstance executor) : this(prototype) { try { executor.Call(Undefined.Value, resolvePromise, rejectPromise); } catch (JavaScriptException ex) { rejectPromise.Call(Undefined.Value, ex.ErrorObject); } }
/// <summary> /// Creates a new Promise instance. /// </summary> /// <param name="prototype"></param> /// <param name="executor"></param> internal PromiseInstance(ObjectInstance prototype, FunctionInstance executor) : this(prototype) { try { executor.Call(Undefined.Value, resolveFunction, rejectFunction); } catch (JavaScriptException ex) { rejectFunction.Call(Undefined.Value, ex.GetErrorObject(Engine)); } }
public PromiseInstance Reject(object reason) { ClrStubFunction func = new ClrStubFunction(this.Engine.FunctionInstancePrototype, (engine, thisObj, args) => { FunctionInstance resolve = (FunctionInstance)args[0]; FunctionInstance reject = (FunctionInstance)args[1]; reject.Call(thisObj, reason); return(Undefined.Value); }); return(this.Construct(func)); }
public void ForEach(FunctionInstance callback, object thisArg) { foreach (var keyValue in TypeUtilities.Iterate(Engine, Entries())) { var keyValueObj = keyValue as ObjectInstance; if (keyValueObj == null) { throw new JavaScriptException(Engine, ErrorType.TypeError, "Invalid iterator return value."); } callback.Call(thisArg, keyValueObj[0], keyValueObj[1], this); } }
/// <summary> /// Creates a new Promise instance. /// </summary> /// <param name="prototype"></param> /// <param name="executor"></param> internal PromiseInstance(ObjectInstance prototype, FunctionInstance executor) : base(prototype) { FunctionInstance resolveFunc = new ClrStubFunction(Engine.FunctionInstancePrototype, (engine, thisObj, param) => { return(Undefined.Value); }); FunctionInstance rejectFunc = new ClrStubFunction(Engine.FunctionInstancePrototype, (engine, thisObj, param) => { return(Undefined.Value); }); try { executor.Call(Undefined.Value, resolveFunc, rejectFunc); } catch (JavaScriptException ex) { rejectFunc.Call(Undefined.Value, ex.ErrorObject); } }
/// <summary> /// Creates a new Promise instance. /// </summary> /// <param name="prototype"></param> /// <param name="executor"></param> internal PromiseInstance(ObjectInstance prototype, FunctionInstance executor) : base(prototype) { FunctionInstance resolveFunc = new ClrStubFunction(Engine.FunctionInstancePrototype, (engine, thisObj, param) => { return Undefined.Value; }); FunctionInstance rejectFunc = new ClrStubFunction(Engine.FunctionInstancePrototype, (engine, thisObj, param) => { return Undefined.Value; }); try { executor.Call(Undefined.Value, resolveFunc, rejectFunc); } catch (JavaScriptException ex) { rejectFunc.Call(Undefined.Value, ex.ErrorObject); } }
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); } }
private void SetInterval(int id, FunctionInstance function, double delay, DateTime previous) { var self = this; var finnishTime = previous.AddMilliseconds(delay); Task.Factory.StartNew(() => { self.cancellationTokenSource.Token.ThrowIfCancellationRequested(); TimeSpan timeout = finnishTime - DateTime.Now; if (timeout < TimeSpan.Zero) timeout = TimeSpan.Zero; self.cancellationTokenSource.Token.WaitHandle.WaitOne(timeout); self.cancellationTokenSource.Token.ThrowIfCancellationRequested(); lock (self) { if (!self.intervals.Contains(id)) return; } self.scriptRunner.BeginInvoke(delegate { function.Call(self.Engine.Global); }); SetInterval(id, function, delay, finnishTime); }, self.cancellationTokenSource.Token); }
public static int SetTimeout(ScriptEngine engine, FunctionInstance function, double delay) { var self = timeoutHandlers[engine]; var finnishTime = DateTime.Now.AddMilliseconds(delay); int id; lock (self) { do { id = self.nextId++; } while (self.timeouts.Contains(id) || self.intervals.Contains(id)); self.timeouts.Add(id); } Task.Factory.StartNew(() => { self.cancellationTokenSource.Token.ThrowIfCancellationRequested(); TimeSpan timeout = finnishTime - DateTime.Now; if (timeout < TimeSpan.Zero) timeout = TimeSpan.Zero; self.cancellationTokenSource.Token.WaitHandle.WaitOne(timeout); self.cancellationTokenSource.Token.ThrowIfCancellationRequested(); lock (self) { if (!self.timeouts.Contains(id)) return; self.timeouts.Remove(id); } self.scriptRunner.BeginInvoke(delegate { function.Call(self.Engine.Global); }); }, self.cancellationTokenSource.Token); return id; }
public TypedArrayInstance From(object source, FunctionInstance mapFn = null, object thisArg = null) { var items = TypeConverter.ToObject(Engine, source); var iterator = TypeUtilities.GetIterator(Engine, items); if (iterator != null) { // Loop. var values = new List<object>(); foreach (var value in TypeUtilities.Iterate(Engine, iterator)) { // Collect the values. values.Add(value); } // Convert the values into a typed array instance. var result = new TypedArrayInstance(this.InstancePrototype, this.type, Engine.ArrayBuffer.Construct(values.Count * BytesPerElement), 0, values.Count); for (int i = 0; i < values.Count; i++) { if (mapFn != null) result[i] = mapFn.Call(thisArg, values[i], i); else result[i] = values[i]; } return result; } else { // There was no iterator symbol value, so fall back on the alternate method. int length = TypeConverter.ToInt32(items["length"]); var result = new TypedArrayInstance(this.InstancePrototype, this.type, Engine.ArrayBuffer.Construct(length * BytesPerElement), 0, length); for (int i = 0; i < length; i++) { if (mapFn != null) result[i] = mapFn.Call(thisArg, items[i], i); else result[i] = items[i]; } return result; } }
private void _Throws(bool shouldThrow, FunctionInstance block, object expected, object message) { if (expected is string) { message = expected; expected = null; } JavaScriptException actual = null; try { block.Call(null); } catch (JavaScriptException e) { actual = e; } message = (expected != null && expected is FunctionInstance ? " (" + (expected as FunctionInstance).Name + ")." : ".") + (message != null ? " " + message : "."); if (shouldThrow && actual == null) Fail(actual, expected, "Missing expected exception" + message, null); if (!shouldThrow && _ExpectedException(actual, expected)) Fail(actual, expected, "Got unwanted exception" + message, null); if ((shouldThrow && actual != null && expected != null && !_ExpectedException(actual, expected)) || (!shouldThrow && actual != null)) throw new JavaScriptException(actual, -1, "Assert.cs"); }