Exemple #1
0
        internal override SObject ExecuteMethod(ScriptProcessor processor, string methodName, SObject caller, SObject This, SObject[] parameters)
        {
            InitializeStatic();

            AddObjectPrototypeAsExtends(processor);

            bool isStaticCall = ReferenceEquals(caller, this);

            // Call any static function defined in this prototype:
            if (_prototypeMembers.ContainsKey(methodName) && _prototypeMembers[methodName].IsStatic)
            {
                if (_prototypeMembers[methodName].IsFunction)
                {
                    var cFunction = (SFunction)_prototypeMembers[methodName].Data;
                    return cFunction.Call(processor, caller, this, parameters); // For a static method, the "This" attribute is the prototype.
                }
                else
                {
                    return processor.ErrorHandler.ThrowError(ErrorType.TypeError, ErrorHandler.MESSAGE_TYPE_NOT_A_FUNCTION, methodName);
                }
            }

            // Call the super class prototype, if one exists:
            if (Extends != null)
            {
                return Extends.ExecuteMethod(processor, methodName, caller, This, parameters);
            }

            return processor.ErrorHandler.ThrowError(ErrorType.ReferenceError, ErrorHandler.MESSAGE_REFERENCE_NOT_DEFINED, methodName);
        }
Exemple #2
0
 internal override SNumber ToNumber(ScriptProcessor processor)
 {
     if (Value)
         return processor.CreateNumber(1);
     else
         return processor.CreateNumber(0);
 }
        internal static string AddOperator(ScriptProcessor processor, SObject left, SObject right)
        {
            if (left is SString || right is SString)
            {
                string strLeft, strRight;

                if (left is SString)
                    strLeft = ((SString)left).Value;
                else
                    strLeft = left.ToString(processor).Value;

                if (right is SString)
                    strRight = ((SString)right).Value;
                else
                    strRight = right.ToString(processor).Value;

                return strLeft + strRight;
            }
            else
            {
                var numbers = GetNumericOperatorParameters(processor, left, right);

                return SNumber.ConvertToScriptString(numbers.Item1 + numbers.Item2);
            }
        }
Exemple #4
0
        public static SObject Create(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            Prototype prototype = null;

            if (parameters.Length > 0)
            {
                var protoParam = parameters[0];
                if (protoParam.TypeOf() == LITERAL_TYPE_STRING)
                {
                    prototype = processor.Context.GetPrototype(((SString)protoParam).Value);
                }
                else if (IsPrototype(protoParam.GetType()))
                {
                    prototype = (Prototype)protoParam;
                }
                else
                {
                    return processor.ErrorHandler.ThrowError(ErrorType.TypeError, ErrorHandler.MESSAGE_REFERENCE_NO_PROTOTYPE, protoParam.TypeOf());
                }
            }

            if (prototype != null)
            {
                var instParams = new SObject[parameters.Length - 1];
                Array.Copy(parameters, 1, instParams, 0, parameters.Length - 1);

                return processor.Context.CreateInstance(prototype, instParams);
            }
            else
            {
                return processor.ErrorHandler.ThrowError(ErrorType.TypeError, ErrorHandler.MESSAGE_REFERENCE_NO_PROTOTYPE, LITERAL_UNDEFINED);
            }
        }
Exemple #5
0
        internal override SObject GetMember(ScriptProcessor processor, SObject accessor, bool isIndexer)
        {
            if (isIndexer && accessor.TypeOf() == LITERAL_TYPE_NUMBER)
            {
                if (IndexerGetFunction != null)
                {
                    return IndexerGetFunction.Call(processor, this, this, new SObject[] { accessor });
                }
                else
                {
                    return processor.Undefined;
                }
            }

            string memberName;
            if (accessor is SString)
                memberName = ((SString)accessor).Value;
            else
                memberName = accessor.ToString(processor).Value;

            if (Members.ContainsKey(memberName))
            {
                return Members[memberName];
            }
            else if (Prototype != null && Prototype.HasMember(processor, memberName))
            {
                return Prototype.GetMember(processor, accessor, isIndexer);
            }
            else if (SuperClass != null)
            {
                return SuperClass.GetMember(processor, accessor, isIndexer);
            }

            return processor.Undefined;
        }
Exemple #6
0
 internal override bool HasMember(ScriptProcessor processor, string memberName)
 {
     if (_prototypeMembers.ContainsKey(memberName))
         return true;
     else
         return base.HasMember(processor, memberName);
 }
 /// <summary>
 /// Returns the content of a variable, or Undefined, if the variable does not exist.
 /// </summary>
 public static SObject GetVariable(ScriptProcessor processor, string identifier)
 {
     if (processor.Context.IsVariable(identifier))
         return processor.Context.GetVariable(identifier).Data;
     else
         return processor.Undefined;
 }
Exemple #8
0
        public static SObject IndexerSet(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var arr = (SArray)instance;

            if (parameters.Length >= 2)
            {
                var accessor = (int)parameters[0].ToNumber(processor).Value;

                if (accessor >= 0)
                {
                    if (accessor < arr.ArrayMembers.Length)
                    {
                        arr.ArrayMembers[accessor] = parameters[1];
                    }
                    else
                    {
                        var arrMembers = arr.ArrayMembers;
                        Array.Resize(ref arrMembers, accessor + 1);
                        arrMembers[accessor] = parameters[1];
                        arr.ArrayMembers = arrMembers;
                    }
                }
            }

            return processor.Undefined;
        }
Exemple #9
0
        public ErrorPrototype(ScriptProcessor processor) : base("Error")
        {
            Constructor = new PrototypeMember(CLASS_METHOD_CTOR, new SFunction(constructor));

            AddMember(processor, new PrototypeMember(MEMBER_NAME_MESSAGE, processor.Undefined));
            AddMember(processor, new PrototypeMember(MEMBER_NAME_TYPE, processor.Undefined));
            AddMember(processor, new PrototypeMember(MEMBER_NAME_LINE, processor.Undefined));
        }
Exemple #10
0
        /// <summary>
        /// Parses a string as an array.
        /// </summary>
        internal new static SObject Parse(ScriptProcessor processor, string exp)
        {
            // Format: [item1, item2, ... itemn]

            if (Regex.IsMatch(exp, REGEX_EMPTY_ARRAY)) return processor.CreateArray(0);

            exp = exp.Remove(exp.Length - 1, 1).Remove(0, 1).Trim(); // Remove [ and ].

            var elements = new List<SObject>();

            var elementStart = 0;
            var index = 0;
            var depth = 0;
            StringEscapeHelper escaper = new LeftToRightStringEscapeHelper(exp, 0);
            string element;

            while (index < exp.Length)
            {
                var t = exp[index];
                escaper.CheckStartAt(index);

                if (!escaper.IsString)
                {
                    if (t == '{' || t == '[' || t == '(')
                    {
                        depth++;
                    }
                    else if (t == '}' || t == ']' || t == ')')
                    {
                        depth--;
                    }
                    else if (t == ',' && depth == 0)
                    {
                        element = exp.Substring(elementStart, index - elementStart);
                        
                        if (string.IsNullOrWhiteSpace(element))
                            elements.Add(processor.Undefined);
                        else
                            elements.Add(processor.ExecuteStatement(new ScriptStatement(element)));

                        elementStart = index + 1;
                    }
                }

                index++;
            }

            element = exp.Substring(elementStart, index - elementStart);

            if (string.IsNullOrWhiteSpace(element))
                elements.Add(processor.Undefined);
            else
                elements.Add(processor.ExecuteStatement(new ScriptStatement(element)));

            return processor.CreateArray(elements.ToArray());
        }
Exemple #11
0
        private static SObject constructor(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var arr = (SArray)instance;

            var length = (int)((SNumber)parameters[0]).Value;
            arr.ArrayMembers = new SObject[length];

            Array.Copy(parameters, 1, arr.ArrayMembers, 0, parameters.Length - 1);
            return arr;
        }
Exemple #12
0
        /// <summary>
        /// Translates a .Net object to a script object.
        /// </summary>
        public static SObject Translate(ScriptProcessor processor, object objIn)
        {
            // todo: C# 7: put a swtich statement type match instead of aweful if case blocks.
            if (objIn == null)
            {
                return TranslateNull(processor);
            }

            if (objIn.GetType() == typeof(SObject) || objIn.GetType().IsSubclassOf(typeof(SObject)))
            {
                // this is already an SObject, return it.
                return (SObject)objIn;
            }

            if (objIn is sbyte || objIn is byte || objIn is short || objIn is ushort || objIn is int || objIn is uint || objIn is long || objIn is ulong || objIn is float || objIn is double)
            {
                return TranslateNumber(processor, Convert.ToDouble(objIn));
            }
            else if (objIn is string || objIn is char)
            {
                return TranslateString(processor, objIn.ToString()); // ToString will return just the string for the string type, and a string from a char.
            }
            else if (objIn is bool)
            {
                return TranslateBool(processor, (bool)objIn);
            }
            else if (objIn is Type)
            {
                return TranslatePrototype(processor, (Type)objIn);
            }
            else if (objIn.GetType().IsArray)
            {
                return TranslateArray(processor, (Array)objIn);
            }
            else if (objIn is BuiltInMethod || objIn is DotNetBuiltInMethod)
            {
                return TranslateFunction((Delegate)objIn);
            }
            else if (objIn is ScriptRuntimeException)
            {
                return TranslateException((ScriptRuntimeException)objIn);
            }
            else if (objIn is NetUndefined)
            {
                return TranslateUndefined(processor);
            }
            else if (objIn is ExpandoObject)
            {
                return TranslateExpandoObject(processor, objIn as ExpandoObject);
            }
            else
            {
                return TranslateObject(processor, objIn);
            }
        }
Exemple #13
0
        private static SObject constructor(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var obj = (SNumber)instance;

            if (parameters[0] is SNumber)
                obj.Value = ((SNumber)parameters[0]).Value;
            else
                obj.Value = parameters[0].ToNumber(processor).Value;

            return obj;
        }
Exemple #14
0
 protected override object OnCalc(IList <object> operands)
 {
     if (operands.Count > 0)
     {
         string info = operands[0] as string;
         if (null != info)
         {
             ScriptProcessor.End(info);
         }
     }
     return(0);
 }
Exemple #15
0
        // TODO: C# 7: put proper Tuple handling in place.

        private static Tuple <PrototypeMember, string> ParseVarStatement(ScriptProcessor processor, ScriptStatement statement)
        {
            var code      = statement.Code;
            var signature = code.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            string identifier;
            var    assignment = "";
            var    isReadOnly = false;
            var    isStatic   = false;

            // Read static:
            if (signature.Contains(VAR_SIGNATURE_STATIC))
            {
                isStatic = true;
                signature.Remove(VAR_SIGNATURE_STATIC);
            }

            // Read readonly:
            if (signature.Contains(VAR_SIGNATURE_READONLY))
            {
                isReadOnly = true;
                signature.Remove(VAR_SIGNATURE_READONLY);
            }

            if (signature[0] != "var" || signature.Count < 2)
            {
                processor.ErrorHandler.ThrowError(ErrorType.SyntaxError, ErrorHandler.MESSAGE_SYNTAX_CLASS_INVALID_VAR_DECLARATION);
            }

            identifier = signature[1];

            if (!ScriptProcessor.IsValidIdentifier(identifier))
            {
                processor.ErrorHandler.ThrowError(ErrorType.SyntaxError, ErrorHandler.MESSAGE_SYNTAX_MISSING_VAR_NAME);
            }

            if (signature.Count > 2)
            {
                if (signature[2].StartsWith("="))
                {
                    assignment = code.Remove(0, code.IndexOf("=") + 1).Trim();
                }
                else
                {
                    processor.ErrorHandler.ThrowError(ErrorType.SyntaxError, ErrorHandler.MESSAGE_SYNTAX_CLASS_INVALID_VAR_DECLARATION);
                }
            }

            var member = new PrototypeMember(identifier, processor.Undefined, isStatic, isReadOnly, false, false);

            return(new Tuple <PrototypeMember, string>(member, assignment));
        }
Exemple #16
0
        /// <summary>
        /// Creates an instance derived from this prototype.
        /// </summary>
        internal SProtoObject CreateInstance(ScriptProcessor processor, SObject[] parameters, bool executeCtor)
        {
            SProtoObject obj = CreateBaseObject();

            obj.IsProtoInstance = true;

            obj.AddMember(MEMBER_NAME_PROTOTYPE, this);

            if (typeof(ObjectPrototype) != GetType())
            {
                // If no extends class is explicitly specified, "Object" is assumed.
                if (Extends == null)
                {
                    Extends = processor.Context.GetPrototype("Object");
                }

                var superInstance = Extends.CreateInstance(processor, null, true);
                obj.AddMember(MEMBER_NAME_SUPER, superInstance);
            }

            foreach (var member in GetInstanceMembers())
            {
                obj.AddMember(member.Identifier, member.Data);
            }

            var indexerGetFunction = GetIndexerGetFunction();

            if (indexerGetFunction != null)
            {
                obj.IndexerGetFunction = indexerGetFunction;
            }

            var indexerSetFunction = GetIndexerSetFunction();

            if (indexerSetFunction != null)
            {
                obj.IndexerSetFunction = indexerSetFunction;
            }

            if (executeCtor)
            {
                Constructor?.ToFunction().Call(processor, obj, obj, parameters);
            }

            // Lock all readonly members after the constructor call, so they can be set in the constructor:
            foreach (PrototypeMember member in GetReadOnlyInstanceMembers())
            {
                obj.Members[member.Identifier].IsReadOnly = true;
            }

            return(obj);
        }
        private ScriptProcessor CreateProcessor()
        {
            if (_prototypeBuffer == null)
            {
                InitializePrototypeBuffer();
            }

            var processor = new ScriptProcessor(_prototypeBuffer);

            ScriptContextManipulator.SetCallbackExecuteMethod(processor, ExecuteMethod);

            return(processor);
        }
Exemple #18
0
 internal override void SetMember(ScriptProcessor processor, SObject accessor, bool isIndexer, SObject value)
 {
     if (processor.Context.HasCallback(CallbackType.SetMember))
     {
         var callback = (DSetMember)processor.Context.GetCallback(CallbackType.SetMember);
         var task     = Task.Factory.StartNew(() => callback(processor, ModuleName, accessor, isIndexer, value));
         task.Wait();
     }
     else
     {
         processor.ErrorHandler.ThrowError(ErrorType.APIError, ErrorHandler.MESSAGE_API_NOT_SUPPORTED);
     }
 }
Exemple #19
0
        public static SObject Where(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            if (parameters.Length >= 1)
            {
                var arr      = (SArray)instance;
                var comparer = (SFunction)Unbox(parameters[0]);

                var results = arr.ArrayMembers.Where((m, i) => ((SBool)comparer.Call(processor, This, This, new[] { m, processor.CreateNumber(i) })).Value);
                return(processor.CreateArray(results.ToArray()));
            }

            return(processor.Undefined);
        }
Exemple #20
0
        public static SObject Select(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            if (parameters.Length >= 1)
            {
                var arr      = (SArray)instance;
                var comparer = (SFunction)Unbox(parameters[0]);

                var result = arr.ArrayMembers.Select(m => comparer.Call(processor, This, This, new[] { m }));
                return(processor.CreateArray(result.ToArray()));
            }

            return(processor.Undefined);
        }
Exemple #21
0
        internal override SObject ExecuteMethod(ScriptProcessor processor, string methodName, SObject caller, SObject This, SObject[] parameters)
        {
            // The statement that entered this method looks like this: this.varName(), where varName is a variable containing an SFunction object.

            if (_context.IsVariable(methodName))
            {
                var methodVariable = _context.GetVariable(methodName);
                var function       = methodVariable.Data as SFunction;
                return(function != null?function.Call(processor, caller, This, parameters)
                           : processor.ErrorHandler.ThrowError(ErrorType.TypeError, ErrorHandler.MessageTypeNotAFunction, methodName));
            }
            return(processor.ErrorHandler.ThrowError(ErrorType.ReferenceError, ErrorHandler.MessageReferenceNotDefined, methodName));
        }
Exemple #22
0
        public static SObject show(ScriptProcessor processor, SObject[] parameters)
        {
            // TODO: get correct location from world screen
            var screenManager = GetComponent <ScreenManager>();
            var townMapScreen = new TownMapScreen(screenManager.ActiveScreen, "johto", "New Bark Town");

            townMapScreen.LoadContent();
            screenManager.SetScreen(townMapScreen);

            ScriptManager.WaitUntil(() => !(screenManager.ActiveScreen is TownMapScreen));

            return(ScriptInAdapter.GetUndefined(processor));
        }
Exemple #23
0
 protected override object OnCalc(IList <object> operands)
 {
     if (operands.Count > 1)
     {
         string file = operands[0] as string;
         string info = operands[1] as string;
         if (!string.IsNullOrEmpty(file) && null != info)
         {
             ScriptProcessor.BeginFile(file, info);
         }
     }
     return(0);
 }
Exemple #24
0
        public static SObject All(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            if (parameters.Length >= 1)
            {
                var arr      = (SArray)instance;
                var comparer = (SFunction)Unbox(parameters[0]);

                var result = arr.ArrayMembers.All(m => ((SBool)comparer.Call(processor, This, This, new[] { m })).Value);
                return(processor.CreateBool(result));
            }

            return(processor.Undefined);
        }
Exemple #25
0
 internal override void SetMember(ScriptProcessor processor, SObject accessor, bool isIndexer, SObject value)
 {
     if (processor.Context.HasCallback(CallbackType.SetMember))
     {
         var callback = (DSetMember)processor.Context.GetCallback(CallbackType.SetMember);
         var task = Task.Factory.StartNew(() => callback(processor, ModuleName, accessor, isIndexer, value));
         task.Wait();
     }
     else
     {
         processor.ErrorHandler.ThrowError(ErrorType.APIError, ErrorHandler.MESSAGE_API_NOT_SUPPORTED);
     }
 }
Exemple #26
0
        public static SObject Replace(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            if (TypeContract.Ensure(parameters, new[] { typeof(SString), typeof(SString) }))
            {
                var str     = ((SString)instance).Value;
                var replace = ((SString)parameters[0]).Value;
                var with    = ((SString)parameters[1]).Value;

                return(processor.CreateString(string.IsNullOrWhiteSpace(replace) ? str : str.Replace(replace, with)));
            }

            return(processor.Undefined);
        }
Exemple #27
0
        // TODO: C# 7: put proper Tuple handling in place.

        private static Tuple <PrototypeMember, string> ParseVarStatement(ScriptProcessor processor, ScriptStatement statement)
        {
            var code      = statement.Code;
            var signature = code.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            var assignment = "";
            var isReadOnly = false;
            var isStatic   = false;

            // Read static:
            if (signature.Contains(VarSignatureStatic))
            {
                isStatic = true;
                signature.Remove(VarSignatureStatic);
            }

            // Read readonly:
            if (signature.Contains(VarSignatureReadonly))
            {
                isReadOnly = true;
                signature.Remove(VarSignatureReadonly);
            }

            if (signature[0] != "var" || signature.Count < 2)
            {
                processor.ErrorHandler.ThrowError(ErrorType.SyntaxError, ErrorHandler.MessageSyntaxClassInvalidVarDeclaration);
            }

            var identifier = signature[1];

            if (!ScriptProcessor.IsValidIdentifier(identifier))
            {
                processor.ErrorHandler.ThrowError(ErrorType.SyntaxError, ErrorHandler.MessageSyntaxMissingVarName);
            }

            if (signature.Count > 2)
            {
                if (signature[2].StartsWith("="))
                {
                    assignment = code.Remove(0, code.IndexOf("=", StringComparison.Ordinal) + 1).Trim();
                }
                else
                {
                    processor.ErrorHandler.ThrowError(ErrorType.SyntaxError, ErrorHandler.MessageSyntaxClassInvalidVarDeclaration);
                }
            }

            var member = new PrototypeMember(identifier, processor.Undefined, isStatic, isReadOnly, false, false);

            return(new Tuple <PrototypeMember, string>(member, assignment));
        }
Exemple #28
0
        public static SObject getEntity(ScriptProcessor processor, SObject[] parameters)
        {
            object[] netObjects;
            if (EnsureTypeContract(parameters, new[] { typeof(string) }, out netObjects))
            {
                var entity = new EntityWrapper {
                    id = (string)netObjects[0]
                };

                return(ScriptInAdapter.Translate(processor, entity));
            }

            return(ScriptInAdapter.GetUndefined(processor));
        }
Exemple #29
0
        static Program()
        {
            var streams = new List <StreamReader>();

            logger            = new Logger();
            presentationLogic = new PresentationLogic();
            var encryptionProcessor          = new Processor();
            IScriptProcessor scriptProcessor = new ScriptProcessor(encryptionProcessor);
            IFileProcessor   fileProcessor   = new FileProcessor(streams);
            IEmailProcessor  emailProcessor  = new EmailProcessor();
            IDatabaseLogic   databaseLogic   = new DatabaseLogic();

            businessLogic = new BusinessLogic(logger, scriptProcessor, fileProcessor, emailProcessor, databaseLogic);
        }
Exemple #30
0
        private static SObject constructor(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var obj = (SError)instance;

            if (parameters.Length > 0)
            {
                SString message;

                if (parameters[0] is SString)
                    message = (SString)parameters[0];
                else
                    message = parameters[0].ToString(processor);

                obj.Members[MEMBER_NAME_MESSAGE].Data = message;
            }

            if (parameters.Length > 1)
            {
                SString errorType;

                if (parameters[1] is SString)
                    errorType = (SString)parameters[1];
                else
                    errorType = parameters[1].ToString(processor);

                obj.Members[MEMBER_NAME_TYPE].Data = errorType;
            }
            else
            {
                obj.Members[MEMBER_NAME_TYPE].Data = processor.CreateString("UserError");
            }

            if (parameters.Length > 2)
            {
                SNumber errorLine;

                if (parameters[2] is SNumber)
                    errorLine = (SNumber)parameters[2];
                else
                    errorLine = parameters[2].ToNumber(processor);

                obj.Members[MEMBER_NAME_LINE].Data = errorLine;
            }
            else
            {
                obj.Members[MEMBER_NAME_LINE].Data = processor.CreateNumber(-1);
            }

            return obj;
        }
Exemple #31
0
        internal override void SetMember(ScriptProcessor processor, SObject accessor, bool isIndexer, SObject value)
        {
            var accessorAsString = accessor as SString;
            var memberName       = accessorAsString != null ? accessorAsString.Value : accessor.ToString(processor).Value;

            if (_context.IsVariable(memberName))
            {
                _context.GetVariable(memberName).Data = value;
            }
            else
            {
                processor.ErrorHandler.ThrowError(ErrorType.ReferenceError, ErrorHandler.MessageReferenceNotDefined, memberName);
            }
        }
Exemple #32
0
        private static SObject constructor(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var obj = (SString)instance;

            if (parameters[0] is SString)
            {
                obj.Value = ((SString)parameters[0]).Value;
                obj.Escaped = ((SString)parameters[0]).Escaped;
            }
            else
                obj.Value = parameters[0].ToString(processor).Value;

            return obj;
        }
Exemple #33
0
        internal override SObject GetMember(ScriptProcessor processor, SObject accessor, bool isIndexer)
        {
            if (isIndexer && accessor.TypeOf() == LITERAL_TYPE_NUMBER)
            {
                if (Prototype.GetIndexerGetFunction() != IndexerGetFunction)
                {
                    IndexerGetFunction = Prototype.GetIndexerGetFunction();
                }

                if (IndexerGetFunction != null)
                {
                    return(IndexerGetFunction.Call(processor, this, this, new SObject[] { accessor }));
                }
                else
                {
                    return(processor.Undefined);
                }
            }

            string memberName;

            if (accessor is SString)
            {
                memberName = ((SString)accessor).Value;
            }
            else
            {
                memberName = accessor.ToString(processor).Value;
            }

            if (Members.ContainsKey(PROPERTY_GET_PREFIX + memberName)) // getter property
            {
                return(((SFunction)Members[PROPERTY_GET_PREFIX + memberName].Data).Call(processor, this, this, new SObject[] { }));
            }
            else if (Members.ContainsKey(memberName))
            {
                return(Members[memberName]);
            }
            else if (Prototype != null && Prototype.HasMember(processor, memberName))
            {
                return(Prototype.GetMember(processor, accessor, isIndexer));
            }
            else if (SuperClass != null)
            {
                return(SuperClass.GetMember(processor, accessor, isIndexer));
            }

            return(processor.Undefined);
        }
        private IEnumerable <string> physicalPathsOf(IEnumerable <AutoBundleItem> autoBundleItems, HashSet <string> excludedFiles)
        {
            var baseUrl = Path.Combine(ProjectPath, "Scripts");

            foreach (var item in autoBundleItems)
            {
                // check if the file path is actually an URL
                if (!string.IsNullOrEmpty(item.File) && !item.File.Contains("?"))
                {
                    item.File = ScriptProcessor.ExpandPaths(item.File, Configuration);

                    if (!excludedFiles.Contains(item.File))
                    {
                        var physicalPath = this.ResolvePhysicalPath(item.File, baseUrl);
                        if (physicalPath == null)
                        {
                            Log?.LogError($"Could not to resolve path for {item.File}. File does not exist in {baseUrl}! Did you forget to include it in the project?");
                        }
                        yield return(physicalPath);
                    }
                    else
                    {
                        Log?.LogMessage(LogLevel, $"    - EXCLUDING {item.File}");
                    }
                }
                else if (!string.IsNullOrEmpty(item.Directory))
                {
                    item.Directory = ScriptProcessor.ExpandPaths(item.Directory, Configuration);

                    var absDirectory = this.GetAbsoluteDirectory(item.Directory);
                    Log?.LogMessage(LogLevel, $"    - Directory '{item.Directory}' -> {absDirectory}");

                    // not using filter for this since we're going to use the one the user provided in the future
                    var dirFiles = Directory.GetFiles(absDirectory, "*", SearchOption.AllDirectories).Where(r => Path.GetExtension(r) == ".js").ToList();
                    foreach (var file in dirFiles)
                    {
#warning We try to match absolute paths here while we match relative paths above?!
                        if (!excludedFiles.Contains(file))
                        {
                            yield return(file);
                        }
                        else
                        {
                            Log?.LogMessage(LogLevel, $"    - EXCLUDING {file} from {item.Directory}");
                        }
                    }
                }
            }
        }
Exemple #35
0
        private static SObject constructor(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var obj = (SNumber)instance;

            if (parameters[0] is SNumber)
            {
                obj.Value = ((SNumber)parameters[0]).Value;
            }
            else
            {
                obj.Value = parameters[0].ToNumber(processor).Value;
            }

            return(obj);
        }
Exemple #36
0
        internal static string IncrementOperator(ScriptProcessor processor, SObject obj)
        {
            // Only variables can be incremented:

            var variable = obj as SVariable;

            if (variable != null)
            {
                var svar = variable;
                svar.Data = processor.CreateNumber(svar.Data.ToNumber(processor).Value + 1D);
                return(svar.Identifier);
            }
            processor.ErrorHandler.ThrowError(ErrorType.SyntaxError, ErrorHandler.MessageSyntaxInvalidIncrement);
            return("");
        }
Exemple #37
0
        /// <summary>
        /// Multiplies an object with -1.
        /// </summary>
        internal static SObject NegateNumber(ScriptProcessor processor, SObject obj)
        {
            double number;

            if (obj is SNumber)
            {
                number = ((SNumber)obj).Value;
            }
            else
            {
                number = obj.ToNumber(processor).Value;
            }

            return(processor.CreateNumber(number * -1));
        }
    public static void Main(string[] args)
    {
        int totalTests  = 0;
        int passedTests = 0;
        var goodScripts = Directory.GetFiles("test-scripts", "T*");

        foreach (var script in goodScripts)
        {
            var pass = true;
            Console.Write(script + ":");
            try {
                var scriptParser = new ScriptProcessor(new StreamReader(File.OpenRead(script)), new VendingMachineFactory());
                scriptParser.Parse();
            }
            catch {
                pass = false;
            }
            Console.WriteLine(pass ? " PASS=Good" : " FAIL=Bad");
            if (pass)
            {
                passedTests++;
            }
            totalTests++;
        }
        var badScripts = Directory.GetFiles("test-scripts", "U*");

        foreach (var script in badScripts)
        {
            var pass = true;
            Console.Write(script + ":");
            try {
                var scriptParser = new ScriptProcessor(new StreamReader(File.OpenRead(script)), new VendingMachineFactory());
                scriptParser.Parse();
            }
            catch {
                pass = false;
            }
            Console.WriteLine(pass ? " PASS=Bad" : " FAIL=Good");
            if (!pass)
            {
                passedTests++;
            }
            totalTests++;
        }

        Console.WriteLine("{0}/{1} tests passed", passedTests, totalTests);
        Console.ReadLine();
    }
Exemple #39
0
        private static Tuple<double, double> GetNumericOperatorParameters(ScriptProcessor processor, SObject left, SObject right)
        {
            double numLeft, numRight;

            if (left is SNumber)
                numLeft = ((SNumber)left).Value;
            else
                numLeft = left.ToNumber(processor).Value;

            if (right is SNumber)
                numRight = ((SNumber)right).Value;
            else
                numRight = right.ToNumber(processor).Value;

            return new Tuple<double, double>(numLeft, numRight);
        }
Exemple #40
0
        public void ServerScriptValidate()
        {
            IDataScripter scripter = new VueDataScripter(_host, _localizer);
            var           sp       = new ScriptProcessor(scripter, _host);
            var           ssi      = new ServerScriptInfo()
            {
                DataModel = _dbContext.LoadModel(null, "a2test.[Document.Load]"),
                Template  = "document.template",
                Path      = "document/server",
                RawData   = "{Document: {Id:173}}",
                Parameter = new { Id = 123, Text = "ParamText" }
            };
            var result = sp.ValidateModel(ssi);

            Assert.IsNull(result);
        }
Exemple #41
0
        private static Tuple<bool, bool> GetBooleanicOperatorParameters(ScriptProcessor processor, SObject left, SObject right)
        {
            bool boolLeft, boolRight;

            if (left is SBool)
                boolLeft = ((SBool)left).Value;
            else
                boolLeft = left.ToBool(processor).Value;

            if (right is SBool)
                boolRight = ((SBool)right).Value;
            else
                boolRight = right.ToBool(processor).Value;

            return new Tuple<bool, bool>(boolLeft, boolRight);
        }
Exemple #42
0
        private static void InitializePrototypeBuffer()
        {
            // load all defined prototypes once to store them in a buffer.
            // these prototypes get added to all newly created ScriptProcessors.

            _prototypeBuffer = new List <SObject>();
            var processor = new ScriptProcessor();

            foreach (var assembly in GetSourceAssemblies())
            {
                foreach (var t in assembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(ScriptPrototypeAttribute), true).Length > 0))
                {
                    _prototypeBuffer.Add(ScriptInAdapter.Translate(processor, t));
                }
            }
        }
Exemple #43
0
 internal override bool HasMember(ScriptProcessor processor, string memberName)
 {
     if (Members.ContainsKey(memberName))
     {
         return(true);
     }
     else if (Prototype != null && Prototype.HasMember(processor, memberName))
     {
         return(true);
     }
     else if (SuperClass != null)
     {
         return(SuperClass.HasMember(processor, memberName));
     }
     return(false);
 }
Exemple #44
0
        private static SObject ExecuteMethod(ScriptProcessor processor, string className, string methodName, SObject[] parameters)
        {
            if (_apiClasses.ContainsKey(className))
            {
                var method = _apiClasses[className].FirstOrDefault(m => m.Name == methodName);

                if (method != null)
                {
                    var result = method.Invoke(null, new object[] { processor, parameters });
                    return((SObject)result);
                }
            }

            // fallback, in case no class/method was found:
            return(ScriptInAdapter.GetUndefined(processor));
        }
Exemple #45
0
        internal override bool HasMember(ScriptProcessor processor, string memberName)
        {
            if (processor.Context.HasCallback(CallbackType.HasMember))
            {
                var callback = (DHasMember)processor.Context.GetCallback(CallbackType.HasMember);
                var task = Task<bool>.Factory.StartNew(() => callback(processor, ModuleName, memberName));
                task.Wait();

                return task.Result;
            }
            else
            {
                // If no API callback function is added to check for member existence, then we just assume that no member exists and return false.
                return false;
            }
        }
Exemple #46
0
        public static SObject load(ScriptProcessor processor, SObject[] parameters)
        {
            object[] netObjects;
            if (EnsureTypeContract(parameters, new[] { typeof(string), typeof(Vector3Wrapper) }, out netObjects))
            {
                var screen = (OverworldScreen)GameProvider.GameInstance.GetService <ScreenManager>().CurrentScreen;

                var position = netObjects[1] as Vector3Wrapper;
                if (position != null)
                {
                    screen.ActiveWorld.LoadMap(netObjects[0] as string, position.X, position.Y, position.Z);
                }
            }

            return(ScriptInAdapter.GetUndefined(processor));
        }
Exemple #47
0
        internal override SObject ExecuteMethod(ScriptProcessor processor, string methodName, SObject caller, SObject This, SObject[] parameters)
        {
            if (processor.Context.HasCallback(CallbackType.ExecuteMethod))
            {
                var callback = (DExecuteMethod)processor.Context.GetCallback(CallbackType.ExecuteMethod);
                var task = Task<SObject>.Factory.StartNew(() => callback(processor, ModuleName, methodName, parameters));
                task.Wait();

                return task.Result;
            }
            else
            {
                processor.ErrorHandler.ThrowError(ErrorType.APIError, ErrorHandler.MESSAGE_API_NOT_SUPPORTED);
                return processor.Undefined;
            }
        }
Exemple #48
0
        internal override SObject GetMember(ScriptProcessor processor, SObject accessor, bool isIndexer)
        {
            if (processor.Context.HasCallback(CallbackType.GetMember))
            {
                var callback = (DGetMember)processor.Context.GetCallback(CallbackType.GetMember);
                var task = Task<SObject>.Factory.StartNew(() => callback(processor, ModuleName, accessor, isIndexer));
                task.Wait();

                return task.Result;
            }
            else
            {
                processor.ErrorHandler.ThrowError(ErrorType.APIError, ErrorHandler.MESSAGE_API_NOT_SUPPORTED);
                return processor.Undefined;
            }
        }
Exemple #49
0
 internal override bool HasMember(ScriptProcessor processor, string memberName)
 {
     if (Members.ContainsKey(memberName))
     {
         return true;
     }
     else if (Prototype != null && Prototype.HasMember(processor, memberName))
     {
         return true;
     }
     else if (SuperClass != null)
     {
         return SuperClass.HasMember(processor, memberName);
     }
     return false;
 }
Exemple #50
0
        public static SObject Pop(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var arr = (SArray)instance;

            if (arr.ArrayMembers.Length > 0)
            {
                var newItems   = new SObject[arr.ArrayMembers.Length - 1];
                var returnItem = arr.ArrayMembers.Last();
                Array.Copy(arr.ArrayMembers, newItems, arr.ArrayMembers.Length - 1);
                arr.ArrayMembers = newItems;

                return(returnItem);
            }

            return(processor.Undefined);
        }
Exemple #51
0
        internal static string DecrementOperator(ScriptProcessor processor, SObject obj)
        {
            // Only variables can be decremented:

            if (obj is SVariable)
            {
                var svar = (SVariable)obj;
                svar.Data = processor.CreateNumber(svar.Data.ToNumber(processor).Value - 1D);
                return(svar.Identifier);
            }
            else
            {
                processor.ErrorHandler.ThrowError(ErrorType.SyntaxError, ErrorHandler.MESSAGE_SYNTAX_INVALID_DECREMENT);
                return("");
            }
        }
Exemple #52
0
        private static SObject constructor(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var obj = (SString)instance;

            if (parameters[0] is SString)
            {
                obj.Value   = ((SString)parameters[0]).Value;
                obj.Escaped = ((SString)parameters[0]).Escaped;
            }
            else
            {
                obj.Value = parameters[0].ToString(processor).Value;
            }

            return(obj);
        }
        internal override SObject GetMember(ScriptProcessor processor, SObject accessor, bool isIndexer)
        {
            string memberName;
            if (accessor is SString)
                memberName = ((SString)accessor).Value;
            else
                memberName = accessor.ToString(processor).Value;

            if (_context.IsVariable(memberName))
            {
                return _context.GetVariable(memberName);
            }
            else
            {
                return processor.ErrorHandler.ThrowError(ErrorType.ReferenceError, ErrorHandler.MESSAGE_REFERENCE_NOT_DEFINED, new object[] { memberName });
            }
        }
Exemple #54
0
        public static SObject IndexerGet(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var arr = (SArray)instance;

            if (parameters.Length >= 1)
            {
                var accessor = (int)parameters[0].ToNumber(processor).Value;

                if (accessor >= 0 && accessor < arr.ArrayMembers.Length)
                {
                    return arr.ArrayMembers[accessor] ??
                            processor.Undefined;
                }
            }

            return processor.Undefined;
        }
        internal override void SetMember(ScriptProcessor processor, SObject accessor, bool isIndexer, SObject value)
        {
            string memberName;
            if (accessor is SString)
                memberName = ((SString)accessor).Value;
            else
                memberName = accessor.ToString(processor).Value;

            if (_context.IsVariable(memberName))
            {
                _context.GetVariable(memberName).Data = value;
            }
            else
            {
                processor.ErrorHandler.ThrowError(ErrorType.ReferenceError, ErrorHandler.MESSAGE_REFERENCE_NOT_DEFINED, memberName );
            }
        }
Exemple #56
0
        public static SObject Concat(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            if (parameters.Length > 0)
            {
                var str = instance as SString;

                string result = str.Value;
                foreach (var param in parameters)
                {
                    string concatStr = param.ToString(processor).Value;
                    result += concatStr;
                }

                return processor.CreateString(result);
            }

            return processor.CreateString((instance as SString).Value);
        }
Exemple #57
0
        internal override SObject GetMember(ScriptProcessor processor, SObject accessor, bool isIndexer)
        {
            InitializeStatic();

            string memberName;
            if (accessor is SString)
                memberName = ((SString)accessor).Value;
            else
                memberName = accessor.ToString(processor).Value;

            if (_prototypeMembers.ContainsKey(memberName))
            {
                return _prototypeMembers[memberName].Data;
            }
            else
            {
                return processor.Undefined;
            }
        }
Exemple #58
0
        /// <summary>
        /// Compares two objects for equality, respecting their typings.
        /// </summary>
        /// <remarks>Used by the === and !== equality operators.</remarks>
        public static bool StrictEquals(ScriptProcessor processor, SObject left, SObject right)
        {
            left = SObject.Unbox(left);
            right = SObject.Unbox(right);

            if (left.TypeOf() != right.TypeOf())
            {
                return false;
            }
            // If they are undefined or null, return true:
            else if (left.TypeOf() == SObject.LITERAL_UNDEFINED || left.TypeOf() == SObject.LITERAL_NULL)
            {
                return true;
            }
            // Both are numbers:
            else if (left.TypeOf() == SObject.LITERAL_TYPE_NUMBER)
            {
                double numLeft = ((SNumber)left).Value;
                double numRight = ((SNumber)right).Value;

                return numLeft == numRight;
            }
            // Both are string:
            else if (left.TypeOf() == SObject.LITERAL_TYPE_STRING)
            {
                string strLeft = ((SString)left).Value;
                string strRight = ((SString)right).Value;

                return strLeft == strRight;
            }
            // Both are bool:
            else if (left.TypeOf() == SObject.LITERAL_TYPE_BOOL)
            {
                bool boolLeft = ((SBool)left).Value;
                bool boolRight = ((SBool)right).Value;

                return boolLeft == boolRight;
            }
            else
            {
                return ReferenceEquals(left, right);
            }
        }
        internal override SObject ExecuteMethod(ScriptProcessor processor, string methodName, SObject caller, SObject This, SObject[] parameters)
        {
            // The statement that entered this method looks like this: this.varName(), where varName is a variable containing an SFunction object.

            if (_context.IsVariable(methodName))
            {
                var methodVariable = _context.GetVariable(methodName);
                var method = methodVariable.Data;

                if (method is SFunction)
                {
                    return ((SFunction)method).Call(processor, caller, This, parameters);
                }
                else
                {
                    return processor.ErrorHandler.ThrowError(ErrorType.TypeError, ErrorHandler.MESSAGE_TYPE_NOT_A_FUNCTION,  methodName );
                }
            }
            return processor.ErrorHandler.ThrowError(ErrorType.ReferenceError, ErrorHandler.MESSAGE_REFERENCE_NOT_DEFINED,  methodName );
        }
Exemple #60
0
        public static SObject CharAt(ScriptProcessor processor, SObject instance, SObject This, SObject[] parameters)
        {
            var str = (instance as SString).Value;

            if (str == "")
                return processor.CreateString("");

            if (TypeContract.Ensure(parameters, typeof(SNumber)))
            {
                var index = (int)(parameters[0] as SNumber).Value;

                if (index < 0 || index >= str.Length)
                    return processor.CreateString("");

                return processor.CreateString(str[index].ToString());
            }
            else
            {
                return processor.CreateString(str[0].ToString());
            }
        }