Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/console/src/core/CommandExecutor.cc @ 1424

Last change on this file since 1424 was 1424, checked in by landauf, 17 years ago

finally got a good approach for the CommandExecutor parser. more to come.

File size: 25.0 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29#include "CommandExecutor.h"
30#include "ConsoleCommand.h"
31#include "util/String.h"
32#include "util/Convert.h"
33#include "Identifier.h"
34#include "Language.h"
35#include "Debug.h"
36#include "TclBind.h"
37
38namespace orxonox
39{
40    CommandExecutor& CommandExecutor::getInstance()
41    {
42        static CommandExecutor instance;
43        return instance;
44    }
45
46    CommandEvaluation& CommandExecutor::getEvaluation()
47    {
48        return CommandExecutor::getInstance().evaluation_;
49    }
50
51    const CommandEvaluation& CommandExecutor::getLastEvaluation()
52    {
53        return CommandExecutor::getInstance().evaluation_;
54    }
55
56    ConsoleCommand& CommandExecutor::addConsoleCommandShortcut(ConsoleCommand* command)
57    {
58        std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandShortcuts_.find(command->getName());
59        if (it != CommandExecutor::getInstance().consoleCommandShortcuts_.end())
60        {
61            COUT(2) << "Warning: Overwriting console-command shortcut with name " << command->getName() << "." << std::endl;
62        }
63
64
65        CommandExecutor::getInstance().consoleCommandShortcuts_[command->getName()] = command;
66        CommandExecutor::getInstance().consoleCommandShortcuts_LC_[getLowercase(command->getName())] = command;
67        return (*command);
68    }
69
70    /**
71        @brief Returns the executor of a console command shortcut with given name.
72        @brief name The name of the requested console command shortcut
73        @return The executor of the requested console command shortcut
74    */
75    ConsoleCommand* CommandExecutor::getConsoleCommandShortcut(const std::string& name)
76    {
77        std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandShortcuts_.find(name);
78        if (it != CommandExecutor::getInstance().consoleCommandShortcuts_.end())
79            return (*it).second;
80        else
81            return 0;
82    }
83
84    /**
85        @brief Returns the executor of a console command shortcut with given name in lowercase.
86        @brief name The name of the requested console command shortcut in lowercase
87        @return The executor of the requested console command shortcut
88    */
89    ConsoleCommand* CommandExecutor::getLowercaseConsoleCommandShortcut(const std::string& name)
90    {
91        std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getInstance().consoleCommandShortcuts_LC_.find(name);
92        if (it != CommandExecutor::getInstance().consoleCommandShortcuts_LC_.end())
93            return (*it).second;
94        else
95            return 0;
96    }
97
98    bool CommandExecutor::execute(const std::string& command, bool useTcl)
99    {
100        if (useTcl)
101            return TclBind::eval(command);
102
103        CommandExecutor::parseIfNeeded(command);
104        return CommandExecutor::getEvaluation().execute();
105    }
106
107    std::string CommandExecutor::complete(const std::string& command)
108    {
109        CommandExecutor::parseIfNeeded(command);
110        return CommandExecutor::getEvaluation().complete();
111    }
112
113    std::string CommandExecutor::hint(const std::string& command)
114    {
115        CommandExecutor::parseIfNeeded(command);
116        return CommandExecutor::getEvaluation().hint();
117    }
118
119    CommandEvaluation CommandExecutor::evaluate(const std::string& command)
120    {
121        CommandExecutor::parse(command);
122        CommandExecutor::getEvaluation().evaluateParams();
123        return CommandExecutor::getEvaluation();
124    }
125
126    void CommandExecutor::parseIfNeeded(const std::string& command)
127    {
128        if (CommandExecutor::getEvaluation().state_ == CS_Uninitialized)
129        {
130            CommandExecutor::parse(command);
131        }
132        else if (CommandExecutor::getEvaluation().originalCommand_ != command)
133        {
134            if (CommandExecutor::getEvaluation().command_ == command)
135            {
136                CommandExecutor::parse(command);
137                CommandExecutor::getEvaluation().bNewCommand_ = false;
138            }
139            else
140            {
141                CommandExecutor::parse(command);
142            }
143        }
144    }
145
146    void CommandExecutor::parse(const std::string& command, bool bInitialize)
147    {
148std::cout << "parse: command: >" << command << "<" << std::endl;
149        if (bInitialize)
150            CommandExecutor::getEvaluation().initialize(command);
151
152        CommandExecutor::getEvaluation().commandTokens_.split(command, " ", SubString::WhiteSpaces, false, '\\', false, '"', false, '(', ')', false, '\0');
153        CommandExecutor::getEvaluation().command_ = command;
154
155        switch (CommandExecutor::getEvaluation().state_)
156        {
157            case CS_Uninitialized:
158            {
159                // Impossible
160                break;
161            }
162            case CS_Empty:
163            {
164                if (CommandExecutor::argumentsGiven() == 0)
165                {
166                    CommandExecutor::createListOfPossibleFunctions("");
167                    CommandExecutor::createListOfPossibleIdentifiers("");
168                    break;
169                }
170                else
171                {
172                    CommandExecutor::getEvaluation().state_ = CS_ShortcutOrIdentifier;
173                    // Move on to next case
174                }
175            }
176            case CS_ShortcutOrIdentifier:
177            {
178                if (CommandExecutor::argumentsGiven() > 1)
179                {
180                    // There's a finished first argument - check if it's a shortcut or a classname
181                    CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(0));
182                    CommandExecutor::getEvaluation().functionclass_ = CommandExecutor::getPossibleIdentifier(CommandExecutor::getArgument(0));
183
184                    if (CommandExecutor::getEvaluation().function_)
185                    {
186                        // It's a shortcut
187                        CommandExecutor::getEvaluation().state_ = CS_Params;
188                        CommandExecutor::getEvaluation().functionclass_ = 0;
189                        // Move on to next case
190                    }
191                    else if (CommandExecutor::getEvaluation().functionclass_)
192                    {
193                        // It's a functionname
194                        CommandExecutor::getEvaluation().state_ = CS_Function;
195                        CommandExecutor::getEvaluation().function_ = 0;
196                        // Move on to next case
197                    }
198                    else
199                    {
200                        // The first argument is bad
201                        CommandExecutor::getEvaluation().state_ = CS_Error;
202                        AddLanguageEntry("commandexecutorunknownfirstargument", "is not a shortcut nor a classname");
203                        CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getArgument(0) + " " + GetLocalisation("commandexecutorunknownfirstargument") + ".";
204                        return;
205                    }
206                }
207                else
208                {
209                    // There's no finished first argument - search possible shortcuts or classnames
210                    CommandExecutor::createListOfPossibleFunctions(CommandExecutor::getArgument(0));
211                    CommandExecutor::createListOfPossibleIdentifiers(CommandExecutor::getArgument(0));
212
213                    unsigned int num_functions = CommandExecutor::getEvaluation().listOfPossibleFunctions_.size();
214                    unsigned int num_identifiers = CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.size();
215
216                    if (num_functions == 1 && num_identifiers == 0)
217                    {
218                        // It's a shortcut
219                        std::string functionname = *(*CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin()).first;
220                        CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(functionname);
221                        if (getLowercase(functionname) != getLowercase(CommandExecutor::getArgument(0)))
222                        {
223                            // Unfinished shortcut
224                            CommandExecutor::getEvaluation().bCommandChanged_ = true;
225                        }
226                        CommandExecutor::getEvaluation().state_ = CS_Params;
227                        CommandExecutor::getEvaluation().functionclass_ = 0;
228                        CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().function_->getName();
229                        if (CommandExecutor::getEvaluation().function_->getParamCount() > 0)
230                            CommandExecutor::getEvaluation().command_ += " ";
231                        // Move on to next case
232                    }
233                    else if (num_identifiers == 1 && num_functions == 0)
234                    {
235                        // It's a classname
236                        std::string classname = *(*CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.begin()).first;
237                        CommandExecutor::getEvaluation().functionclass_ = CommandExecutor::getPossibleIdentifier(classname);
238                        if (getLowercase(classname) != getLowercase(CommandExecutor::getArgument(0)))
239                        {
240                            // Unfinished classname
241                            CommandExecutor::getEvaluation().bCommandChanged_ = true;
242                        }
243                        CommandExecutor::getEvaluation().state_ = CS_Function;
244                        CommandExecutor::getEvaluation().function_ = 0;
245                        CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " ";
246                        // Move on to next case
247                    }
248                    else if (num_identifiers == 0 && num_functions == 0)
249                    {
250                        // No possibilities
251                        CommandExecutor::getEvaluation().state_ = CS_Error;
252                        AddLanguageEntry("commandexecutorunknownfirstargumentstart", "There is no command or classname starting with");
253                        CommandExecutor::getEvaluation().errorMessage_ = "Error: " + GetLocalisation("commandexecutorunknownfirstargumentstart") + " " + CommandExecutor::getArgument(0) + ".";
254                        return;
255                    }
256                    else
257                    {
258                        // There are several possiblilities
259                        std::list<std::pair<const std::string*, const std::string*> > temp;
260                        temp.insert(temp.end(), CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin(), CommandExecutor::getEvaluation().listOfPossibleFunctions_.end());
261                        temp.insert(temp.end(), CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.begin(), CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.end());
262                        CommandExecutor::getEvaluation().command_ = CommandExecutor::getCommonBegin(temp);
263                        CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(0));
264                        CommandExecutor::getEvaluation().functionclass_ = CommandExecutor::getPossibleIdentifier(CommandExecutor::getArgument(0));
265                        return;
266                    }
267                }
268            }
269            case CS_Function:
270            {
271                if (CommandExecutor::getEvaluation().functionclass_)
272                {
273                    // There is a classname - search for the commandname
274                    if (CommandExecutor::argumentsGiven() > 2)
275                    {
276                        // There is a finished second argument - check if it's a commandname
277                        CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(1), CommandExecutor::getEvaluation().functionclass_);
278
279                        if (CommandExecutor::getEvaluation().function_)
280                        {
281                            // It's a function
282                            CommandExecutor::getEvaluation().state_ = CS_Params;
283                            // Move on to next case
284                        }
285                        else
286                        {
287                            // The second argument is bad
288                            CommandExecutor::getEvaluation().state_ = CS_Error;
289                            AddLanguageEntry("commandexecutorunknownsecondargument", "is not a function of");
290                            CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getArgument(1) + " " + GetLocalisation("commandexecutorunknownsecondargument") + " " + CommandExecutor::getEvaluation().functionclass_->getName() + ".";
291                            return;
292                        }
293                    }
294                    else
295                    {
296                        // There is no finished second argument - search for possibilities
297                        CommandExecutor::createListOfPossibleFunctions(CommandExecutor::getArgument(1), CommandExecutor::getEvaluation().functionclass_);
298                        unsigned int num_functions = CommandExecutor::getEvaluation().listOfPossibleFunctions_.size();
299
300                        if (num_functions == 1)
301                        {
302                            // It's a function
303                            std::string functionname = *(*CommandExecutor::getEvaluation().listOfPossibleFunctions_.begin()).first;
304                            CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(functionname, CommandExecutor::getEvaluation().functionclass_);
305                            if (getLowercase(functionname) != getLowercase(CommandExecutor::getArgument(1)))
306                            {
307                                // Unfinished function
308                                CommandExecutor::getEvaluation().bCommandChanged_ = true;
309                            }
310                            CommandExecutor::getEvaluation().state_ = CS_Params;
311                            CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " " + CommandExecutor::getEvaluation().function_->getName();
312                            if (CommandExecutor::getEvaluation().function_->getParamCount() > 0)
313                                CommandExecutor::getEvaluation().command_ += " ";
314                            // Move on to next case
315                        }
316                        else if (num_functions == 0)
317                        {
318                            // No possibilities
319                            CommandExecutor::getEvaluation().state_ = CS_Error;
320                            AddLanguageEntry("commandexecutorunknownsecondargumentstart", "has no function starting with");
321                            CommandExecutor::getEvaluation().errorMessage_ = "Error: " + CommandExecutor::getEvaluation().functionclass_->getName() + " " + GetLocalisation("commandexecutorunknownsecondargumentstart") + " " + CommandExecutor::getArgument(1) + ".";
322                            return;
323                        }
324                        else
325                        {
326                            // There are several possibilities
327                            CommandExecutor::getEvaluation().command_ = CommandExecutor::getEvaluation().functionclass_->getName() + " " + CommandExecutor::getCommonBegin(CommandExecutor::getEvaluation().listOfPossibleFunctions_);
328                            CommandExecutor::getEvaluation().function_ = CommandExecutor::getPossibleCommand(CommandExecutor::getArgument(1), CommandExecutor::getEvaluation().functionclass_);
329                            return;
330                        }
331                    }
332                }
333                else
334                {
335                    // There is no classname - move on to CS_Shortcut_Params
336                }
337            }
338std::cout << "Waiting for arguments" << std::endl;
339            case CS_Params:
340            {
341            }
342            case CS_Finished:
343            {
344                // Nothing more to do
345                break;
346            }
347            case CS_Error:
348            {
349                // Bad, very bad
350                break;
351            }
352        }
353    }
354
355    unsigned int CommandExecutor::argumentsFinished()
356    {
357        unsigned int argumentsGiven = CommandExecutor::argumentsGiven();
358        if (argumentsGiven > 0)
359            return argumentsGiven - 1;
360        else
361            return 0;
362    }
363
364    unsigned int CommandExecutor::argumentsGiven()
365    {
366        if (CommandExecutor::getEvaluation().command_.size() > 0 && CommandExecutor::getEvaluation().command_[CommandExecutor::getEvaluation().command_.size() - 1] == ' ')
367            return CommandExecutor::getEvaluation().commandTokens_.size() + 1;
368        else
369            return CommandExecutor::getEvaluation().commandTokens_.size();
370    }
371
372    bool CommandExecutor::enoughArgumentsGiven(ConsoleCommand* command)
373    {
374        if (CommandExecutor::getEvaluation().functionclass_)
375            return (CommandExecutor::getEvaluation().commandTokens_.size() >= (2 + command->getParamCount()));
376        else
377            return (CommandExecutor::getEvaluation().commandTokens_.size() >= (1 + command->getParamCount()));
378    }
379
380    std::string CommandExecutor::getArgument(unsigned int index)
381    {
382        if (index < (CommandExecutor::getEvaluation().commandTokens_.size()))
383            return CommandExecutor::getEvaluation().commandTokens_[index];
384        else
385            return "";
386    }
387
388    std::string CommandExecutor::getLastArgument()
389    {
390        return CommandExecutor::getArgument(CommandExecutor::argumentsGiven());
391    }
392
393    void CommandExecutor::createListOfPossibleIdentifiers(const std::string& fragment)
394    {
395        CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.clear();
396        std::string lowercase = getLowercase(fragment);
397        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMapBegin(); it != Identifier::getLowercaseIdentifierMapEnd(); ++it)
398            if ((*it).second->hasConsoleCommands())
399                if ((*it).first.find(lowercase) == 0 || fragment == "")
400                    CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.push_back(std::pair<const std::string*, const std::string*>(&(*it).first, &(*it).second->getName()));
401
402        CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.sort(CommandExecutor::compareStringsInList);
403    }
404
405    void CommandExecutor::createListOfPossibleFunctions(const std::string& fragment, Identifier* identifier)
406    {
407        CommandExecutor::getEvaluation().listOfPossibleFunctions_.clear();
408        std::string lowercase = getLowercase(fragment);
409        if (!identifier)
410        {
411            for (std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getLowercaseConsoleCommandShortcutMapBegin(); it != CommandExecutor::getLowercaseConsoleCommandShortcutMapEnd(); ++it)
412                if ((*it).first.find(lowercase) == 0 || fragment == "")
413                    CommandExecutor::getEvaluation().listOfPossibleFunctions_.push_back(std::pair<const std::string*, const std::string*>(&(*it).first, &(*it).second->getName()));
414        }
415        else
416        {
417            for (std::map<std::string, ConsoleCommand*>::const_iterator it = identifier->getLowercaseConsoleCommandMapBegin(); it != identifier->getLowercaseConsoleCommandMapEnd(); ++it)
418                if ((*it).first.find(lowercase) == 0 || fragment == "")
419                    CommandExecutor::getEvaluation().listOfPossibleFunctions_.push_back(std::pair<const std::string*, const std::string*>(&(*it).first, &(*it).second->getName()));
420        }
421
422        CommandExecutor::getEvaluation().listOfPossibleFunctions_.sort(CommandExecutor::compareStringsInList);
423    }
424
425    void CommandExecutor::createListOfPossibleArguments(const std::string& fragment, ConsoleCommand* command, unsigned int param)
426    {
427        CommandExecutor::getEvaluation().listOfPossibleArguments_.clear();
428        std::string lowercase = getLowercase(fragment);
429        for (std::list<std::pair<std::string, std::string> >::const_iterator it = command->getArgumentCompletionListBegin(param); it != command->getArgumentCompletionListEnd(param); ++it)
430            if ((*it).first.find(lowercase) == 0 || fragment == "")
431                CommandExecutor::getEvaluation().listOfPossibleArguments_.push_back(std::pair<const std::string*, const std::string*>(&(*it).first, &(*it).second));
432
433        CommandExecutor::getEvaluation().listOfPossibleArguments_.sort(CommandExecutor::compareStringsInList);
434    }
435
436    Identifier* CommandExecutor::getPossibleIdentifier(const std::string& name)
437    {
438        std::string lowercase = getLowercase(name);
439        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMap().find(lowercase);
440        if ((it != Identifier::getLowercaseIdentifierMapEnd()) && (*it).second->hasConsoleCommands())
441            return (*it).second;
442
443        return 0;
444    }
445
446    ConsoleCommand* CommandExecutor::getPossibleCommand(const std::string& name, Identifier* identifier)
447    {
448        std::string lowercase = getLowercase(name);
449        if (!identifier)
450        {
451            std::map<std::string, ConsoleCommand*>::const_iterator it = CommandExecutor::getLowercaseConsoleCommandShortcutMap().find(lowercase);
452            if (it != CommandExecutor::getLowercaseConsoleCommandShortcutMapEnd())
453                return (*it).second;
454        }
455        else
456        {
457            std::map<std::string, ConsoleCommand*>::const_iterator it = identifier->getLowercaseConsoleCommandMap().find(lowercase);
458            if (it != identifier->getLowercaseConsoleCommandMapEnd())
459                return (*it).second;
460        }
461        return 0;
462    }
463
464    const std::string* CommandExecutor::getPossibleArgument(const std::string& name, ConsoleCommand* command, unsigned int param)
465    {
466        std::string lowercase = getLowercase(name);
467        for (std::list<std::pair<std::string, std::string> >::const_iterator it = command->getArgumentCompletionListBegin(param); it != command->getArgumentCompletionListEnd(param); ++it)
468            if ((*it).first == lowercase)
469                return &(*it).second;
470
471        return 0;
472    }
473
474    std::string CommandExecutor::getCommonBegin(const std::list<std::pair<const std::string*, const std::string*> >& list)
475    {
476        if (list.size() == 0)
477        {
478            return "";
479        }
480        else if (list.size() == 1)
481        {
482            return ((*(*list.begin()).first) + " ");
483        }
484        else
485        {
486            std::string output = "";
487            for (unsigned int i = 0; true; i++)
488            {
489                char temp = 0;
490                for (std::list<std::pair<const std::string*, const std::string*> >::const_iterator it = list.begin(); it != list.end(); ++it)
491                {
492                    if ((*(*it).first).size() > i)
493                    {
494                        if (it == list.begin())
495                        {
496                            temp = (*(*it).first)[i];
497                        }
498                        else
499                        {
500                            if (temp != (*(*it).first)[i])
501                                return output;
502                        }
503                    }
504                    else
505                    {
506                        return output;
507                    }
508                }
509                output += temp;
510            }
511            return output;
512        }
513    }
514
515    bool CommandExecutor::compareStringsInList(const std::pair<const std::string*, const std::string*>& first, const std::pair<const std::string*, const std::string*>& second)
516    {
517        return ((*first.first) < (*second.first));
518    }
519}
Note: See TracBrowser for help on using the repository browser.