private static string GetExceptionString(JavaScriptValue exception)
        {
            var code = JavaScriptPropertyId.FromString("Code");

            if (exception.ValueType == JavaScriptValueType.Error)
            {
                JavaScriptPropertyId messageName  = JavaScriptPropertyId.FromString("message");
                JavaScriptValue      messageValue = exception.GetProperty(messageName);
                string message = messageValue.ToString();

                double column = -1, line = -1;
                var    lineProp = JavaScriptPropertyId.FromString("line");
                var    colProp  = JavaScriptPropertyId.FromString("column");
                if (exception.HasProperty(lineProp))
                {
                    line = exception.GetProperty(lineProp).ConvertToNumber().ToDouble();
                }

                if (exception.HasProperty(colProp))
                {
                    column = exception.GetProperty(lineProp).ConvertToNumber().ToDouble();
                }

                return(string.Format("{0}, at {1}:{2}", message, (int)line, (int)column));
            }

            if (exception.ValueType == JavaScriptValueType.Object && exception.HasProperty(code))
            {
                return(exception.GetProperty(code).ConvertToString().ToString());
            }

            return(string.Format("{0}", exception.ConvertToString().ToString()));
        }
Пример #2
0
        private string JSValueToString(JavaScriptValue val)
        {
            switch (val.ValueType)
            {
            case JavaScriptValueType.Boolean:
                return(val.ToBoolean() ? "true" : "false");

            case JavaScriptValueType.Number:
                try
                {
                    return(val.ToInt32().ToString());
                }
                catch (JavaScriptException)
                {
                    return(val.ToDouble().ToString(CultureInfo.InvariantCulture));
                }

            case JavaScriptValueType.Error:
                var keys = val.GetOwnPropertyNames();
                throw new Exception("Error in js");

            case JavaScriptValueType.String:
                return(val.ToString());

            case JavaScriptValueType.Array:
//                    int length = val.GetProperty(JavaScriptPropertyId.FromString("length")).ToInt32();
//                    return "Array";
            case JavaScriptValueType.Object:
                return(val.ToJsonString());

            default:
                return(val.ValueType.ToString());
            }
        }
Пример #3
0
        private object Visit(JavaScriptValue value, IShibaContext context)
        {
            switch (value.ValueType)
            {
            case JavaScriptValueType.Error:
            case JavaScriptValueType.Object:
                return(VisitJavascriptObject(value));

            case JavaScriptValueType.Array:
                return(VisitJavascriptArray(value));

            case JavaScriptValueType.Boolean:
                return(value.ToBoolean());

            case JavaScriptValueType.Null:
                return(null);

            case JavaScriptValueType.Number:
                return(value.ToDouble());

            case JavaScriptValueType.String:
                return(value.ToString());

            case JavaScriptValueType.Undefined:
            case JavaScriptValueType.Function:
            default:
                return(value);
            }
        }
Пример #4
0
        /// <summary>
        /// Converts a <see cref="JavaScriptValue"/> with a string type to a host value.
        /// </summary>
        private object ToHostString(JavaScriptValue arg, Type toType)
        {
            if (!toType.IsAssignableFrom(typeof(string)))
            {
                throw new Exception($"Cannot convert javascript string to type: {toType}");
            }

            return(arg.ToString());
        }
        private void PrintScriptException(JavaScriptValue exception)
        {
            // Get message.
            JavaScriptPropertyId messageName  = JavaScriptPropertyId.FromString("message");
            JavaScriptValue      messageValue = exception.GetProperty(messageName);
            string message = messageValue.ToString();

            Log(string.Format("chakrahost: exception: {0}", message));
        }
Пример #6
0
        /// <summary>
        /// Executes Emmet command with the specified identifier on the specified editor view.
        /// </summary>
        /// <param name="cmdId">Identifier of the command to execute.</param>
        /// <param name="view">Editor to execute command in.</param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Indicates that the specified command identifier was not found.
        /// </exception>
        public bool RunCommand(int cmdId, ICodeEditor view)
        {
            if (!_initialized)
            {
                InitializeEngine();
            }

            string script;

            switch (cmdId)
            {
            case PackageIds.CmdIDExpandAbbreviation:
                script = GetExpandAbbreviationScript(view);
                break;

            case PackageIds.CmdIDWrapWithAbbreviation:
                script = GetWrapWithAbbreviationScript(view);
                if (script is null)
                {
                    return(false);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(
                          nameof(cmdId),
                          cmdId,
                          "Specified command identifier not found.");
            }

            Trace($"Running script: {script}");
            JavaScriptContext.Current = _context;
            JavaScriptValue result = JavaScriptContext.RunScript(script, _currentSourceContext++);

            if (result.ValueType is JavaScriptValueType.Boolean)
            {
                Trace("Emmet engine failed to execute command.");
                return(false);
            }

            string replacement = result.ToString();

            JavaScriptContext.Idle();
            if (cmdId is PackageIds.CmdIDExpandAbbreviation)
            {
                view.ReplaceCurrentLine(replacement);
            }
            else
            {
                view.ReplaceSelection(replacement);
            }

            Trace($"Command {script} completed successfully.");
            return(true);
        }
Пример #7
0
        JavaScriptErrorCode FetchImportedModuleCallback(
            JavaScriptModuleRecord referencingModule,
            JavaScriptValue specifierAsValue,
            out JavaScriptModuleRecord outDependentModuleRecord
            )
        {
            string specifier = specifierAsValue.ToString();

            Loader.Debug($"Javascript.Module.RecordDelegate FetchImportedModuleCallback for specifier: '{specifier}'");

            string normalizedSpecifier = resolver.Normalize(referencingModule.HostUrl, specifier);

            JavaScriptModuleRecord dependentModuleRecord;

            if (normalizedSpecifier == null)
            {
                dependentModuleRecord           = JavaScriptModuleRecord.Initialize(null, "<invalid record>");
                dependentModuleRecord.Exception = JavaScriptValue.CreateError($"Could not find module '{specifier}' from '{referencingModule.HostUrl}'");
            }
            else if (cache.Has(normalizedSpecifier))
            {
                dependentModuleRecord = cache.GetOrInvalid(normalizedSpecifier);
            }
            else
            {
                dependentModuleRecord         = JavaScriptModuleRecord.Initialize(referencingModule, normalizedSpecifier);
                dependentModuleRecord.HostUrl = normalizedSpecifier;
                cache.Set(normalizedSpecifier, dependentModuleRecord);

                moduleParseQueue.Enqueue(() => {
                    Loader.Debug($"Javascript.Module.RecordDelegate parsing source for '{specifier}'");
                    string source = "";
                    try {
                        source = resolver.Read(normalizedSpecifier);
                    } catch (Exception loadException) {
                        dependentModuleRecord.Exception = JavaScriptValue.CreateError($"Couldn't read file '{normalizedSpecifier}': " + loadException);
                    }

                    try {
                        // if we couldn't read the file for whatever reason, we must still call ParseSource
                        // so that the internals will move on to the next step and show us the Exception set above
                        dependentModuleRecord.ParseSource(source); // can throw syntax errors
                    } catch {
                        // will set Exception for us!
                    }
                });
            }

            dependencies.Add(dependentModuleRecord);

            outDependentModuleRecord = dependentModuleRecord;
            return(JavaScriptErrorCode.NoError); // Error case gets handled by Exception being set on the module record
        }
Пример #8
0
        private static void PrintScriptException(JavaScriptValue exception)
        {
            //
            // Get message.
            //

            JavaScriptPropertyId messageName  = JavaScriptPropertyId.FromString("message");
            JavaScriptValue      messageValue = exception.GetProperty(messageName);
            string message = messageValue.ToString();

            Console.Error.WriteLine("chakrahost: exception: {0}", message);
        }
Пример #9
0
        Object JavaScriptValueToObject(JavaScriptValue val)
        {
            switch (val.ValueType)
            {
            case JavaScriptValueType.String:
                return(val.ToString());

            case JavaScriptValueType.Null:
            case JavaScriptValueType.Undefined:
                return(null);
            }
            throw new InvalidCastException($"JavaScriptValueToObject. Unknown value type: {val.ValueType}");
        }
        public static Color ToColor(this JavaScriptValue v)
        {
            switch (v.ValueType)
            {
            case JavaScriptValueType.String:
                var s = v.ToString();
                // TODO: do this
                return(Color.White);

            case JavaScriptValueType.Object:
                if (v.Has("r") && v.Has("g") && v.Has("b"))
                {
                    var a = v.Has("a") ? v.Get("a").ConvertToNumber().ToInt32() : 255;
                    return(Color.FromByteFormat(
                               (byte)v.Get("r").ConvertToNumber().ToInt32(),
                               (byte)v.Get("g").ConvertToNumber().ToInt32(),
                               (byte)v.Get("b").ConvertToNumber().ToInt32(),
                               (byte)a));
                }
                else
                {
                    return(Color.White);
                }

            case JavaScriptValueType.Array:
                var length = v.Length();
                if (length == 4)
                {
                    return(Color.FromByteFormat(
                               (byte)v.Get(0).ConvertToNumber().ToInt32(),
                               (byte)v.Get(1).ConvertToNumber().ToInt32(),
                               (byte)v.Get(2).ConvertToNumber().ToInt32(),
                               (byte)v.Get(3).ConvertToNumber().ToInt32()));
                }
                else if (length == 3)
                {
                    return(Color.FromByteFormat(
                               (byte)v.Get(0).ConvertToNumber().ToInt32(),
                               (byte)v.Get(1).ConvertToNumber().ToInt32(),
                               (byte)v.Get(2).ConvertToNumber().ToInt32(),
                               0));
                }
                else
                {
                    return(Color.White);
                }

            default:
                return(Color.White);
            }
        }
Пример #11
0
        /// <summary>
        ///     Converts a JavaScript value into a c# object (this does not affect private variable
        ///     only public properties / getters and setters).
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <param name="type">The type of object you are expecting.</param>
        /// <returns>The converted object.</returns>
        public object FromJavaScriptValue(JavaScriptValue value, Type type)
        {
            var jsonObject = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("JSON"));
            var stringify  = jsonObject.GetProperty(JavaScriptPropertyId.FromString("stringify"));

            switch (value.ValueType)
            {
            case JavaScriptValueType.Undefined:
            case JavaScriptValueType.Null:
                return(null);

            case JavaScriptValueType.Number:
            {
                var number = stringify.CallFunction(JavaScriptValue.GlobalObject, value.ConvertToObject());
                return(JsonConvert.DeserializeObject(number.ToString(), type));
            }

            case JavaScriptValueType.String:
                return(value.ToString());

            case JavaScriptValueType.Boolean:
                return(value.ToBoolean());

            case JavaScriptValueType.Object:
            {
                var number = stringify.CallFunction(JavaScriptValue.GlobalObject, value.ConvertToObject());
                return(JsonConvert.DeserializeObject(number.ToString(), type));
            }

            case JavaScriptValueType.Function:

                // Somehow create a func to return back to c# that calls JS??

                return(null);

            case JavaScriptValueType.Array:
            {
                var number = stringify.CallFunction(JavaScriptValue.GlobalObject, value.ConvertToObject());
                return(JsonConvert.DeserializeObject(number.ToString(), type));
            }

            default:
                Console.WriteLine($"Type {value.ValueType} is not supported!");
                return(null);
            }
        }
Пример #12
0
        private IEnumerable <Span> GetValueSpans(JavaScriptValue value, int level = 0, bool inArray = false)
        {
            switch (value.ValueType)
            {
            case JavaScriptValueType.Null:
                return(new Span[] { new Span("null") });

            case JavaScriptValueType.Undefined:
                return(new Span[] { new Span("undefined") });

            case JavaScriptValueType.String:
                return(new Span[] { $"\"{value.ToString().Replace("\"", "\\\"")}\"".DarkGreen() });

            case JavaScriptValueType.Boolean:
                return(new Span[] { new Span(value.ToBoolean() ? "true" : "false") });

            case JavaScriptValueType.Number:
                try
                {
                    return(new Span[] { value.ToInt32().ToString().Red() });
                }
                catch (JavaScriptException)
                {
                    return(new Span[] { value.ToDouble().ToString(CultureInfo.InvariantCulture).Red() });
                }

            case JavaScriptValueType.Function:
                return(new Span[] { GetFuncRep(value).Magenta() });

            case JavaScriptValueType.Error:
                return(new Span[] { value.ToJsonString().DarkRed() });

            case JavaScriptValueType.Object:
                return(GetObjectSpans(value, level, inArray));

            case JavaScriptValueType.Array:
                return(GetArraySpans(value, level));

            default:
                return(new Span[] { new Span(value.ValueType.ToString()), });
            }
        }
Пример #13
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     using (new JavaScriptContext.Scope(context))
     {
         string script = inputText.Text;
         try
         {
             JavaScriptValue result       = JavaScriptContext.RunScript(script);
             JavaScriptValue stringResult = result.ConvertToString();
             outputText.Text += stringResult.ToString() + "\n";
             inputText.SelectAll();
         }
         catch (JavaScriptScriptException ex)
         {
             PrintScriptException(ex.Error);
         }
         catch (Exception ex)
         {
             Debug.WriteLine("chakrahost: failed to run script: {0}", ex.Message);
         }
     }
 }
Пример #14
0
        public static object Conv(JavaScriptValue val, Type t)
        {
            object obj = null;

            if (t.IsEnum && val.ValueType == JavaScriptValueType.String)
            {
                try
                {
                    // 3.5にはEnum.TryParseがない
                    obj = Enum.Parse(t, val.ToString());
                }
                catch
                {
                    obj = Activator.CreateInstance(t);
                }
            }
            else
            {
                var v = JSValue.Make(val);
                obj = v.ConvertTo(t);
            }
            return(obj);
        }
Пример #15
0
        /// <summary>
        ///     User implemented callback to fetch additional imported modules in ES modules.
        /// </summary>
        /// <remarks>
        ///     The callback is invoked on the current runtime execution thread, therefore execution is blocked until
        ///     the callback completes. Notify the host to fetch the dependent module. This is the "import" part
        ///     before HostResolveImportedModule in ES6 spec. This notifies the host that the referencing module has
        ///     the specified module dependency, and the host needs to retrieve the module back.
        ///
        ///     Callback should:
        ///     1. Check if the requested module has been requested before - if yes return the existing
        ///         module record
        ///     2. If no create and initialize a new module record with JsInitializeModuleRecord to
        ///         return and schedule a call to JsParseModuleSource for the new record.
        /// </remarks>
        /// <param name="referencingModule">The referencing module that is requesting the dependent module.</param>
        /// <param name="specifier">The specifier coming from the module source code.</param>
        /// <param name="dependentModuleRecord">The ModuleRecord of the dependent module. If the module was requested
        ///                                     before from other source, return the existing ModuleRecord, otherwise
        ///                                     return a newly created ModuleRecord.</param>
        /// <returns>
        ///     Returns a <c>JsNoError</c> if the operation succeeded an error code otherwise.
        /// </returns>
        /// <see cref="JavaScriptFetchImportedModuleCallBack"/>
        private JavaScriptErrorCode LoadModuleImpl(JavaScriptModuleRecord referencingModule, JavaScriptValue specifier, out JavaScriptModuleRecord dependentModuleRecord)
        {
            var specifierString = specifier.ToString();

            if (_moduleLeases.TryGetValue(specifierString, out var lease))
            {
                dependentModuleRecord = lease.Module;
                return(JavaScriptErrorCode.NoError);
            }

            var alias = ResourceModuleUtils.GetResourceAlias(specifierString);

            if (alias is null)
            {
                dependentModuleRecord           = JavaScriptModuleRecord.Initialize(referencingModule, specifier);
                dependentModuleRecord.HostUrl   = specifierString; // Only for debugging
                dependentModuleRecord.Exception = JavaScriptValue.CreateTypeError($"Failed to resolve module for specifier '{specifierString}'");
                _moduleLeases.Add(specifierString, new ModuleLease(dependentModuleRecord));
                dependentModuleRecord = _moduleLeases[specifierString].Module;
                return(JavaScriptErrorCode.NoError);
            }

            dependentModuleRecord         = JavaScriptModuleRecord.Initialize(referencingModule, specifier);
            dependentModuleRecord.HostUrl = specifierString; // Only for debugging
            _moduleLeases.Add(specifierString, new ModuleLease(dependentModuleRecord));

            // Fire off a task in the threadpool
            Task.Run(async() =>
            {
                var module = _moduleLeases[specifierString].Module;
                try
                {
                    var resource = await _resourceManager.GetResourceAsync(alias);

                    if (resource is object)
                    {
                        var script = _resourceScriptFactory.CreateFromExtension(resource, Path.GetExtension(specifierString));

                        _dispatcher.Invoke(() =>
                        {
                            using (_context.GetScope())
                            {
                                module.ParseSource(script);
                            }
                        });
                    }
                    else
                    {
                        _dispatcher.Invoke(() =>
                        {
                            using (_context.GetScope())
                            {
                                ThrowModuleException(module, JavaScriptValue.CreateError($"Could not find the resource '{specifierString}'"));
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    _dispatcher.Invoke(() =>
                    {
                        using (_context.GetScope())
                        {
                            ThrowModuleException(module, JavaScriptValue.CreateError(e.Message));
                        }
                    });
                }

                void ThrowModuleException(JavaScriptModuleRecord module, JavaScriptValue error)
                {
                    error.AddRef();
                    module.Exception = error;

                    if (!JavaScriptContext.HasException)
                    {
                        JavaScriptContext.SetException(error);
                    }

                    try
                    {
                        Native.ThrowIfError(JavaScriptErrorCode.ScriptException);
                    }
                    catch (Exception e)
                    {
                        OnResourceLoadError?.Invoke(e);
                    }
                    finally
                    {
                        error.Release();
                    }
                }
            });

            return(JavaScriptErrorCode.NoError);
        }
 private JToken VisitString(JavaScriptValue value)
 {
     return(JValue.CreateString(value.ToString()));
 }
Пример #17
0
 private JavaScriptErrorCode FetchImportedModule(JavaScriptModuleRecord reference, JavaScriptValue name, out JavaScriptModuleRecord result)
 {
     System.Diagnostics.Debug.WriteLine($"FetchImportedModule [{name.ToString()}]");
     result = createModule(reference, name.ToString());
     return(JavaScriptErrorCode.NoError);
 }
 private JToken VisitString(JavaScriptValue value)
 {
     return JValue.CreateString(value.ToString());
 }
Пример #19
0
        private static object ConvertJavaScriptValue(JavaScriptValue value)
        {
            JavaScriptValueType t = value.ValueType;

            if (t == JavaScriptValueType.Boolean)
            {
                return(value.ToBoolean());
            }
            else if (t == JavaScriptValueType.Number)
            {
                return(value.ToDouble());
            }
            else if (t == JavaScriptValueType.String)
            {
                return(value.ToString());
            }
            else if (t == JavaScriptValueType.Null)
            {
                return(null);
            }
            else if (t == JavaScriptValueType.Undefined)
            {
                return(null);
            }
            else if (t == JavaScriptValueType.Object)
            {
                Dictionary <string, object> dictionary = new Dictionary <string, object>();
                JavaScriptValue             propNames  = value.GetOwnPropertyNames();

                int             i = 0;
                JavaScriptValue index;

                while (propNames.HasIndexedProperty(index = JavaScriptValue.FromInt32(i)))
                {
                    JavaScriptValue      propName  = propNames.GetIndexedProperty(index);
                    JavaScriptPropertyId propId    = JavaScriptPropertyId.FromString(propName.ToString());
                    JavaScriptValue      propValue = value.GetProperty(propId);
                    object value2 = ConvertJavaScriptValue(propValue);
                    dictionary.Add(propName.ToString(), value2);
                    //Debug.WriteLine(propName.ToString() + ": " + propValue.ConvertToString().ToString());
                    i += 1;
                }

                return(dictionary);
            }
            else if (t == JavaScriptValueType.Array)
            {
                JavaScriptPropertyId lengthPropId = JavaScriptPropertyId.FromString("length");
                JavaScriptValue      arrayLength  = value.GetProperty(lengthPropId);
                int      length = (int)arrayLength.ToDouble();
                object[] array  = new object[length];

                int             i;
                JavaScriptValue index;

                for (i = 0; i < length; i++)
                {
                    if (value.HasIndexedProperty(index = JavaScriptValue.FromInt32(i)))
                    {
                        JavaScriptValue prop = value.GetIndexedProperty(index);
                        array[i] = ConvertJavaScriptValue(prop);
                    }
                }

                return(array);
            }
            return(null);
        }