Ejemplo n.º 1
0
        public object Invoke(DispatchIdentifier id, DispatchType dispType, JsValue[] args, out Type returnType)
        {
            if (id.Tag == DispatchIdentifierType.String) {
                if (id.AsString == "length") {
                    return GetLength(dispType, out returnType);
                }
                else {
                    returnType = typeof(void);
                    return null;
                }
            }
            else {
                int intId = id.AsInt;
                if (intId == this.target.Length) {
                    return GetLength(dispType, out returnType);
                }

                if (intId >= 0 && intId < this.target.Length) {
                    Debug.WriteLine(string.Format("{0}, {1}[{2}]", dispType, this.target, id));
                    if (dispType == DispatchType.PropertyGet) {
                        returnType = this.elementType;
                        return this.target.GetValue(intId);
                    }

                    if (dispType == DispatchType.PropertySet) {
                        object value = this.bridge.UnwrapValue(args.First(), this.elementType);
                        this.target.SetValue(value, intId);
                        returnType = typeof(void);
                        return null;
                    }
                }
            }

            throw new NotSupportedException();
        }
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.2.1
        /// </summary>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public ObjectInstance Construct(JsValue[] arguments)
        {
            if (arguments.Length > 0)
            {
                var value = arguments[0];
                var valueObj = value.TryCast<ObjectInstance>();
                if (valueObj != null)
                {
                    return valueObj;
                }
                var type = value.Type;
                if (type == Types.String || type == Types.Number || type == Types.Boolean)
                {
                    return TypeConverter.ToObject(_engine, value);
                }
            }

            var obj = new ObjectInstance(_engine)
                {
                    Extensible = true,
                    Prototype = Engine.Object.PrototypeObject
                };

            return obj;
        }
Ejemplo n.º 3
0
        private JsValue Bind(JsValue thisObj, JsValue[] arguments)
        {
            var target = thisObj.TryCast<ICallable>(x =>
            {
                throw new JavaScriptException(Engine.TypeError);
            });
            
            var thisArg = arguments.At(0);
            var f = new BindFunctionInstance(Engine) {Extensible = true};
            f.TargetFunction = thisObj;
            f.BoundThis = thisArg;
            f.BoundArgs = arguments.Skip(1).ToArray();
            f.Prototype = Engine.Function.PrototypeObject;

            var o = target as FunctionInstance;
            if (o != null)
            {
                var l = TypeConverter.ToNumber(o.Get("length")) - (arguments.Length - 1);
                f.FastAddProperty("length", System.Math.Max(l, 0), false, false, false); 
            }
            else
            {
                f.FastAddProperty("length", 0, false, false, false); 
            }
            

            var thrower = Engine.Function.ThrowTypeError;
            f.DefineOwnProperty("caller", new PropertyDescriptor(thrower, thrower, false, false), false);
            f.DefineOwnProperty("arguments", new PropertyDescriptor(thrower, thrower, false, false), false);


            return f;
        }
Ejemplo n.º 4
0
        public object Invoke(DispatchIdentifier id, DispatchType dispType, JsValue[] jsArgs, out Type returnType)
        {
            MemberInfo member = GetMember(id.AsString);
            if (member == null) {
                returnType = typeof(void);
                return null;
            }

            Debug.WriteLine(string.Format("{0}, {1}.{2}", dispType, this.target, member.Name));
            if (member is MethodInfo && dispType == DispatchType.PropertyGet) {
                var method = (MethodInfo)member;
                return GetMethodAsProperty((MethodInfo)member, this.target, out returnType);
            }

            var args = this.bridge.UnwrapParameters(jsArgs, dispType, member);
            if (dispType.IsMethod()) {
                var method = (MethodBase)member;
                returnType = method.IsConstructor ? method.DeclaringType : ((MethodInfo)method).ReturnType;
                return method.Invoke(this.target, args);
            }

            if (dispType.IsPropertyGet()) {
                var pi = (PropertyInfo)member;
                returnType = pi.PropertyType;
                return pi.GetValue(this.target, null);
            }

            if (dispType.IsPropertyPut()) {
                var pi = (PropertyInfo)member;
                pi.SetValue(this.target, args.First(), null);
                returnType = typeof(void);
                return null;
            }
            throw new NotSupportedException();
        }
        public JsValue Call(JsValue thisObject, JsValue[] arguments)
        {
            // direct calls on a NamespaceReference constructor object is creating a generic type 
            var genericTypes = new Type[arguments.Length];
            for (int i = 0; i < arguments.Length; i++)
            {
                var genericTypeReference = arguments.At(i);
                if (genericTypeReference == Undefined.Instance || !genericTypeReference.IsObject() || genericTypeReference.AsObject().Class != "TypeReference")
                {
                    throw new JavaScriptException(Engine.TypeError, "Invalid generic type parameter");
                }

                genericTypes[i] = arguments.At(0).As<TypeReference>().Type;
            }

            var typeReference = GetPath(_path + "`" + arguments.Length.ToString(CultureInfo.InvariantCulture)).As<TypeReference>();

            if (typeReference == null)
            {
                return Undefined.Instance;
            }

            var genericType = typeReference.Type.MakeGenericType(genericTypes);

            return TypeReference.CreateTypeReference(Engine, genericType);
        }
Ejemplo n.º 6
0
        /// Implementation from ObjectInstance official specs as the one 
        /// in ObjectInstance is optimized for the general case and wouldn't work 
        /// for arrays
        public override void Put(string propertyName, JsValue value, bool throwOnError)
        {
            if (!CanPut(propertyName))
            {
                if (throwOnError)
                {
                    throw new JavaScriptException(Engine.TypeError);
                }

                return;
            }

            var ownDesc = GetOwnProperty(propertyName);

            if (ownDesc.IsDataDescriptor())
            {
                var valueDesc = new PropertyDescriptor(value: value, writable: null, enumerable: null, configurable: null);
                DefineOwnProperty(propertyName, valueDesc, throwOnError);
                return;
            }

            // property is an accessor or inherited
            var desc = GetProperty(propertyName);

            if (desc.IsAccessorDescriptor())
            {
                var setter = desc.Set.Value.TryCast<ICallable>();
                setter.Call(new JsValue(this), new[] { value });
            }
            else
            {
                var newDesc = new PropertyDescriptor(value, true, true, true);
                DefineOwnProperty(propertyName, newDesc, throwOnError);
            }
        }
Ejemplo n.º 7
0
        public virtual bool HasInstance(JsValue v)
        {
            var vObj = v.TryCast<ObjectInstance>();
            if (vObj == null)
            {
                return false;
            }
            
            var po = Get("prototype");
            if (!po.IsObject())
            {
                throw new JavaScriptException(_engine.TypeError, string.Format("Function has non-object prototype '{0}' in instanceof check", TypeConverter.ToString(po)));
            }

            var o = po.AsObject();
            
            if (o == null)
            {
                throw new JavaScriptException(_engine.TypeError);    
            }

            while (true)
            {
                vObj = vObj.Prototype;

                if (vObj == null)
                {
                    return false;
                }
                if (vObj == o)
                {
                    return true;
                }
            }
        }
Ejemplo n.º 8
0
        public JsValue Stringify(JsValue thisObject, JsValue[] arguments)
        {
            JsValue 
                value = Undefined.Instance, 
                replacer = Undefined.Instance,
                space = Undefined.Instance;

            if (arguments.Length > 2)
            {
                space = arguments[2];
            }

            if (arguments.Length > 1)
            {
                replacer = arguments[1];
            }

            if (arguments.Length > 0)
            {
                value = arguments[0];
            }

            var serializer = new JsonSerializer(_engine);
            if (value == Undefined.Instance && replacer == Undefined.Instance) {
                return Undefined.Instance;
            }
            else {
                return serializer.Serialize(value, replacer, space);
            }
        }
Ejemplo n.º 9
0
        public override void Put(string propertyName, JsValue value, bool throwOnError)
        {
            if (!CanPut(propertyName))
            {
                if (throwOnError)
                {
                    throw new JavaScriptException(Engine.TypeError);
                }

                return;
            }

            var ownDesc = GetOwnProperty(propertyName);

            if (ownDesc == null)
            {
                if (throwOnError)
                {
                    throw new JavaScriptException(Engine.TypeError, "Unknown member: " + propertyName);
                }
                else
                {
                    return;
                }
            }

            ownDesc.Value = value;
        }
Ejemplo n.º 10
0
        public JsValue ToString(JsValue thisObject, JsValue[] arguments)
        {
            var o = thisObject.TryCast<ObjectInstance>();
            if (o == null)
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            var name = TypeConverter.ToString(o.Get("name"));

            var msgProp = o.Get("message");
            string msg;
            if (msgProp == Undefined.Instance)
            {
                msg = "";
            }
            else
            {
                msg = TypeConverter.ToString(msgProp);
            }
            if (name == "")
            {
                return msg;
            }
            if (msg == "")
            {
                return name;
            }
            return name + ": " + msg;
        }
Ejemplo n.º 11
0
        private JsValue IsPrototypeOf(JsValue thisObject, JsValue[] arguments)
        {
            var arg = arguments[0];
            if (!arg.IsObject())
            {
                return false;
            }

            var v = arg.AsObject();

            var o = TypeConverter.ToObject(Engine, thisObject);
            while (true)
            {
                v = v.Prototype;

                if (v == null)
                {
                    return false;
                }

                if (o == v)
                {
                    return true;
                }

            }
        }
Ejemplo n.º 12
0
        private JsValue Parse(JsValue thisObj, JsValue[] arguments)
        {
            DateTime result;
            var date = TypeConverter.ToString(arguments.At(0));

            if (!DateTime.TryParseExact(date, new[]
            {
                "yyyy-MM-ddTHH:mm:ss.FFF",
                "yyyy-MM-ddTHH:mm:ss",
                "yyyy-MM-ddTHH:mm",
                "yyyy-MM-dd",
                "yyyy-MM",
                "yyyy"
            }, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out result))
            {
                if (!DateTime.TryParseExact(date, new[]
                {
                    // Formats used in DatePrototype toString methods
                    "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
                    "ddd MMM dd yyyy",
                    "HH:mm:ss 'GMT'K",

                    // standard formats
                    "yyyy-M-dTH:m:s.FFFK",
                    "yyyy/M/dTH:m:s.FFFK",
                    "yyyy-M-dTH:m:sK",
                    "yyyy/M/dTH:m:sK",
                    "yyyy-M-dTH:mK",
                    "yyyy/M/dTH:mK",
                    "yyyy-M-d H:m:s.FFFK",
                    "yyyy/M/d H:m:s.FFFK",
                    "yyyy-M-d H:m:sK",
                    "yyyy/M/d H:m:sK",
                    "yyyy-M-d H:mK",
                    "yyyy/M/d H:mK",
                    "yyyy-M-dK",
                    "yyyy/M/dK",
                    "yyyy-MK",
                    "yyyy/MK",
                    "yyyyK",
                    "THH:mm:ss.FFFK",
                    "THH:mm:ssK",
                    "THH:mmK",
                    "THHK"
                }, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result))
                {
                    if (!DateTime.TryParse(date, Engine.Options.GetCulture(), DateTimeStyles.AdjustToUniversal, out result))
                    {
                        if (!DateTime.TryParse(date, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result))
                        {
                            // unrecognized dates should return NaN (15.9.4.2)
                            return double.NaN;
                        }
                    }
                }
            }

            return FromDateTime(result);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-13.2.1
        /// </summary>
        /// <param name="thisArg"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public override JsValue Call(JsValue thisArg, JsValue[] arguments)
        {
            using (new StrictModeScope(Strict, true))
            {
                // setup new execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.3
                JsValue thisBinding;
                if (StrictModeScope.IsStrictModeCode)
                {
                    thisBinding = thisArg;
                }
                else if (thisArg == Undefined.Instance || thisArg == Null.Instance)
                {
                    thisBinding = Engine.Global;
                }
                else if (!thisArg.IsObject())
                {
                    thisBinding = TypeConverter.ToObject(Engine, thisArg);
                }
                else
                {
                    thisBinding = thisArg;
                }

                var localEnv = LexicalEnvironment.NewDeclarativeEnvironment(Engine, Scope);

                Engine.EnterExecutionContext(localEnv, localEnv, thisBinding);

                try
                {
                    Engine.DeclarationBindingInstantiation(
                        DeclarationBindingType.FunctionCode,
                        _functionDeclaration.FunctionDeclarations,
                        _functionDeclaration.VariableDeclarations,
                        this,
                        arguments);

                    var result = Engine.ExecuteStatement(_functionDeclaration.Body);

                    if (result.Type == Completion.Throw)
                    {
                        JavaScriptException ex = new JavaScriptException(result.GetValueOrDefault());
                        ex.Location = result.Location;
                        throw ex;
                    }

                    if (result.Type == Completion.Return)
                    {
                        return result.GetValueOrDefault();
                    }
                }
                finally
                {
                    Engine.LeaveExecutionContext();
                }

                return Undefined.Instance;
            }
        }
Ejemplo n.º 14
0
        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;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2
        /// </summary>
        public static JsValue ParseInt(JsValue thisObject, JsValue[] arguments)
        {
            string inputString = TypeConverter.ToString(arguments.At(0));
            var s = inputString.Trim();

            var sign = 1;
            if (!System.String.IsNullOrEmpty(s))
            {
                if (s[0] == '-')
                {
                    sign = -1;
                }
                
                if (s[0] == '-' || s[0] == '+')
                {
                    s = s.Substring(1);
                }
            }

            var stripPrefix = true;

            int radix = arguments.Length > 1 ? TypeConverter.ToInt32(arguments[1]) : 0;

            if (radix == 0)
            {
                if (s.Length >= 2 && s.StartsWith("0x") || s.StartsWith("0X"))
                {
                    radix = 16;
                }
                else
                {
                    radix = 10;
                }
            }
            else if (radix < 2 || radix > 36)
            {
                return double.NaN;
            }
            else if(radix != 16)
            {
                stripPrefix = false;
            }

            if (stripPrefix && s.Length >= 2 && s.StartsWith("0x") || s.StartsWith("0X"))
            {
                s = s.Substring(2);
            }

            try
            {
                return sign * Parse(s, radix).AsNumber();
            }
            catch
            {
                return double.NaN;
            }

        }
Ejemplo n.º 16
0
        public override JsValue Call(JsValue thisObject, JsValue[] arguments)
        {
            if (arguments.Length == 0)
            {
                return "";
            }

            return TypeConverter.ToString(arguments[0]);
        }
        public override JsValue Call(JsValue thisObject, JsValue[] arguments)
        {
            if (arguments.Length == 0)
            {
                return false;
            }

            return TypeConverter.ToBoolean(arguments[0]);
        }
Ejemplo n.º 18
0
        public override JsValue Call(JsValue thisObject, JsValue[] arguments)
        {
            var f = TargetFunction.TryCast<FunctionInstance>(x =>
            {
                throw new JavaScriptException(Engine.TypeError);
            });

            return f.Call(BoundThis, BoundArgs.Union(arguments).ToArray());
        }
Ejemplo n.º 19
0
        public ObjectInstance Construct(JsValue[] arguments)
        {
            var target = TargetFunction.TryCast<IConstructor>(x =>
            {
                throw new JavaScriptException(Engine.TypeError);
            });

            return target.Construct(BoundArgs.Union(arguments).ToArray());
        }
Ejemplo n.º 20
0
 public override bool HasInstance(JsValue v)
 {
     var f = TargetFunction.TryCast<FunctionInstance>(x =>
     {
         throw new JavaScriptException(Engine.TypeError);
     });
       
     return f.HasInstance(v);
 }
Ejemplo n.º 21
0
        public static bool IsArrayIndex(JsValue p, out uint index)
        {
            index = ParseArrayIndex(TypeConverter.ToString(p));

            return index != uint.MaxValue;

            // 15.4 - Use an optimized version of the specification
            // return TypeConverter.ToString(index) == TypeConverter.ToString(p) && index != uint.MaxValue;
        }
Ejemplo n.º 22
0
        private JsValue ToRegExpString(JsValue thisObj, JsValue[] arguments)
        {
            var regExp = thisObj.TryCast<RegExpInstance>();

            return "/" + regExp.Source + "/"
                + (regExp.Flags.Contains("g") ? "g" : "")
                + (regExp.Flags.Contains("i") ? "i" : "")
                + (regExp.Flags.Contains("m") ? "m" : "")
                ;
        }
Ejemplo n.º 23
0
        private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
        {
            var o = TypeConverter.ToObject(Engine, thisObject);
            var toString = o.Get("toString").TryCast<ICallable>(x =>
            {
                throw new JavaScriptException(Engine.TypeError);
            });

            return toString.Call(o, Arguments.Empty);
        }
Ejemplo n.º 24
0
 private static JsValue FromCharCode(JsValue thisObj, JsValue[] arguments)
 {
     var chars = new char[arguments.Length];
     for (var i = 0; i < chars.Length; i++ )
     {
         chars[i] = (char)TypeConverter.ToUint16(arguments[i]);
     }
     
     return new System.String(chars);
 }
Ejemplo n.º 25
0
        private JsValue ValueOf(JsValue thisObj, JsValue[] arguments)
        {
            var number = thisObj.TryCast<NumberInstance>();
            if (number == null)
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            return number.PrimitiveValue;
        }
Ejemplo n.º 26
0
        private JsValue ToStringString(JsValue thisObj, JsValue[] arguments)
        {
            var s = TypeConverter.ToObject(Engine, thisObj) as StringInstance;
            if (s == null)
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            return s.PrimitiveValue;
        }
Ejemplo n.º 27
0
        private JsValue IsArray(JsValue thisObj, JsValue[] arguments)
        {
            if (arguments.Length == 0)
            {
                return false;
            }

            var o = arguments.At(0);

            return o.IsObject() && o.AsObject().Class == "Array";
        }
Ejemplo n.º 28
0
 private JsValue PropertyIsEnumerable(JsValue thisObject, JsValue[] arguments)
 {
     var p = TypeConverter.ToString(arguments[0]);
     var o = TypeConverter.ToObject(Engine, thisObject);
     var desc = o.GetOwnProperty(p);
     if (desc == PropertyDescriptor.Undefined)
     {
         return false;
     }
     return desc.Enumerable.HasValue && desc.Enumerable.Value.AsBoolean();
 }
Ejemplo n.º 29
0
        private JsValue ToString(JsValue thisObj, JsValue[] arguments)
        {
            var func = thisObj.TryCast<FunctionInstance>();

            if (func == null)
            {
                throw new JavaScriptException(Engine.TypeError, "Function object expected.");       
            }

            return System.String.Format("function() {{ ... }}");
        }
Ejemplo n.º 30
0
        private JsValue Test(JsValue thisObj, JsValue[] arguments)
        {
            var r = TypeConverter.ToObject(Engine, thisObj);
            if (r.Class != "RegExp")
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            var match = Exec(r, arguments);
            return match != Null.Instance;
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Returns the arguments at the provided position or Undefined if not present
 /// </summary>
 /// <param name="args"></param>
 /// <param name="index">The index of the parameter to return</param>
 /// <param name="undefinedValue">The value to return is the parameter is not provided</param>
 /// <returns></returns>
 public static JsValue At(this JsValue[] args, int index, JsValue undefinedValue)
 {
     return(args.Length > index ? args[index] : undefinedValue);
 }
Ejemplo n.º 32
0
 private JsValue Now(JsValue thisObj, JsValue[] arguments)
 {
     return(System.Math.Floor((DateTime.UtcNow - Epoch).TotalMilliseconds));
 }
Ejemplo n.º 33
0
 public override JsValue Call(JsValue thisObject, JsValue[] arguments)
 {
     return(PrototypeObject.ToString(Construct(Arguments.Empty), Arguments.Empty));
 }
Ejemplo n.º 34
0
        private static JsValue ToLocaleUpperCase(JsValue thisObj, JsValue[] arguments)
        {
            var s = TypeConverter.ToString(thisObj);

            return(s.ToUpper());
        }
Ejemplo n.º 35
0
        private JsValue Split(JsValue thisObj, JsValue[] arguments)
        {
            TypeConverter.CheckObjectCoercible(Engine, thisObj);
            var s = TypeConverter.ToString(thisObj);

            var separator = arguments.At(0);

            // Coerce into a number, true will become 1
            var l     = arguments.At(1);
            var a     = (ArrayInstance)Engine.Array.Construct(Arguments.Empty);
            var limit = l == Undefined.Instance ? UInt32.MaxValue : TypeConverter.ToUint32(l);
            var len   = s.Length;

            if (limit == 0)
            {
                return(a);
            }

            if (separator == Null.Instance)
            {
                separator = Null.Text;
            }
            else if (separator == Undefined.Instance)
            {
                return((ArrayInstance)Engine.Array.Construct(Arguments.From(s)));
            }
            else
            {
                if (!separator.IsRegExp())
                {
                    separator = TypeConverter.ToString(separator); // Coerce into a string, for an object call toString()
                }
            }

            var rx = TypeConverter.ToObject(Engine, separator) as RegExpInstance;

            const string regExpForMatchingAllCharactere = "(?:)";

            if (rx != null &&
                rx.Source != regExpForMatchingAllCharactere // We need pattern to be defined -> for s.split(new RegExp)
                )
            {
                var match = rx.Value.Match(s, 0);

                if (!match.Success) // No match at all return the string in an array
                {
                    a.DefineOwnProperty("0", new PropertyDescriptor(s, true, true, true), false);
                    return(a);
                }

                int lastIndex = 0;
                int index     = 0;
                while (match.Success && index < limit)
                {
                    if (match.Length == 0 && (match.Index == 0 || match.Index == len || match.Index == lastIndex))
                    {
                        match = match.NextMatch();
                        continue;
                    }

                    // Add the match results to the array.
                    a.DefineOwnProperty(index++.ToString(), new PropertyDescriptor(s.Substring(lastIndex, match.Index - lastIndex), true, true, true), false);

                    if (index >= limit)
                    {
                        return(a);
                    }

                    lastIndex = match.Index + match.Length;
                    for (int i = 1; i < match.Groups.Count; i++)
                    {
                        var group = match.Groups[i];
                        var item  = Undefined.Instance;
                        if (group.Captures.Count > 0)
                        {
                            item = match.Groups[i].Value;
                        }

                        a.DefineOwnProperty(index++.ToString(), new PropertyDescriptor(item, true, true, true), false);

                        if (index >= limit)
                        {
                            return(a);
                        }
                    }

                    match = match.NextMatch();
                    if (!match.Success) // Add the last part of the split
                    {
                        a.DefineOwnProperty(index++.ToString(), new PropertyDescriptor(s.Substring(lastIndex), true, true, true), false);
                    }
                }

                return(a);
            }
            else
            {
                var segments = new List <string>();
                var sep      = TypeConverter.ToString(separator);

                if (sep == string.Empty || (rx != null && rx.Source == regExpForMatchingAllCharactere)) // for s.split(new RegExp)
                {
                    foreach (var c in s)
                    {
                        segments.Add(c.ToString());
                    }
                }
                else
                {
                    segments = s.Split(new[] { sep }, StringSplitOptions.None).ToList();
                }

                for (int i = 0; i < segments.Count && i < limit; i++)
                {
                    a.DefineOwnProperty(i.ToString(), new PropertyDescriptor(segments[i], true, true, true), false);
                }

                return(a);
            }
        }
Ejemplo n.º 36
0
 protected override void AddLoadedCounter(JsValue reference, string name, long value)
 {
     throw new NotSupportedException("Counters aren't supported by SQL ETL");
 }
Ejemplo n.º 37
0
 protected override void AddLoadedTimeSeries(JsValue reference, string name, IEnumerable <SingleResult> entries)
 {
     throw new NotSupportedException("Time series aren't supported by SQL ETL");
 }
Ejemplo n.º 38
0
 public Engine SetValue(string name, JsValue value)
 {
     Global.Put(name, value, false);
     return(this);
 }
Ejemplo n.º 39
0
        internal static JsValue TriggerPromiseReactions(Engine engine, List <PromiseReaction> reactions, JsValue result)
        {
            foreach (var reaction in reactions)
            {
                engine.AddToEventLoop(NewPromiseReactionJob(reaction, result));
            }

            return(JsValue.Undefined);
        }
Ejemplo n.º 40
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4
        /// </summary>
        /// <param name="thisObject"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public JsValue EncodeUriComponent(JsValue thisObject, JsValue[] arguments)
        {
            var uriString = TypeConverter.ToString(arguments.At(0));

            return(Encode(uriString, UriUnescaped));
        }
Ejemplo n.º 41
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.4
        /// </summary>
        public static JsValue IsNaN(JsValue thisObject, JsValue[] arguments)
        {
            var x = TypeConverter.ToNumber(arguments.At(0));

            return(double.IsNaN(x));
        }
Ejemplo n.º 42
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.3
        /// </summary>
        public static JsValue ParseFloat(JsValue thisObject, JsValue[] arguments)
        {
            var inputString   = TypeConverter.ToString(arguments.At(0));
            var trimmedString = StringPrototype.TrimStartEx(inputString);

            var sign = 1;

            if (trimmedString.Length > 0)
            {
                if (trimmedString[0] == '-')
                {
                    sign          = -1;
                    trimmedString = trimmedString.Substring(1);
                }
                else if (trimmedString[0] == '+')
                {
                    trimmedString = trimmedString.Substring(1);
                }
            }

            if (trimmedString.StartsWith("Infinity"))
            {
                return(sign * double.PositiveInfinity);
            }

            if (trimmedString.StartsWith("NaN"))
            {
                return(double.NaN);
            }

            var separator = (char)0;

            bool    isNan  = true;
            decimal number = 0;
            var     i      = 0;

            for (; i < trimmedString.Length; i++)
            {
                var c = trimmedString[i];
                if (c == '.')
                {
                    i++;
                    separator = '.';
                    break;
                }

                if (c == 'e' || c == 'E')
                {
                    i++;
                    separator = 'e';
                    break;
                }

                var digit = c - '0';

                if (digit >= 0 && digit <= 9)
                {
                    isNan  = false;
                    number = number * 10 + digit;
                }
                else
                {
                    break;
                }
            }

            decimal pow = 0.1m;

            if (separator == '.')
            {
                for (; i < trimmedString.Length; i++)
                {
                    var c = trimmedString[i];

                    var digit = c - '0';

                    if (digit >= 0 && digit <= 9)
                    {
                        isNan   = false;
                        number += digit * pow;
                        pow    *= 0.1m;
                    }
                    else if (c == 'e' || c == 'E')
                    {
                        i++;
                        separator = 'e';
                        break;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            var exp     = 0;
            var expSign = 1;

            if (separator == 'e')
            {
                if (i < trimmedString.Length)
                {
                    if (trimmedString[i] == '-')
                    {
                        expSign = -1;
                        i++;
                    }
                    else if (trimmedString[i] == '+')
                    {
                        i++;
                    }
                }

                for (; i < trimmedString.Length; i++)
                {
                    var c = trimmedString[i];

                    var digit = c - '0';

                    if (digit >= 0 && digit <= 9)
                    {
                        exp = exp * 10 + digit;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            if (isNan)
            {
                return(double.NaN);
            }

            for (var k = 1; k <= exp; k++)
            {
                if (expSign > 0)
                {
                    number *= 10;
                }
                else
                {
                    number /= 10;
                }
            }

            return((double)(sign * number));
        }
Ejemplo n.º 43
0
        public ExecutionContext EnterExecutionContext(LexicalEnvironment lexicalEnvironment, LexicalEnvironment variableEnvironment, JsValue thisBinding)
        {
            var executionContext = new ExecutionContext
            {
                LexicalEnvironment  = lexicalEnvironment,
                VariableEnvironment = variableEnvironment,
                ThisBinding         = thisBinding
            };

            _executionContexts.Push(executionContext);

            return(executionContext);
        }
Ejemplo n.º 44
0
        public JsValue Serialize(JsValue value, JsValue replacer, JsValue space)
        {
            _stack = new Stack <object>();

            // for JSON.stringify(), any function passed as the first argument will return undefined
            // if the replacer is not defined. The function is not called either.
            if (value.Is <ICallable>() && replacer == Undefined.Instance)
            {
                return(Undefined.Instance);
            }

            if (replacer.IsObject())
            {
                if (replacer.Is <ICallable>())
                {
                    _replacerFunction = replacer;
                }
                else
                {
                    var replacerObj = replacer.AsObject();
                    if (replacerObj.Class == "Array")
                    {
                        _propertyList = new List <string>();
                    }

                    foreach (var property in replacerObj.GetOwnProperties().Select(x => x.Value))
                    {
                        JsValue v    = _engine.GetValue(property);
                        string  item = null;
                        if (v.IsString())
                        {
                            item = v.AsString();
                        }
                        else if (v.IsNumber())
                        {
                            item = TypeConverter.ToString(v);
                        }
                        else if (v.IsObject())
                        {
                            var propertyObj = v.AsObject();
                            if (propertyObj.Class == "String" || propertyObj.Class == "Number")
                            {
                                item = TypeConverter.ToString(v);
                            }
                        }

                        if (item != null && !_propertyList.Contains(item))
                        {
                            _propertyList.Add(item);
                        }
                    }
                }
            }

            if (space.IsObject())
            {
                var spaceObj = space.AsObject();
                if (spaceObj.Class == "Number")
                {
                    space = TypeConverter.ToNumber(spaceObj);
                }
                else if (spaceObj.Class == "String")
                {
                    space = TypeConverter.ToString(spaceObj);
                }
            }

            // defining the gap
            if (space.IsNumber())
            {
                if (space.AsNumber() > 0)
                {
                    _gap = new System.String(' ', (int)System.Math.Min(10, space.AsNumber()));
                }
                else
                {
                    _gap = string.Empty;
                }
            }
            else if (space.IsString())
            {
                var stringSpace = space.AsString();
                _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10);
            }
            else
            {
                _gap = string.Empty;
            }

            var wrapper = _engine.Object.Construct(Arguments.Empty);

            wrapper.DefineOwnProperty("", new PropertyDescriptor(value, true, true, true), false);

            return(Str("", wrapper));
        }
Ejemplo n.º 45
0
 public void Init()
 {
     instance = new JsValue();
 }
Ejemplo n.º 46
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(JsValue obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Ejemplo n.º 47
0
 public override JsValue Call(JsValue thisObject, JsValue[] arguments)
 {
     // direct calls on a TypeReference constructor object is equivalent to the new operator
     return(Construct(arguments));
 }
Ejemplo n.º 48
0
 protected abstract void AddLoadedCounter(JsValue reference, string name, long value);
Ejemplo n.º 49
0
        private JsValue Replace(JsValue thisObj, JsValue[] arguments)
        {
            TypeConverter.CheckObjectCoercible(Engine, thisObj);

            var thisString   = TypeConverter.ToString(thisObj);
            var searchValue  = arguments.At(0);
            var replaceValue = arguments.At(1);

            // If the second parameter is not a function we create one
            var replaceFunction = replaceValue.TryCast <FunctionInstance>();

            if (replaceFunction == null)
            {
                replaceFunction = new ClrFunctionInstance(Engine, (self, args) =>
                {
                    var replaceString = TypeConverter.ToString(replaceValue);
                    var matchValue    = TypeConverter.ToString(args.At(0));
                    var matchIndex    = (int)TypeConverter.ToInteger(args.At(args.Length - 2));

                    // Check if the replacement string contains any patterns.
                    bool replaceTextContainsPattern = replaceString.IndexOf('$') >= 0;

                    // If there is no pattern, replace the pattern as is.
                    if (replaceTextContainsPattern == false)
                    {
                        return(replaceString);
                    }

                    // Patterns
                    // $$	Inserts a "$".
                    // $&	Inserts the matched substring.
                    // $`	Inserts the portion of the string that precedes the matched substring.
                    // $'	Inserts the portion of the string that follows the matched substring.
                    // $n or $nn	Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
                    var replacementBuilder = new StringBuilder();
                    for (int i = 0; i < replaceString.Length; i++)
                    {
                        char c = replaceString[i];
                        if (c == '$' && i < replaceString.Length - 1)
                        {
                            c = replaceString[++i];
                            if (c == '$')
                            {
                                replacementBuilder.Append('$');
                            }
                            else if (c == '&')
                            {
                                replacementBuilder.Append(matchValue);
                            }
                            else if (c == '`')
                            {
                                replacementBuilder.Append(thisString.Substring(0, matchIndex));
                            }
                            else if (c == '\'')
                            {
                                replacementBuilder.Append(thisString.Substring(matchIndex + matchValue.Length));
                            }
                            else if (c >= '0' && c <= '9')
                            {
                                int matchNumber1 = c - '0';

                                // The match number can be one or two digits long.
                                int matchNumber2 = 0;
                                if (i < replaceString.Length - 1 && replaceString[i + 1] >= '0' && replaceString[i + 1] <= '9')
                                {
                                    matchNumber2 = matchNumber1 * 10 + (replaceString[i + 1] - '0');
                                }

                                // Try the two digit capture first.
                                if (matchNumber2 > 0 && matchNumber2 < args.Length - 2)
                                {
                                    // Two digit capture replacement.
                                    replacementBuilder.Append(TypeConverter.ToString(args[matchNumber2]));
                                    i++;
                                }
                                else if (matchNumber1 > 0 && matchNumber1 < args.Length - 2)
                                {
                                    // Single digit capture replacement.
                                    replacementBuilder.Append(TypeConverter.ToString(args[matchNumber1]));
                                }
                                else
                                {
                                    // Capture does not exist.
                                    replacementBuilder.Append('$');
                                    i--;
                                }
                            }
                            else
                            {
                                // Unknown replacement pattern.
                                replacementBuilder.Append('$');
                                replacementBuilder.Append(c);
                            }
                        }
                        else
                        {
                            replacementBuilder.Append(c);
                        }
                    }

                    return(replacementBuilder.ToString());
                });
            }

            // searchValue is a regular expression

            if (searchValue.IsNull())
            {
                searchValue = new JsValue(Null.Text);
            }
            if (searchValue.IsUndefined())
            {
                searchValue = new JsValue(Undefined.Text);
            }

            var rx = TypeConverter.ToObject(Engine, searchValue) as RegExpInstance;

            if (rx != null)
            {
                // Replace the input string with replaceText, recording the last match found.
                string result = rx.Value.Replace(thisString, match =>
                {
                    var args = new List <JsValue>();

                    for (var k = 0; k < match.Groups.Count; k++)
                    {
                        var group = match.Groups[k];
                        args.Add(group.Value);
                    }

                    args.Add(match.Index);
                    args.Add(thisString);

                    var v = TypeConverter.ToString(replaceFunction.Call(Undefined.Instance, args.ToArray()));
                    return(v);
                }, rx.Global == true ? -1 : 1);

                // Set the deprecated RegExp properties if at least one match was found.
                //if (lastMatch != null)
                //    this.Engine.RegExp.SetDeprecatedProperties(input, lastMatch);

                return(result);
            }

            // searchValue is a string
            else
            {
                var substr = TypeConverter.ToString(searchValue);

                // Find the first occurrance of substr.
                int start = thisString.IndexOf(substr, StringComparison.Ordinal);
                if (start == -1)
                {
                    return(thisString);
                }
                int end = start + substr.Length;

                var args = new List <JsValue>();
                args.Add(substr);
                args.Add(start);
                args.Add(thisString);

                var replaceString = TypeConverter.ToString(replaceFunction.Call(Undefined.Instance, args.ToArray()));

                // Replace only the first match.
                var result = new StringBuilder(thisString.Length + (substr.Length - substr.Length));
                result.Append(thisString, 0, start);
                result.Append(replaceString);
                result.Append(thisString, end, thisString.Length - end);
                return(result.ToString());
            }
        }
Ejemplo n.º 50
0
 protected abstract void AddLoadedAttachment(JsValue reference, string name, Attachment attachment);
Ejemplo n.º 51
0
        private static JsValue ToLowerCase(JsValue thisObj, JsValue[] arguments)
        {
            var s = TypeConverter.ToString(thisObj);

            return(s.ToLowerInvariant());
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Invoke the current value as function.
        /// </summary>
        /// <param name="value">The function to call.</param>
        /// <param name="thisObj">The this value inside the function call.</param>
        /// <param name="arguments">The arguments of the function call.</param>
        /// <returns>The value returned by the function call.</returns>
        public JsValue Invoke(JsValue value, object thisObj, object[] arguments)
        {
            var callable = value.TryCast <ICallable>();

            if (callable == null)
            {
                throw new ArgumentException("Can only invoke functions");
            }

            return(callable.Call(JsValue.FromObject(this, thisObj), arguments.Select(x => JsValue.FromObject(this, x)).ToArray()));
        }
Ejemplo n.º 53
0
        public JsValue Invoke(MethodInfo[] methodInfos, JsValue thisObject, JsValue[] jsArguments)
        {
            var arguments = ProcessParamsArrays(jsArguments, methodInfos);
            var methods   = TypeConverter.FindBestMatch(Engine, methodInfos, arguments).ToList();
            var converter = Engine.ClrTypeConverter;

            foreach (var method in methods)
            {
                var parameters     = new object[arguments.Length];
                var argumentsMatch = true;

                for (var i = 0; i < arguments.Length; i++)
                {
                    var parameterType = method.GetParameters()[i].ParameterType;

                    if (parameterType == typeof(JsValue))
                    {
                        parameters[i] = arguments[i];
                    }
                    else if (parameterType == typeof(JsValue[]) && arguments[i].IsArray())
                    {
                        // Handle specific case of F(params JsValue[])

                        var arrayInstance = arguments[i].AsArray();
                        var len           = TypeConverter.ToInt32(arrayInstance.Get("length"));
                        var result        = new JsValue[len];
                        for (var k = 0; k < len; k++)
                        {
                            var pk = k.ToString();
                            result[k] = arrayInstance.HasProperty(pk)
                                ? arrayInstance.Get(pk)
                                : JsValue.Undefined;
                        }

                        parameters[i] = result;
                    }
                    else
                    {
                        if (!converter.TryConvert(arguments[i].ToObject(), parameterType, CultureInfo.InvariantCulture, out parameters[i]))
                        {
                            argumentsMatch = false;
                            break;
                        }

                        var lambdaExpression = parameters[i] as LambdaExpression;
                        if (lambdaExpression != null)
                        {
                            parameters[i] = lambdaExpression.Compile();
                        }
                    }
                }

                if (!argumentsMatch)
                {
                    continue;
                }

                // todo: cache method info
                return(JsValue.FromObject(Engine, method.Invoke(thisObject.ToObject(), parameters.ToArray())));
            }

            throw new JavaScriptException(Engine.TypeError, "No public methods with the specified arguments were found.");
        }
Ejemplo n.º 54
0
 /// <summary>
 /// Invoke the current value as function.
 /// </summary>
 /// <param name="value">The function to call.</param>
 /// <param name="arguments">The arguments of the function call.</param>
 /// <returns>The value returned by the function call.</returns>
 public JsValue Invoke(JsValue value, params object[] arguments)
 {
     return(Invoke(value, null, arguments));
 }
Ejemplo n.º 55
0
 public override JsValue Call(JsValue thisObject, JsValue[] arguments)
 {
     return(Invoke(_methods, thisObject, arguments));
 }
Ejemplo n.º 56
0
 public Engine SetValue(string name, Object obj)
 {
     return(SetValue(name, JsValue.FromObject(this, obj)));
 }
Ejemplo n.º 57
0
 public static IDocumentType ToDoctype(JsValue arg)
 {
     return(null);
 }
Ejemplo n.º 58
0
 private JsValue Utc(JsValue thisObj, JsValue[] arguments)
 {
     return(TimeClip(ConstructTimeValue(arguments, useUtc: true)));
 }
Ejemplo n.º 59
0
 public static IWindow ToWindow(JsValue arg)
 {
     return(null);
 }
Ejemplo n.º 60
0
 public static IMessagePort ToMessagePort(JsValue arg)
 {
     return(null);
 }