public void Execute(ArgumentList arguments, TaskList tasklist, TagList tags, TagFolder folder)
 {
     ILister lister = new Lister();
     if (arguments.GetParameter(arguments.GetLength() - 1) == "--export")
         lister = new HtmlLister();
     lister.ListFiltered(tasklist.FilterTasks(arguments.GetParameter(1)), arguments.GetParameter(1));
 }
示例#2
0
        public static void TestPoint(Server server, ISender sender, ArgumentList args)
        {
            string param;
            Player player = server.GetPlayerByName(sender.Name);

            if (args.TryGetString(0, out param))
            {
                switch (param.ToUpper())
                {
                    case "LOBBY":
                        player.sendMessage("Teleporting to the lobby", Login.plugin.chatColor);
                        Login.plugin.TeleportPlayerToPoint(player, Login.LOBBY);
                        break;
                    case "VALIDATED":
                        player.sendMessage("Teleporting to the validated point", Login.plugin.chatColor);
                        Login.plugin.TeleportPlayerToPoint(player, Login.VALIDATED);
                        break;
                    default:
                        player.sendMessage("You must specify either lobby or validated", Login.plugin.chatColor);
                        break;
                }
            }
            else
                player.sendMessage("You must specify either lobby or validated", Login.plugin.chatColor);
        }
        /// <summary>
        /// Teleports specified player to sending player's location.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void TeleportHere(ISender sender, ArgumentList args)
        {
            if (sender is Player)
            {
                Player player = ((Player)sender);
                Player subject;

                if (args.TryPopOne(out subject))
                {
                    if (subject == null)
                    {
                        sender.Message("Cannot find player");
                        return;
                    }

                    subject.Teleport(player);

                    Utils.NotifyAllOps("Teleported " + subject.name + " to " +
                        player.name + " [" + sender.SenderName + "]", true);
                }
            }
            else
            {
                throw new CommandError("This command is for players only");
            }
        }
示例#4
0
        public static void SetPoint(Server server, ISender sender, ArgumentList args)
        {
            string param;
            Player player = server.GetPlayerByName(sender.Name);

            if (args.TryGetString(0, out param))
            {
                switch (param.ToUpper())
                {
                    case "LOBBY":
                        player.PluginData["lobby"] = true;
                        player.sendMessage("Hit a block where you want the lobby to be", Login.plugin.chatColor);
                        break;
                    case "VALIDATED":
                        player.PluginData["validated"] = true;
                        player.sendMessage("Hit a block where you want the validated point to be", Login.plugin.chatColor);
                        break;
                    default:
                        player.sendMessage("You must specify either lobby or validated", Login.plugin.chatColor);
                        break;
                }
            }
            else
                player.sendMessage("You must specify either lobby or validated", Login.plugin.chatColor);
        }
        public static void ExampleCommand(ISender sender, ArgumentList args)
        {
            TDSM_Plugin MyPlugin = (TDSM_Plugin)args.Plugin; //Get the plugin object who's assigned to the "tdsmpluginexample"

            //if the user enters /tdsmpluginexample -test 1, it will retreive the next value '1' and put into 'arg' as an integer.
            int arg;
            if (args.TryParseOne<int>("-test", out arg))
                sender.sendMessage(sender.Name + " Argument: " + arg);
            else
            {
                //For new people to .NET, I would not really expect you to understand everything just yet.
                string platform = Platform.Type.ToString();
                switch (Platform.Type)
                {
                    case Platform.PlatformType.LINUX:
                        platform = "Linux";
                        break;
                    case Platform.PlatformType.MAC:
                        platform = "Mac";
                        break;
                    case Platform.PlatformType.WINDOWS:
                        platform = "Windows";
                        break;
                }

                (sender as Player).sendMessage("TDSM Plugin Example, Running OS: " + platform, ChatColor.DarkGreen);
            }
        }
示例#6
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if ((arguments == null) || (arguments.Count != 2))
            {
                result = Utility.WrongNumberOfArguments(
                    this, 1, arguments, "message");

                return ReturnCode.Error;
            }

            try
            {
                interpreter.Host.WriteResult(ReturnCode.Ok, arguments[1], true);
            }
            catch (Exception exception)
            {
                Log.Error("Script error ", exception);
                result = "Error on command execution " + exception.Message;
            }
            return ReturnCode.Ok;
        }
示例#7
0
        public void Mux(object sender, DoWorkEventArgs e)
        {
            var inputM2TsFlags = _keepM2TsAudio ? null : "--no-audio";
            var inputMkvFlags = _keepM2TsAudio ? "--no-audio" : null;

            var args = new ArgumentList();

            // Chapter file
            args.AddIfAllNonEmpty("--chapters", _inputChaptersPath);

            // Output file
            args.AddAll("-o", _outputMkvPath);

            // Input M2TS file
            args.AddNonEmpty("--no-video", inputM2TsFlags, _inputM2TsPath);

            // If an input chapter file is specified, exclude chapters from the input MKV file
            if (!string.IsNullOrEmpty(_inputChaptersPath))
                args.Add("--no-chapters");

            // Input MKV file
            args.AddNonEmpty(inputMkvFlags, _inputMkvPath);

            Execute(args, sender, e);
        }
        /// <summary>
        /// Heals one or all players.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="message">Message to send</param>
        public void Heal(ISender sender, ArgumentList args)
        {
            Player subject;

            if (args.TryPopOne(out subject))
            {
                subject = sender as Player;
                if (subject == null)
                {
                    sender.Message("Need a heal target");
                    return;
                }

                NetMessage.SendData((int)Packet.HEAL_PLAYER, -1, -1, String.Empty, subject.whoAmI, (float)subject.statLifeMax);
                subject.Message("You have been healed!", Color.Green);
            }
            else if (args.TryPop("-all"))
            {
                foreach (var plr in Main.player)
                {
                    if (plr.active)
                    {
                        NetMessage.SendData((int)Packet.HEAL_PLAYER, -1, -1, String.Empty, plr.whoAmI, (float)plr.statLifeMax);
                        plr.Message("You have been healed!", Color.Green);
                    }
                }
            }
            else if (sender is Player)
            {
                var plr = sender as Player;
                NetMessage.SendData((int)Packet.HEAL_PLAYER, -1, -1, String.Empty, plr.whoAmI, (float)plr.statLifeMax);
                plr.Message("You have been healed!", Color.Green);
            }
            else throw new CommandError("Nobody specified to heal");
        }
示例#9
0
 // bans if ban = true, unbans if ban = false
 public static void ban(String name, String bannedby, bool ban)
 {
     Player player = FindPlayer(name);
     Sender sender = new ConsoleSender();
     ArgumentList command = new ArgumentList();
     command.Add(name);
     if (player != null)
     {
         if (player.Name != null)
         {
             if (ban)
             {
                 Commands.Ban(sender, command);
                 server.sendToOneClient(Packet.PLAYER_BANNED(name), bannedby);
             }
         }
     }
     else
     {
         if (ban)
             server.sendToOneClient(Packet.PLAYER_NOT_FOUND_ERROR(), bannedby);
         else
         {
             Commands.UnBan(sender, command);
             server.sendToOneClient(Packet.PLAYER_UNBANNED(name), bannedby);
         }
     }
 }
        /// <summary>
        /// Refreshes a players area
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void Refresh(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            var player = sender as Player;

            if (player == null)
            {
                sender.Message(255, "This is a player command");
                return;
            }

            if (player.whoAmI < 0)
                return;

            if (!player.Op)
            {
                var diff = DateTime.Now - player.GetLastCostlyCommand();

                if (diff < TimeSpan.FromSeconds(30))
                {
                    sender.Message(255, "You must wait {0:0} more seconds before using this command.", 30.0 - diff.TotalSeconds);
                    return;
                }

                player.SetLastCostlyCommand(DateTime.Now);
            }

            NetMessage.SendTileSquare(player.whoAmI, (int)(player.position.X / 16), (int)(player.position.Y / 16), 32);
        }
示例#11
0
        public static void roll(Server server, ISender sender, ArgumentList args)
        {
            Random random = new Random();
            int result = 0;
            int times = 1;
            int die = 6;

            if (args.Count > 0)
            {
                string[] arg = args[0].Split('d');
                times = Int32.Parse(arg[0]);
                die = Int32.Parse(arg[1]);
            }

            for (int i = 0; i < times; i++)
            {
                result += random.Next(1, die);
            }

            Player player = server.GetPlayerByName(sender.Name);

            if (! player.PluginData.ContainsKey("roll"))
            {
                player.PluginData.Add("roll", result);
            }
            else
            {
                player.PluginData["roll"] = result;
            }

            server.notifyAll(player.Name + " rolled a " + player.PluginData["roll"] + " on " + times.ToString() + "d" + die.ToString(), true);
        }
        /// <summary>
        /// Fast forwards time
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void FastForwardTime(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            Core.TimeFastForwarding = !Core.TimeFastForwarding;
            sender.Message("Time is now " + (Core.TimeFastForwarding ? "fast" : "normal") + "!");
        }
示例#13
0
        void PasswordCommand(ISender sender, ArgumentList args)
        {
            Player player = sender as Player;
                Protection temp = new Protection ();
                Pair<Action, Protection> pair = new Pair<Action, Protection> (Action.NOTHING, null);

                if (args.Count != 1) {
                    player.SendMessage ("Usage: /cpassword <password>", 255, 255, 0, 0);
                    return;
                }

                string Extra = args[0];

                temp = new Protection ();
                temp.Owner = player.Name;
                temp.Type = Protection.PASSWORD_PROTECTION;
                temp.Data = SHA1.Hash (Extra);

                char[] pass = Extra.ToCharArray ();
                for (int index = 0; index < pass.Length; index++) {
                    pass [index] = '*';
                }

                pair.First = Action.CREATE;
                pair.Second = temp;

                player.SendMessage ("Password: "******"Open the chest to protect it!", 255, 0, 255, 0);

            // cache the action if it's not null!
            if (pair.First != Action.NOTHING) {
                ResetActions (player);
                Cache.Actions.Add (player.Name, pair);
            }
        }
        /// <summary>
        /// Prints a player list, Possibly readable by bots.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void List(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            var players = from p in Terraria.Main.player
                                   where p.active && !p.IsOp()
                                   select p.name;
            var ops = from p in Terraria.Main.player
                               where p.active && p.IsOp()
                               select p.name;

            var pn = players.Count();
            var on = ops.Count();

            if (on + pn == 0)
            {
                sender.Message("No players online.");
                return;
            }

            string ps = String.Empty;
            string os = String.Empty;

            if (pn > 0)
                ps = (on > 0 ? " | Players: " : "Players: ") + String.Join(", ", players);

            if (on > 0)
                os = "Ops: " + String.Join(", ", ops);

            sender.SendMessage(string.Concat(os, ps, " (", on + pn, "/", Netplay.MaxConnections, ")"), 255, 255, 240, 20);
        }
示例#15
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if ((arguments == null) || (arguments.Count < 2))
            {
                result = Utility.WrongNumberOfArguments(
                    this, 1, arguments, "command");

                return ReturnCode.Error;
            }

            try
            {
                var processor = new CommandLineProcessor();
                var o = processor.Pharse(arguments.Select(argument => (string) argument).Skip(1).ToArray());
                if (!(o is string) && o is IEnumerable)
                    result = new StringList(o);
                else
                {
                    result = o == null ? "" : new Variant(o).ToString();
                }
            }
            catch (Exception exception)
            {
                Log.Error("Script error ", exception);
                result = "Error on command execution " + exception.Message;
            }
            return ReturnCode.Ok;
        }
        /// <summary>
        /// Enables or disables NPC spawning
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void NPCSpawning(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            Core.StopNPCSpawning = !Core.StopNPCSpawning;
            sender.Message("NPC spawning is now " + (Core.StopNPCSpawning ? "off" : "on") + "!");
        }
        void AddAccount(ISender sender, ArgumentList args)
        {
            if (!Storage.IsAvailable)
                throw new CommandError("No permissions plugin or data plugin is attached");

            var a = 0;
            string name, pass;
            APIAccount acc = null;

            //api addaccount "username" "password"
            if (!args.TryGetString(a++, out name))
                throw new CommandError("Expected username after addaccount");

            if (!args.TryGetString(a++, out pass))
                throw new CommandError("Expected password after username");

            acc = APIAccountManager.FindByName(name);
            if (acc == null)
            {
                acc = APIAccountManager.Create(name, pass);
                if (acc.Id > 0)
                {
                    sender.SendMessage("Successfully created account.", R: 0, B: 0);
                }
                else
                {
                    sender.SendMessage("Failed to create account.", G: 0, B: 0);
                }
            }
            else
            {
                throw new CommandError("Existing API account found by " + name);
            }
        }
示例#18
0
	    internal Object GetArgumentValue(ICommandInterpreter interpreter, ArgumentList args, string[] allArguments)
		{
			object value = null;

			if (IsInterpreter)
				return interpreter;

			if (IsAllArguments)
			{
				args.Clear();
				args.Unnamed.Clear();
				return allArguments;
			}

			foreach (string name in AllNames)
			{
				ArgumentList.Item argitem;
				if (args.TryGetValue(name, out argitem))
				{
					if (Parameter.ParameterType == typeof(string[]))
						value = argitem.Values;
					else if (IsFlag)
					{
						bool result;
						value = (String.IsNullOrEmpty(argitem.Value) || (bool.TryParse(argitem.Value, out result) && result));
					}
					else
						value = argitem.Value;
					args.Remove(name);
				}
			}

			return base.ChangeType(value, Parameter.ParameterType, Required, DefaultValue); 
		}
        /// <summary>
        /// Adds a player or ip (Exception) to the ban list.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public static void Ban(ISender sender, ArgumentList args)
        {
            Player banee;
            string playerName = null;

            if (args.TryGetOnlinePlayer(0, out banee))
            {
                playerName = banee.Name;
                banee.Kick("You have been banned from this Server.");
                Server.BanList.addException(NetPlay.slots[banee.whoAmi].
                        remoteAddress.Split(':')[0]);
            }
            else if(!args.TryGetString(0, out playerName))
            {
                throw new CommandError("A player or IP was expected.");
            }

            Server.BanList.addException(playerName);

            Server.notifyOps(playerName + " has been banned {" + sender.Name + "}", true);
            if (!Server.BanList.Save())
            {
                Server.notifyOps("BanList Failed to Save due to " + sender.Name + "'s command", true);
            }
        }
 //TODO sort commands in alphabetical order.
 /// <summary>
 /// Shuts down an exists.
 /// </summary>
 /// <param name="sender">Sending entity</param>
 /// <param name="args">Arguments sent with command</param>
 public static void Clear(ISender sender, ArgumentList args)
 {
     if (sender is ConsoleSender)
     {
         Console.Clear();
     }
 }
 public static void ExampleCommand(ISender sender, ArgumentList args)
 {
     TDSM_Plugin MyPlugin = (TDSM_Plugin)args.Plugin; //Get the plugin object who's assigned to the "tdsmpluginexample"
     int arg;
     //if the user enters /tdsmpluginexample -test 1, it will retreive the next value '1' and put into 'arg' as an integer.
     if (args.TryParseOne<int>("-test", out arg))
     {
         sender.sendMessage(sender.Name + " Argument: " + arg);
     }
     else
     {
         //For new people, I would not really expect you to understand the following.
         //If needed I can simplify this down...
         string Platform = Terraria_Server.Definitions.Platform.Type.ToString();
         switch (Terraria_Server.Definitions.Platform.Type)
         {
             case Terraria_Server.Definitions.Platform.PlatformType.LINUX:
                 Platform = "Linux";
                 break;
             case Terraria_Server.Definitions.Platform.PlatformType.MAC:
                 Platform = "Mac";
                 break;
             case Terraria_Server.Definitions.Platform.PlatformType.WINDOWS:
                 Platform = "Windows";
                 break;
         }
         (sender as Player).sendMessage("TDSM Plugin Example, Running OS: " + Platform, ChatColor.DarkGreen);
     }
 }
示例#22
0
        public static void InvalidatePlayer(Server server, ISender sender, ArgumentList args)
        {
            string playerName, param;
            Player player = server.GetPlayerByName(sender.Name);

            if (args.TryGetString(0, out playerName))
            {
                if (server.GetPlayerByName(playerName) != null)
                {
                    Login.plugin.SetPlayerInvalid(playerName);
                    SendMessage(player, "You have invalidated " + playerName);
                }
                else
                {
                    if (args.TryGetString(1, out param))
                    {
                        if (param.ToUpper() == "FORCE")
                        {
                            Login.plugin.SetPlayerInvalid(playerName);
                            SendMessage(player, "You have invalidated " + playerName);
                        }
                        else
                            SendMessage(player, "Usage: /invalidate <player> (force)");
                    }
                    else
                    {
                        SendMessage(player, "There is no current player names " + playerName);
                        SendMessage(player, "Use /invalidate <player> force to remove offline players");
                    }
                }
            }
            else
                SendMessage(player, "You must supply a player name");
        }
        /// <summary>
        /// De-OPs a given Player.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public static void DeopPlayer(ISender sender, ArgumentList args)
        {
            var playerName = args.GetString(0);
            Player player;
            if (args.TryGetOnlinePlayer(0, out player))
            {
                playerName = player.Name;

                if (Player.isInOpList(playerName))
                {
                    player.sendMessage("You have been De-Opped!.", ChatColor.Green);
                }

                player.Op = false;
                if (player.HasClientMod)
                {
                    NetMessage.SendData(Packet.CLIENT_MOD, player.whoAmi);
                }
            }

            if (Player.isInOpList(playerName))
            {
                Server.notifyOps("De-Opping " + playerName + " {" + sender.Name + "}", true);
                Server.OpList.removeException(playerName + ":" + Player.GetPlayerPassword(playerName));
            }

            if (!Server.OpList.Save())
            {
                Server.notifyOps("OpList Failed to Save due. {" + sender.Name + "}", true);
                return;
            }
        }
        /// <summary>
        /// Changes the time to dusk
        /// </summary>
        /// <param name="sender">Sending entity</param>
        /// <param name="args">Arguments sent with command</param>
        public static void Dusk(ISender sender, ArgumentList args)
        {
            Main.dayTime = false;
            Main.time = 0.0;
            NetMessage.SendData(7, -1, -1, String.Empty, 0, 0f, 0f, 0f, 0);

            sender.Message("Time set to dusk");
        }
 public AssemblyFileProcessor(ArgumentList args, bool addMissing)
 {
     _args = args;
     _addMissing = addMissing;
     _pattern = new Regex(MatchAttribute, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
     _variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
     _todo = new Dictionary<string, string>(StringComparer.Ordinal);
 }
示例#26
0
 public void Execute(ArgumentList arguments, TaskList tasklist, TagList tags, TagFolder folder)
 {
     FileIO loader = new FileIO();
     if (tasklist.MarkAsDone(arguments.GetParameter(1)))
     loader.SaveTasks(tasklist.GetTasks());
         else
             Console.WriteLine("No task with that id found to mark as done");
 }
示例#27
0
 public void Execute(ArgumentList arguments, TaskList tasks, TagList tags, TagFolder folder)
 {
     FileIO loader = new FileIO();
     TaskTagger tagTasks = new TaskTagger(tasks.GetTasks());
     if (tagTasks.Untag(arguments.GetParameter(1), arguments.GetParameter(2)))
         loader.SaveTasks(tagTasks.GetTasks());
     else
         Console.WriteLine("No task with that id found to untag");
 }
 //TODO sort commands in alphabetical order.
 /// <summary>
 /// Clears the console text.
 /// </summary>
 /// <param name="sender">Sending entity</param>
 /// <param name="args">Arguments sent with command</param>
 public static void Clear(ISender sender, ArgumentList args)
 {
     if (sender is ConsoleSender)
     {
         Console.Clear();
     }
     else
         sender.Message("clear: This is a console only command");
 }
        /// <summary>
        /// Closes the Server all connections.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void Exit(ISender sender, ArgumentList args)
        {
            var accessLevel = Core.Config.ExitAccessLevel;
            if (accessLevel == -1 && sender is Player)
            {
                sender.Message("You cannot perform that action.", 255, 238, 130, 238);
                return;
            }
            else if (!sender.HasAccessLevel((AccessLevel)accessLevel))
            {
                sender.Message("You cannot perform that action.", 255, 238, 130, 238);
                return;
            }

            string message;
            args.TryGetString(0, out message);

            if (String.IsNullOrEmpty(message))
                message = "Server is going down";

            //            args.ParseNone();

            Utils.NotifyAllOps("Exiting on request.");

            if (Netplay.anyClients)
            {
                for (var x = 0; x < Main.player.Length; x++)
                {
                    if (Main.player[x].active)
                    {
                        NetMessage.SendData((int)Packet.DISCONNECT, x, -1, message);

            #if CUSTOM_SOCKETS
                        var rc = Netplay.Clients[x];
                        if (rc != null && rc.Socket != null && rc.Socket is ClientConnection)
                        {
                            (rc.Socket as ClientConnection).Flush();
                        }
            #endif
                    }
                }

                //Prevent further connections
                Terraria.Netplay.Connection.Socket.StopListening();

                //                //Wait for total disconnection
                //                while (Netplay.anyClients)
                //                {
                //                    System.Threading.Thread.Sleep(100);
                //                }
            }

            Terraria.IO.WorldFile.saveWorld(false);
            Terraria.Netplay.disconnect = true;

            throw new OTA.Misc.ExitException(sender.SenderName + " requested that TDSM is to shutdown.");
        }
 //TODO sort commands in alphabetical order.
 /// <summary>
 /// Shuts down an exists.
 /// </summary>
 /// <param name="sender">Sending entity</param>
 /// <param name="args">Arguments sent with command</param>
 public static void Clear(ISender sender, ArgumentList args)
 {
     if (sender is ConsoleSender)
     {
         Console.Clear();
     }
     else
         throw new CommandError("This is a console only command");
 }
示例#31
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    IScriptLocation location = null;

                    code = ScriptOps.GetAndCheckProcedureLocation(
                        interpreter, this, ref location, ref result);

                    if (code == ReturnCode.Ok)
                    {
                        string       procedureName      = this.Name;
                        ArgumentList procedureArguments = this.Arguments;

                        if (procedureArguments != null)
                        {
                            bool hasArgs      = procedureArguments.IsVariadic(true);
                            int  totalArgs    = hasArgs ? procedureArguments.Count - 1 : procedureArguments.Count;
                            int  optionalArgs = procedureArguments.GetOptionalCount();

                            if ((arguments.Count > 0) &&
                                ((((arguments.Count - 1) >= (totalArgs - optionalArgs)) &&
                                  ((arguments.Count - 1) <= totalArgs)) ||
                                 (hasArgs && ((arguments.Count - 1) >= (totalArgs - optionalArgs)))))
                            {
                                ICallFrame frame = null;

                                try
                                {
                                    frame = interpreter.NewProcedureCallFrame(
                                        procedureName, CallFrameFlags.Procedure,
                                        null, this, arguments);

                                    VariableDictionary variables = frame.Variables;

                                    frame.ProcedureArguments = new ArgumentList(arguments[0]);

                                    for (int argumentIndex = 0; argumentIndex < procedureArguments.Count; argumentIndex++)
                                    {
                                        string varName = procedureArguments[argumentIndex].Name;

                                        if (!variables.ContainsKey(varName))
                                        {
                                            ArgumentFlags flags = ArgumentFlags.None;
                                            object        varValue;

                                            if (hasArgs && (argumentIndex == (procedureArguments.Count - 1)))
                                            {
                                                //
                                                // NOTE: This argument is part of an argument list.
                                                //
                                                flags |= ArgumentFlags.ArgumentList;

                                                //
                                                // NOTE: Build the list for the final formal argument value,
                                                //       which consists of all the remaining argument values.
                                                //
                                                ArgumentList argsArguments = new ArgumentList();

                                                for (int argsArgumentIndex = argumentIndex + 1;
                                                     argsArgumentIndex < arguments.Count; argsArgumentIndex++)
                                                {
                                                    //
                                                    // NOTE: Sync up the argument name and flags for use when
                                                    //       debugging (below).
                                                    //
                                                    Argument argsArgument = Argument.GetOrCreate(
                                                        interpreter, arguments[argsArgumentIndex].Flags | flags,
                                                        String.Format("{0}{1}{2}", varName, Characters.Space,
                                                                      argsArguments.Count), arguments[argsArgumentIndex],
                                                        interpreter.HasNoCacheArgument());

                                                    argsArguments.Add(argsArgument);
                                                }

                                                varValue = argsArguments;
                                            }
                                            else
                                            {
                                                if ((argumentIndex + 1) < arguments.Count)
                                                {
                                                    //
                                                    // NOTE: Sync up the argument name for use when
                                                    //       debugging (below) and use the value
                                                    //       supplied by the caller.
                                                    //
                                                    varValue = Argument.GetOrCreate(interpreter,
                                                                                    arguments[argumentIndex + 1].Flags | flags,
                                                                                    varName, arguments[argumentIndex + 1],
                                                                                    interpreter.HasNoCacheArgument());
                                                }
                                                else
                                                {
                                                    //
                                                    // NOTE: We cannot sync up the argument name here
                                                    //       because we are out-of-bounds on that list
                                                    //       and it cannot be extended (i.e. it would
                                                    //       break [info level]); therefore, we punt
                                                    //       on that for now.  Use the default value
                                                    //       for this argument, if any; otherwise, use
                                                    //       an empty string.
                                                    //
                                                    object @default = procedureArguments[argumentIndex].Default;
                                                    varValue = (@default != null) ? @default : Argument.NoValue;
                                                }
                                            }

                                            code = interpreter.SetVariableValue2(VariableFlags.Argument, frame,
                                                                                 varName, varValue, ref result);

                                            if (code != ReturnCode.Ok)
                                            {
                                                break;
                                            }

                                            //
                                            // BUGFIX: Now, also keep track of this argument in the procedure
                                            //         arguments list.  Primarily because we do not want to
                                            //         have to redo this logic later (i.e. for [scope]).
                                            //
                                            frame.ProcedureArguments.Add(Argument.GetOrCreate(
                                                                             interpreter, flags, varName, varValue,
                                                                             interpreter.HasNoCacheArgument()));
                                        }
                                    }

                                    //
                                    // NOTE: Make sure we succeeded in creating the call frame.
                                    //
                                    if (code == ReturnCode.Ok)
                                    {
                                        ICallFrame savedFrame = null;
                                        interpreter.PushProcedureCallFrame(frame, true, ref savedFrame);

                                        try
                                        {
#if DEBUGGER && DEBUGGER_EXECUTE
                                            if (DebuggerOps.CanHitBreakpoints(interpreter,
                                                                              EngineFlags.None, BreakpointType.BeforeProcedureBody))
                                            {
                                                code = interpreter.CheckBreakpoints(
                                                    code, BreakpointType.BeforeProcedureBody, procedureName,
                                                    null, null, this, null, clientData, arguments,
                                                    ref result);
                                            }
#endif

                                            if (code == ReturnCode.Ok)
                                            {
                                                bool locked = false;

                                                try
                                                {
                                                    bool atomic = EntityOps.IsAtomic(this);

                                                    if (atomic)
                                                    {
                                                        interpreter.InternalTryLock(ref locked); /* TRANSACTIONAL */
                                                    }
                                                    if (!atomic || locked)
                                                    {
#if ARGUMENT_CACHE || PARSE_CACHE
                                                        EngineFlags savedEngineFlags = EngineFlags.None;
                                                        bool        nonCaching       = EntityOps.IsNonCaching(this);

                                                        if (nonCaching)
                                                        {
                                                            interpreter.BeginProcedureBodyNoCaching(
                                                                ref savedEngineFlags);
                                                        }

                                                        try
                                                        {
#endif
                                                        string body = this.Body;

                                                        interpreter.ReturnCode = ReturnCode.Ok;

                                                        code = interpreter.EvaluateScript(
                                                            body, location, ref result);
#if ARGUMENT_CACHE || PARSE_CACHE
                                                    }
                                                    finally
                                                    {
                                                        if (nonCaching)
                                                        {
                                                            interpreter.EndProcedureBodyNoCaching(
                                                                ref savedEngineFlags);
                                                        }
                                                    }
#endif
                                                    }
                                                    else
                                                    {
                                                        result = "could not lock interpreter";
                                                        code   = ReturnCode.Error;
                                                    }
                                                }
                                                finally
                                                {
                                                    interpreter.InternalExitLock(ref locked); /* TRANSACTIONAL */
                                                }

#if DEBUGGER && DEBUGGER_EXECUTE
                                                if (DebuggerOps.CanHitBreakpoints(interpreter,
                                                                                  EngineFlags.None, BreakpointType.AfterProcedureBody))
                                                {
                                                    code = interpreter.CheckBreakpoints(
                                                        code, BreakpointType.AfterProcedureBody, procedureName,
                                                        null, null, this, null, clientData, arguments,
                                                        ref result);
                                                }
#endif

                                                //
                                                // BUGFIX: If an opaque object handle is being returned, add
                                                //         a reference to it now.
                                                //
                                                if ((code == ReturnCode.Ok) || (code == ReturnCode.Return))
                                                {
                                                    code = interpreter.AddObjectReference(
                                                        code, result, ObjectReferenceType.Return,
                                                        ref result);
                                                }

                                                if (code == ReturnCode.Return)
                                                {
                                                    code = Engine.UpdateReturnInformation(interpreter);
                                                }
                                                else if (code == ReturnCode.Error)
                                                {
                                                    Engine.AddErrorInformation(interpreter, result,
                                                                               String.Format("{0}    (procedure \"{1}\" line {2})",
                                                                                             Environment.NewLine, FormatOps.Ellipsis(procedureName),
                                                                                             Interpreter.GetErrorLine(interpreter)));
                                                }
                                            }
                                        }
                                        finally
                                        {
                                            /* IGNORED */
                                            interpreter.PopProcedureCallFrame(frame, ref savedFrame);
                                        }
                                    }
                                }
                                finally
                                {
                                    if (frame != null)
                                    {
                                        IDisposable disposable = frame as IDisposable;

                                        if (disposable != null)
                                        {
                                            disposable.Dispose();
                                            disposable = null;
                                        }

                                        frame = null;
                                    }
                                }
                            }
                            else
                            {
                                if (procedureArguments.Count > 0)
                                {
                                    result = String.Format(
                                        "wrong # args: should be \"{0} {1}\"",
                                        Parser.Quote(procedureName),
                                        procedureArguments.ToRawString(ToStringFlags.Decorated,
                                                                       Characters.Space.ToString()));
                                }
                                else
                                {
                                    result = String.Format(
                                        "wrong # args: should be \"{0}\"",
                                        Parser.Quote(procedureName));
                                }

                                code = ReturnCode.Error;
                            }
                        }
                        else
                        {
                            result = "invalid procedure argument list";
                            code   = ReturnCode.Error;
                        }
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
示例#32
0
 public void TestJoinNull()
 {
     ArgumentList.Join(null);
 }
示例#33
0
文件: Wide.cs 项目: jdruin/F5Eagle
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count == (this.Arguments + 1))
                    {
                        Variant variant1 = null;

                        code = Value.GetVariant(interpreter,
                                                (IGetValue)arguments[1], ValueFlags.AnyVariant,
                                                interpreter.CultureInfo, ref variant1, ref error);

                        if (code == ReturnCode.Ok)
                        {
                            try
                            {
                                if (variant1.IsDateTime())
                                {
                                    value = ConversionOps.ToLong((DateTime)variant1.Value);
                                }
                                else if (variant1.IsDouble())
                                {
                                    variant1.Value = Math.Truncate((double)variant1.Value);

                                    if (variant1.ConvertTo(typeof(long)))
                                    {
                                        value = (long)variant1.Value;
                                    }
                                    else
                                    {
                                        error = "wide integer value too large to represent";
                                        code  = ReturnCode.Error;
                                    }
                                }
                                else if (variant1.IsDecimal())
                                {
                                    variant1.Value = Math.Truncate((decimal)variant1.Value);

                                    if (variant1.ConvertTo(typeof(long)))
                                    {
                                        value = (long)variant1.Value;
                                    }
                                    else
                                    {
                                        error = "wide integer value too large to represent";
                                        code  = ReturnCode.Error;
                                    }
                                }
                                else if (variant1.IsWideInteger())
                                {
                                    value = (long)variant1.Value; /* NOP */
                                }
                                else if (variant1.IsInteger())
                                {
                                    value = ConversionOps.ToLong((int)variant1.Value);
                                }
                                else if (variant1.IsBoolean())
                                {
                                    value = ConversionOps.ToLong((bool)variant1.Value);
                                }
                                else
                                {
                                    error = String.Format(
                                        "expected wide integer but got \"{0}\"",
                                        arguments[1]);

                                    code = ReturnCode.Error;
                                }
                            }
                            catch (Exception e)
                            {
                                Engine.SetExceptionErrorCode(interpreter, e);

                                error = String.Format(
                                    "caught math exception: {0}",
                                    e);

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        if (arguments.Count > (this.Arguments + 1))
                        {
                            error = String.Format(
                                "too many arguments for math function \"{0}\"",
                                base.Name);
                        }
                        else
                        {
                            error = String.Format(
                                "too few arguments for math function \"{0}\"",
                                base.Name);
                        }

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
示例#34
0
        ///////////////////////////////////////////////////////////////////////

        #region IDebugger Members
        public void AddInfo(
            StringPairList list,
            DetailFlags detailFlags
            )
        {
            CheckDisposed();

            bool empty = HostOps.HasEmptyContent(detailFlags);

            if (empty || (suspendCount > 0))
            {
                list.Add("SuspendCount", suspendCount.ToString());
            }

            if (empty || Enabled)
            {
                list.Add("Enabled", Enabled.ToString());
            }

            if (empty || (Loops > 0))
            {
                list.Add("Loops", Loops.ToString());
            }

            if (empty || (Active > 0))
            {
                list.Add("Active", Active.ToString());
            }

            if (empty || SingleStep)
            {
                list.Add("SingleStep", SingleStep.ToString());
            }

#if BREAKPOINTS
            if (empty || BreakOnToken)
            {
                list.Add("BreakOnToken", BreakOnToken.ToString());
            }
#endif

            if (empty || BreakOnExecute)
            {
                list.Add("BreakOnExecute", BreakOnExecute.ToString());
            }

            if (empty || BreakOnCancel)
            {
                list.Add("BreakOnCancel", BreakOnCancel.ToString());
            }

            if (empty || BreakOnError)
            {
                list.Add("BreakOnError", BreakOnError.ToString());
            }

            if (empty || BreakOnReturn)
            {
                list.Add("BreakOnReturn", BreakOnReturn.ToString());
            }

            if (empty || BreakOnTest)
            {
                list.Add("BreakOnTest", BreakOnTest.ToString());
            }

            if (empty || BreakOnExit)
            {
                list.Add("BreakOnExit", BreakOnExit.ToString());
            }

            if (empty || (Steps > 0))
            {
                list.Add("Steps", Steps.ToString());
            }

            if (empty || (Types != BreakpointType.None))
            {
                list.Add("Types", Types.ToString());
            }

#if BREAKPOINTS
            BreakpointDictionary breakpoints = Breakpoints;

            if (empty || ((breakpoints != null) && (breakpoints.Count > 0)))
            {
                list.Add("Breakpoints", (breakpoints != null) ?
                         breakpoints.Count.ToString() : FormatOps.DisplayNull);
            }
#endif

#if DEBUGGER_ARGUMENTS
            ArgumentList executeArguments = ExecuteArguments;

            if (empty || (executeArguments != null))
            {
                list.Add("ExecuteArguments", (executeArguments != null) ?
                         executeArguments.ToString(ToStringFlags.NameAndValue,
                                                   null, false) : FormatOps.DisplayNull);
            }
#endif

            if (empty || !String.IsNullOrEmpty(Command))
            {
                list.Add("Command", FormatOps.DisplayString(
                             FormatOps.ReplaceNewLines(FormatOps.NormalizeNewLines(
                                                           Command))));
            }

            if (empty || !String.IsNullOrEmpty(Result))
            {
                list.Add("Result", FormatOps.DisplayString(
                             FormatOps.ReplaceNewLines(FormatOps.NormalizeNewLines(
                                                           Result))));
            }

            QueueList <string, string> queue = Queue;

            if (empty || ((queue != null) && (queue.Count > 0)))
            {
                list.Add("Queue", (queue != null) ?
                         queue.Count.ToString() : FormatOps.DisplayNull);
            }

            StringList callbackArguments = CallbackArguments;

            if (empty || ((callbackArguments != null) &&
                          (callbackArguments.Count > 0)))
            {
                list.Add("CallbackArguments", (callbackArguments != null) ?
                         callbackArguments.ToString() : FormatOps.DisplayNull);
            }

            if (interpreter != null)
            {
                interpreter.GetHostDebuggerInfo(ref list, detailFlags);
            }
            else if (empty)
            {
                list.Add((IPair <string>)null);
                list.Add("Interpreter");
                list.Add((IPair <string>)null);
                list.Add("Id", FormatOps.DisplayNull);
            }
        }
示例#35
0
 public override void Accept(ArgumentList arglist)
 {
     arglist.VisitChildren(this);
 }
 private string NormalTranslate()
 {
     return($"{Expression.Translate()}{ArgumentList.Translate()}");
 }
示例#37
0
文件: ListIn.cs 项目: jdruin/F5Eagle
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    try
                    {
                        string  name     = null;
                        Variant operand1 = null;
                        Variant operand2 = null;

                        code = Value.GetOperandsFromArguments(interpreter,
                                                              this, arguments, ValueFlags.String,
                                                              interpreter.CultureInfo, ref name,
                                                              ref operand1, ref operand2, ref error);

                        if (code == ReturnCode.Ok)
                        {
                            StringList list = null;

                            code = Parser.SplitList(
                                interpreter, (string)operand2.Value, 0,
                                Length.Invalid, true, ref list, ref error);

                            if (code == ReturnCode.Ok)
                            {
                                value = list.Contains((string)operand1.Value);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Engine.SetExceptionErrorCode(interpreter, e);

                        error = String.Format(
                            "caught math exception: {0}",
                            e);

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
示例#38
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    try
                    {
                        string  name     = null;
                        Variant operand1 = null;
                        Variant operand2 = null;

                        code = Value.GetOperandsFromArguments(interpreter,
                                                              this, arguments, ValueFlags.AnyVariant,
                                                              interpreter.CultureInfo, ref name,
                                                              ref operand1, ref operand2, ref error);

                        if (code == ReturnCode.Ok)
                        {
                            code = Value.FixupVariants(
                                this, operand1, operand2, null, null, false, false,
                                ref error);

                            if (code == ReturnCode.Ok)
                            {
                                if (operand1.IsDouble())
                                {
                                    value = Interpreter.FixIntermediatePrecision(
                                        Math.Pow((double)operand1.Value, (double)operand2.Value));
                                }
                                else if (operand1.IsDecimal())
                                {
                                    if (operand1.ConvertTo(typeof(double)))
                                    {
                                        if (operand2.ConvertTo(typeof(double)))
                                        {
                                            value = Interpreter.FixIntermediatePrecision(
                                                Math.Pow((double)operand1.Value, (double)operand2.Value));
                                        }
                                        else
                                        {
                                            error = String.Format(
                                                "could not convert \"{0}\" to double",
                                                operand2.Value);

                                            code = ReturnCode.Error;
                                        }
                                    }
                                    else
                                    {
                                        error = String.Format(
                                            "could not convert \"{0}\" to double",
                                            operand1.Value);

                                        code = ReturnCode.Error;
                                    }
                                }
                                else if (operand1.IsWideInteger())
                                {
                                    value = MathOps.Pow((long)operand1.Value, (long)operand2.Value);
                                }
                                else if (operand1.IsInteger())
                                {
                                    value = MathOps.Pow((int)operand1.Value, (int)operand2.Value);
                                }
                                else if (operand1.IsBoolean())
                                {
                                    value = MathOps.Pow(ConversionOps.ToInt((bool)operand1.Value),
                                                        ConversionOps.ToInt((bool)operand2.Value));
                                }
                                else
                                {
                                    error = String.Format(
                                        "unsupported operand type for operator {0}",
                                        FormatOps.OperatorName(name, this.Lexeme));

                                    code = ReturnCode.Error;
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Engine.SetExceptionErrorCode(interpreter, e);

                        error = String.Format(
                            "caught math exception: {0}",
                            e);

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
示例#39
0
        /// <exception cref="BadSyntaxException">
        /// The <paramref name="declaration"/> does not fit to the syntax.
        /// </exception>
        public override void InitFromString(string declaration)
        {
            Match match = propertyRegex.Match(declaration);

            RaiseChangedEvent = false;

            try {
                if (match.Success)
                {
                    ClearModifiers();
                    ReadAccess  = AccessModifier.Default;
                    WriteAccess = AccessModifier.Default;

                    Group nameGroup      = match.Groups["name"];
                    Group typeGroup      = match.Groups["type"];
                    Group accessGroup    = match.Groups["access"];
                    Group modifierGroup  = match.Groups["modifier"];
                    Group nameDotGroup   = match.Groups["namedot"];
                    Group argsGroup      = match.Groups["args"];
                    Group getGroup       = match.Groups["get"];
                    Group setGroup       = match.Groups["set"];
                    Group getAccessGroup = match.Groups["getaccess"];
                    Group setAccessGroup = match.Groups["setaccess"];

                    ArgumentList.InitFromString(argsGroup.Value);

                    // Validating identifier's name
                    if ((nameGroup.Value != "this" || !HasParameter) &&
                        CSharpLanguage.Instance.IsForbiddenName(nameGroup.Value))
                    {
                        throw new BadSyntaxException(Strings.ErrorInvalidName);
                    }
                    else
                    {
                        ValidName = nameGroup.Value;
                    }

                    // Validating type's name
                    if (CSharpLanguage.Instance.IsForbiddenTypeName(typeGroup.Value))
                    {
                        throw new BadSyntaxException(Strings.ErrorInvalidTypeName);
                    }
                    else
                    {
                        ValidType = typeGroup.Value;
                    }

                    IsExplicitImplementation = nameDotGroup.Success;
                    AccessModifier           = Language.TryParseAccessModifier(accessGroup.Value);
                    IsReadonly  = getGroup.Success && !setGroup.Success;
                    IsWriteonly = !getGroup.Success && setGroup.Success;
                    ReadAccess  = Language.TryParseAccessModifier(getAccessGroup.Value);
                    WriteAccess = Language.TryParseAccessModifier(setAccessGroup.Value);

                    foreach (Capture modifierCapture in modifierGroup.Captures)
                    {
                        if (modifierCapture.Value == "static")
                        {
                            IsStatic = true;
                        }
                        if (modifierCapture.Value == "virtual")
                        {
                            IsVirtual = true;
                        }
                        if (modifierCapture.Value == "abstract")
                        {
                            IsAbstract = true;
                        }
                        if (modifierCapture.Value == "override")
                        {
                            IsOverride = true;
                        }
                        if (modifierCapture.Value == "sealed")
                        {
                            IsSealed = true;
                        }
                        if (modifierCapture.Value == "new")
                        {
                            IsHider = true;
                        }
                    }
                }
                else
                {
                    throw new BadSyntaxException(Strings.ErrorInvalidDeclaration);
                }
            }
            finally {
                RaiseChangedEvent = true;
            }
        }
示例#40
0
 public ProcCall(Location location, DMExpression target, ArgumentList arguments) : base(location)
 {
     _target    = target;
     _arguments = arguments;
 }
示例#41
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if ((arguments.Count == 3) || (arguments.Count == 4))
                    {
                        string  channelId = arguments[1];
                        Channel channel   = interpreter.GetChannel(channelId, ref result);

                        if (channel != null)
                        {
                            long offset = 0;

                            code = Value.GetWideInteger2(
                                (IGetValue)arguments[2], ValueFlags.AnyWideInteger,
                                interpreter.CultureInfo, ref offset, ref result);

                            if (code == ReturnCode.Ok)
                            {
                                SeekOrigin origin = SeekOrigin.Begin;

                                if (arguments.Count >= 4)
                                {
                                    object enumValue = EnumOps.TryParseEnum(
                                        typeof(MapSeekOrigin), arguments[3],
                                        true, true);

                                    if (enumValue is MapSeekOrigin)
                                    {
                                        origin = (SeekOrigin)enumValue;
                                    }
                                    else
                                    {
                                        result = String.Format(
                                            "bad origin \"{0}\": must be start, current, or end",
                                            arguments[3]);

                                        code = ReturnCode.Error;
                                    }
                                }

                                if (code == ReturnCode.Ok)
                                {
                                    try
                                    {
                                        if (channel.CanSeek)
                                        {
                                            channel.Seek(offset, origin);
                                            result = String.Empty;
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "error during seek on \"{0}\": invalid argument",
                                                channelId);

                                            code = ReturnCode.Error;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        Engine.SetExceptionErrorCode(interpreter, e);

                                        result = e;
                                        code   = ReturnCode.Error;
                                    }
                                }
                            }
                        }
                        else
                        {
                            code = ReturnCode.Error;
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"seek channelId offset ?origin?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
        /// <summary>
        /// Summon a Boss
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void SummonBoss(ISender sender, ArgumentList args)
        {
            var    count    = args.GetInt(0);
            var    bossName = args.GetString(1).ToLower();
            Player target;

            if (!args.TryGetOnlinePlayer(2, out target))
            {
                if (sender is Player)
                {
                    target = sender as Player;
                }
                else
                {
                    target = Main.player.Where(x => x.active).Random();
                    if (null == target)
                    {
                        throw new CommandError("No players online");
                    }
                }
            }

            //            int type = -1, type1 = -1;
            //            string name = null;
            var queue = new Queue <Boss>();

            switch (bossName)
            {
            case "wyvern":
                //                    type = 87;
                queue.Enqueue(new Boss()
                {
                    type = 87
                });
                break;

            case "brain":
            case "brain of cthulhu":
                //                    type = 266;
                queue.Enqueue(new Boss()
                {
                    type = 266
                });
                break;

            //                case "crimson mimic":
            //                    type = 474;
            //                    break;
            case "corrupt mimic":
                //                    type = 473;
                queue.Enqueue(new Boss()
                {
                    type = 473
                });
                break;
            //                case "hallowed mimic":
            //                    type = 475;
            //                    break;

            case "duke fishron":
            case "duke":
            case "fishron":
                //                    type = 370;
                queue.Enqueue(new Boss()
                {
                    type = 370
                });
                break;

            case "everscream":
                World.SetTime(16200.0, false);
                //                    type = 344;
                queue.Enqueue(new Boss()
                {
                    type = 344
                });
                break;

            case "eye":
            case "cthulhu":
            case "eye of cthulhu":
                World.SetTime(16200.0, false);
                //                    type = 4;
                queue.Enqueue(new Boss()
                {
                    type = 4
                });
                break;

            case "dutchman":
            case "flying dutchman":
                //                    type = 491;
                queue.Enqueue(new Boss()
                {
                    type = 491
                });
                break;

            case "golem":
                //                    type = 245;
                queue.Enqueue(new Boss()
                {
                    type = 245
                });
                break;

            case "goblin summoner":
                //                    type = 471;
                queue.Enqueue(new Boss()
                {
                    type = 471
                });
                break;

            case "king":
            case "king slime":
                //                    type = 50;
                queue.Enqueue(new Boss()
                {
                    type = 50
                });
                break;

            case "ice golem":
                //                    type = 243;
                queue.Enqueue(new Boss()
                {
                    type = 243
                });
                break;

            case "ice queen":
                World.SetTime(16200.0, false);
                //                    type = 345;
                queue.Enqueue(new Boss()
                {
                    type = 345
                });
                break;

            case "lunatic":
            case "cultist":
            case "lunatic cultist":
                //                    type = 439;
                queue.Enqueue(new Boss()
                {
                    type = 439
                });
                break;

            case "saucer":
            case "martian saucer":
                //                    type = 395;
                queue.Enqueue(new Boss()
                {
                    type = 395
                });
                break;

            case "moon":
            case "moon lord":
                //                    type = 398;
                queue.Enqueue(new Boss()
                {
                    type = 398
                });
                break;

            case "mothron":
                if (!Main.eclipse)
                {
                    throw new CommandError("Mothron can only be spawned during a solar eclipse. See the worldevent command.");
                }
                //                    type = 477;
                queue.Enqueue(new Boss()
                {
                    type = 477
                });
                break;

            case "wood":
            case "mourning wood":
                World.SetTime(16200.0, false);
                //                    type = 325;
                queue.Enqueue(new Boss()
                {
                    type = 325
                });
                break;

            case "paladin":
                //                    type = 290;
                queue.Enqueue(new Boss()
                {
                    type = 290
                });
                break;

            case "captain":
            case "pirate":
            case "pirate captain":
                World.SetTime(16200.0, false);
                //                    type = 216;
                queue.Enqueue(new Boss()
                {
                    type = 216
                });
                break;

            case "plantera":
                //                    type = 262;
                queue.Enqueue(new Boss()
                {
                    type = 262
                });
                break;

            case "pumpking":
                World.SetTime(16200.0, false);
                //                    type = 327;
                queue.Enqueue(new Boss()
                {
                    type = 327
                });
                break;

            case "queen":
            case "queen bee":
                //                    type = 222;
                queue.Enqueue(new Boss()
                {
                    type = 222
                });
                break;

            case "santa":
            case "santa nk1":
            case "santa-nk1":
                World.SetTime(16200.0, false);
                //                    type = 346;
                queue.Enqueue(new Boss()
                {
                    type = 346
                });
                break;

            case "skeletron":
                World.SetTime(16200.0, false);
                //                    type = 35;
                queue.Enqueue(new Boss()
                {
                    type = 35
                });
                break;

            case "prime":
            case "skeletron prime":
                //                    type = 127;
                queue.Enqueue(new Boss()
                {
                    type = 127
                });
                break;

            case "nebula":
            case "nebula pillar":
                //                    type = 507;
                queue.Enqueue(new Boss()
                {
                    type = 507
                });
                break;

            case "solar":
            case "solar pillar":
                //                    type = 517;
                queue.Enqueue(new Boss()
                {
                    type = 517
                });
                break;

            case "stardust":
            case "stardust pillar":
                //                    type = 493;
                queue.Enqueue(new Boss()
                {
                    type = 493
                });
                break;

            case "vortex":
            case "vortex pillar":
                //                    type = 422;
                queue.Enqueue(new Boss()
                {
                    type = 422
                });
                break;

            case "destroyer":
            case "the destroyer":
                World.SetTime(16200.0, false);
                //                    type = 134;
                queue.Enqueue(new Boss()
                {
                    type = 134
                });
                break;

            case "twins":
            case "the twins":
                World.SetTime(16200.0, false);
                //                    type = 125;
                //                    type1 = 126;
                queue.Enqueue(new Boss()
                {
                    type = 125,
                    name = "The Twins"
                });
                queue.Enqueue(new Boss()
                {
                    type   = 126,
                    ignore = true
                });
                break;

            case "eater":
            case "eater of worlds":
                //                    type = 13;
                queue.Enqueue(new Boss()
                {
                    type = 13
                });
                break;

            case "wall":
            case "flesh":
            case "wall of flesh":
                if (Main.wof > 0 && Main.npc[Main.wof].active)
                {
                    throw new CommandError("The Wall Of Flesh is already active");
                }

                if (target.position.Y / 16 < (float)(Main.maxTilesY - 205))     //As per NPC.SpawnWOF
                {
                    throw new CommandError("Player must be in The Underworld to spawn the Eater Of Worlds");
                }

                //                    type = 113;
                queue.Enqueue(new Boss()
                {
                    type = 113
                });
                break;

            case "deathcradle":
                count = 1;
                var items = new int[]
                {
                    87, 266, 473,
                    370, 344, 4,
                    491, 245, 471,
                    50, 243, 345,
                    439, 395, 398,
                    477, 325, 290,
                    216, 262, 327,
                    222, 346, 35,
                    127, 507, 517,
                    493, 422, 134,
                    125, 126, 13
                };
                World.SetTime(16200.0, false);

                foreach (var item in items)
                {
                    queue.Enqueue(new Boss()
                    {
                        type   = item,
                        ignore = true
                    });
                }

                Core._likeABoss = true;
                Tools.NotifyAllPlayers("Easter egg found: Like a boss mini game!", Color.Purple, true);

                break;

            default:
                throw new CommandError("Unknown boss: " + bossName);
            }

            while (count-- > 0)
            {
                while (queue.Count > 0)
                {
                    var boss     = queue.Dequeue();
                    var position = World.GetRandomClearTile(target.position.X / 16f, target.position.Y / 16f);
                    var id       = NPC.NewNPC((int)(position.X * 16f), (int)(position.Y * 16f), boss.type);

                    Main.npc[id].SetDefaults(boss.type);
                    Main.npc[id].SetDefaults(Main.npc[id].name);

                    if (count == 0 && !boss.ignore)
                    {
                        var tms = String.Empty;
                        if (count > 1)
                        {
                            tms = " " + count + " times";
                        }
                        Tools.NotifyAllPlayers((boss.name ?? Main.npc[id].name) + " [" + boss.type + "]" + " summoned by " + sender.SenderName + tms, Color.Purple, true);
                    }
                }
            }
        }
示例#43
0
        public override ReturnCode Execute(Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Result result)
        {
            int lineNumber;

            if (int.TryParse(arguments[1].String, out lineNumber))
            {
                RaiseBreakpointHitEvent(lineNumber);
            }
            else
            {
                //line number not available
                result = "Line number argument is missing. Syntax should be 'breakpoint {lineNumber}'";
                return(ReturnCode.Error);
            }

            return(ReturnCode.Ok);
        }
示例#44
0
        static int Main(string[] raw)
        {
            ArgumentList args = new ArgumentList(raw);

            using (DisposingList dispose = new DisposingList())
                using (Log.AppStart(Environment.CommandLine))
                {
                    if (args.Contains("nologo") == false)
                    {
                        Console.WriteLine("XhtmlValidate.exe");
                        Console.WriteLine("Copyright 2010 by Roger Knapp, Licensed under the Apache License, Version 2.0");
                        Console.WriteLine("");
                    }

                    if ((args.Unnamed.Count == 0) || args.Contains("?") || args.Contains("help"))
                    {
                        return(DoHelp());
                    }

                    try
                    {
                        FileList files = new FileList();
                        files.RecurseFolders = true;
                        foreach (string spec in args.Unnamed)
                        {
                            Uri uri;
                            if (Uri.TryCreate(spec, UriKind.Absolute, out uri) && !(uri.IsFile || uri.IsUnc))
                            {
                                using (WebClient wc = new WebClient())
                                {
                                    TempFile tfile = new TempFile();
                                    dispose.Add(tfile);
                                    wc.DownloadFile(uri, tfile.TempPath);
                                    files.Add(tfile.Info);
                                }
                            }
                            else
                            {
                                files.Add(spec);
                            }
                        }
                        if (files.Count == 0)
                        {
                            return(1 + DoHelp());
                        }

                        XhtmlValidation validator = new XhtmlValidation(XhtmlDTDSpecification.Any);
                        foreach (FileInfo f in files)
                        {
                            validator.Validate(f.FullName);
                        }
                    }
                    catch (ApplicationException ae)
                    {
                        Log.Error(ae);
                        Console.Error.WriteLine();
                        Console.Error.WriteLine(ae.Message);
                        Environment.ExitCode = -1;
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                        Console.Error.WriteLine();
                        Console.Error.WriteLine(e.ToString());
                        Environment.ExitCode = -1;
                    }
                }

            if (args.Contains("wait"))
            {
                Console.WriteLine();
                Console.WriteLine("Press [Enter] to continue...");
                Console.ReadLine();
            }

            return(Environment.ExitCode);
        }
示例#45
0
        public void Test()
        {
            ArgumentList args = new ArgumentList("-test=value", "/Test", "\"/other:value\"");

            Assert.AreEqual(2, args.Count);

            Assert.AreEqual(1, args[0].Count);
            Assert.AreEqual("test", args[0].Name);
            Assert.AreEqual("value", args[1].Value);

            Assert.AreEqual(1, args[1].Count);
            Assert.AreEqual("other", args[1].Name);
            Assert.AreEqual("value", args[1].Value);

            string[] keys = args.Keys;
            Assert.AreEqual(2, keys.Length);
            Assert.AreEqual("other", keys[0]);            //alpha-sorted
            Assert.AreEqual("test", keys[1]);
            Assert.AreEqual(0, new ArgumentList("unnamed").Keys.Length);
            Assert.AreEqual(0, new ArgumentList(/*empty*/).Keys.Length);

            ArgumentList.DefaultComparison = StringComparer.Ordinal;
            Assert.AreEqual(StringComparer.Ordinal, ArgumentList.DefaultComparison);

            ArgumentList.NameDelimeters = new char[] { '=' };
            Assert.AreEqual('=', ArgumentList.NameDelimeters[0]);

            ArgumentList.PrefixChars = new char[] { '/' };
            Assert.AreEqual('/', ArgumentList.PrefixChars[0]);

            args = new ArgumentList("-test=value", "/Test", "\"/other:value\"");
            Assert.AreEqual(2, args.Count);
            Assert.AreEqual(0, args[0].Count);
            Assert.AreEqual("Test", args[0].Name);
            Assert.AreEqual(null, args[1].Value);

            Assert.AreEqual(1, args.Unnamed.Count);
            foreach (string sval in args.Unnamed)
            {
                Assert.AreEqual("-test=value", sval);
            }

            Assert.AreEqual(0, args[1].Count);
            Assert.AreEqual("other:value", args[1].Name);
            Assert.AreEqual(null, args[1].Value);

            args.Unnamed = new string[0];
            Assert.AreEqual(0, args.Unnamed.Count);

            args.Add("other", "value");
            Assert.AreEqual(null, (string)args["Test"]);
            Assert.AreEqual("value", (string)args["other"]);
            Assert.AreEqual("value", (string)args.SafeGet("other"));
            Assert.IsNotNull(args.SafeGet("other-not-existing"));
            Assert.AreEqual(null, (string)args.SafeGet("other-not-existing"));

            string test;

            ArgumentList.Item item;

            args = new ArgumentList();
            Assert.AreEqual(0, args.Count);
            Assert.IsFalse(args.TryGetValue(String.Empty, out item));
            args.Add(String.Empty, null);
            Assert.IsTrue(args.TryGetValue(String.Empty, out item));

            args = new ArgumentList();
            Assert.AreEqual(0, args.Count);
            Assert.IsFalse(args.TryGetValue(String.Empty, out test));
            args.Add(String.Empty, null);
            Assert.IsTrue(args.TryGetValue(String.Empty, out test));

            test = item;
            Assert.IsNull(test);

            string[] testarry = item;
            Assert.IsNotNull(testarry);
            Assert.AreEqual(0, testarry.Length);

            item.Value = "roger";
            Assert.AreEqual("roger", item.Value);
            Assert.AreEqual(1, item.Values.Length);
            Assert.AreEqual("roger", item.Values[0]);

            Assert.Contains("roger", item.ToArray());
            Assert.AreEqual(1, item.ToArray().Length);

            item.AddRange(new string[] { "wuz", "here" });
            Assert.AreEqual(3, item.Values.Length);
            Assert.AreEqual("roger wuz here", String.Join(" ", item));

            item.Values = new string[] { "roger", "was", "here" };
            Assert.AreEqual("roger was here", String.Join(" ", item));

            KeyValuePair <string, string[]> testkv = item;

            Assert.AreEqual(String.Empty, testkv.Key);
            Assert.AreEqual(3, testkv.Value.Length);
            Assert.AreEqual("roger was here", String.Join(" ", testkv.Value));
        }
示例#46
0
文件: Pow.cs 项目: jdruin/F5Eagle
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count == (this.Arguments + 1))
                    {
                        double[] doubleValue = { 0.0, 0.0 };

                        code = Value.GetDouble(
                            (IGetValue)arguments[1], interpreter.CultureInfo,
                            ref doubleValue[0], ref error);

                        if (code == ReturnCode.Ok)
                        {
                            code = Value.GetDouble(
                                (IGetValue)arguments[2], interpreter.CultureInfo,
                                ref doubleValue[1], ref error);
                        }

                        if (code == ReturnCode.Ok)
                        {
                            try
                            {
                                value = Interpreter.FixIntermediatePrecision(
                                    Math.Pow(doubleValue[0], doubleValue[1]));
                            }
                            catch (Exception e)
                            {
                                Engine.SetExceptionErrorCode(interpreter, e);

                                error = String.Format(
                                    "caught math exception: {0}",
                                    e);

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        if (arguments.Count > (this.Arguments + 1))
                        {
                            error = String.Format(
                                "too many arguments for math function \"{0}\"",
                                base.Name);
                        }
                        else
                        {
                            error = String.Format(
                                "too few arguments for math function \"{0}\"",
                                base.Name);
                        }

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
示例#47
0
        /// <summary>
        /// Outputs statistics of the servers performance.
        /// </summary>
        /// <param name="sender">Sending player</param>
        /// <param name="args">Arguments sent with command</param>
        public void ServerStatus(ISender sender, ArgumentList args)
        {
            args.ParseNone();

            var process = System.Diagnostics.Process.GetCurrentProcess();

            sender.Message(String.Format("Virtual memory:  {0:0.0}/{1:0.0}MB",
                                         process.VirtualMemorySize64 / 1024.0 / 1024.0,
                                         process.PeakVirtualMemorySize64 / 1024.0 / 1024.0));
            sender.Message(String.Format("Physical memory: {0:0.0}/{1:0.0}MB",
                                         process.WorkingSet64 / 1024.0 / 1024.0,
                                         process.PeakWorkingSet64 / 1024.0 / 1024.0));
            var time = process.TotalProcessorTime;

            sender.Message(String.Format("Total cpu usage:        {0:0.00}% ({1})",
                                         100.0 * time.TotalMilliseconds / (DateTime.Now - process.StartTime).TotalMilliseconds, time));

            //if (LoadMonitor.LoadLastSecond >= 0)
            //    sender.Message(String.Format("Cpu usage last second:  {0:0.00}%", LoadMonitor.LoadLastSecond));

            //if (LoadMonitor.LoadLastMinute >= 0)
            //    sender.Message(String.Format("Cpu usage last minute:  {0:0.00}%", LoadMonitor.LoadLastMinute));

            //sender.Message(String.Format("Last world update took: {0:0.000}ms (plr: {1:0.0}ms, npc: {2:0.0}ms, proj: {3:0.0}ms, item: {4:0.0}ms, world: {5:0.0}ms, time: {6:0.0}ms, inva: {7:0.0}ms, serv: {8:0.0}ms)",
            //    Program.LastUpdateTime.TotalMilliseconds,
            //    Main.LastPlayerUpdateTime.TotalMilliseconds,
            //    Main.LastNPCUpdateTime.TotalMilliseconds,
            //    Main.LastProjectileUpdateTime.TotalMilliseconds,
            //    Main.LastItemUpdateTime.TotalMilliseconds,
            //    Main.LastWorldUpdateTime.TotalMilliseconds,
            //    Main.LastTimeUpdateTime.TotalMilliseconds,
            //    Main.LastInvasionUpdateTime.TotalMilliseconds,
            //    Main.LastServerUpdateTime.TotalMilliseconds
            //    ));

            var projs  = 0;
            var uprojs = 0;
            var npcs   = 0;
            var unpcs  = 0;
            var items  = 0;

            foreach (var npc in Main.npc)
            {
                if (!npc.active)
                {
                    continue;
                }
                npcs += 1;
                if (!npc.netUpdate)
                {
                    continue;
                }
                unpcs += 1;
            }

            foreach (var proj in Main.projectile)
            {
                if (!proj.active)
                {
                    continue;
                }
                projs += 1;
                if (!proj.netUpdate)
                {
                    continue;
                }
                uprojs += 1;
            }

            foreach (var item in Main.item)
            {
                if (!item.active)
                {
                    continue;
                }
                items += 1;
            }

            sender.Message(String.Format("NPCs: {0}a/{1}u, projectiles: {2}a/{3}u, items: {4}", npcs, unpcs, projs, uprojs, items));
            //long diff = Connection.TotalOutgoingBytesUnbuffered - Connection.TotalOutgoingBytes;
            //sender.Message(String.Format("NPCs: {0}a/{1}u, projectiles: {2}a/{3}u, items: {4}, bytes saved: {5:0.0}K ({6:0.0}%)", npcs, unpcs, projs, uprojs, items, diff, diff * 100.0 / Connection.TotalOutgoingBytesUnbuffered));

            //#if BANDWIDTH_ANALYSIS
            //          var sb = new System.Text.StringBuilder ();
            //          for (int i = 0; i < 255; i++)
            //          {
            //              var p = Networking.Connection.packetsPerMessage [i];
            //              var b = Networking.Connection.bytesPerMessage [i];
            //              if (p > 0)
            //                  sb.AppendFormat ("{0}({1}p, {2}B), ", (Packet)i, p, b);
            //          }
            //
            //          sender.Message (sb.ToString());
            //#endif
        }
示例#48
0
文件: Puts.cs 项目: jdruin/F5Eagle
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        OptionDictionary options = new OptionDictionary(
                            new IOption[] {
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-nonewline", null)
                        });

                        int argumentIndex = Index.Invalid;

                        code = interpreter.GetOptions(options, arguments, 0, 1, Index.Invalid, false, ref argumentIndex, ref result);

                        if (code == ReturnCode.Ok)
                        {
                            if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) >= arguments.Count))
                            {
                                bool newLine = true;

                                if (options.IsPresent("-nonewline"))
                                {
                                    newLine = false;
                                }

                                string channelId = Channel.StdOut;

                                if ((argumentIndex + 1) < arguments.Count)
                                {
                                    channelId = arguments[argumentIndex];
                                }

                                Channel channel = interpreter.GetChannel(channelId, ref result);

                                if (channel != null)
                                {
                                    Encoding encoding = null;

                                    if (interpreter.GetChannelEncoding(channel, ref encoding) == ReturnCode.Ok)
                                    {
                                        string output = arguments[arguments.Count - 1];

                                        try
                                        {
                                            if (channel.IsVirtualOutput)
                                            {
                                                //
                                                // NOTE: The encoding is ignored, because this is directly
                                                //       from the input string, which is already Unicode.
                                                //
                                                channel.AppendVirtualOutput(output);

                                                if (newLine)
                                                {
                                                    channel.AppendVirtualOutput(Channel.NewLine);
                                                }

                                                result = String.Empty;
                                            }
                                            else
                                            {
                                                BinaryWriter binaryWriter = interpreter.GetChannelBinaryWriter(channel);

                                                if (binaryWriter != null)
                                                {
                                                    byte[] bytes = null;

                                                    code = StringOps.GetBytes(
                                                        encoding, output, EncodingType.Binary, ref bytes,
                                                        ref result);

                                                    if (code == ReturnCode.Ok)
                                                    {
                                                        channel.CheckAppend();

#if CONSOLE
                                                        if (channel.IsConsoleStream)
                                                        {
                                                            int offset = 0;
                                                            int count  = bytes.Length;

                                                            while (count > 0)
                                                            {
                                                                int writeCount = Math.Min(
                                                                    count, _Hosts.Console.SafeWriteSize);

                                                                binaryWriter.Write(bytes, offset, writeCount);

                                                                offset += writeCount;
                                                                count  -= writeCount;
                                                            }
                                                        }
                                                        else
#endif
                                                        {
                                                            binaryWriter.Write(bytes);
                                                        }

                                                        if (newLine)
                                                        {
                                                            binaryWriter.Write(Channel.NewLine);
                                                        }

#if MONO || MONO_HACKS
                                                        //
                                                        // HACK: *MONO* As of Mono 2.8.0, it seems that Mono "loses"
                                                        //       output unless a flush is performed right after a
                                                        //       write.  So far, this has only been observed for the
                                                        //       console channels; however, always using flush here
                                                        //       on Mono shouldn't cause too many problems, except a
                                                        //       slight loss in performance.
                                                        //       https://bugzilla.novell.com/show_bug.cgi?id=645193
                                                        //
                                                        if (CommonOps.Runtime.IsMono())
                                                        {
                                                            binaryWriter.Flush(); /* throw */
                                                        }
                                                        else
#endif
                                                        {
                                                            //
                                                            // NOTE: Check if we should automatically flush the channel
                                                            //       after each "logical" write done by this command.
                                                            //
                                                            /* IGNORED */
                                                            channel.CheckAutoFlush();
                                                        }

                                                        result = String.Empty;
                                                    }
                                                }
                                                else
                                                {
                                                    result = String.Format(
                                                        "failed to get binary writer for channel \"{0}\"",
                                                        channelId);

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Engine.SetExceptionErrorCode(interpreter, e);

                                            result = e;
                                            code   = ReturnCode.Error;
                                        }
                                    }
                                    else
                                    {
                                        result = String.Format(
                                            "failed to get encoding for channel \"{0}\"",
                                            channelId);

                                        code = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    code = ReturnCode.Error;
                                }
                            }
                            else
                            {
                                if ((argumentIndex != Index.Invalid) &&
                                    Option.LooksLikeOption(arguments[argumentIndex]))
                                {
                                    result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"puts ?-nonewline? ?channelId? string\"";
                                }

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"puts ?-nonewline? ?channelId? string\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
示例#49
0
 public void TestParseNull()
 {
     ArgumentList.Parse(null);
 }
示例#50
0
        void WhitelistMan(ISender sender, ArgumentList args)
        {
            var    index = 0;
            var    cmd = args.GetString(index++);
            string name, ip;

            switch (cmd)
            {
            case "status":
            case "current":
            case "?":
                sender.Message("The whitelist is currently " + (Core.Config.WhitelistEnabled ? "enabled" : "disabled"));
                break;

            case "reload":
                Core.Whitelist.Load();
                Utils.NotifyAllOps("The whitelist was reloaded");
                break;

            case "enable":
                if (!Core.Config.WhitelistEnabled)
                {
                    Core.Config.WhitelistEnabled = true;

                    if (!ConfigUpdater.IsAvailable || ConfigUpdater.Set("whitelist", Core.Config.WhitelistEnabled))
                    {
                        Utils.NotifyAllOps("The whitelist was enabled");
                    }
                    else
                    {
                        sender.Message("Failed to save to config, whitelist is only enabled this session.", Color.Red);
                    }
                }
                else
                {
                    sender.Message("The whitelist is already enabled", Color.Red);
                }
                break;

            case "disable":
                if (Core.Config.WhitelistEnabled)
                {
                    Core.Config.WhitelistEnabled = false;

                    if (!ConfigUpdater.IsAvailable || ConfigUpdater.Set("whitelist", Core.Config.WhitelistEnabled))
                    {
                        Utils.NotifyAllOps("The whitelist was disabled");
                    }
                    else
                    {
                        sender.Message("Failed to save to config, whitelist is only disabled this session.", Color.Red);
                    }
                }
                else
                {
                    sender.Message("The whitelist is already disabled", Color.Red);
                }
                break;

            case "addplayer":
                if (!args.TryGetString(index++, out name))
                {
                    throw new CommandError("Expected player name after [addplayer]");
                }

                var addName = Prefix_WhitelistName + name;
                if (Core.Whitelist.Add(addName))
                {
                    Utils.NotifyAllOps(String.Format("Player {0} was added to the whitelist", name));

                    if (!Core.Config.WhitelistEnabled)
                    {
                        sender.Message("Note, the whitelist is not enabled", Color.Orange);
                    }
                }
                else
                {
                    sender.Message("Failed to add " + name + " to the whitelist", Color.Red);
                }
                break;

            case "removeplayer":
                if (!args.TryGetString(index++, out name))
                {
                    throw new CommandError("Expected player name after [removeplayer]");
                }

                var removeName = Prefix_WhitelistName + name;
                if (Core.Whitelist.Remove(removeName))
                {
                    Utils.NotifyAllOps(String.Format("Player {0} was removed from the whitelist", name));

                    if (!Core.Config.WhitelistEnabled)
                    {
                        sender.Message("Note, the whitelist is not enabled", Color.Orange);
                    }
                }
                else
                {
                    sender.Message("Failed to remove " + name + " from the whitelist", Color.Red);
                }
                break;

            case "addip":
                if (!args.TryGetString(index++, out ip))
                {
                    throw new CommandError("Expected IP after [addip]");
                }

                var addIP = Prefix_WhitelistIp + ip;
                if (Core.Whitelist.Add(addIP))
                {
                    Utils.NotifyAllOps(String.Format("IP {0} was added to the whitelist", ip));

                    if (!Core.Config.WhitelistEnabled)
                    {
                        sender.Message("Note, the whitelist is not enabled", Color.Orange);
                    }
                }
                else
                {
                    sender.Message("Failed to add " + ip + " to the whitelist", Color.Red);
                }
                break;

            case "removeip":
                if (!args.TryGetString(index++, out ip))
                {
                    throw new CommandError("Expected IP after [removeip]");
                }

                var removeIP = Prefix_WhitelistIp + ip;
                if (Core.Whitelist.Remove(removeIP))
                {
                    Utils.NotifyAllOps(String.Format("IP {0} was removed from the whitelist", ip));

                    if (!Core.Config.WhitelistEnabled)
                    {
                        sender.Message("Note, the whitelist is not enabled", Color.Orange);
                    }
                }
                else
                {
                    sender.Message("Failed to remove " + ip + " from the whitelist", Color.Red);
                }
                break;

            default:
                throw new CommandError("Unknown whitelist command: " + cmd);
            }
        }
示例#51
0
文件: Unsetf.cs 项目: jdruin/F5Eagle
        ///////////////////////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        VariableFlags flags = VariableFlags.None;

                        object enumValue = EnumOps.TryParseFlagsEnum(
                            interpreter, typeof(VariableFlags),
                            flags.ToString(), arguments[1],
                            interpreter.CultureInfo, true, true,
                            true, ref result);

                        if (enumValue is VariableFlags)
                        {
                            flags = (VariableFlags)enumValue;

                            if (arguments.Count > 2)
                            {
                                for (int argumentIndex = 2;
                                     argumentIndex < arguments.Count;
                                     argumentIndex++)
                                {
                                    if (interpreter.UnsetVariable(flags,
                                                                  arguments[argumentIndex],
                                                                  ref result) != ReturnCode.Ok)
                                    {
                                        return(ReturnCode.Error);
                                    }
                                }

                                result = String.Empty;
                                return(ReturnCode.Ok);
                            }

                            //
                            // NOTE: Do nothing if no more arguments supplied,
                            //       so as to match command documentation
                            //       (COMPAT: Tcl).
                            //
                            result = String.Empty;
                            return(ReturnCode.Ok);
                        }
                        else
                        {
                            return(ReturnCode.Error);
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"unsetf varFlags ?varName varName ...?\"";
                        return(ReturnCode.Error);
                    }
                }
                else
                {
                    result = "invalid argument list";
                    return(ReturnCode.Error);
                }
            }
            else
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }
        }
示例#52
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            if (interpreter == null)
            {
                error = "invalid interpreter";
                return(ReturnCode.Error);
            }

            if (arguments == null)
            {
                error = "invalid argument list";
                return(ReturnCode.Error);
            }

            string localName = (arguments.Count > 0) ?
                               (string)arguments[0] : this.Name;

            if (arguments.Count != (this.Operands + 1))
            {
                if (ExpressionParser.IsOperatorNameOnly(localName))
                {
                    error = String.Format(InfixSyntaxError,
                                          FormatOps.OperatorName(localName),
                                          Characters.Colon);
                }
                else
                {
                    error = String.Format(PrefixSyntaxError,
                                          FormatOps.OperatorName(localName));
                }

                return(ReturnCode.Error);
            }

            string errorInfo   = "{0}    (\"if\" expression)";
            Result localResult = null; /* REUSED */

            if (interpreter.EvaluateExpressionWithErrorInfo(
                    arguments[1], errorInfo,
                    ref localResult) != ReturnCode.Ok)
            {
                error = localResult;
                return(ReturnCode.Error);
            }

            bool boolValue = false;

            if (Engine.ToBoolean(
                    localResult, interpreter.CultureInfo,
                    ref boolValue, ref localResult) != ReturnCode.Ok)
            {
                error = localResult;
                return(ReturnCode.Error);
            }

            if (boolValue)
            {
                errorInfo   = "{0}    (\"then\" expression)";
                localResult = null;

                if (interpreter.EvaluateExpressionWithErrorInfo(
                        arguments[2], errorInfo,
                        ref localResult) == ReturnCode.Ok)
                {
                    value = localResult;
                    return(ReturnCode.Ok);
                }
                else
                {
                    error = localResult;
                    return(ReturnCode.Error);
                }
            }
            else
            {
                errorInfo   = "{0}    (\"else\" expression)";
                localResult = null;

                if (interpreter.EvaluateExpressionWithErrorInfo(
                        arguments[3], errorInfo,
                        ref localResult) == ReturnCode.Ok)
                {
                    value = localResult;
                    return(ReturnCode.Ok);
                }
                else
                {
                    error = localResult;
                    return(ReturnCode.Error);
                }
            }
        }
示例#53
0
        ///////////////////////////////////////////////////////////////////////

        #region INotify Members
        public override ReturnCode Notify(
            Interpreter interpreter,
            IScriptEventArgs eventArgs,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            //
            // NOTE: If we are disabled -OR- there are no event arguments -OR-
            //       this event does not match the kind we are interested in
            //       then just return "success" now.
            //
            if (disabled || (eventArgs == null) ||
                !FlagOps.HasFlags(
                    eventArgs.NotifyTypes, NotifyType.Engine, false) ||
                !FlagOps.HasFlags(
                    eventArgs.NotifyFlags, NotifyFlags.Executed, false))
            {
                return(ReturnCode.Ok);
            }

            //
            // NOTE: In "direct" mode, skip [almost] all the tracing ceremony
            //       and just call into Trace.WriteLine().  Otherwise, use the
            //       TraceOps class and all its special handling.  Either way,
            //       figure out the String.Format() arguments ahead of time,
            //       based on our current "normalize" and "ellipsis" settings.
            //
            try
            {
                string arg0 = FormatOps.WrapTraceOrNull(
                    normalizeArguments, ellipsisArguments, quoteArguments,
                    displayArguments, eventArgs.Arguments);

                string arg1 = FormatOps.WrapTraceOrNull(
                    normalizeResult, ellipsisResult, quoteResult,
                    displayResult, eventArgs.Result);

                if (direct)
                {
                    //
                    // NOTE: This is just an extremely thin wrapper around
                    //       the Trace.WriteLine method.
                    //
                    DebugOps.TraceWriteLine(String.Format(
                                                directFormat, arg0, arg1), directCategory);
                }
                else
                {
                    //
                    // NOTE: Use the tracing subsystem.
                    //
                    TraceOps.DebugTrace(String.Format(
                                            normalFormat, arg0, arg1), normalCategory,
                                        TracePriority.EngineDebug);
                }

                return(ReturnCode.Ok);
            }
            catch (Exception e)
            {
                TraceOps.DebugTrace(
                    e, typeof(Trace).Name,
                    TracePriority.EngineError);

                result = e;
                return(ReturnCode.Error);
            }
        }
示例#54
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 4)
                    {
                        lock (interpreter.SyncRoot) /* TRANSACTIONAL */
                        {
                            StringList list = null;

                            code = interpreter.GetListVariableValue(
                                VariableFlags.None, arguments[1], true, false, false, ref list,
                                ref result);

                            if (code == ReturnCode.Ok)
                            {
                                Result       value         = list;
                                int          argumentIndex = 2;                                   // start at first index.
                                int          listIndex     = argumentIndex - 2;
                                StringList[] lists         = new StringList[arguments.Count - 3]; // only count index args.
                                int[]        index         = new int[arguments.Count - 3];

                                do
                                {
                                    if ((value != null) && (value.Value is StringList))
                                    {
                                        lists[listIndex] = (StringList)value.Value;
                                    }
                                    else
                                    {
                                        lists[listIndex] = null;

                                        //
                                        // WARNING: Cannot cache list representation here, the list
                                        //          is modified below.
                                        //
                                        code = Parser.SplitList(
                                            interpreter, value, 0, Length.Invalid,
                                            false, ref lists[listIndex], ref result);

                                        if (code != ReturnCode.Ok)
                                        {
                                            break;
                                        }
                                    }

                                    index[listIndex] = Index.Invalid;

                                    code = Value.GetIndex(
                                        arguments[argumentIndex], lists[listIndex].Count,
                                        ValueFlags.AnyIndex, interpreter.CultureInfo,
                                        ref index[listIndex], ref result);

                                    if (code != ReturnCode.Ok)
                                    {
                                        break;
                                    }

                                    if ((index[listIndex] < 0) ||
                                        (index[listIndex] >= lists[listIndex].Count))
                                    {
                                        result = "list index out of range";
                                        code   = ReturnCode.Error;
                                        break;
                                    }

                                    argumentIndex++;

                                    if ((argumentIndex + 1) >= arguments.Count) // stop just before the value.
                                    {
                                        //
                                        // NOTE: Re-integrate the changes back up to the original list.
                                        //
                                        lists[listIndex][index[listIndex]] = arguments[argumentIndex];

                                        for (; listIndex > 0; listIndex--)
                                        {
                                            lists[listIndex - 1][index[listIndex - 1]] = lists[listIndex].ToString();
                                        }

                                        break;
                                    }

                                    //
                                    // NOTE: Advance to handling the next nested list.
                                    //
                                    value = lists[listIndex][index[listIndex]];
                                    listIndex++;
                                }while (true);

                                if (code == ReturnCode.Ok)
                                {
                                    code = interpreter.SetListVariableValue(
                                        VariableFlags.None, arguments[1],
                                        lists[0], null, ref result);
                                }

                                if (code == ReturnCode.Ok)
                                {
                                    result = lists[0];
                                }
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"lset varName index ?index...? value\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
示例#55
0
 public SuperCallStatement(SourceLocation location, ClassDeclaration parent, ArgumentList argumentList)
     : base(location)
 {
     Parent    = parent;
     Arguments = argumentList;
 }
示例#56
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if ((arguments.Count == 1) || (arguments.Count == 2))
                    {
                        string directory;

                        if (arguments.Count == 2)
                        {
                            directory = arguments[1];
                        }
                        else
                        {
                            directory = PathOps.GetUserDirectory(true);

                            if (directory == null)
                            {
                                result = "failed to get home or profile directory for user";
                                code   = ReturnCode.Error;
                            }
                        }

                        if (code == ReturnCode.Ok)
                        {
                            try
                            {
                                directory = PathOps.ResolveFullPath(interpreter, directory);

                                if (!String.IsNullOrEmpty(directory))
                                {
                                    Directory.SetCurrentDirectory(directory);
                                    result = String.Empty;
                                }
                                else
                                {
                                    result = "unrecognized path";
                                    code   = ReturnCode.Error;
                                }
                            }
                            catch (Exception e)
                            {
                                Engine.SetExceptionErrorCode(interpreter, e);

                                result = e;
                                code   = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"cd ?dirName?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
示例#57
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if (interpreter == null)
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }

            if (arguments == null)
            {
                result = "invalid argument list";
                return(ReturnCode.Error);
            }

            if (arguments.Count < 2)
            {
                result = "wrong # args: should be \"variable ?name value...? name ?value?\"";
                return(ReturnCode.Error);
            }

            ICallFrame localFrame = null;

            if (interpreter.GetVariableFrameViaResolvers(
                    LookupFlags.Default, ref localFrame,
                    ref result) != ReturnCode.Ok)
            {
                return(ReturnCode.Error);
            }

            if (localFrame == null)
            {
                result = "local call frame is invalid";
                return(ReturnCode.Error);
            }

            if (!localFrame.IsVariable)
            {
                result = "local call frame does not support variables";
                return(ReturnCode.Error);
            }

            bool       useNamespaces    = interpreter.AreNamespacesEnabled();
            INamespace currentNamespace = null;

            if (useNamespaces &&
                interpreter.GetCurrentNamespaceViaResolvers(
                    null, LookupFlags.Default, ref currentNamespace,
                    ref result) != ReturnCode.Ok)
            {
                return(ReturnCode.Error);
            }

            ICallFrame otherFrame = null;

            if ((currentNamespace != null) &&
                !interpreter.IsGlobalNamespace(currentNamespace))
            {
                otherFrame = currentNamespace.VariableFrame;
            }
            else
            {
                otherFrame = interpreter.CurrentGlobalFrame;
            }

            for (int argumentIndex = 1;
                 argumentIndex < arguments.Count;
                 argumentIndex += 2)
            {
                string varName = arguments[argumentIndex];

                lock (interpreter.SyncRoot) /* TRANSACTIONAL */
                {
                    VariableFlags flags = VariableFlags.NoElement;

                    if (!useNamespaces)
                    {
                        flags |= VariableFlags.GlobalOnly;
                    }

                    IVariable otherVariable = null;
                    Result    error         = null;

                    if (interpreter.GetVariableViaResolversWithSplit(
                            varName, ref flags, ref otherVariable,
                            ref error) != ReturnCode.Ok)
                    {
                        if (FlagOps.HasFlags(
                                flags, VariableFlags.NotFound, true))
                        {
                            error = null;

                            if (interpreter.AddVariable2(
                                    VariableFlags.Undefined | flags,
                                    varName, null, true, ref otherVariable,
                                    ref error) != ReturnCode.Ok)
                            {
                                result = error;
                                return(ReturnCode.Error);
                            }
                        }
                        else
                        {
                            //
                            // NOTE: We did not search for the variable, let
                            //       the caller know why.
                            //
                            result = error;
                            return(ReturnCode.Error);
                        }
                    }

                    //
                    // NOTE: Create the variable link between the local frame
                    //       (i.e. a procedure, etc) and the other frame (i.e.
                    //       namespace or global).
                    //
                    if (CallFrameOps.IsLocal(localFrame))
                    {
                        error = null;

                        if (ScriptOps.LinkVariable(
                                interpreter, localFrame, varName, otherFrame,
                                varName, ref error) != ReturnCode.Ok)
                        {
                            result = error;
                            return(ReturnCode.Error);
                        }
                    }

                    //
                    // NOTE: If they provided a value, set it now.
                    //
                    // BUGFIX: This must be done after setting up the link
                    //         and not before; otherwise, the LinkVariable
                    //         method will detect a defined variable with
                    //         the same name in the local call frame and
                    //         refuse to overwrite it (by design).
                    //
                    if ((argumentIndex + 1) < arguments.Count)
                    {
                        error = null;

                        if (interpreter.SetVariableValue2(
                                VariableFlags.None, otherFrame, varName,
                                null, arguments[argumentIndex + 1].Value, null,
                                ref otherVariable, ref error) != ReturnCode.Ok)
                        {
                            result = error;
                            return(ReturnCode.Error);
                        }
                    }
                }
            }

            result = String.Empty;
            return(ReturnCode.Ok);
        }
示例#58
0
        ///////////////////////////////////////////////////////////////////////

        #region INotify Members (Required)
        /// <summary>
        /// Receives notifications when an event occurs that the plugin has
        /// declared it wants to be notified about.
        /// </summary>
        /// <param name="interpreter">
        /// The interpreter context we are executing in.
        /// </param>
        /// <param name="eventArgs">
        /// Contains data related to the event.  The exact data depends on the
        /// type of event being processed.
        /// </param>
        /// <param name="clientData">
        /// The extra data supplied for this event, if any.
        /// </param>
        /// <param name="result">
        /// Upon success, this may contain an informational message.
        /// Upon failure, this must contain an appropriate error message.
        /// </param>
        /// <returns>
        /// ReturnCode.Ok on success, ReturnCode.Error on failure.
        /// </returns>
        public override ReturnCode Notify(
            Interpreter interpreter,    /* in */
            IScriptEventArgs eventArgs, /* in */
            IClientData clientData,     /* in */
            ArgumentList arguments,     /* in */
            ref Result result           /* out */
            )
        {
            ReturnCode code = ReturnCode.Ok;

            //
            // NOTE: If there is no data associated with this event, just
            //       return.  We do not know how to handle these types of
            //       events and nothing else should be done.  The best advice
            //       when implementing this interface is "when in doubt, just
            //       do nothing".
            //
            if (eventArgs == null)
            {
                return(code);
            }

            //
            // NOTE: Make sure that notification matches the types and flags
            //       that we care about.  In theory, this should be handled
            //       by the core library before we get called; however, it
            //       cannot really hurt to double check.
            //
            if (!Utility.HasFlags(
                    eventArgs.NotifyTypes, NotifyType.Script, true) ||
                !Utility.HasFlags(
                    eventArgs.NotifyFlags, NotifyFlags.Completed, true))
            {
                return(code);
            }

#if false
            //
            // NOTE: This is the interpreter involved in the event, which may
            //       be different from the interpreter context we are executing
            //       in.  This example does not make use of this interpreter;
            //       therefore, this code block is commented out.
            //
            /* NOT USED */
            Interpreter eventInterpreter = eventArgs.Interpreter;

            if (eventInterpreter == null)
            {
                return(code);
            }
#endif

            //
            // NOTE: Grab the extra data associated with this "event" now.  The
            //       exact contents will vary depending on the event type being
            //       serviced.  The source code associated with the event type
            //       in question should be consulted to determine the necessary
            //       type conversion(s).
            //
            IClientData eventClientData = eventArgs.ClientData;

            if (eventClientData == null)
            {
                return(code);
            }

            //
            // NOTE: In this case, the data associated with the event is an
            //       "object list".  If the data does not conform to that type,
            //       bail out now.
            //
            IList <object> list = eventClientData.Data as IList <object>;

            if (list == null)
            {
                return(code);
            }

            //
            // NOTE: Attempt to fetch the text of the script that was just
            //       completed.
            //
            string text;

            try
            {
                //
                // NOTE: The third element should contain the full text of the
                //       completed script.
                //
                text = list[2] as string;

                if (text != null)
                {
                    //
                    // NOTE: The third and fourth elements should contain the
                    //       offset and number of characters for the completed
                    //       script, respectively.
                    //
                    text = text.Substring((int)list[3], (int)list[4]);
                }
            }
            catch
            {
                //
                // NOTE: Somehow, the data does not conform to expectations for
                //       this event type.  Gracefully ignore it.
                //
                text = null;
            }

            //
            // NOTE: To display the text of the completed script, both the
            //       interpreter and the text itself is required.
            //
            if ((interpreter != null) && (text != null))
            {
                //
                // NOTE: Grab the host from the interpreter context we are
                //       executing in.
                //
                IInteractiveHost interactiveHost = interpreter.Host;

                if (interactiveHost != null)
                {
                    //
                    // NOTE: Emit a message to the interpreter host that
                    //       includes the full text of the completed script.
                    //
                    interactiveHost.WriteLine(String.Format(
                                                  "{0}: script completed{1}{2}", GetType().FullName,
                                                  Environment.NewLine, text));
                }
            }

            return(code);
        }
示例#59
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count == (this.Arguments + 1))
                    {
                        Variant variant1 = null;

                        code = Value.GetVariant(interpreter,
                                                (IGetValue)arguments[1], ValueFlags.AnyVariant,
                                                interpreter.CultureInfo, ref variant1, ref error);

                        int intValue = 0;

                        if (code == ReturnCode.Ok)
                        {
                            code = Value.GetInteger2(
                                (IGetValue)arguments[2], ValueFlags.AnyInteger,
                                interpreter.CultureInfo, ref intValue,
                                ref error);
                        }

                        if (code == ReturnCode.Ok)
                        {
                            try
                            {
                                if (variant1.IsDouble())
                                {
                                    //
                                    // NOTE: No FixPrecision, Already rounding.
                                    //
                                    value = Math.Round((double)variant1.Value, intValue);
                                }
                                else if (variant1.IsDecimal())
                                {
                                    //
                                    // NOTE: No FixPrecision, Already rounding.
                                    //
                                    value = Math.Round((decimal)variant1.Value, intValue);
                                }
                                else if (variant1.IsWideInteger())
                                {
                                    value = ((long)variant1.Value);
                                }
                                else if (variant1.IsInteger())
                                {
                                    value = ((int)variant1.Value);
                                }
                                else if (variant1.IsBoolean())
                                {
                                    value = ((bool)variant1.Value);
                                }
                                else
                                {
                                    error = String.Format(
                                        "unsupported variant type for function \"{0}\"",
                                        base.Name);

                                    code = ReturnCode.Error;
                                }
                            }
                            catch (Exception e)
                            {
                                Engine.SetExceptionErrorCode(interpreter, e);

                                error = String.Format(
                                    "caught math exception: {0}",
                                    e);

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        if (arguments.Count > (this.Arguments + 1))
                        {
                            error = String.Format(
                                "too many arguments for math function \"{0}\"",
                                base.Name);
                        }
                        else
                        {
                            error = String.Format(
                                "too few arguments for math function \"{0}\"",
                                base.Name);
                        }

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
示例#60
0
文件: Lsearch.cs 项目: jdruin/F5Eagle
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        OptionDictionary options = new OptionDictionary(
                            new IOption[] {
                            new Option(null, OptionFlags.None, 1, Index.Invalid, "-ascii", null),
                            new Option(null, OptionFlags.None, 1, Index.Invalid, "-dictionary", null),
                            new Option(null, OptionFlags.None, 1, Index.Invalid, "-integer", null),
                            new Option(null, OptionFlags.None, 1, Index.Invalid, "-real", null),
                            new Option(null, OptionFlags.None, 2, Index.Invalid, "-decreasing", null),
                            new Option(null, OptionFlags.None, 2, Index.Invalid, "-increasing", null),
                            new Option(null, OptionFlags.None, 3, Index.Invalid, "-exact", null),
                            new Option(null, OptionFlags.None, 3, Index.Invalid, "-substring", null),
                            new Option(null, OptionFlags.None, 3, Index.Invalid, "-glob", null),
                            new Option(null, OptionFlags.None, 3, Index.Invalid, "-regexp", null),
                            new Option(null, OptionFlags.None, 3, Index.Invalid, "-sorted", null), // NOTE: Implies "-exact"
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-variable", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-inverse", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-subindices", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-all", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-inline", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-nocase", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-not", null),
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-start", null),
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-index", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                        });

                        int argumentIndex = Index.Invalid;

                        code = interpreter.GetOptions(options, arguments, 0, 1, Index.Invalid, false, ref argumentIndex, ref result);

                        if (code == ReturnCode.Ok)
                        {
                            if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) == arguments.Count))
                            {
                                StringList list = null;

                                ///////////////////////////////////////////////////////////////////////
                                //
                                // HACK: *PERF* This option enables an optimization that allows us to
                                //       use the cached list representation for a particular script
                                //       variable, if any, instead of re-parsing the string.  If this
                                //       option is enabled, the first non-option argument is NOT the
                                //       list to search; rather, it is the variable name containing
                                //       the list to search.
                                //
                                bool isVariable = false;

                                if (options.IsPresent("-variable"))
                                {
                                    isVariable = true;
                                }

                                if (isVariable)
                                {
                                    /* IGNORED */
                                    interpreter.GetListVariableValue(
                                        VariableFlags.None, arguments[argumentIndex], false, true,
                                        true, ref list);
                                }

                                ///////////////////////////////////////////////////////////////////////
                                //
                                // NOTE: If no list representation is available, then parse the first
                                //       non-option argument string into a list.
                                //
                                if (list == null)
                                {
                                    code = Parser.SplitList(
                                        interpreter, arguments[argumentIndex], 0,
                                        Length.Invalid, true, ref list, ref result);
                                }

                                if (code == ReturnCode.Ok)
                                {
                                    Variant value     = null;
                                    string  indexText = null;

                                    if (options.IsPresent("-index", ref value))
                                    {
                                        indexText = value.ToString();
                                    }

                                    bool inverse = false;

                                    if (options.IsPresent("-inverse"))
                                    {
                                        inverse = true;
                                    }

                                    bool subIndexes = false;

                                    if (options.IsPresent("-subindices"))
                                    {
                                        subIndexes = true;
                                    }

                                    if ((indexText != null) || !subIndexes)
                                    {
                                        string start = null;

                                        if (options.IsPresent("-start", ref value))
                                        {
                                            start = value.ToString();
                                        }

                                        int startIndex = Index.Invalid;

                                        if (start != null)
                                        {
                                            code = Value.GetIndex(
                                                start, list.Count, ValueFlags.AnyIndex,
                                                interpreter.CultureInfo, ref startIndex,
                                                ref result);
                                        }

                                        if (code == ReturnCode.Ok)
                                        {
                                            bool all = false;

                                            if (options.IsPresent("-all"))
                                            {
                                                all = true;
                                            }

                                            bool inline = false;

                                            if (options.IsPresent("-inline"))
                                            {
                                                inline = true;
                                            }

                                            if (startIndex < list.Count)
                                            {
                                                if (startIndex < 0)
                                                {
                                                    startIndex = 0;
                                                }

                                                bool ascending = true; // FIXME: PRI 5: Default handling.

                                                if (options.IsPresent("-decreasing"))
                                                {
                                                    ascending = false;
                                                }
                                                else if (options.IsPresent("-increasing"))
                                                {
                                                    ascending = true;
                                                }

                                                MatchMode mode   = StringOps.DefaultMatchMode;
                                                bool      sorted = false;

                                                if (options.IsPresent("-sorted"))
                                                {
                                                    mode   = MatchMode.Exact;
                                                    sorted = true;
                                                }
                                                else if (options.IsPresent("-exact"))
                                                {
                                                    mode = MatchMode.Exact;
                                                }
                                                else if (options.IsPresent("-substring"))
                                                {
                                                    mode = MatchMode.SubString;
                                                }
                                                else if (options.IsPresent("-regexp"))
                                                {
                                                    mode = MatchMode.RegExp;
                                                }
                                                else if (options.IsPresent("-glob"))
                                                {
                                                    mode = MatchMode.Glob;
                                                }

                                                bool noCase = false;

                                                if (options.IsPresent("-nocase"))
                                                {
                                                    noCase = true;
                                                }

                                                bool not = false;

                                                if (options.IsPresent("-not"))
                                                {
                                                    not = true;
                                                }

                                                IntDictionary      duplicates = null;
                                                IComparer <string> comparer   = null;

                                                if (options.IsPresent("-exact") || options.IsPresent("-sorted"))
                                                {
                                                    if (options.IsPresent("-dictionary"))
                                                    {
                                                        comparer = new _Comparers.StringDictionaryComparer(
                                                            interpreter, ascending, indexText, true, false,
                                                            interpreter.CultureInfo, ref duplicates);
                                                    }
                                                    else if (options.IsPresent("-integer"))
                                                    {
                                                        comparer = new _Comparers.StringIntegerComparer(
                                                            interpreter, ascending, indexText, true, false,
                                                            interpreter.CultureInfo, ref duplicates);
                                                    }
                                                    else if (options.IsPresent("-real"))
                                                    {
                                                        comparer = new _Comparers.StringRealComparer(
                                                            interpreter, ascending, indexText, true, false,
                                                            interpreter.CultureInfo, ref duplicates);
                                                    }
                                                    else if (options.IsPresent("-ascii") || true) // FIXME: PRI 5: Default handling.
                                                    {
                                                        //
                                                        // NOTE: Check for things that the .NET Framework will not do by
                                                        //       default (via String.Compare).
                                                        //
                                                        if (!ascending || (indexText != null) || noCase)
                                                        {
                                                            comparer = new _Comparers.StringAsciiComparer(
                                                                interpreter, ascending, indexText, true, noCase,
                                                                false, interpreter.CultureInfo, ref duplicates);
                                                        }
                                                    }
                                                }
                                                else if (options.IsPresent("-regexp"))
                                                {
                                                    comparer = new _Comparers.StringRegexpComparer(
                                                        interpreter, ascending, indexText, true, noCase,
                                                        false, interpreter.CultureInfo, ref duplicates);
                                                }
                                                else if (options.IsPresent("-substring"))
                                                {
                                                    comparer = new _Comparers.StringSubStringComparer(
                                                        interpreter, ascending, indexText, true, noCase,
                                                        false, interpreter.CultureInfo, ref duplicates);
                                                }
                                                else if (options.IsPresent("-glob") || true) // FIXME: PRI 5: Default handling.
                                                {
                                                    comparer = new _Comparers.StringGlobComparer(
                                                        interpreter, ascending, indexText, true, noCase,
                                                        false, interpreter.CultureInfo, ref duplicates);
                                                }

                                                try
                                                {
                                                    string     pattern   = arguments[argumentIndex + 1];
                                                    int        listIndex = Index.Invalid;
                                                    StringList matches   = all ? new StringList() : null;

                                                    if (sorted && ((indexText == null) || (comparer != null)) && !all && !not && !inverse)
                                                    {
                                                        //
                                                        // NOTE: Use the built-in binary search with the selected comparer.
                                                        //
                                                        listIndex = list.BinarySearch(startIndex, list.Count - startIndex, pattern, comparer);

                                                        if (listIndex < 0)
                                                        {
                                                            listIndex = Index.Invalid;
                                                        }
                                                    }
                                                    else if ((comparer != null) || all || not || inverse)
                                                    {
                                                        //
                                                        // NOTE: Some custom handling is required, use the selected comparer
                                                        //       and options.
                                                        //
                                                        for (int searchIndex = startIndex; searchIndex < list.Count; searchIndex++)
                                                        {
                                                            //
                                                            // NOTE: If we have a comparer object, use it; otherwise, use our
                                                            //       fallback matching routine.
                                                            //
                                                            bool match;

                                                            if (inverse)
                                                            {
                                                                if (comparer != null)
                                                                {
                                                                    match = (comparer.Compare(pattern, list[searchIndex]) == 0);
                                                                }
                                                                else
                                                                {
                                                                    match = StringOps.Match(interpreter, mode, pattern, list[searchIndex], noCase);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                if (comparer != null)
                                                                {
                                                                    match = (comparer.Compare(list[searchIndex], pattern) == 0);
                                                                }
                                                                else
                                                                {
                                                                    match = StringOps.Match(interpreter, mode, list[searchIndex], pattern, noCase);
                                                                }
                                                            }

                                                            //
                                                            // NOTE: Do we want to consider this to be a match?
                                                            //
                                                            if ((match && !not) || (!match && not))
                                                            {
                                                                if (all)
                                                                {
                                                                    if (inline)
                                                                    {
                                                                        if (subIndexes)
                                                                        {
                                                                            string subValue = null;

                                                                            code = ListOps.SelectFromSubList(
                                                                                interpreter, list[searchIndex], indexText, false,
                                                                                interpreter.CultureInfo, ref subValue, ref result);

                                                                            if (code != ReturnCode.Ok)
                                                                            {
                                                                                break;
                                                                            }

                                                                            matches.Add(subValue);
                                                                        }
                                                                        else
                                                                        {
                                                                            matches.Add(list[searchIndex]);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (subIndexes)
                                                                        {
                                                                            IntList indexList = new IntList(new int[] { searchIndex });

                                                                            code = ListOps.SelectFromSubList(
                                                                                interpreter, list[searchIndex], indexText, false,
                                                                                interpreter.CultureInfo, ref indexList, ref result);

                                                                            if (code != ReturnCode.Ok)
                                                                            {
                                                                                break;
                                                                            }

                                                                            matches.Add(indexList.ToString());
                                                                        }
                                                                        else
                                                                        {
                                                                            matches.Add(searchIndex.ToString());
                                                                        }
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    listIndex = searchIndex;
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //
                                                        // NOTE: No special handling required, use built-in find routine.
                                                        //
                                                        listIndex = list.IndexOf(pattern, startIndex);
                                                    }

                                                    //
                                                    // NOTE: Make sure nothing in the search loop failed.
                                                    //
                                                    if (code == ReturnCode.Ok)
                                                    {
                                                        //
                                                        // NOTE: Handle the result(s) of the search and build the result.
                                                        //
                                                        if (all)
                                                        {
                                                            //
                                                            // NOTE: This may be an empty list.
                                                            //
                                                            result = matches;
                                                        }
                                                        else
                                                        {
                                                            if (listIndex != Index.Invalid)
                                                            {
                                                                //
                                                                // NOTE: Match found, returning index or value, based on
                                                                //       "-inline" option.
                                                                //
                                                                if (inline)
                                                                {
                                                                    result = list[listIndex];
                                                                }
                                                                else
                                                                {
                                                                    if (subIndexes)
                                                                    {
                                                                        IntList indexList = new IntList(new int[] { listIndex });

                                                                        code = ListOps.SelectFromSubList(
                                                                            interpreter, list[listIndex], indexText, false,
                                                                            interpreter.CultureInfo, ref indexList, ref result);

                                                                        if (code == ReturnCode.Ok)
                                                                        {
                                                                            result = indexList.ToString();
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        result = listIndex;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                //
                                                                // NOTE: Match not found, returning invalid index or empty
                                                                //       value, based on "-inline" option.
                                                                //
                                                                if (inline)
                                                                {
                                                                    result = String.Empty;
                                                                }
                                                                else
                                                                {
                                                                    result = Index.Invalid;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    Engine.SetExceptionErrorCode(interpreter, e);

                                                    if (e.InnerException != null)
                                                    {
                                                        result = e.InnerException.Message;
                                                    }
                                                    else if (e is ScriptException)
                                                    {
                                                        result = e.Message;
                                                    }
                                                    else
                                                    {
                                                        result = e;
                                                    }

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                            else
                                            {
                                                if (all || inline)
                                                {
                                                    result = String.Empty;
                                                }
                                                else
                                                {
                                                    result = Index.Invalid;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        result = "-subindices cannot be used without -index option";
                                        code   = ReturnCode.Error;
                                    }
                                }
                            }
                            else
                            {
                                if ((argumentIndex != Index.Invalid) &&
                                    Option.LooksLikeOption(arguments[argumentIndex]))
                                {
                                    result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"lsearch ?options? list pattern\"";
                                }

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"lsearch ?options? list pattern\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }