Пример #1
0
        public static Variable GetVariableFromString(string str, ParsingScript script, int startIndex = 0)
        {
            ParsingScript tempScript = script.GetTempScript(str, startIndex);
            Variable      result     = Utils.GetItem(tempScript);

            return(result);
        }
Пример #2
0
        protected override Variable Evaluate(ParsingScript script)
        {
            // 1. Get the name of the variable.
            string varName = Utils.GetToken(script, Constants.NEXT_ARG_ARRAY);

            Utils.CheckNotEmpty(script, varName, m_name);

            // 2. Get the current value of the variable.
            ParserFunction func         = ParserFunction.GetFunction(varName, script);
            Variable       currentValue = func.GetValue(script);

            // 3. Get the value to be added or appended.
            Variable newValue = Utils.GetItem(script);

            // 4. Take either the string part if it is defined,
            // or the numerical part converted to a string otherwise.
            string arg1 = currentValue.AsString();
            string arg2 = newValue.AsString();

            // 5. The variable becomes a string after adding a string to it.
            newValue.Reset();
            newValue.String = arg1 + arg2;

            ParserFunction.AddGlobalOrLocalVariable(varName, new GetVarFunction(newValue));

            return(newValue);
        }
Пример #3
0
        protected override Parser.Result Evaluate(string data, ref int from)
        {
            // 1. Get the name of the variable.
            string varName = Utils.GetToken(data, ref from, Constants.NEXT_ARG_ARRAY);

            if (from >= data.Length)
            {
                throw new ArgumentException("Couldn't append variable");
            }

            // 2. Get the current value of the variable.
            ParserFunction func = ParserFunction.GetFunction(varName);

            Parser.Result currentValue = func.GetValue(data, ref from);

            // 3. Get the value to be looked for.
            Parser.Result searchValue = Utils.GetItem(data, ref from);

            // 4. Take either the string part if it is defined,
            // or the numerical part converted to a string otherwise.
            string basePart = currentValue.String != null ? currentValue.String :
                              currentValue.Value.ToString();
            string search = searchValue.String != null ? searchValue.String :
                            searchValue.Value.ToString();

            int result = basePart.IndexOf(search);

            return(new Parser.Result(result, null));
        }
Пример #4
0
        protected override Variable Evaluate(ParsingScript script)
        {
            // 1. Get the name of the variable.
            string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY);

            Utils.CheckNotEnd(script, m_name);

            // 2. Get the current value of the variable.
            ParserFunction func = ParserFunction.GetFunction(varName);

            Utils.CheckNotNull(varName, func);
            Variable currentValue = func.GetValue(script);

            Utils.CheckArray(currentValue, varName);

            // 3. Get the variable to remove.
            Variable item = Utils.GetItem(script);

            Utils.CheckNonNegativeInt(item);

            currentValue.Tuple.RemoveAt(item.AsInt());

            ParserFunction.AddGlobalOrLocalVariable(varName,
                                                    new GetVarFunction(currentValue));
            return(Variable.EmptyInstance);
        }
Пример #5
0
        protected override Variable Evaluate(ParsingScript script)
        {
            string        search   = Utils.GetItem(script).AsString();
            List <string> patterns = Utils.GetFunctionArgs(script);

            bool ignoreCase = true;

            if (patterns.Count > 0 && patterns.Last().Equals("case"))
            {
                ignoreCase = false;
                patterns.RemoveAt(patterns.Count - 1);
            }
            if (patterns.Count == 0)
            {
                patterns.Add("*.*");
            }

            List <Variable> results = null;

            try
            {
                string        pwd   = Directory.GetCurrentDirectory();
                List <string> files = Utils.GetStringInFiles(pwd, search, patterns.ToArray(), ignoreCase);

                results = Utils.ConvertToResults(files.ToArray(), true);
            }
            catch (Exception exc)
            {
                throw new ArgumentException("Couldn't find pattern: " + exc.Message);
            }

            return(new Variable(results));
        }
Пример #6
0
        protected override Parser.Result Evaluate(string data, ref int from)
        {
            string processName = Utils.GetItem(data, ref from).String;

            if (string.IsNullOrWhiteSpace(processName))
            {
                throw new ArgumentException("Couldn't extract process name");
            }

            List <string> args      = Utils.GetFunctionArgs(data, ref from);
            int           processId = -1;

            try
            {
                Process pr = Process.Start(processName, string.Join("", args.ToArray()));
                processId = pr.Id;
            }
            catch (System.ComponentModel.Win32Exception exc)
            {
                throw new ArgumentException("Couldn't start [" + processName + "]: " + exc.Message);
            }

            m_interpreter.AppendOutput("Process " + processName + " started, id: " + processId);
            return(new Parser.Result(processId));
        }
Пример #7
0
        protected override Variable Evaluate(ParsingScript script)
        {
            string pathname = Utils.GetItem(script).AsString();

            bool isFile = File.Exists(pathname);
            bool isDir  = Directory.Exists(pathname);

            if (!isFile && !isDir)
            {
                throw new ArgumentException("[" + pathname + "] doesn't exist");
            }
            try
            {
                if (isFile)
                {
                    File.Delete(pathname);
                }
                else
                {
                    Directory.Delete(pathname, true);
                }
            }
            catch (Exception exc)
            {
                throw new ArgumentException("Couldn't delete [" + pathname + "] :" + exc.Message);
            }

            return(Variable.EmptyInstance);
        }
Пример #8
0
        public static List <Variable> GetArgs(string data, ref int from,
                                              char start, char end, out bool isList)
        {
            List <Variable> args = new List <Variable>();

            isList = from < data.Length && data[from] == Constants.START_GROUP;

            if (from >= data.Length || data[from] == Constants.END_STATEMENT)
            {
                return(args);
            }

            int lastChar = from;

            Utils.GetBodyBetween(data, ref lastChar, start, end);

            while (from < lastChar)
            {
                Variable item = Utils.GetItem(data, ref from);
                if (item.Equals(Variable.EmptyInstance))
                {
                    break;
                }

                args.Add(item);
            }


            MoveForwardIf(data, ref from, end, Constants.SPACE);

            return(args);
        }
Пример #9
0
        protected override Variable Evaluate(ParsingScript script)
        {
            // 1. Get the name of the variable.
            string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY);

            Utils.CheckNotEnd(script, Constants.CONTAINS);

            // 2. Get the current value of the variable.
            List <Variable> arrayIndices = Utils.GetArrayIndices(ref varName);

            ParserFunction func = ParserFunction.GetFunction(varName);

            Utils.CheckNotNull(varName, func);
            Variable currentValue = func.GetValue(script);

            // 2b. Special dealings with arrays:
            Variable query = arrayIndices.Count > 0 ?
                             Utils.ExtractArrayElement(currentValue, arrayIndices) :
                             currentValue;

            // 3. Get the value to be looked for.
            Variable searchValue = Utils.GetItem(script);

            Utils.CheckNotEnd(script, Constants.CONTAINS);

            // 4. Check if the value to search for exists.
            bool exists = query.Exists(searchValue, true /* notEmpty */);

            script.MoveBackIf(Constants.START_GROUP);
            return(new Variable(exists));
        }
Пример #10
0
        public static List <string> GetFunctionArgs(string data, ref int from)
        {
            List <string> args     = new List <string>();
            bool          moreArgs = true;

            while (moreArgs)
            {
                moreArgs = Utils.SeparatorExists(data, from);
                Parser.Result item = Utils.GetItem(data, ref from);

                // Separate treatment for an array.
                // Only 1-dimensional arrays are supported at the moment.
                if (item.Tuple != null && item.Tuple.Count > 0)
                {
                    for (int i = 0; i < item.Tuple.Count; i++)
                    {
                        Parser.Result arg = item.Tuple[i];
                        args.Add((arg.String != null ? arg.String : arg.Value.ToString()) + '\n');
                    }
                    continue;
                }

                if (item.String == null && Double.IsNaN(item.Value))
                {
                    break;
                }
                args.Add(item.String != null ? item.String : item.Value.ToString());
            }

            return(args);
        }
Пример #11
0
        protected override Variable Evaluate(ParsingScript script)
        {
            Variable varValue = Utils.GetItem(script);

            // Check if the variable to be set has the form of x[a][b]...,
            // meaning that this is an array element.
            List <Variable> arrayIndices = Utils.GetArrayIndices(ref m_name);

            if (arrayIndices.Count == 0)
            {
                ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue));
                return(varValue);
            }

            Variable array;

            ParserFunction pf = ParserFunction.GetFunction(m_name);

            if (pf != null)
            {
                array = pf.GetValue(script);
            }
            else
            {
                array = new Variable();
            }

            ExtendArray(array, arrayIndices, 0, varValue);

            ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array));
            return(array);
        }
Пример #12
0
        protected override Variable Evaluate(ParsingScript script)
        {
            var objectName = m_processFirstToken ? Utils.GetItem(script).AsString() : "";

            GetParameters(script);

            if (Name.ToUpper() == "MSG")
            {
                string caption  = GetParameter("caption");
                int    duration = GetIntParameter("duration");
                return(new Variable(objectName));
            }
            if (Name.ToUpper() == "DEFINE")
            {
                string   name  = GetParameter("name");
                double   size  = GetIntParameter("size");
                string   type  = GetParameter("type");
                double   value = GetIntParameter("value");
                string   init  = GetParameter("init");
                Variable dup   = GetVariableParameter("dup");
                return(new Variable(objectName));
            }
            if (Name.ToUpper() == "SET_OBJECT")
            {
                string prop = GetParameter("property");
                bool   val  = GetBoolParameter("value");
                return(new Variable(objectName));
            }

            return(new Variable(objectName));
        }
Пример #13
0
        protected override Variable Evaluate(ParsingScript script)
        {
            string pathname = Utils.GetItem(script).AsString();

            bool isFile = File.Exists(pathname);
            bool isDir  = Directory.Exists(pathname);

            if (!isFile && !isDir)
            {
                throw new ArgumentException("[" + pathname + "] doesn't exist");
            }
            bool exists = false;

            try
            {
                if (isFile)
                {
                    exists = File.Exists(pathname);
                }
                else
                {
                    exists = Directory.Exists(pathname);
                }
            }
            catch (Exception exc)
            {
                throw new ArgumentException("Couldn't delete [" + pathname + "] :" + exc.Message);
            }

            return(new Variable(Convert.ToDouble(exists)));
        }
Пример #14
0
        protected override Variable Evaluate(ParsingScript script)
        {
            if (script.Substr().StartsWith(" .."))
            {
                script.Forward();
            }
            string newDir = Utils.GetItem(script).AsString();

            try
            {
                if (newDir == "..")
                {
                    string        pwd    = Directory.GetCurrentDirectory();
                    DirectoryInfo parent = Directory.GetParent(pwd);
                    if (parent == null)
                    {
                        throw new ArgumentException("No parent exists.");
                    }
                    newDir = parent.FullName;
                }
                if (newDir.Length == 0)
                {
                    newDir = Environment.GetEnvironmentVariable("HOME");
                }
                Directory.SetCurrentDirectory(newDir);

                newDir = Directory.GetCurrentDirectory();
            }
            catch (Exception exc)
            {
                throw new ArgumentException("Couldn't change directory: " + exc.Message);
            }

            return(new Variable(newDir));
        }
Пример #15
0
        protected override Parser.Result Evaluate(string data, ref int from)
        {
            // 1. Get the name of the variable.
            string varName = Utils.GetToken(data, ref from, Constants.NEXT_ARG_ARRAY);

            if (from >= data.Length)
            {
                throw new ArgumentException("Couldn't append variable");
            }

            // 2. Get the current value of the variable.
            ParserFunction func = ParserFunction.GetFunction(varName);

            Parser.Result currentValue = func.GetValue(data, ref from);

            // 3. Get the value to be added or appended.
            Parser.Result newValue = Utils.GetItem(data, ref from);

            // 4. Take either the string part if it is defined,
            // or the numerical part converted to a string otherwise.
            string arg1 = currentValue.String != null ? currentValue.String :
                          currentValue.Value.ToString();
            string arg2 = newValue.String != null ? newValue.String :
                          newValue.Value.ToString();

            // 5. The variable becomes a string after adding a string to it.
            newValue.Reset();
            newValue.String = arg1 + arg2;

            ParserFunction.AddFunction(varName, new GetVarFunction(newValue));

            return(newValue);
        }
Пример #16
0
        public static List <Variable> GetArgs(ParsingScript script,
                                              char start, char end, Action <bool> outList)
        {
            List <Variable> args   = new List <Variable>();
            bool            isList = script.StillValid() && script.Current == Constants.START_GROUP;

            if (!script.StillValid() || script.Current == Constants.END_STATEMENT)
            {
                return(args);
            }

            ParsingScript tempScript = script.GetTempScript(script.String, script.Pointer);

            /*ParsingScript tempScript = new ParsingScript(script.String, script.Pointer);
             * tempScript.ParentScript = script;
             * tempScript.InTryBlock = script.InTryBlock;*/

            if (script.Current != start && script.TryPrev() != start &&
                (script.Current == ' ' || script.TryPrev() == ' '))
            { // Allow functions with space separated arguments
                start = ' ';
                end   = Constants.END_STATEMENT;
            }

            // ScriptingEngine - body is unsed (used in Debugging) but GetBodyBetween has sideeffects
#pragma warning disable 219
            string body = Utils.GetBodyBetween(tempScript, start, end);
#pragma warning restore 219
            // After the statement above tempScript.Parent will point to the last
            // character belonging to the body between start and end characters.

            while (script.Pointer < tempScript.Pointer)
            {
                Variable item = Utils.GetItem(script, false);
                args.Add(item);
                if (script.Pointer < tempScript.Pointer)
                {
                    script.MoveForwardIf(Constants.END_GROUP);
                    script.MoveForwardIf(Constants.NEXT_ARG);
                }
                if (script.Pointer == tempScript.Pointer - 1)
                {
                    script.MoveForwardIf(Constants.END_ARG, Constants.END_GROUP);
                }
            }

            if (script.Pointer <= tempScript.Pointer)
            {
                // Eat closing parenthesis, if there is one, but only if it closes
                // the current argument list, not one after it.
                script.MoveForwardIf(Constants.END_ARG, end);
            }

            script.MoveForwardIf(Constants.SPACE);
            //script.MoveForwardIf(Constants.SPACE, Constants.END_STATEMENT);
            outList(isList);
            return(args);
        }
Пример #17
0
        protected override Variable Evaluate(string data, ref int from)
        {
            Variable varValue = Utils.GetItem(data, ref from);

            // Специален случай за добавяне на низ (или число) към низ.

            while (varValue.Type != Variable.VarType.NUMBER &&
                   from > 0 && data[from - 1] == '+')
            {
                Variable addition = Utils.GetItem(data, ref from);
                varValue.String += addition.AsString();
            }

            // Проверете дали променливата, която трябва да бъде настроена, има формата на x (0),
            // означава, че това е масив елемент.
            int arrayIndex = Utils.ExtractArrayElement(ref _name);

            if (arrayIndex < 0)
            {
                ParserFunction.AddGlobalOrLocalVariable(_name, new GetVarFunction(varValue));
                return(varValue);
            }

            Variable currentValue;

            ParserFunction pf = ParserFunction.GetFunction(_name);

            if (pf != null)
            {
                currentValue = pf.GetValue(data, ref from);
            }
            else
            {
                currentValue = new Variable();
            }

            List <Variable> tuple = currentValue.Tuple == null ?
                                    new List <Variable>() :
                                    currentValue.Tuple;

            if (tuple.Count > arrayIndex)
            {
                tuple[arrayIndex] = varValue;
            }
            else
            {
                for (int i = tuple.Count; i < arrayIndex; i++)
                {
                    tuple.Add(Variable.EmptyInstance);
                }
                tuple.Add(varValue);
            }
            currentValue.Tuple = tuple;

            ParserFunction.AddGlobalOrLocalVariable(_name, new GetVarFunction(currentValue));
            return(currentValue);
        }
Пример #18
0
        protected override Variable Evaluate(ParsingScript script)
        {
            string   filename = Utils.GetStringOrVarValue(script);
            Variable line     = Utils.GetItem(script);

            Utils.WriteFileText(filename, line.AsString() + Environment.NewLine);

            return(Variable.EmptyInstance);
        }
Пример #19
0
        protected override Variable Evaluate(ParsingScript script)
        {
            Variable sleepms = Utils.GetItem(script);
            Utils.CheckPosInt(sleepms, script);

            Thread.Sleep((int)sleepms.Value);

            return Variable.EmptyInstance;
        }
Пример #20
0
        protected override Variable Evaluate(ParsingScript script)
        {
            string filename = Utils.GetItem(script).AsString();
            string lines    = Utils.GetLinesFromList(script);

            Utils.AppendFileText(filename, lines);

            return(Variable.EmptyInstance);
        }
Пример #21
0
        protected override Variable Evaluate(ParsingScript script)
        {
            Variable varName = Utils.GetItem(script);

            Utils.CheckNotNull(varName, m_name);

            List <Variable> results = varName.GetAllKeys();

            return(new Variable(results));
        }
Пример #22
0
        protected override Variable Evaluate(ParsingScript script)
        {
            string filename = Utils.GetItem(script).AsString();

            string[] lines = Utils.GetFileLines(filename);

            List <Variable> results = Utils.ConvertToResults(lines);

            return(new Variable(results));
        }
Пример #23
0
        void ProcessArrayFor(ParsingScript script, string forString)
        {
            var    tokens  = forString.Split(' ');
            var    sep     = tokens.Length > 2 ? tokens[1] : "";
            string varName = tokens[0];

            if (sep != Constants.FOR_EACH && sep != Constants.FOR_IN && sep != Constants.FOR_OF)
            {
                int index = forString.IndexOf(Constants.FOR_EACH);
                if (index <= 0 || index == forString.Length - 1)
                {
                    Utils.ThrowErrorMsg("Expecting: for(item :/in/of array)",
                                        script, Constants.FOR);
                }
                varName = forString.Substring(0, index);
            }

            ParsingScript forScript = script.GetTempScript(forString, varName.Length + sep.Length + 1);

            forScript.Debugger = script.Debugger;

            Variable arrayValue = Utils.GetItem(forScript);

            if (arrayValue.Type == Variable.VarType.STRING)
            {
                arrayValue = new Variable(new List <string>(arrayValue.ToString().ToCharArray().Select(c => c.ToString())));
            }

            int cycles = arrayValue.Count;

            if (cycles == 0)
            {
                SkipBlock(script);
                return;
            }
            int startForCondition = script.Pointer;

            for (int i = 0; i < cycles; i++)
            {
                script.Pointer = startForCondition;
                Variable current = arrayValue.GetValue(i);
                ParserFunction.AddGlobalOrLocalVariable(varName,
                                                        new GetVarFunction(current));
                Variable result = ProcessBlock(script);
                if (result.IsReturn || result.Type == Variable.VarType.BREAK)
                {
                    //script.Pointer = startForCondition;
                    //SkipBlock(script);
                    //return;
                    break;
                }
            }
            script.Pointer = startForCondition;
            SkipBlock(script);
        }
Пример #24
0
        protected override Variable Evaluate(ParsingScript script)
        {
            Variable portRes = Utils.GetItem(script);

            Utils.CheckPosInt(portRes, script);
            int port = (int)portRes.Value;

            try
            {
                IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddress     = ipHostInfo.AddressList[0];
                IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, port);

                Socket listener = new Socket(AddressFamily.InterNetwork,
                                             SocketType.Stream, ProtocolType.Tcp);

                listener.Bind(localEndPoint);
                listener.Listen(10);

                Socket handler = null;
                while (true)
                {
                    Interpreter.Instance.AppendOutput("Waiting for connections on " + port + " ...", true);
                    handler = listener.Accept();

                    // Data buffer for incoming data.
                    byte[] bytes    = new byte[1024];
                    int    bytesRec = handler.Receive(bytes);
                    string received = Encoding.UTF8.GetString(bytes, 0, bytesRec);

                    Interpreter.Instance.AppendOutput("Received from " + handler.RemoteEndPoint.ToString() +
                                                      ": [" + received + "]", true);

                    byte[] msg = Encoding.UTF8.GetBytes(received);
                    handler.Send(msg);

                    if (received.Contains("<EOF>"))
                    {
                        break;
                    }
                }

                if (handler != null)
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception exc)
            {
                throw new ArgumentException("Couldn't start server: (" + exc.Message + ")");
            }

            return(Variable.EmptyInstance);
        }
Пример #25
0
        protected override Variable Evaluate(string data, ref int from)
        {
            Utils.MoveForwardIf(data, ref from, Constants.SPACE);

            Variable result = Utils.GetItem(data, ref from);

            // Ако сме в завръщането, ние сме готови:
            from = data.Length;

            return(result);
        }
Пример #26
0
 void GetParameters(ParsingScript script)
 {
     m_parameters = new Dictionary <string, Variable>();
     while (script.Current != Constants.END_STATEMENT)
     {
         var labelName = Utils.GetToken(script, Constants.TOKEN_SEPARATION);
         var value     = script.Current == Constants.END_STATEMENT ? Variable.EmptyInstance :
                         Utils.GetItem(script, false);
         m_parameters[labelName.ToLower()] = value;
     }
 }
Пример #27
0
        protected override Variable Evaluate(ParsingScript script)
        {
            // 1. Extract what to throw.
            Variable arg = Utils.GetItem(script);

            // 2. Convert it to a string.
            string result = arg.AsString();

            // 3. Throw it!
            throw new ArgumentException(result);
        }
Пример #28
0
        protected override Variable Evaluate(ParsingScript script)
        {
            string varName = Utils.GetToken(script, Constants.NEXT_ARG_ARRAY);
            Utils.CheckNotEmpty(script, varName, m_name);

            Variable varValue = Utils.GetItem(script);
            string strValue = varValue.AsString();
            Environment.SetEnvironmentVariable(varName, strValue);

            return new Variable(varName);
        }
Пример #29
0
        protected override Variable Evaluate(ParsingScript script)
        {
            string pattern = Utils.GetItem(script).String;

            if (string.IsNullOrWhiteSpace(pattern))
            {
                throw new ArgumentException("Couldn't extract process name");
            }

            int MAX_PROC_NAME = 26;

            Interpreter.Instance.AppendOutput(Utils.GetLine(), true);
            Interpreter.Instance.AppendOutput(String.Format("{0} {1} {2} {3} {4} {5}",
                                                            "Process Id".PadRight(15), "Process Name".PadRight(MAX_PROC_NAME),
                                                            "Working Set".PadRight(15), "Virt Mem".PadRight(15),
                                                            "Start Time".PadRight(15), "CPU Time".PadRight(25)), true);

            Process[]       processes = Process.GetProcessesByName(pattern);
            List <Variable> results   = new List <Variable>(processes.Length);

            for (int i = 0; i < processes.Length; i++)
            {
                Process pr         = processes[i];
                int     workingSet = (int)(((double)pr.WorkingSet64) / 1000000.0);
                int     virtMemory = (int)(((double)pr.VirtualMemorySize64) / 1000000.0);
                string  procTitle  = pr.ProcessName + " " + pr.MainWindowTitle.Split(null)[0];
                string  startTime  = pr.StartTime.ToString();
                if (procTitle.Length > MAX_PROC_NAME)
                {
                    procTitle = procTitle.Substring(0, MAX_PROC_NAME);
                }
                string procTime = string.Empty;
                try
                {
                    procTime = pr.TotalProcessorTime.ToString().Substring(0, 11);
                }
                catch (Exception) { }

                results.Add(new Variable(
                                string.Format("{0,15} {1," + MAX_PROC_NAME + "} {2,15} {3,15} {4,15} {5,25}",
                                              pr.Id, procTitle,
                                              workingSet, virtMemory, startTime, procTime)));
                Interpreter.Instance.AppendOutput(results.Last().String, true);
            }
            Interpreter.Instance.AppendOutput(Utils.GetLine(), true);

            if (script.TryCurrent() == Constants.NEXT_ARG)
            {
                script.Forward(); // eat end of statement semicolon
            }

            return(new Variable(results));
        }
Пример #30
0
        protected override Variable Evaluate(ParsingScript script)
        {
            script.MoveForwardIf(Constants.SPACE);

            Variable result = Utils.GetItem(script);

            // If we are in Return, we are done:
            script.SetDone();
            result.IsReturn = true;

            return(result);
        }