Inheritance: System.Runtime.Serialization.IDeserializationCallback
 /// <summary>
 /// Creates a new ThrowTypeErrorFunction instance.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="message"> The TypeError message. </param>
 internal ThrowTypeErrorFunction(ObjectInstance prototype, string message)
     : base(prototype)
 {
     this.FastSetProperty("length", 0);
     this.IsExtensible = false;
     this.message = message;
 }
Esempio n. 2
0
 public void AddObject(string name, ObjectInstance obj)
 {
     if(name != null && obj != null)
     {
         engine.SetGlobalValue(name, obj);
     }
 }
Esempio n. 3
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new DataView instance.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="buffer"> An existing ArrayBuffer to use as the storage for the new
 /// DataView object. </param>
 /// <param name="byteOffset"> The offset, in bytes, to the first byte in the specified
 /// buffer for the new view to reference. If not specified, the view of the buffer will
 /// start with the first byte. </param>
 /// <param name="byteLength"> The number of elements in the byte array. If unspecified,
 /// length of the view will match the buffer's length. </param>
 internal DataViewInstance(ObjectInstance prototype, ArrayBufferInstance buffer, int byteOffset, int byteLength)
     : base(prototype)
 {
     this.buffer = buffer;
     this.byteOffset = byteOffset;
     this.byteLength = byteLength;
 }
Esempio n. 4
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new JSON object.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 internal JSONObject(ObjectInstance prototype)
     : base(prototype)
 {
     var properties = GetDeclarativeProperties(Engine);
     properties.Add(new PropertyNameAndValue(Engine.Symbol.ToStringTag, "JSON", PropertyAttributes.Configurable));
     FastSetProperties(properties);
 }
Esempio n. 5
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a function which calls a .NET method, with no name or length.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="call"> The delegate to call when calling the JS method. </param>
 internal ClrStubFunction(ObjectInstance prototype, Func<ScriptEngine, object, object[], object> call)
     : base(prototype)
 {
     // Let's not even bother with setting the name and length!
     // Use sparingly.
     this.callBinder = call;
 }
Esempio n. 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LoaderInstance"/> class.
 /// </summary>
 /// <param name="prototype">The prototype.</param>
 /// <param name="scriptRunner">The script runner.</param>
 public LoaderInstance(ObjectInstance prototype, ScriptRunner scriptRunner)
     : base(prototype)
 {
     this.scriptRunner = scriptRunner;
     this.webClient = new WebClient();
     this.PopulateFunctions();
 }
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new instance of a built-in constructor function.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="name"> The name of the function. </param>
        /// <param name="instancePrototype">  </param>
        protected ClrFunction(ObjectInstance prototype, string name, ObjectInstance instancePrototype)
            : base(prototype)
        {
            if (name == null)
                throw new ArgumentNullException("name");
            if (instancePrototype == null)
                throw new ArgumentNullException("instancePrototype");

            // This is a constructor so ignore the "this" parameter when the function is called.
            thisBinding = this;

            // Search through every method in this type looking for [JSCallFunction] and [JSConstructorFunction] attributes.
            var callBinderMethods = new List<JSBinderMethod>(1);
            var constructBinderMethods = new List<JSBinderMethod>(1);
            var methods = this.GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
            foreach (var method in methods)
            {
                // Search for the [JSCallFunction] and [JSConstructorFunction] attributes.
                var callAttribute = (JSCallFunctionAttribute) Attribute.GetCustomAttribute(method, typeof(JSCallFunctionAttribute));
                var constructorAttribute = (JSConstructorFunctionAttribute)Attribute.GetCustomAttribute(method, typeof(JSConstructorFunctionAttribute));

                // Can't declare both attributes.
                if (callAttribute != null && constructorAttribute != null)
                    throw new InvalidOperationException("Methods cannot be marked with both [JSCallFunction] and [JSConstructorFunction].");

                if (callAttribute != null)
                {
                    // Method is marked with [JSCallFunction]
                    callBinderMethods.Add(new JSBinderMethod(method, callAttribute.Flags));
                }
                else if (constructorAttribute != null)
                {
                    var binderMethod = new JSBinderMethod(method, constructorAttribute.Flags);
                    constructBinderMethods.Add(binderMethod);
                    
                    // Constructors must return ObjectInstance or a derived type.
                    if (typeof(ObjectInstance).IsAssignableFrom(binderMethod.ReturnType) == false)
                        throw new InvalidOperationException(string.Format("Constructors must return {0} (or a derived type).", typeof(ObjectInstance).Name));
                }
            }

            // Initialize the Call function.
            if (callBinderMethods.Count > 0)
                this.callBinder = new JSBinder(callBinderMethods);
            else
                this.callBinder = new JSBinder(new JSBinderMethod(new Func<object>(() => Undefined.Value).Method));

            // Initialize the Construct function.
            if (constructBinderMethods.Count > 0)
                this.constructBinder = new JSBinder(constructBinderMethods);
            else
                this.constructBinder = new JSBinder(new JSBinderMethod(new Func<ObjectInstance>(() => this.Engine.Object.Construct()).Method));

            // Add function properties.
            this.FastSetProperty("name", name);
            this.FastSetProperty("length", this.callBinder.FunctionLength);
            this.FastSetProperty("prototype", instancePrototype);
            instancePrototype.FastSetProperty("constructor", this, PropertyAttributes.NonEnumerable);
        }
 /// <summary>
 /// Creates a new ThrowTypeErrorFunction instance.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="message"> The TypeError message. </param>
 internal ThrowTypeErrorFunction(ObjectInstance prototype, string message)
     : base(prototype)
 {
     this.FastSetProperty("name", "ThrowTypeError", PropertyAttributes.Configurable);
     this.FastSetProperty("length", 0, PropertyAttributes.Configurable);
     this.IsExtensible = false;
     this.message = message;
 }
Esempio n. 9
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new Object object.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="instancePrototype"> The prototype for instances created by this function. </param>
 internal ObjectConstructor(ObjectInstance prototype, ObjectInstance instancePrototype)
     : base(prototype, __STUB__Construct, __STUB__Call)
 {
     // Initialize the constructor properties.
     var properties = GetDeclarativeProperties(Engine);
     InitializeConstructorProperties(properties, "Object", 1, instancePrototype);
     FastSetProperties(properties);
 }
Esempio n. 10
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new set iterator.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="set"> The set to iterate over. </param>
 /// <param name="list"> The linked list to iterate over. </param>
 /// <param name="kind"> The type of values to return. </param>
 internal SetIterator(ObjectInstance prototype, SetInstance set, LinkedList<object> list, Kind kind)
     : base(prototype)
 {
     this.set = set;
     this.set.BeforeDelete += Set_BeforeDelete;
     this.list = list;
     this.kind = kind;
 }
Esempio n. 11
0
 public XMLDocInstance(ObjectInstance prototype, string path)
     : this(prototype)
 {
     _doc = new XmlDocument();
     _path = path;
     _doc.AppendChild(_doc.CreateXmlDeclaration("1.0", null, null));
     _doc.AppendChild(_doc.CreateComment("Generated by Sphere SFML XML Content Serializer v1.0"));
 }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JsEventObject"/> class.
        /// </summary>
        /// <param name="prototype">The prototype.</param>
        /// <param name="runner">The runner.</param>
        public JsEventObject(ObjectInstance prototype, ScriptRunner runner)
            : base(prototype)
        {
            this.runner = runner;
            this.events = new Dictionary<string, List<FunctionInstance>>();

            PopulateFunctions(typeof(JsEventObject));
        }
Esempio n. 13
0
 /// <summary>
 /// Creates a new string instance.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="value"> The value to initialize the instance. </param>
 public StringInstance(ObjectInstance prototype, string value)
     : base(prototype)
 {
     if (value == null)
         throw new ArgumentNullException("value");
     this.value = value;
     this.FastSetProperty("length", value.Length);
 }
Esempio n. 14
0
 /// <summary>
 /// Initializes the prototype properties.
 /// </summary>
 /// <param name="obj"> The object to set the properties on. </param>
 /// <param name="constructor"> A reference to the constructor that owns the prototype. </param>
 internal static void InitializePrototypeProperties(ObjectInstance obj, SymbolConstructor constructor)
 {
     var engine = obj.Engine;
     var properties = GetDeclarativeProperties(engine);
     properties.Add(new PropertyNameAndValue("constructor", constructor, PropertyAttributes.NonEnumerable));
     properties.Add(new PropertyNameAndValue(engine.Symbol.ToStringTag, "Symbol", PropertyAttributes.Configurable));
     obj.FastSetProperties(properties);
 }
Esempio n. 15
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new map constructor.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 internal WeakMapConstructor(ObjectInstance prototype)
     : base(prototype, __STUB__Construct, __STUB__Call)
 {
     // Initialize the constructor properties.
     var properties = new List<PropertyNameAndValue>();
     InitializeConstructorProperties(properties, "WeakMap", 0, WeakMapInstance.CreatePrototype(Engine, this));
     FastSetProperties(properties);
 }
Esempio n. 16
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new derived error function.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="type"> The type of error, e.g. Error, RangeError, etc. </param>
 internal ErrorConstructor(ObjectInstance prototype, ErrorType type)
     : base(prototype, __STUB__Construct, __STUB__Call)
 {
     // Initialize the constructor properties.
     var properties = new List<PropertyNameAndValue>(3);
     InitializeConstructorProperties(properties, type.ToString(), 1, ErrorInstance.CreatePrototype(Engine, this, type));
     FastSetProperties(properties);
 }
Esempio n. 17
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new Boolean object.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 internal BooleanConstructor(ObjectInstance prototype)
     : base(prototype, __STUB__Construct, __STUB__Call)
 {
     // Initialize the constructor properties.
     var properties = new List<PropertyNameAndValue>(3);
     InitializeConstructorProperties(properties, "Boolean", 1, BooleanInstance.CreatePrototype(Engine, this));
     FastSetProperties(properties);
 }
Esempio n. 18
0
 /// <summary>
 /// Creates a new constructor function.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="construct"> The delegate to call when calling the JS method as a constructor. </param>
 /// <param name="call"> The delegate to call when function is called. </param>
 internal ClrStubFunction(ObjectInstance prototype,
     Func<ScriptEngine, object, object[], ObjectInstance> construct,
     Func<ScriptEngine, object, object[], object> call)
     : base(prototype)
 {
     this.callBinder = call;
     this.constructBinder = construct;
 }
Esempio n. 19
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new Error instance with the given name, message and optionally a stack trace.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="name"> The initial value of the name property.  Pass <c>null</c> to avoid
        /// creating this property. </param>
        /// <param name="message"> The initial value of the message property.  Pass <c>null</c> to
        /// avoid creating this property. </param>
        internal ErrorInstance(ObjectInstance prototype, string name, string message)
            : base(prototype)
        {
            if (name != null)
                this.FastSetProperty("name", name, PropertyAttributes.FullAccess);
            if (message != null)
                this.FastSetProperty("message", message, PropertyAttributes.FullAccess);
        }
Esempio n. 20
0
 /// <summary>
 /// Called by derived classes to create a new object instance.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain.  Cannot be <c>null</c>. </param>
 protected ObjectInstance(ObjectInstance prototype)
 {
     if (prototype == null)
         throw new ArgumentNullException("prototype");
     this.prototype = prototype;
     this.engine = prototype.Engine;
     this.schema = this.engine.EmptySchema;
 }
Esempio n. 21
0
 /// <summary>
 /// Called by derived classes to create a new object instance.
 /// </summary>
 /// <param name="engine"> The script engine associated with this object. </param>
 /// <param name="prototype"> The next object in the prototype chain.  Can be <c>null</c>. </param>
 protected ObjectInstance(ScriptEngine engine, ObjectInstance prototype)
 {
     if (engine == null)
         throw new ArgumentNullException("engine");
     this.engine = engine;
     this.prototype = prototype;
     this.schema = engine.EmptySchema;
 }
Esempio n. 22
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new map iterator.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="map"> The map to iterate over. </param>
 /// <param name="list"> The linked list to iterate over. </param>
 /// <param name="kind"> The type of values to return. </param>
 internal MapIterator(ObjectInstance prototype, MapInstance map, LinkedList<KeyValuePair<object, object>> list, Kind kind)
     : base(prototype)
 {
     this.map = map;
     this.map.BeforeDelete += Map_BeforeDelete;
     this.list = list;
     this.kind = kind;
 }
Esempio n. 23
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new String object.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 internal StringConstructor(ObjectInstance prototype)
     : base(prototype, __STUB__Construct, __STUB__Call)
 {
     // Initialize the constructor properties.
     var properties = GetDeclarativeProperties(Engine);
     InitializeConstructorProperties(properties, "String", 1, StringInstance.CreatePrototype(Engine, this));
     FastSetProperties(properties);
 }
Esempio n. 24
0
 //     INITIALIZATION
 //_________________________________________________________________________________________
 /// <summary>
 /// Creates a new RegExp object.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 internal RegExpConstructor(ObjectInstance prototype)
     : base(prototype, __STUB__Construct, __STUB__Call)
 {
     // Initialize the constructor properties.
     var properties = GetDeclarativeProperties(Engine);
     InitializeConstructorProperties(properties, "RegExp", 2, RegExpInstance.CreatePrototype(Engine, this));
     AddDeprecatedProperties(properties);
     FastSetProperties(properties);
 }
Esempio n. 25
0
        public JSImageInstance(ObjectInstance prototype)
            : base(prototype)
        {
            this["width"] = 0;
            this["height"] = 0;

            this.PopulateFunctions();
            this.PopulateFields();
        }
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new Global object.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        internal GlobalObject(ObjectInstance prototype)
            : base(prototype)
        {
            // Add the global constants.
            // Infinity, NaN and undefined are read-only in ECMAScript 5.
            this.FastSetProperty("Infinity", double.PositiveInfinity, PropertyAttributes.Sealed);
            this.FastSetProperty("NaN", double.NaN, PropertyAttributes.Sealed);
            this.FastSetProperty("undefined", Undefined.Value, PropertyAttributes.Sealed);
        }
Esempio n. 27
0
 /// <summary>
 /// Constructs the object's prototype, not bound to any context.
 /// </summary>
 /// <param name="nextPrototype">Prototype of the prototype</param>
 /// <param name="extended">Whether extending a base object or not</param>
 public ContextObjectInstance(ObjectInstance nextPrototype, bool extended)
     : base(nextPrototype)
 {
     // This one derives from ObjectInstance directly, so this is not necessary:
     // if (!extended) {
         // Populate();
     // }
     // It's necessary in all other inherited objects, though.
 }
Esempio n. 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientInstance"/> class.
 /// </summary>
 /// <param name="prototype">The prototype.</param>
 /// <param name="runner">The runner.</param>
 public ClientInstance(ObjectInstance prototype, ScriptRunner runner)
     : base(prototype, runner)
 {
     client = new IrcClient();
     client.Message += new EventHandler<IrcMessageEventArgs>(client_Message);
     client.ChannelJoin += new EventHandler<IrcChannelEventArgs>(client_ChannelJoin);
     client.Disconnect += new EventHandler<EventArgs>(client_Disconnect);
     client.SslValidate += new EventHandler<SslValidateEventArgs>(client_SslValidate);
     PopulateFunctions();
 }
Esempio n. 29
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new ThrowTypeErrorFunction instance.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        internal ThrowTypeErrorFunction(ObjectInstance prototype)
            : base(prototype)
        {
            this.FastSetProperty("length", 0);
            this.IsExtensible = false;
            this.body = new FunctionDelegate((engine, scope, thisObject, functionObject, argumentValues) =>
                {
                    throw new JavaScriptException(this.Engine, "TypeError", "It is illegal to access the 'callee' or 'caller' property in strict mode");
                });
        }
Esempio n. 30
0
        /// <summary>
        /// Creates a new instance of a function which calls a .NET method.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="name"> The name of the function. </param>
        /// <param name="length"> The "typical" number of arguments expected by the function. </param>
        /// <param name="call"> The delegate to call when calling the JS method. </param>
        public ClrStubFunction(ObjectInstance prototype, string name, int length, Func<ScriptEngine, object, object[], object> call)
            : base(prototype)
        {
            this.callBinder = call;

            // Set name and length properties.
            var properties = new List<PropertyNameAndValue>(2);
            properties.Add(new PropertyNameAndValue("name", name, PropertyAttributes.Configurable));
            properties.Add(new PropertyNameAndValue("length", length, PropertyAttributes.Configurable));
            FastSetProperties(properties);
        }
        public static T FromObject <T>(Jurassic.Library.ObjectInstance instance) where T : new()
        {
            if (instance == null)
            {
                return(default(T));
            }

            var ret = new T();

            foreach (var pi in ret.GetType().GetProperties())
            {
                try
                {
                    var value = instance.GetPropertyValue(JsonPropertyName(pi));
                    if (pi.PropertyType.IsPrimitive || pi.PropertyType == typeof(string))
                    {
                        pi.SetValue(ret, Convert.ChangeType(value, pi.PropertyType), null);
                    }
                }
                catch { }
            }
            return(ret);
        }
        public static ResultPerPageFree FromObjectInstance(Jurassic.Library.ObjectInstance instance)
        {
            /*为了简单,省去1万地反射...*/
            var ret = new ResultPerPageFree();

            foreach (var pi in ret.GetType().GetProperties())
            {
                try
                {
                    var value = instance.GetPropertyValue(JsonPropertyName(pi));
                    if (pi.Name == "GroupsList")
                    {
                        var ls = value as ArrayInstance;
                        if (ls != null)
                        {
                            var wxGroups = (from ObjectInstance o in ls.ElementValues select FromObject <WxGroup>(o)).ToList();
                            pi.SetValue(ret, wxGroups, null);
                        }
                    }
                    else if (pi.Name == "FriendsList")
                    {
                        var ls = value as ArrayInstance;
                        if (ls != null)
                        {
                            var wxGroups = (from ObjectInstance o in ls.ElementValues select FromObject <WxUserFree>(o)).ToList();
                            pi.SetValue(ret, wxGroups, null);
                        }
                    }
                    else
                    {
                        pi.SetValue(ret, Convert.ChangeType(value, pi.PropertyType), null);
                    }
                }
                catch { }
            }
            return(ret);
        }
Esempio n. 33
0
 /// <summary>
 /// Creates a new ArrayBuffer instance from an existing buffer.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 /// <param name="buffer"> The buffer to use. </param>
 private ArrayBufferInstance(ObjectInstance prototype, byte[] buffer)
     : base(prototype)
 {
     this.buffer = buffer;
 }
Esempio n. 34
0
        /// <summary>
        /// Serializes an object into a JSON string.
        /// </summary>
        /// <param name="value"> The object to serialize. </param>
        /// <param name="result"> The StringBuilder to write the JSON representation of the
        /// object to. </param>
        private void SerializeObject(ObjectInstance value, StringBuilder result)
        {
            // Add the spacer string to the current separator string.
            string previousSeparator = this.separator;

            this.separator += this.Indentation;

            // Check for cyclical references.
            if (this.objectStack.Contains(value) == true)
            {
                throw new JavaScriptException(this.engine, "TypeError", "The given object must not contain cyclical references");
            }
            this.objectStack.Push(value);

            // Create a list of property names to serialize.
            var propertiesToSerialize = this.SerializableProperties;

            if (propertiesToSerialize == null)
            {
                propertiesToSerialize = new List <string>();
                foreach (var property in value.Properties)
                {
                    if (property.IsEnumerable == true)
                    {
                        propertiesToSerialize.Add(property.Name);
                    }
                }
            }

            result.Append('{');
            int serializedPropertyCount = 0;

            foreach (string propertyName in propertiesToSerialize)
            {
                // Transform the value using the replacer function or toJSON().
                object propertyValue = TransformPropertyValue(value, propertyName);

                // Undefined values are not serialized.
                if (propertyValue == null || propertyValue == Undefined.Value || propertyValue is FunctionInstance)
                {
                    continue;
                }

                // Append the separator.
                if (serializedPropertyCount > 0)
                {
                    result.Append(',');
                }
                result.Append(this.separator);

                // Append the property name and value to the result.
                QuoteString(propertyName, result);
                result.Append(':');
                if (string.IsNullOrEmpty(this.Indentation) == false)
                {
                    result.Append(' ');
                }
                SerializePropertyValue(propertyValue, result);

                // Keep track of how many properties we have serialized.
                serializedPropertyCount++;
            }
            if (serializedPropertyCount > 0)
            {
                result.Append(previousSeparator);
            }
            result.Append('}');

            // Remove this object from the stack.
            this.objectStack.Pop();

            // Restore the separator to it's previous value.
            this.separator = previousSeparator;
        }
Esempio n. 35
0
 public bool Some(FunctionInstance callbackFunction, ObjectInstance context = null)
 {
     return(new TypedArrayAdapter(this).Some(callbackFunction, context));
 }
Esempio n. 36
0
 public static ObjectInstance PreventExtensions(ObjectInstance obj)
 {
     obj.IsExtensible = false;
     return(obj);
 }
Esempio n. 37
0
 public static new bool IsExtensible(ObjectInstance obj)
 {
     return(obj.IsExtensible);
 }
Esempio n. 38
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new instance of a built-in constructor function.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="name"> The name of the function. </param>
        /// <param name="instancePrototype">  </param>
        protected ClrFunction(ObjectInstance prototype, string name, ObjectInstance instancePrototype)
            : base(prototype)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (instancePrototype == null)
            {
                throw new ArgumentNullException("instancePrototype");
            }

            // This is a constructor so ignore the "this" parameter when the function is called.
            thisBinding = this;

            // Search through every method in this type looking for [JSCallFunction] and [JSConstructorFunction] attributes.
            var callBinderMethods      = new List <JSBinderMethod>(1);
            var constructBinderMethods = new List <JSBinderMethod>(1);
            var methods = this.GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);

            foreach (var method in methods)
            {
                // Search for the [JSCallFunction] and [JSConstructorFunction] attributes.
                var callAttribute        = (JSCallFunctionAttribute)Attribute.GetCustomAttribute(method, typeof(JSCallFunctionAttribute));
                var constructorAttribute = (JSConstructorFunctionAttribute)Attribute.GetCustomAttribute(method, typeof(JSConstructorFunctionAttribute));

                // Can't declare both attributes.
                if (callAttribute != null && constructorAttribute != null)
                {
                    throw new InvalidOperationException("Methods cannot be marked with both [JSCallFunction] and [JSConstructorFunction].");
                }

                if (callAttribute != null)
                {
                    // Method is marked with [JSCallFunction]
                    callBinderMethods.Add(new JSBinderMethod(method, callAttribute.Flags));
                }
                else if (constructorAttribute != null)
                {
                    var binderMethod = new JSBinderMethod(method, constructorAttribute.Flags);
                    constructBinderMethods.Add(binderMethod);

                    // Constructors must return ObjectInstance or a derived type.
                    if (typeof(ObjectInstance).IsAssignableFrom(binderMethod.ReturnType) == false)
                    {
                        throw new InvalidOperationException(string.Format("Constructors must return {0} (or a derived type).", typeof(ObjectInstance).Name));
                    }
                }
            }

            // Initialize the Call function.
            if (callBinderMethods.Count > 0)
            {
                this.callBinder = new JSBinder(callBinderMethods);
            }
            else
            {
                this.callBinder = new JSBinder(new JSBinderMethod(new Func <object>(() => Undefined.Value).Method));
            }

            // Initialize the Construct function.
            if (constructBinderMethods.Count > 0)
            {
                this.constructBinder = new JSBinder(constructBinderMethods);
            }
            else
            {
                this.constructBinder = new JSBinder(new JSBinderMethod(new Func <ObjectInstance>(() => this.Engine.Object.Construct()).Method));
            }

            // Add function properties.
            this.FastSetProperty("name", name);
            this.FastSetProperty("length", this.callBinder.FunctionLength);
            this.FastSetProperty("prototype", instancePrototype);
            instancePrototype.FastSetProperty("constructor", this, PropertyAttributes.NonEnumerable);

            this.Engine.RegisterClrFunction(this);
        }
Esempio n. 39
0
 /// <summary>
 /// Creates a new instance of a built-in function object.
 /// </summary>
 /// <param name="engine"> The associated script engine. </param>
 /// <param name="prototype"> The next object in the prototype chain.  Can be <c>null</c>. </param>
 protected FunctionInstance(ScriptEngine engine, ObjectInstance prototype)
     : base(engine, prototype)
 {
 }
Esempio n. 40
0
 public int FindIndex(FunctionInstance callbackFunction, ObjectInstance context = null)
 {
     return(new TypedArrayAdapter(this).FindIndex(callbackFunction, context));
 }
Esempio n. 41
0
 /// <summary>
 /// Creates a new ArrayWrapper instance.
 /// </summary>
 /// <param name="wrappedInstance"> The array-like object that is being wrapped. </param>
 /// <param name="length"> The number of elements in the array. </param>
 protected ArrayAdapter(ObjectInstance wrappedInstance, int length)
 {
     this.wrappedInstance = wrappedInstance;
     this.length          = length;
 }
Esempio n. 42
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new Math object.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        internal MathObject(ObjectInstance prototype)
            : base(prototype)
        {
        }
Esempio n. 43
0
 public static string ToString(ObjectInstance thisObject)
 {
     return(string.Format("/{0}/{1}",
                          TypeConverter.ToString(thisObject["source"]),
                          TypeConverter.ToString(thisObject["flags"])));
 }
Esempio n. 44
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new string iterator.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="iteratedString"> The string to iterate over. </param>
        internal StringIterator(ObjectInstance prototype, string iteratedString)
            : base(prototype)
        {
            this.enumerator = StringInfo.GetTextElementEnumerator(iteratedString);
        }
Esempio n. 45
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new ArrayBuffer instance.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="size"> The size, in bytes, of the array buffer to create. </param>
        public ArrayBufferInstance(ObjectInstance prototype, int size)
            : base(prototype)
        {
            this.buffer = new byte[size];
        }
Esempio n. 46
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new boolean instance.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="value"> The value to initialize the instance with. </param>
        public BooleanInstance(ObjectInstance prototype, bool value)
            : base(prototype)
        {
            this.value = value;
        }
Esempio n. 47
0
        //     OBJECT SERIALIZATION AND DESERIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a property descriptor from an object containing any of the following
        /// properties: configurable, writable, enumerable, value, get, set.
        /// </summary>
        /// <param name="obj"> The object to get the property values from. </param>
        /// <param name="defaults"> The values to use if the relevant value is not specified. </param>
        /// <returns> A PropertyDescriptor that corresponds to the object. </returns>
        public static PropertyDescriptor FromObject(ObjectInstance obj, PropertyDescriptor defaults)
        {
            if (obj == null)
            {
                return(PropertyDescriptor.Undefined);
            }

            // Read configurable attribute.
            bool configurable = defaults.IsConfigurable;

            if (obj.HasProperty("configurable"))
            {
                configurable = TypeConverter.ToBoolean(obj["configurable"]);
            }

            // Read writable attribute.
            bool writable = defaults.IsWritable;

            if (obj.HasProperty("writable"))
            {
                writable = TypeConverter.ToBoolean(obj["writable"]);
            }

            // Read enumerable attribute.
            bool enumerable = defaults.IsEnumerable;

            if (obj.HasProperty("enumerable"))
            {
                enumerable = TypeConverter.ToBoolean(obj["enumerable"]);
            }

            // Read property value.
            object value = defaults.Value;

            if (obj.HasProperty("value"))
            {
                value = obj["value"];
            }

            // The descriptor is an accessor if get or set is present.
            bool isAccessor = false;

            // Read get accessor.
            FunctionInstance getter = defaults.Getter;

            if (obj.HasProperty("get"))
            {
                if (obj.HasProperty("value"))
                {
                    throw new JavaScriptException(obj.Engine, ErrorType.TypeError, "Property descriptors cannot have both 'get' and 'value' set");
                }
                if (obj.HasProperty("writable"))
                {
                    throw new JavaScriptException(obj.Engine, ErrorType.TypeError, "Property descriptors with 'get' or 'set' defined must not have 'writable' set");
                }
                if (obj["get"] is FunctionInstance)
                {
                    getter = (FunctionInstance)obj["get"];
                }
                else if (TypeUtilities.IsUndefined(obj["get"]) == true)
                {
                    getter = null;
                }
                else
                {
                    throw new JavaScriptException(obj.Engine, ErrorType.TypeError, "Property descriptor 'get' must be a function");
                }
                isAccessor = true;
            }

            // Read set accessor.
            FunctionInstance setter = defaults.Setter;

            if (obj.HasProperty("set"))
            {
                if (obj.HasProperty("value"))
                {
                    throw new JavaScriptException(obj.Engine, ErrorType.TypeError, "Property descriptors cannot have both 'set' and 'value' set");
                }
                if (obj.HasProperty("writable"))
                {
                    throw new JavaScriptException(obj.Engine, ErrorType.TypeError, "Property descriptors with 'get' or 'set' defined must not have 'writable' set");
                }
                if (obj["set"] is FunctionInstance)
                {
                    setter = (FunctionInstance)obj["set"];
                }
                else if (TypeUtilities.IsUndefined(obj["set"]) == true)
                {
                    setter = null;
                }
                else
                {
                    throw new JavaScriptException(obj.Engine, ErrorType.TypeError, "Property descriptor 'set' must be a function");
                }
                isAccessor = true;
            }

            // Build up the attributes enum.
            PropertyAttributes attributes = PropertyAttributes.Sealed;

            if (configurable == true)
            {
                attributes |= PropertyAttributes.Configurable;
            }
            if (writable == true)
            {
                attributes |= PropertyAttributes.Writable;
            }
            if (enumerable == true)
            {
                attributes |= PropertyAttributes.Enumerable;
            }

            // Either a value or an accessor is possible.
            object descriptorValue = value;

            if (isAccessor == true)
            {
                descriptorValue = new PropertyAccessorValue(getter, setter);
            }

            // Create the new property descriptor.
            return(new PropertyDescriptor(descriptorValue, attributes));
        }
Esempio n. 48
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new WeakMap instance.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        public WeakMapInstance(ObjectInstance prototype)
            : base(prototype)
        {
            this.store = new ConditionalWeakTable <ObjectInstance, object>();
        }
Esempio n. 49
0
 /// <summary>
 /// Creates a new instance of a built-in function object.
 /// </summary>
 /// <param name="prototype"> The next object in the prototype chain. </param>
 protected FunctionInstance(ObjectInstance prototype)
     : base(prototype)
 {
 }
Esempio n. 50
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new RegExp object.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        internal RegExpConstructor(ObjectInstance prototype)
            : base(prototype, "RegExp", new RegExpInstance(prototype.Engine.Object.InstancePrototype, string.Empty))
        {
            this.InitializeDeprecatedProperties();
        }
Esempio n. 51
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new Number instance and initializes it to the given value.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="value"> The value to initialize to. </param>
        public NumberInstance(ObjectInstance prototype, double value)
            : base(prototype)
        {
            this.value = value;
        }
Esempio n. 52
0
 public PromiseInstance Race(ObjectInstance iterable)
 {
     throw new NotImplementedException();
 }
Esempio n. 53
0
 public ObjectInstance Construct()
 {
     return(ObjectInstance.CreateRawObject(this.InstancePrototype));
 }
Esempio n. 54
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new set instance.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        internal SetInstance(ObjectInstance prototype)
            : base(prototype)
        {
            this.store = new Dictionary <object, LinkedListNode <object> >(new SameValueZeroComparer());
            this.list  = new LinkedList <object>();
        }
Esempio n. 55
0
        //     METHODS
        //_________________________________________________________________________________________


        /// <summary>
        /// Populates the given object with properties, field and methods based on the given .NET
        /// type.
        /// </summary>
        /// <param name="target"> The object to populate. </param>
        /// <param name="type"> The .NET type to search for methods. </param>
        /// <param name="flags"> <c>BindingFlags.Static</c> to populate static methods;
        /// <c>BindingFlags.Instance</c> to populate instance methods. </param>
        internal static void PopulateMembers(ObjectInstance target, Type type, BindingFlags flags)
        {
            // Register static methods as functions.
            var methodGroups = new Dictionary <string, List <MethodBase> >();

            foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.DeclaredOnly | flags))
            {
                switch (member.MemberType)
                {
                case MemberTypes.Method:
                    MethodInfo        method = (MethodInfo)member;
                    List <MethodBase> methodGroup;
                    if (methodGroups.TryGetValue(method.Name, out methodGroup) == true)
                    {
                        methodGroup.Add(method);
                    }
                    else
                    {
                        methodGroups.Add(method.Name, new List <MethodBase>()
                        {
                            method
                        });
                    }
                    break;

                case MemberTypes.Property:
                    PropertyInfo property  = (PropertyInfo)member;
                    var          getMethod = property.GetGetMethod();
                    ClrFunction  getter    = getMethod == null ? null : new ClrFunction(target.Engine.Function.InstancePrototype, new ClrBinder(getMethod));
                    var          setMethod = property.GetSetMethod();
                    ClrFunction  setter    = setMethod == null ? null : new ClrFunction(target.Engine.Function.InstancePrototype, new ClrBinder(setMethod));
                    target.DefineProperty(property.Name, new PropertyDescriptor(getter, setter, PropertyAttributes.NonEnumerable), false);

                    // Property getters and setters also show up as methods, so remove them here.
                    // NOTE: only works if properties are enumerated after methods.
                    if (getMethod != null)
                    {
                        methodGroups.Remove(getMethod.Name);
                    }
                    if (setMethod != null)
                    {
                        methodGroups.Remove(setMethod.Name);
                    }
                    break;

                case MemberTypes.Field:
                    FieldInfo   field       = (FieldInfo)member;
                    ClrFunction fieldGetter = new ClrFunction(target.Engine.Function.InstancePrototype, new FieldGetterBinder(field));
                    ClrFunction fieldSetter = new ClrFunction(target.Engine.Function.InstancePrototype, new FieldSetterBinder(field));
                    target.DefineProperty(field.Name, new PropertyDescriptor(fieldGetter, fieldSetter, PropertyAttributes.NonEnumerable), false);
                    break;

                case MemberTypes.Constructor:
                case MemberTypes.NestedType:
                case MemberTypes.Event:
                case MemberTypes.TypeInfo:
                    // Support not yet implemented.
                    break;
                }
            }
            foreach (var methodGroup in methodGroups.Values)
            {
                var binder   = new ClrBinder(methodGroup);
                var function = new ClrFunction(target.Engine.Function.InstancePrototype, binder);
                target.FastSetProperty(binder.Name, function, PropertyAttributes.NonEnumerable, overwriteAttributes: true);
            }
        }
Esempio n. 56
0
 public TypedArrayInstance Map(FunctionInstance callbackFunction, ObjectInstance context = null)
 {
     return((TypedArrayInstance) new TypedArrayAdapter(this).Map(callbackFunction, context));
 }
Esempio n. 57
0
        public PromiseInstance All(ObjectInstance iterable)
        {
            if (iterable == null)
            {
                throw new JavaScriptException(ErrorType.TypeError, "The parameter must be an iterable.");
            }

            var promises = TypeUtilities.ForOf(iterable.Engine, iterable).ToList();
            var results  = Engine.Array.Construct(new object[promises.Count]);
            var count    = promises.Count;

            var promise = new PromiseInstance(iterable.Engine.Promise.InstancePrototype);

            // The promise is resolved immediately if the iterable is empty.
            if (promises.Count == 0)
            {
                promise.Resolve(results);
                return(promise);
            }

            for (var i = 0; i < promises.Count; i++)
            {
                if (promise.State != PromiseState.Pending)
                {
                    break;
                }

                if (promises[i] is PromiseInstance p)
                {
                    if (p.State == PromiseState.Rejected)
                    {
                        promise.Reject(p.Result);
                        break;
                    }
                    else if (p.State == PromiseState.Fulfilled)
                    {
                        results[i] = p.Result;
                        if (--count == 0)
                        {
                            promise.Resolve(results);
                            break;
                        }
                        continue;
                    }

                    var j = i; // Some C# versions need this.
                    p.Then(new ClrStubFunction(Engine.FunctionInstancePrototype, "", 1, (engine, thisObj, args) =>
                    {
                        if (promise.State != PromiseState.Pending)
                        {
                            return(Undefined.Value);
                        }

                        results[j] = args[0];

                        if (--count == 0)
                        {
                            promise.Resolve(results);
                        }
                        return(Undefined.Value);
                    }),
                           new ClrStubFunction(Engine.FunctionInstancePrototype, "", 1, (engine, thisObj, args) =>
                    {
                        promise.Reject(args[0]);
                        return(Undefined.Value);
                    }));

                    continue;
                }
                else if (promises[i] is ObjectInstance obj && obj.HasProperty("then"))
                {
                    FunctionInstance then;
                    try
                    {
                        then = obj.GetPropertyValue("then") as FunctionInstance;
                    }
                    catch (JavaScriptException jex)
                    {
                        promise.Reject(jex.GetErrorObject(Engine));
                        break;
                    }

                    if (then != null)
                    {
                        try
                        {
                            var j       = i; // Some C# versions need this.
                            var resolve = new ClrStubFunction(iterable.Engine.Function.InstancePrototype, (engine, ths, arg) =>
                            {
                                if (promise.State != PromiseState.Pending)
                                {
                                    return(Undefined.Value);
                                }

                                results[j] = arg.Length == 0
                                    ? Undefined.Value
                                    : arg[0];

                                if (--count == 0)
                                {
                                    promise.Resolve(results);
                                }
                                return(Undefined.Value);
                            });

                            then.Call(obj, resolve, promise.RejectFunction);
                            continue;
                        }
                        catch (JavaScriptException jex)
                        {
                            promise.Reject(jex.GetErrorObject(Engine));
                            break;
                        }
                    }
                }

                results[i] = promises[i];
                if (--count == 0)
                {
                    promise.Resolve(results);
                    break;
                }
            }

            return(promise);
        }
Esempio n. 58
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new symbol instance.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        /// <param name="symbol"> The symbol primitive. </param>
        public SymbolInstance(ObjectInstance prototype, Symbol symbol)
            : base(prototype)
        {
            this.symbol = symbol;
        }
Esempio n. 59
0
 public void ForEach(FunctionInstance callbackFunction, ObjectInstance context = null)
 {
     new TypedArrayAdapter(this).ForEach(callbackFunction, context);
 }
Esempio n. 60
0
        //     INITIALIZATION
        //_________________________________________________________________________________________

        /// <summary>
        /// Creates a new Global object.
        /// </summary>
        /// <param name="prototype"> The next object in the prototype chain. </param>
        internal GlobalObject(ObjectInstance prototype)
            : base(prototype)
        {
        }