示例#1
0
        private static void RunEvalLoop()
        {
            while (true)
            {
                try
                {
                    Console.Write("> ");

                    int    bufferSize = 1024 * 16;
                    string statement;
                    using (Stream inStream = Console.OpenStandardInput(bufferSize))
                    {
                        Console.SetIn(new StreamReader(inStream, Console.InputEncoding, false, bufferSize));
                        statement = Console.ReadLine();
                    }

                    if (statement == "exit")
                    {
                        break;
                    }

                    JsValue result = _engine.Execute(statement);
                    bool    isNull = result.IsNull();
                    Console.WriteLine(isNull ? "null" : result);
                }
                catch (Exception e)
                {
                    var color = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e);
                    Console.ForegroundColor = color;
                }
            }
        }
示例#2
0
        static public AssetReference FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(None);
            }

            if (obj.IsObject())
            {
                var ob    = obj.AsObject();
                var v0    = ob.Get("type");
                var value = ob.Get("value");

                var type = (AssetReferenceType)v0.AsNumber();

                return(new AssetReference(type, value));
            }
            else
            {
                var ob = obj.ToObject();

                if (ob is Object)
                {
                    return(new AssetReference(AssetReferenceType.Object, obj));
                }

                return(new AssetReference(AssetReferenceType.Procedural, obj));
            }
        }
示例#3
0
        internal static ObjectInstance ToBooleanOrObject(this JsValue x, out bool boolVal)
        {
            if (x.IsObject())
            {
                boolVal = false;
                return(x.AsObject());
            }

            switch (x.Type)
            {
            case Types.Boolean:
                boolVal = x.AsBoolean();
                break;

            case Types.Number:
                boolVal = x.AsNumber() != 0;
                break;

            default:
                boolVal = !x.IsNull() && !x.IsUndefined();
                break;
            }

            return(null);
        }
 public bool AsNativeBool(JsValue jsValue)
 {
     if (jsValue.IsNull() || jsValue.IsUndefined())
     {
         return(false);
     }
     return(jsValue.AsBoolean());
 }
 private static string?ConvertToStringHandlingNulls(JsonInstance json, JsValue value)
 {
     if (value.IsNull() || value.IsUndefined())
     {
         return(null);
     }
     return(json.Stringify(JsValue.Undefined, new[] { value }).AsString());
 }
 public int AsNativeInt(JsValue value)
 {
     if (value.IsNull() || value.IsUndefined())
     {
         return(0);
     }
     return((int)Math.Round(value.AsNumber()));
 }
 public Decimal?AsNativeDecimal(JsValue value)
 {
     if (value.IsNull() || value.IsUndefined())
     {
         return(null);
     }
     return(Decimal.Parse(value.ToString()));
 }
        private JsValue From(JsValue thisObj, JsValue[] arguments)
        {
            var source      = arguments.At(0);
            var mapFunction = arguments.At(1);
            var callable    = !mapFunction.IsUndefined() ? GetCallable(mapFunction) : null;
            var thisArg     = arguments.At(2);

            if (source.IsNullOrUndefined())
            {
                ExceptionHelper.ThrowTypeError(_engine, "Cannot convert undefined or null to object");
            }

            if (source is JsString jsString)
            {
                var a = _engine.Array.ConstructFast((uint)jsString.Length);
                for (int i = 0; i < jsString._value.Length; i++)
                {
                    a.SetIndexValue((uint)i, JsString.Create(jsString._value[i]), updateLength: false);
                }
                return(a);
            }

            if (thisObj.IsNull() || !(source is ObjectInstance objectInstance))
            {
                return(_engine.Array.ConstructFast(0));
            }

            if (objectInstance is IObjectWrapper wrapper && wrapper.Target is IEnumerable enumerable)
            {
                return(ConstructArrayFromIEnumerable(enumerable));
            }

            if (objectInstance.IsArrayLike)
            {
                return(ConstructArrayFromArrayLike(thisObj, objectInstance, callable, thisArg));
            }

            ObjectInstance instance;

            if (thisObj is IConstructor constructor)
            {
                instance = constructor.Construct(System.Array.Empty <JsValue>(), thisObj);
            }
            else
            {
                instance = _engine.Array.ConstructFast(0);
            }

            if (objectInstance.TryGetIterator(_engine, out var iterator))
            {
                var protocol = new ArrayProtocol(_engine, thisArg, instance, iterator, callable);
                protocol.Execute();
            }

            return(instance);
        }
示例#9
0
        private object ConvertValue(JsValue value, Type targetType)
        {
            if (value.IsUndefined())
            {
                return(null);
            }

            if (value.IsNull())
            {
                return(default);
        public virtual bool TryPropertyReference(Engine engine, Reference reference, ref JsValue value)
        {
            if (reference.GetReferencedName() == "reduce" &&
                value.IsArray() && value.AsArray().GetLength() == 0)
            {
                value = Null.Instance;
                return(true);
            }

            return(value.IsNull() || value.IsUndefined());
        }
示例#11
0
        public void setEventListener(IReactComponent element, string eventType, JsValue value)
        {
            var hasValue = value != null && !value.IsNull() && !value.IsUndefined() && !value.IsBoolean();
            var callback = value.As <FunctionInstance>();

            if (hasValue && callback == null)
            {
                throw new Exception("The callback for an event must be a function.");
            }

            element.SetEventListener(eventType, new Callback(callback));
        }
 public string AsNativeString(JsValue jsValue)
 {
     if (jsValue.IsNull() || jsValue.IsUndefined())
     {
         return(null);
     }
     if (jsValue.IsString())
     {
         return(jsValue.AsString());
     }
     return(jsValue.ToString());
 }
示例#13
0
        public static RectOffset FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (int)obj.AsNumber();
                return(new RectOffset(num, num, num, num));
            }

            if (obj.IsArray())
            {
                var len = obj.AsArray().Length;

                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];
                var v2 = obj.AsArray()[2];
                var v3 = obj.AsArray()[3];

                var top    = v0.IsNumber() ? (int)v0.AsNumber() : 0;
                var right  = v1.IsNumber() ? (int)v1.AsNumber() : (len < 2 ? top : 0);
                var bottom = v2.IsNumber() ? (int)v2.AsNumber() : top;
                var left   = v3.IsNumber() ? (int)v3.AsNumber() : right;
                return(new RectOffset(left, right, top, bottom));
            }

            if (obj.IsObject())
            {
                var ob   = obj.AsObject();
                var vert = ob.Get("vertical");
                var hor  = ob.Get("horizontal");

                var v0 = ob.Get("top");
                var v1 = ob.Get("right");
                var v2 = ob.Get("bottom");
                var v3 = ob.Get("left");

                var val1 = vert.IsNumber() ? (int)vert.AsNumber() : 0;
                var val2 = hor.IsNumber() ? (int)hor.AsNumber() : 0;

                var top    = v0.IsNumber() ? (int)v0.AsNumber() : val1;
                var right  = v1.IsNumber() ? (int)v1.AsNumber() : val2;
                var bottom = v2.IsNumber() ? (int)v2.AsNumber() : val1;
                var left   = v3.IsNumber() ? (int)v3.AsNumber() : val2;

                return(new RectOffset(left, right, top, bottom));
            }

            return(null);
        }
示例#14
0
 private string GetDebugValue(JsValue obj, bool recursive)
 {
     if (obj.IsString())
     {
         var debugValue = obj.ToString();
         return(recursive ? '"' + debugValue + '"' : debugValue);
     }
     if (obj.IsArray())
     {
         var sb      = new StringBuilder("[");
         var array   = obj.AsArray();
         var jsValue = (int)array.Get("length").AsNumber();
         for (var i = 0; i < jsValue; i++)
         {
             if (i != 0)
             {
                 sb.Append(",");
             }
             sb.Append(GetDebugValue(array.Get(i.ToString()), true));
         }
         sb.Append("]");
         return(sb.ToString());
     }
     if (obj.IsObject())
     {
         var result = new ScriptRunnerResult(this, obj);
         using (var jsonObj = result.TranslateToObject(_jsonCtx))
         {
             return(jsonObj.ToString());
         }
     }
     if (obj.IsBoolean())
     {
         return(obj.AsBoolean().ToString());
     }
     if (obj.IsNumber())
     {
         return(obj.AsNumber().ToString(CultureInfo.InvariantCulture));
     }
     if (obj.IsNull())
     {
         return("null");
     }
     if (obj.IsUndefined())
     {
         return("undefined");
     }
     return(obj.ToString());
 }
示例#15
0
        public static Vector4?FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (float)obj.AsNumber();
                return(new Vector4(num, num, num, num));
            }

            if (obj.IsArray())
            {
                var len = obj.AsArray().Length;

                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];
                var v2 = obj.AsArray()[2];
                var v3 = obj.AsArray()[3];

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                var z = v2.IsNumber() ? (float)v2.AsNumber() : 0;
                var w = v3.IsNumber() ? (float)v3.AsNumber() : 0;
                return(new Vector4(x, y, z, w));
            }

            if (obj.IsObject())
            {
                var ob = obj.AsObject();

                var v0 = ob.Get("x");
                var v1 = ob.Get("y");
                var v2 = ob.Get("z");
                var v3 = ob.Get("w");

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                var z = v2.IsNumber() ? (float)v2.AsNumber() : 0;
                var w = v3.IsNumber() ? (float)v3.AsNumber() : 0;

                return(new Vector4(x, y, z, w));
            }

            return(null);
        }
        public IDictionary <String, Object> AsNativeObject(JsValue jsValue)
        {
            if (jsValue.IsNull() || jsValue.IsUndefined())
            {
                return(null);
            }
            var            ret   = new Dictionary <String, Object>();
            ObjectInstance value = jsValue.AsObject();

            foreach (var prop in value.GetOwnProperties())
            {
                var v = value.GetOwnProperty(prop.Key);
                if (v != null)
                {
                    var jsv = v.Value;
                    if (!jsv.HasValue || jsv.Value.IsNull())
                    {
                        ret[prop.Key] = null;
                    }
                    else if (jsv.Value.IsBoolean())
                    {
                        ret[prop.Key] = jsv.Value.AsBoolean();
                    }
                    else if (jsv.Value.IsNumber())
                    {
                        double d = jsv.Value.AsNumber();
                        if (d % 1 == 0)
                        {
                            ret[prop.Key] = (int)d;
                        }
                        else
                        {
                            ret[prop.Key] = d;
                        }
                    }
                    else if (jsv.Value.IsObject())
                    {
                        // TODO protect against circular reference
                        ret[prop.Key] = AsNativeObject(jsv.Value);
                    }
                    else if (jsv.Value.IsString())
                    {
                        ret[prop.Key] = jsv.Value.AsString();
                    }
                }
            }
            return(ret);
        }
        private JsValue AddAttachment(JsValue self, JsValue[] args)
        {
            JsValue attachmentReference = null;
            string  name = null; // will preserve original name

            switch (args.Length)
            {
            case 2:
                if (args[0].IsString() == false)
                {
                    ThrowInvalidSriptMethodCall($"First argument of {Transformation.AddAttachment}(name, attachment) must be string");
                }

                name = args[0].AsString();
                attachmentReference = args[1];
                break;

            case 1:
                attachmentReference = args[0];
                break;

            default:
                ThrowInvalidSriptMethodCall($"{Transformation.AddAttachment} must have one or two arguments");
                break;
            }

            if (attachmentReference.IsNull())
            {
                return(self);
            }

            if (attachmentReference.IsString() == false || attachmentReference.AsString().StartsWith(Transformation.AttachmentMarker) == false)
            {
                var message =
                    $"{Transformation.AddAttachment}() method expects to get the reference to an attachment while it got argument of '{attachmentReference.Type}' type";

                if (attachmentReference.IsString())
                {
                    message += $" (value: '{attachmentReference.AsString()}')";
                }

                ThrowInvalidSriptMethodCall(message);
            }

            _currentRun.AddAttachment(self, name, attachmentReference);

            return(self);
        }
        private async Task SetScriptResultAsync(
            IContext context, ExecuteScriptSettings settings, JsValue result, CancellationToken cancellationToken)
        {
            if (result != null && !result.IsNull())
            {
                var value = result.Type == Types.Object
                    ? JsonConvert.SerializeObject(result.ToObject())
                    : result.ToString();

                await context.SetVariableAsync(settings.OutputVariable, value, cancellationToken);
            }
            else
            {
                await context.DeleteVariableAsync(settings.OutputVariable, cancellationToken);
            }
        }
        public void ShouldBeANumber()
        {
            var value = new JsValue(2);

            Assert.Equal(false, value.IsBoolean());
            Assert.Equal(false, value.IsArray());
            Assert.Equal(false, value.IsDate());
            Assert.Equal(false, value.IsNull());
            Assert.Equal(true, value.IsNumber());
            Assert.Equal(2, value.AsNumber());
            Assert.Equal(false, value.IsObject());
            Assert.Equal(true, value.IsPrimitive());
            Assert.Equal(false, value.IsRegExp());
            Assert.Equal(false, value.IsString());
            Assert.Equal(false, value.IsUndefined());
        }
示例#20
0
 public void Log(JsValue value, params JsValue[] values)
 {
     if (values == null || values.Length == 0)
     {
         if (value == null || value.IsNull())
         {
             Logger.Log("null");
             return;
         }
         else if (value.IsUndefined())
         {
             Logger.Log("undefined");
         }
     }
     Logger.Log(value + " " + JintUnity.Utils.Join(" ", values));
 }
示例#21
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2
        /// </summary>
        /// <param name="thisObject"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public JsValue ToObjectString(JsValue thisObject, JsValue[] arguments)
        {
            if (thisObject.IsUndefined())
            {
                return("[object Undefined]");
            }

            if (thisObject.IsNull())
            {
                return("[object Null]");
            }

            var o = TypeConverter.ToObject(Engine, thisObject);

            return("[object " + o.Class + "]");
        }
        public List <T> ToNativeArray <T>(JsValue v, Func <JsValue, T> converter)
        {
            if (v.IsNull() || v.IsUndefined())
            {
                return(null);
            }

            List <T> list  = new List <T>();
            var      array = v.AsArray();
            var      len   = (int)array.Get("length").AsNumber();

            for (var i = 0; i < len; i++)
            {
                list.Add(converter(array.Get(i.ToString())));
            }
            return(list);
        }
示例#23
0
 private static void WriteResult(JsValue result)
 {
     if (result.IsObject() && result.AsObject().Class == "Function")
     {
         CliConsole.WriteGood(result.ToString());
         CliConsole.WriteLine();
     }
     else if (!result.IsNull())
     {
         string text = Serializer.Serialize(result.ToObject(), true);
         CliConsole.WriteGood(text);
     }
     else
     {
         CliConsole.WriteLessImportant("null");
         CliConsole.WriteLine();
     }
 }
示例#24
0
        public virtual string PutDocument(string key, JsValue document, JsValue metadata, JsValue etagJs, Engine engine)
        {
            if (document.IsObject() == false)
            {
                throw new InvalidOperationException(
                          $"Created document must be a valid object which is not null or empty. Document key: '{key}'.");
            }

            long?etag = null;

            if (etagJs.IsNumber())
            {
                etag = (long)etagJs.AsNumber();
            }
            else if (etagJs.IsNull() == false && etagJs.IsUndefined() == false && etagJs.ToString() != "None")
            {
                throw new InvalidOperationException($"Invalid ETag value for document '{key}'");
            }

            var data = ToBlittable(document.AsObject());

            if (metadata.IsObject())
            {
                data["@metadata"] = ToBlittable(metadata.AsObject());
            }

            if (DebugMode)
            {
                DebugActions.PutDocument.Add(new DynamicJsonValue
                {
                    ["Key"]  = key,
                    ["Etag"] = etag,
                    ["Data"] = data,
                });
            }

            var dataReader = _context.ReadObject(data, key, BlittableJsonDocumentBuilder.UsageMode.ToDisk);
            var put        = _database.DocumentsStorage.Put(_context, key, etag, dataReader);

            return(put.Key);
        }
示例#25
0
文件: Utils.cs 项目: russlank/Jint.Ex
        public static object GetItem(this Jint.Native.Array.ArrayInstance a, int index)
        {
            JsValue l = a.Get(index.ToString());

            if (l.IsNull())
            {
                return(null);
            }
            if (l.IsNumber())
            {
                return(l.AsNumber());
            }
            if (l.IsBoolean())
            {
                return(l.AsBoolean());
            }
            if (l.IsString())
            {
                return(l.AsString());
            }
            if (l.IsNumber())
            {
                return(l.AsNumber());
            }
            if (l.IsUndefined())
            {
                return("undefined");
            }
            if (l.IsObject())
            {
                return(l.AsObject());
            }
            if (l.IsRegExp())
            {
                return(l.AsObject());
            }

            throw new ArgumentException(string.Format("Cannot deal with JsValue {0}", l));
        }
示例#26
0
        public static Vector2?FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (float)obj.AsNumber();
                return(new Vector2(num, num));
            }

            if (obj.IsArray())
            {
                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                return(new Vector2(x, y));
            }

            if (obj.IsObject())
            {
                var ob = obj.AsObject();

                var v0 = ob.Get("x");
                var v1 = ob.Get("y");

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;

                return(new Vector2(x, y));
            }

            return(null);
        }
        public virtual bool TryPropertyReference(Engine engine, Reference reference, ref JsValue value)
        {
            if (reference.GetReferencedName() == Constants.Documents.Metadata.Key &&
                reference.GetBase() is BlittableObjectInstance boi)
            {
                value = engine.Invoke(ScriptRunner.SingleRun.GetMetadataMethod, boi);
                return(true);
            }
            if (reference.GetReferencedName() == "reduce" &&
                value.IsArray() && value.AsArray().Length == 0)
            {
                value = Null.Instance;
                return(true);
            }

            if (value is DynamicJsNull)
            {
                value = DynamicJsNull.ImplicitNull;
                return(true);
            }

            return(value.IsNull() || value.IsUndefined());
        }
示例#28
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2
        /// </summary>
        /// <param name="thisObject"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public JsValue ToObjectString(JsValue thisObject, JsValue[] arguments)
        {
            if (thisObject.IsUndefined())
            {
                return("[object Undefined]");
            }

            if (thisObject.IsNull())
            {
                return("[object Null]");
            }

            var o = TypeConverter.ToObject(Engine, thisObject);

            var tag = o.Get(GlobalSymbolRegistry.ToStringTag);

            if (!tag.IsString())
            {
                tag = o.Class.ToString();
            }

            return("[object " + tag + "]");
        }
示例#29
0
        public static JToken Map(JsValue value)
        {
            if (value == null || value.IsNull())
            {
                return(JValue.CreateNull());
            }

            if (value.IsUndefined())
            {
                return(JValue.CreateUndefined());
            }

            if (value.IsString())
            {
                return(new JValue(value.AsString()));
            }

            if (value.IsBoolean())
            {
                return(new JValue(value.AsBoolean()));
            }

            if (value.IsNumber())
            {
                return(new JValue(value.AsNumber()));
            }

            if (value.IsDate())
            {
                return(new JValue(value.AsDate().ToDateTime()));
            }

            if (value.IsRegExp())
            {
                return(JValue.CreateString(value.AsRegExp().Value?.ToString()));
            }

            if (value.IsArray())
            {
                var arr = value.AsArray();

                var target = new JArray();

                for (var i = 0; i < arr.GetLength(); i++)
                {
                    target.Add(Map(arr.Get(i.ToString())));
                }

                return(target);
            }

            if (value.IsObject())
            {
                var obj = value.AsObject();

                var target = new JObject();

                foreach (var kvp in obj.GetOwnProperties())
                {
                    target[kvp.Key] = Map(kvp.Value.Value);
                }

                return(target);
            }

            throw new ArgumentException("Invalid json type.", nameof(value));
        }
示例#30
0
        private object ToBlittableValue(JsValue v, string propertyKey, bool recursiveCall)
        {
            if (v.IsBoolean())
            {
                return(v.AsBoolean());
            }

            if (v.IsString())
            {
                const string RavenDataByteArrayToBase64 = "raven-data:byte[];base64,";
                var          valueAsObject = v.ToObject();
                var          value         = valueAsObject?.ToString();
                if (value != null && value.StartsWith(RavenDataByteArrayToBase64))
                {
                    value = value.Remove(0, RavenDataByteArrayToBase64.Length);
                    var byteArray = Convert.FromBase64String(value);
                    return(Encoding.UTF8.GetString(byteArray));
                }
                return(value);
            }

            if (v.IsNumber())
            {
                var num = v.AsNumber();

                KeyValuePair <object, JsValue> property;
                if (_propertiesByValue.TryGetValue(propertyKey, out property))
                {
                    var originalValue = property.Key;
                    if (originalValue is float || originalValue is int)
                    {
                        // If the current value is exactly as the original value, we can return the original value before we made the JS conversion,
                        // which will convert a Int64 to jsFloat.
                        var jsValue = property.Value;
                        if (jsValue.IsNumber() && Math.Abs(num - jsValue.AsNumber()) < double.Epsilon)
                        {
                            return(originalValue);
                        }

                        //We might have change the type of num from Integer to long in the script by design
                        //Making sure the number isn't a real float before returning it as integer
                        if (originalValue is int && (Math.Abs(num - Math.Floor(num)) <= double.Epsilon || Math.Abs(num - Math.Ceiling(num)) <= double.Epsilon))
                        {
                            return((long)num);
                        }
                        return(num); //float
                    }
                }

                // If we don't have the type, assume that if the number ending with ".0" it actually an integer.
                var integer = Math.Truncate(num);
                if (Math.Abs(num - integer) < double.Epsilon)
                {
                    return((long)integer);
                }
                return(num);
            }
            if (v.IsNull() || v.IsUndefined())
            {
                return(null);
            }
            if (v.IsArray())
            {
                var jsArray = v.AsArray();
                var array   = new DynamicJsonArray();

                foreach (var property in jsArray.GetOwnProperties())
                {
                    if (InheritedProperties.Contains(property.Key))
                    {
                        continue;
                    }

                    var jsInstance = property.Value.Value;
                    if (!jsInstance.HasValue)
                    {
                        continue;
                    }

                    var ravenJToken = ToBlittableValue(jsInstance.Value, propertyKey + "[" + property.Key + "]", recursiveCall);
                    if (ravenJToken == null)
                    {
                        continue;
                    }

                    array.Add(ravenJToken);
                }

                return(array);
            }
            if (v.IsDate())
            {
                return(v.AsDate().ToDateTime());
            }
            if (v.IsObject())
            {
                return(ToBlittable(v.AsObject(), propertyKey, recursiveCall));
            }
            if (v.IsRegExp())
            {
                return(null);
            }

            throw new NotSupportedException(v.Type.ToString());
        }