Пример #1
0
        public MacheteRuntimeException CreateError(string message)
        {
            var args  = CreateArgs(new[] { CreateString(message) });
            var error = ErrorConstructor.Op_Construct(args);

            return(new MacheteRuntimeException(error));
        }
Пример #2
0
        /// <summary>
        /// Prints all enum options from provided object
        /// </summary>
        /// <param name="enums">Object to print enums from</param>
        public void PrintEnumValues(Type enums)
        {
            Array enumValues;

            try
            {
                enumValues = Enum.GetValues(enums);
            }
            catch (Exception ex)
            {
                switch (ex)
                {
                case InvalidOperationException ioe:
                case ArgumentException ae:
                    _simpleLogger.WriteLog(ErrorConstructor.ConstructErrorMessageFromException(ex));
                    _consoleWrapper.WriteToConsole(ex.Message);
                    return;
                }

                _simpleLogger.WriteLog(ErrorConstructor.ConstructErrorMessageFromException(ex));
                throw;
            }

            _consoleWrapper.WriteToConsole("\nAvailable Options:");
            foreach (var value in enumValues)
            {
                _consoleWrapper.WriteToConsole(value.ToString());
            }
        }
Пример #3
0
        /// <summary>
        /// Creates the Error prototype object.
        /// </summary>
        /// <param name="engine"> The script environment. </param>
        /// <param name="constructor"> A reference to the constructor that owns the prototype. </param>
        /// <param name="type"> The type of error, e.g. Error, RangeError, etc. </param>
        internal static ObjectInstance CreatePrototype(ScriptEngine engine, ErrorConstructor constructor, ErrorType type)
        {
            var result     = CreateRawObject(GetPrototype(engine, type));
            var properties = GetDeclarativeProperties(engine);

            properties.Add(new PropertyNameAndValue("constructor", constructor, PropertyAttributes.NonEnumerable));
            properties.Add(new PropertyNameAndValue("name", type.ToString(), PropertyAttributes.NonEnumerable));
            properties.Add(new PropertyNameAndValue("message", string.Empty, PropertyAttributes.NonEnumerable));
            result.InitializeProperties(properties);
            return(result);
        }
Пример #4
0
 public JavaScriptException(ErrorConstructor errorConstructor, string message, Exception inner)
     : base(message, inner)
 {
     if (inner != null)
     {
         _errorObject = errorConstructor.Construct(new JsValue[] { message, inner.ToString() });
     }
     else
     {
         _errorObject = errorConstructor.Construct(new JsValue[] { message });
     }
 }
        /// <summary>
        /// Creates instance of any type with provided values
        /// </summary>
        /// <typeparam name="T">Type of instance to create</typeparam>
        /// <param name="input">Input parameters</param>
        /// <returns>New object of provided type</returns>
        public T TryCreateNewInstance <T>(params object[] input)
        {
            if (input is null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            T instance = default(T);

            try
            {
                instance = (T)Activator.CreateInstance(typeof(T), input);
            }
            catch (Exception ex)
            {
                _simpleLogger.WriteLog(ErrorConstructor.ConstructErrorMessageFromException(ex));
                switch (ex)
                {
                case ArgumentException ax:
                case FormatException fx:
                case TypeLoadException tx:
                case NotSupportedException nx:
                case MissingMethodException mme:
                case MemberAccessException mae:
                case OverflowException oe:
                case IndexOutOfRangeException iore:
                case System.Reflection.TargetInvocationException tie:
                    Console.WriteLine(ex.Message);
                    return(default(T));

                default:
                    throw;
                }
            }

            return(instance);
        }
Пример #6
0
        //     SERIALIZATION
        //_________________________________________________________________________________________

#if !SILVERLIGHT
        /// <summary>
        /// Initializes a new instance of the ObjectInstance class with serialized data.
        /// </summary>
        /// <param name="info"> The SerializationInfo that holds the serialized object data about
        /// the exception being thrown. </param>
        /// <param name="context"> The StreamingContext that contains contextual information about
        /// the source or destination. </param>
        private ScriptEngine(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
        {
            // Set the DeserializationEnvironment to this script engine.
            ScriptEngine.DeserializationEnvironment = this;

            // Create the initial hidden class schema.  This must be done first.
            this.emptySchema = HiddenClassSchema.CreateEmptySchema();

            // Deserialize the compatibility mode.
            this.compatibilityMode = (CompatibilityMode)info.GetInt32("compatibilityMode");

            // Deserialize the ForceStrictMode flag.
            this.ForceStrictMode = info.GetBoolean("forceStrictMode");

            // Deserialize the built-in objects.
            this.globalObject        = (GlobalObject)info.GetValue("globalObject", typeof(GlobalObject));
            this.arrayConstructor    = (ArrayConstructor)info.GetValue("arrayConstructor", typeof(ArrayConstructor));
            this.booleanConstructor  = (BooleanConstructor)info.GetValue("booleanConstructor", typeof(BooleanConstructor));
            this.dateConstructor     = (DateConstructor)info.GetValue("dateConstructor", typeof(DateConstructor));
            this.functionConstructor = (FunctionConstructor)info.GetValue("functionConstructor", typeof(FunctionConstructor));
            this.jsonObject          = (JSONObject)info.GetValue("jsonObject", typeof(JSONObject));
            this.mathObject          = (MathObject)info.GetValue("mathObject", typeof(MathObject));
            this.numberConstructor   = (NumberConstructor)info.GetValue("numberConstructor", typeof(NumberConstructor));
            this.objectConstructor   = (ObjectConstructor)info.GetValue("objectConstructor", typeof(ObjectConstructor));
            this.regExpConstructor   = (RegExpConstructor)info.GetValue("regExpConstructor", typeof(RegExpConstructor));
            this.stringConstructor   = (StringConstructor)info.GetValue("stringConstructor", typeof(StringConstructor));

            // Deserialize the built-in error objects.
            this.errorConstructor          = (ErrorConstructor)info.GetValue("errorConstructor", typeof(ErrorConstructor));
            this.rangeErrorConstructor     = (ErrorConstructor)info.GetValue("rangeErrorConstructor", typeof(ErrorConstructor));
            this.typeErrorConstructor      = (ErrorConstructor)info.GetValue("typeErrorConstructor", typeof(ErrorConstructor));
            this.syntaxErrorConstructor    = (ErrorConstructor)info.GetValue("syntaxErrorConstructor", typeof(ErrorConstructor));
            this.uriErrorConstructor       = (ErrorConstructor)info.GetValue("uriErrorConstructor", typeof(ErrorConstructor));
            this.evalErrorConstructor      = (ErrorConstructor)info.GetValue("evalErrorConstructor", typeof(ErrorConstructor));
            this.referenceErrorConstructor = (ErrorConstructor)info.GetValue("referenceErrorConstructor", typeof(ErrorConstructor));
        }
Пример #7
0
        public Engine(Action <Options> options)
        {
            _executionContexts = new Stack <ExecutionContext>();

            Global = GlobalObject.CreateGlobalObject(this);

            Object   = ObjectConstructor.CreateObjectConstructor(this);
            Function = FunctionConstructor.CreateFunctionConstructor(this);

            Array   = ArrayConstructor.CreateArrayConstructor(this);
            String  = StringConstructor.CreateStringConstructor(this);
            RegExp  = RegExpConstructor.CreateRegExpConstructor(this);
            Number  = NumberConstructor.CreateNumberConstructor(this);
            Boolean = BooleanConstructor.CreateBooleanConstructor(this);
            Date    = DateConstructor.CreateDateConstructor(this);
            Math    = MathInstance.CreateMathObject(this);
            Json    = JsonInstance.CreateJsonObject(this);

            Error          = ErrorConstructor.CreateErrorConstructor(this, "Error");
            EvalError      = ErrorConstructor.CreateErrorConstructor(this, "EvalError");
            RangeError     = ErrorConstructor.CreateErrorConstructor(this, "RangeError");
            ReferenceError = ErrorConstructor.CreateErrorConstructor(this, "ReferenceError");
            SyntaxError    = ErrorConstructor.CreateErrorConstructor(this, "SyntaxError");
            TypeError      = ErrorConstructor.CreateErrorConstructor(this, "TypeError");
            UriError       = ErrorConstructor.CreateErrorConstructor(this, "URIError");

            // Because the properties might need some of the built-in object
            // their configuration is delayed to a later step

            Global.Configure();

            Object.Configure();
            Object.PrototypeObject.Configure();

            Function.Configure();
            Function.PrototypeObject.Configure();

            Array.Configure();
            Array.PrototypeObject.Configure();

            String.Configure();
            String.PrototypeObject.Configure();

            RegExp.Configure();
            RegExp.PrototypeObject.Configure();

            Number.Configure();
            Number.PrototypeObject.Configure();

            Boolean.Configure();
            Boolean.PrototypeObject.Configure();

            Date.Configure();
            Date.PrototypeObject.Configure();

            Math.Configure();
            Json.Configure();

            Error.Configure();
            Error.PrototypeObject.Configure();

            // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3
            GlobalEnvironment = new LexicalEnvironment();
            GlobalEnvironment.Setup(new ObjectEnvironmentRecord(this, Global, false), null);

            // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1
            EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global);

            Options = new Options();

            if (options != null)
            {
                options(Options);
            }

            Eval = new EvalFunctionInstance(this, new string[0], LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode);
            Global.FastAddProperty("eval", Eval, true, false, true);

            _statements  = new StatementInterpreter(this);
            _expressions = new ExpressionInterpreter(this);

            if (Options._IsClrAllowed)
            {
                Global.FastAddProperty("System", new NamespaceReference(this, "System"), false, false, false);
                Global.FastAddProperty("importNamespace", new ClrFunctionInstance(this, (thisObj, arguments) =>
                {
                    return(new NamespaceReference(this, TypeConverter.ToString(arguments.At(0))));
                }), false, false, false);
            }

            ClrTypeConverter = new DefaultTypeConverter(this);
            BreakPoints      = new List <BreakPoint>();
            DebugHandler     = new DebugHandler(this);
        }
Пример #8
0
 public JavaScriptException(ErrorConstructor errorConstructor, string message)
     : base(message)
 {
     _errorObject = errorConstructor.Construct(new JsValue[] { message });
 }
Пример #9
0
 public JavaScriptException(ErrorConstructor errorConstructor) : base("")
 {
     _errorObject = errorConstructor.Construct(Arguments.Empty);
 }
Пример #10
0
 public JavaScriptException(ErrorConstructor errorConstructor) : base("")
 {
     _errorObject = errorConstructor.Construct(Arguments.Empty);
     CallStack    = errorConstructor.Engine.CallStack;
 }
Пример #11
0
 public JavaScriptException(ErrorConstructor errorConstructor, string message, Exception innerException)
     : base(message, innerException)
 {
     Error = errorConstructor.Construct(new JsValue[] { message });
 }
Пример #12
0
        public Engine(Action <Options> options)
        {
            _executionContexts = new ExecutionContextStack();

            Global = GlobalObject.CreateGlobalObject(this);

            Object   = ObjectConstructor.CreateObjectConstructor(this);
            Function = FunctionConstructor.CreateFunctionConstructor(this);

            Symbol   = SymbolConstructor.CreateSymbolConstructor(this);
            Array    = ArrayConstructor.CreateArrayConstructor(this);
            Map      = MapConstructor.CreateMapConstructor(this);
            Set      = SetConstructor.CreateSetConstructor(this);
            Iterator = IteratorConstructor.CreateIteratorConstructor(this);
            String   = StringConstructor.CreateStringConstructor(this);
            RegExp   = RegExpConstructor.CreateRegExpConstructor(this);
            Number   = NumberConstructor.CreateNumberConstructor(this);
            Boolean  = BooleanConstructor.CreateBooleanConstructor(this);
            //            Date = DateConstructor.CreateDateConstructor(this);
            Math = MathInstance.CreateMathObject(this);
            Json = JsonInstance.CreateJsonObject(this);

            Error          = ErrorConstructor.CreateErrorConstructor(this, "Error");
            EvalError      = ErrorConstructor.CreateErrorConstructor(this, "EvalError");
            RangeError     = ErrorConstructor.CreateErrorConstructor(this, "RangeError");
            ReferenceError = ErrorConstructor.CreateErrorConstructor(this, "ReferenceError");
            SyntaxError    = ErrorConstructor.CreateErrorConstructor(this, "SyntaxError");
            TypeError      = ErrorConstructor.CreateErrorConstructor(this, "TypeError");
            UriError       = ErrorConstructor.CreateErrorConstructor(this, "URIError");

            GlobalSymbolRegistry = new GlobalSymbolRegistry();

            // Because the properties might need some of the built-in object
            // their configuration is delayed to a later step

            Global.Configure();

            Object.Configure();
            Object.PrototypeObject.Configure();

            Symbol.Configure();
            Symbol.PrototypeObject.Configure();

            Function.Configure();
            Function.PrototypeObject.Configure();

            Array.Configure();
            Array.PrototypeObject.Configure();

            Map.Configure();
            Map.PrototypeObject.Configure();

            Set.Configure();
            Set.PrototypeObject.Configure();

            Iterator.Configure();
            Iterator.PrototypeObject.Configure();

            String.Configure();
            String.PrototypeObject.Configure();

            RegExp.Configure();
            RegExp.PrototypeObject.Configure();

            Number.Configure();
            Number.PrototypeObject.Configure();

            Boolean.Configure();
            Boolean.PrototypeObject.Configure();

            //            Date.Configure();
            //            Date.PrototypeObject.Configure();

            Math.Configure();
            Json.Configure();

            Error.Configure();
            Error.PrototypeObject.Configure();

            // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3
            GlobalEnvironment = LexicalEnvironment.NewObjectEnvironment(this, Global, null, false);

            // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1
            EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global);

            Options = new Options();

            options?.Invoke(Options);

            // gather some options as fields for faster checks
            _isDebugMode = Options.IsDebugMode;

            if (_isDebugMode)
            {
                MyAPIGateway.Utilities.ShowMessage("SpaceJS", "Debug mode enabled.");
            }

            _isStrict                 = Options.IsStrict;
            _maxStatements            = Options._MaxStatements;
            _referenceResolver        = Options.ReferenceResolver;
            _memoryLimit              = Options._MemoryLimit;
            _runBeforeStatementChecks = (_maxStatements > 0 && _maxStatements < int.MaxValue) ||
                                        Options._TimeoutInterval.Ticks > 0 ||
                                        _memoryLimit > 0 ||
                                        _isDebugMode;

            _referencePool         = new ReferencePool();
            _argumentsInstancePool = new ArgumentsInstancePool(this);
            _jsValueArrayPool      = new JsValueArrayPool();

            Eval = new EvalFunctionInstance(this, System.ArrayExt.Empty <string>(), LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode);
            Global.FastAddProperty("eval", Eval, true, false, true);

            _statements  = new StatementInterpreter(this);
            _expressions = new ExpressionInterpreter(this);

            /*            if (Options._IsClrAllowed)
             *          {
             *              Global.FastAddProperty("System", new NamespaceReference(this, "System"), false, false, false);
             *              Global.FastAddProperty("importNamespace", new ClrFunctionInstance(
             *                  this,
             *                  "importNamespace",
             *                  (thisObj, arguments) => new NamespaceReference(this, TypeConverter.ToString(arguments.At(0)))), false, false, false);
             *          }
             */
            //            ClrTypeConverter = new DefaultTypeConverter(this);
        }
Пример #13
0
        public ScriptEngine()
        {
            // Create the initial hidden class schema.  This must be done first.
            this.emptySchema = HiddenClassSchema.CreateEmptySchema();

            // Create the base of the prototype chain.
            var baseObject = ObjectInstance.CreateRootObject(this);

            // Create the global object.
            this.globalObject = new GlobalObject(baseObject);

            // Create the function object that second to last in the prototype chain.
            var baseFunction = UserDefinedFunction.CreateEmptyFunction(baseObject);

            // Object must be created first, then function.
            this.objectConstructor   = new ObjectConstructor(baseFunction, baseObject);
            this.functionConstructor = new FunctionConstructor(baseFunction, baseFunction);

            // Create all the built-in objects.
            this.mathObject = new MathObject(baseObject);
            this.jsonObject = new JSONObject(baseObject);

            // Create all the built-in functions.
            this.arrayConstructor   = new ArrayConstructor(baseFunction);
            this.booleanConstructor = new BooleanConstructor(baseFunction);
            this.dateConstructor    = new DateConstructor(baseFunction);
            this.numberConstructor  = new NumberConstructor(baseFunction);
            this.regExpConstructor  = new RegExpConstructor(baseFunction);
            this.stringConstructor  = new StringConstructor(baseFunction);

            // Create the error functions.
            this.errorConstructor          = new ErrorConstructor(baseFunction, "Error");
            this.rangeErrorConstructor     = new ErrorConstructor(baseFunction, "RangeError");
            this.typeErrorConstructor      = new ErrorConstructor(baseFunction, "TypeError");
            this.syntaxErrorConstructor    = new ErrorConstructor(baseFunction, "SyntaxError");
            this.uriErrorConstructor       = new ErrorConstructor(baseFunction, "URIError");
            this.evalErrorConstructor      = new ErrorConstructor(baseFunction, "EvalError");
            this.referenceErrorConstructor = new ErrorConstructor(baseFunction, "ReferenceError");

            // Populate the instance prototypes (TODO: optimize this, currently takes about 15ms).
            this.globalObject.PopulateFunctions();
            this.objectConstructor.PopulateFunctions();
            this.objectConstructor.InstancePrototype.PopulateFunctions();
            this.functionConstructor.InstancePrototype.PopulateFunctions(typeof(FunctionInstance));
            this.mathObject.PopulateFunctions();
            this.mathObject.PopulateFields();
            this.jsonObject.PopulateFunctions();
            this.arrayConstructor.PopulateFunctions();
            this.arrayConstructor.InstancePrototype.PopulateFunctions();
            this.booleanConstructor.InstancePrototype.PopulateFunctions();
            this.dateConstructor.PopulateFunctions();
            this.dateConstructor.InstancePrototype.PopulateFunctions();
            this.numberConstructor.InstancePrototype.PopulateFunctions();
            this.numberConstructor.PopulateFields();
            this.regExpConstructor.InstancePrototype.PopulateFunctions();
            this.stringConstructor.PopulateFunctions();
            this.stringConstructor.InstancePrototype.PopulateFunctions();
            this.errorConstructor.InstancePrototype.PopulateFunctions();

            // Add them as JavaScript-accessible properties of the global instance.
            this.globalObject.FastSetProperty("Array", this.arrayConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("Boolean", this.booleanConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("Date", this.dateConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("Function", this.functionConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("JSON", this.jsonObject, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("Math", this.mathObject, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("Number", this.numberConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("Object", this.objectConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("RegExp", this.regExpConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("String", this.stringConstructor, PropertyAttributes.NonEnumerable);

            // And the errors.
            this.globalObject.FastSetProperty("Error", this.errorConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("RangeError", this.rangeErrorConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("TypeError", this.typeErrorConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("SyntaxError", this.syntaxErrorConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("URIError", this.uriErrorConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("EvalError", this.evalErrorConstructor, PropertyAttributes.NonEnumerable);
            this.globalObject.FastSetProperty("ReferenceError", this.referenceErrorConstructor, PropertyAttributes.NonEnumerable);
        }